Compare commits

..
4 Commits
Author SHA1 Message Date
Yurii c8f6c57983 updated logging for TLJ locks 2025-08-08 12:39:16 +01:00
Yurii 61b089fe55 updated workflow for TLJ locks 2025-08-08 11:34:02 +01:00
Yurii 8b0e7df582 improved error handling and logging in Salto 2025-08-01 15:18:38 +01:00
Yurii 25eab0dc75 added check if the room exists 2025-07-25 17:36:08 +01:00
5 changed files with 196 additions and 52 deletions
+19 -11
View File
@@ -24,6 +24,12 @@ const (
AssaAbloy = "assaabloy"
Omnitec = "omnitec"
Salto = "salto"
TLJ = "tlj"
)
var (
Cert string
LockServerURL string
)
type (
@@ -33,29 +39,36 @@ type (
}
AssaLockServer struct {
encoderAddr string
command string
encoderAddr string
command string
}
OmniLockServer struct {
encoderAddr string // Encoder unit address
command []byte // Command to be sent to the lock server
command []byte // Command to be sent to the lock server
}
SaltoLockServer struct {
encoderAddr string
command []byte
encoderAddr string
command []byte
}
TLJLockServer struct {
encoderAddr string
command string
}
)
func NewLockServer(lockType, encoderAddr string, fatalError func(error)) LockServer {
switch lockType {
switch strings.ToLower(lockType) {
case AssaAbloy:
return &AssaLockServer{encoderAddr: encoderAddr}
case Omnitec:
return &OmniLockServer{encoderAddr: encoderAddr}
case Salto:
return &SaltoLockServer{encoderAddr: encoderAddr}
case TLJ:
return &TLJLockServer{encoderAddr: encoderAddr}
default:
fatalError(fmt.Errorf("unsupported LockType: %s; must be 'assaabloy' or 'omnitec'", lockType))
return nil // This line will never be reached, but is needed to satisfy the compiler
@@ -100,8 +113,3 @@ func sendAndReceive(conn net.Conn, command []byte) (string, error) {
response := buf[:n]
return string(response), nil
}
+76 -32
View File
@@ -77,59 +77,103 @@ func (lock *SaltoLockServer) BuildCommand(req DoorCardRequest, checkIn, checkOut
// LockSequence performs the full ENQ/ACK handshake and command exchange
func (lock *SaltoLockServer) LockSequence(conn net.Conn) error {
const timeout = 10 * time.Second
log.Infof("Sending command: %q", string(lock.command))
const timeout = 10 * time.Second
var (
err error
resp []byte
)
reader := bufio.NewReader(conn)
// 1. Send ENQ
if _, err := conn.Write([]byte{ENQ}); err != nil {
return fmt.Errorf("failed to send ENQ: %w", err)
if _, e := conn.Write([]byte{ENQ}); e != nil {
return fmt.Errorf("failed to send ENQ: %w", e)
}
// 2. Expect ACK
conn.SetReadDeadline(time.Now().Add(timeout))
b, err := reader.ReadByte()
if err != nil {
return fmt.Errorf("error awaiting ACK to ENQ: %w", err)
}
if b != ACK {
if b, e := reader.ReadByte(); e != nil {
return fmt.Errorf("error awaiting ACK to ENQ: %w", e)
} else if b != ACK {
return fmt.Errorf("expected ACK after ENQ, got 0x%X", b)
}
// 3. Send the command frame
if _, err := conn.Write(lock.command); err != nil {
return fmt.Errorf("failed to send command frame: %w", err)
// 3. Send command frame
if _, e := conn.Write(lock.command); e != nil {
return fmt.Errorf("failed to send command frame: %w", e)
}
// 4. Expect ACK to command
conn.SetReadDeadline(time.Now().Add(timeout))
b, err = reader.ReadByte()
if err != nil {
return fmt.Errorf("error awaiting ACK to command: %w", err)
}
if b == NAK {
if b, e := reader.ReadByte(); e != nil {
return fmt.Errorf("error awaiting ACK to command: %w", e)
} else if b == NAK {
return fmt.Errorf("command rejected (NAK)")
} else if b != ACK {
return fmt.Errorf("expected ACK to command, got 0x%X", b)
}
// 5. Read response: expect STX
// 5. Expect STX
conn.SetReadDeadline(time.Now().Add(timeout))
b, err = reader.ReadByte()
if err != nil {
return fmt.Errorf("error reading response STX: %w", err)
stx, e := reader.ReadByte()
if e != nil {
return fmt.Errorf("error reading STX: %w", e)
}
if b != STX {
return fmt.Errorf("expected STX at response start, got 0x%X", b)
resp = append(resp, stx)
if stx != STX {
err = fmt.Errorf("expected STX, got 0x%X", stx)
}
// 6. Read until ETX
var resp []byte
// 6. Read separator after STX
conn.SetReadDeadline(time.Now().Add(timeout))
if sep, e := reader.ReadByte(); e == nil {
resp = append(resp, sep)
} else if err == nil {
err = fmt.Errorf("error reading separator after STX: %w", e)
}
// 7. Read command code (e.g., CN, TD)
conn.SetReadDeadline(time.Now().Add(timeout))
b1, e1 := reader.ReadByte()
if e1 == nil {
resp = append(resp, b1)
} else if err == nil {
err = fmt.Errorf("error reading first response byte: %w", e1)
}
b2, e2 := reader.ReadByte()
if e2 == nil {
resp = append(resp, b2)
} else if err == nil {
err = fmt.Errorf("error reading second response byte: %w", e2)
}
switch {
case b1 == 'C' && b2 == 'N':
log.Infof("LockSequence: command response is CN (normal)")
case b1 == 'C' && b2 == 'C':
log.Infof("LockSequence: command response is CC (follow-up)")
case b1 == 'T' && b2 == 'D':
log.Warnf("LockSequence: command response is TD (room does not exist)")
if err == nil {
err = fmt.Errorf("lock response indicates room does not exist")
}
default:
log.Warnf("LockSequence: unexpected command response %q", string(resp))
if err == nil {
err = fmt.Errorf("error encoding keycard, unexpected response")
}
}
// 8. Read rest of message until ETX
for {
conn.SetReadDeadline(time.Now().Add(timeout))
c, err := reader.ReadByte()
if err != nil {
return fmt.Errorf("error reading response body: %w", err)
c, e := reader.ReadByte()
if e != nil {
if err == nil {
err = fmt.Errorf("error reading response body: %w", e)
}
break
}
resp = append(resp, c)
if c == ETX {
@@ -137,14 +181,14 @@ func (lock *SaltoLockServer) LockSequence(conn net.Conn) error {
}
}
// 7. (Optional) Read LRC or final CR
// 9. Optional: read trailing byte (LRC or CR)
conn.SetReadDeadline(time.Now().Add(timeout))
if lrc, err := reader.ReadByte(); err == nil {
if lrc, e := reader.ReadByte(); e == nil {
resp = append(resp, lrc)
} else {
log.Warnf("LockSequence: failed to read trailing LRC/CR: %v", err)
log.Warnf("LockSequence: failed to read trailing LRC/CR: %v", e)
}
log.Infof("LockSequence: received response: % X", resp)
return nil
log.Infof("LockSequence: received response: %q", string(resp))
return err
}
+71
View File
@@ -0,0 +1,71 @@
package lockserver
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"time"
log "github.com/sirupsen/logrus"
)
// GuestCardResponse represents the JSON response from the GuestCard API call.
type GuestCardResponse struct {
Code string `json:"code"`
CardID string `json:"CardID"`
CommandID int `json:"CommandID"` // optional
Msg string `json:"Msg"` // error message if Code != "0"
}
func (lock *TLJLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error {
params := url.Values{}
params.Set("cer", Cert)
params.Set("room", doorReq.RoomField)
params.Set("BeginTime", checkIn.Format("2006-01-02 15:04:05"))
params.Set("EndTime", checkOut.Format("2006-01-02 15:04:05"))
switch doorReq.FollowStr {
case "0":
params.Set("CheckInMode", "new")
case "1":
params.Set("CheckInMode", "follow")
}
lock.command = fmt.Sprintf("%s/GuestCard?%s", LockServerURL, params.Encode())
return nil
}
func (lock *TLJLockServer) LockSequence(conn net.Conn) error {
log.Infof("Sending command: %q", lock.command)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(lock.command)
if err != nil {
return fmt.Errorf("HTTP request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected HTTP status: %s", resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %v", err)
}
// Parse response JSON
var result GuestCardResponse
err = json.Unmarshal(body, &result)
if err != nil {
return fmt.Errorf("invalid JSON response: %v", err)
}
if result.Code != "0" {
log.Printf("API error %s: %s", result.Code, result.Msg)
return fmt.Errorf("API error %s: %s", result.Code, result.Msg)
}
log.Printf("Guest card created successfully: CardID=%s, CommandID=%d", result.CardID, result.CommandID)
return nil
}
+18 -9
View File
@@ -30,7 +30,7 @@ import (
)
const (
buildVersion = "1.0.6"
buildVersion = "1.0.10"
serviceName = "hardlink"
customLayout = "2006-01-02 15:04:05 -0700"
transactionUrl = "http://127.0.0.1:18181/start-transaction/"
@@ -42,11 +42,12 @@ type configRec struct {
LockserverUrl string `yaml:"lockservUrl"`
LockType string `yaml:"lockType"`
EncoderAddress string `yaml:"encoderAddr"`
Cert string `yaml:"cert"`
DispenserPort string `yaml:"dispensPort"`
DispenserAdrr string `yaml:"dispensAddr"`
PrinterName string `yaml:"printerName"`
LogDir string `yaml:"logdir"`
isPayment bool `yaml:"isPayment"`
IsPayment bool `yaml:"isPayment"`
}
// App holds shared resources.
@@ -67,10 +68,13 @@ func newApp(dispPort *serial.Port, lockConn net.Conn, config configRec) *App {
func main() {
// Load config
config := readConfig()
printer.Layout = readTicketLayout()
printer.PrinterName = config.PrinterName
var lockConn net.Conn
lockserver.Cert = config.Cert
lockserver.LockServerURL = config.LockserverUrl
// Setup logging and get file handle
logFile, err := setupLogging(config.LogDir)
if err != nil {
@@ -100,12 +104,17 @@ func main() {
log.Infof("Dispenser initialized on port %s, %s", config.DispenserPort, status)
// Initialize lock-server connection once
lockConn, err := lockserver.InitializeServerConnection(config.LockserverUrl)
if err != nil {
fatalError(err)
switch strings.ToLower(config.LockType) {
case lockserver.TLJ:
default:
lockConn, err = lockserver.InitializeServerConnection(config.LockserverUrl)
if err != nil {
fatalError(err)
}
defer lockConn.Close()
log.Infof("Connected to lock server at %s", config.LockserverUrl)
}
defer lockConn.Close()
log.Infof("Connected to lock server at %s", config.LockserverUrl)
// db, err := payment.InitMSSQL(config.dbport, config.dbname, config.dbuser, config.dbpassword)
// if err != nil {
@@ -113,7 +122,7 @@ func main() {
// }
// defer db.Close()
if config.isPayment {
if config.IsPayment {
startClient := func() (*exec.Cmd, error) {
cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe")
err := cmd.Start()
+12
View File
@@ -2,6 +2,18 @@
builtVersion is a const in main.go
#### 1.0.10 - 08 August 2024
updated logging for TLJ locks
#### 1.0.9 - 08 August 2024
added TLJ lock server and implemented workflow for TLJ locks
#### 1.0.8 - 01 August 2024
improved error handling and logging in Salto
#### 1.0.7 - 25 July 2024
added check if the room exists
#### 1.0.6 - 25 July 2024
updated workflow for Salto locks