Compare commits

...
4 Commits
Author SHA1 Message Date
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
Yurii fc91f2c0f2 updated workflow for Salto locks 2025-07-25 14:32:30 +01:00
Yurii 5ce9fdcf0b added encoding keycard copy for Salto locks 2025-07-24 15:12:06 +01:00
6 changed files with 184 additions and 81 deletions
+2 -2
View File
@@ -10,11 +10,11 @@ import (
)
// Build key encoding request command for the Assa Abloy lock server.
func (lock *AssaLockServer) BuildCommand(lockId string, checkIn, checkOut time.Time) error {
func (lock *AssaLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error {
ci := checkIn.Format("200601021504")
co := checkOut.Format("200601021504")
lock.command = fmt.Sprintf("CCA;EA%s;GR%s;CO%s;CI%s;AM1;\r\n", lock.encoderAddr, lockId, co, ci)
lock.command = fmt.Sprintf("CCA;EA%s;GR%s;CO%s;CI%s;AM1;\r\n", lock.encoderAddr, doorReq.RoomField, co, ci)
return nil
}
+9 -1
View File
@@ -12,6 +12,14 @@ import (
log "github.com/sirupsen/logrus"
)
// DoorCardRequest is the JSON payload for /issue-door-card.
type DoorCardRequest struct {
RoomField string `json:"roomField"`
CheckinTime string `json:"checkinTime"`
CheckoutTime string `json:"checkoutTime"`
FollowStr string `json:"followStr"`
}
const (
AssaAbloy = "assaabloy"
Omnitec = "omnitec"
@@ -20,7 +28,7 @@ const (
type (
LockServer interface {
BuildCommand(lockId string, checkIn, checkOut time.Time) error
BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error
LockSequence(conn net.Conn) error
}
+2 -2
View File
@@ -13,7 +13,7 @@ import (
)
// Build key encoding request command for the Omnitec lock server.
func (lock *OmniLockServer) BuildCommand(lockId string, checkIn, checkOut time.Time) error {
func (lock *OmniLockServer) BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error {
const funcName = "OmniLockServer.BuildCommand"
hostname, err := os.Hostname()
if err != nil {
@@ -21,7 +21,7 @@ func (lock *OmniLockServer) BuildCommand(lockId string, checkIn, checkOut time.T
}
// Format lockId as 4-digit zero-padded string
idInt, err := strconv.Atoi(lockId)
idInt, err := strconv.Atoi(doorReq.RoomField)
if err != nil {
return fmt.Errorf("[%s] failed to convert lockId to integer: %v", funcName, err)
}
+151 -60
View File
@@ -1,103 +1,194 @@
package lockserver
import (
"bufio"
"fmt"
"net"
"time"
// "strings"
log "github.com/sirupsen/logrus"
)
const (
STX = 0x02 // Start of Text
ETX = 0x03 // End of Text
ENQ = 0x05 // Enquiry from host
ACK = 0x06 // Positive response
NAK = 0x15 // Negative response
STX = 0x02 // Start of Text
ETX = 0x03 // End of Text
ENQ = 0x05 // Enquiry from host
ACK = 0x06 // Positive response
NAK = 0x15 // Negative response
separator = 0xB3 // '│' character in ASCII (179 decimal)
)
// calculateLRC computes the Longitudinal Redundancy Check over data
func calculateLRC(data []byte) byte {
lrc := byte(0x00)
var lrc byte
for _, b := range data {
lrc ^= b
}
return lrc
}
// simple join that avoids importing strings just for this.
func stringJoin(parts []string, sep string) string {
if len(parts) == 0 {
return ""
}
out := parts[0]
for _, p := range parts[1:] {
out += sep + p
}
return out
}
// BuildCommand builds a Salto card‑issuance command in the form:
// STX|CN|<encoder addres>|E|<room>| | | | | |<start>|<expiry>|ETX|<LRC>
// where <start> and <expiry> are hhmmDDMMYY, and LRC is the XOR of all bytes
func (lock *SaltoLockServer) BuildCommand(lockId string, checkIn, checkOut time.Time) error {
// format helper: hhmmDDMMYY
// BuildCommand assembles the SALTO frame with fields #0–#10, STX/ETX and LRC
func (lock *SaltoLockServer) BuildCommand(req DoorCardRequest, checkIn, checkOut time.Time) error {
// helper: hh[mm]DDMMYY
fmtStamp := func(t time.Time) string {
return fmt.Sprintf("%02d%02d%02d%02d%02d",
t.Hour(), t.Minute(), t.Day(), int(t.Month()), t.Year()%100)
}
start := fmtStamp(checkIn)
expiry := fmtStamp(checkOut)
// the 12 fields between STX and ETX
// command type
cmd := "CN"
if req.FollowStr == "1" {
cmd = "CC"
}
// fields 0–10
fields := []string{
"CN", lock.encoderAddr, "E", lockId, "", "", "", "", "", "", start, expiry,
cmd,
lock.encoderAddr,
"E",
req.RoomField,
"", // optional field 4
"", // 5
"", // 6
"", // 7
"", // 8
start,
expiry,
}
body := "|" + stringJoin(fields, "|") + "|" // leading/trailing pipes, so the ETX ends the last field
// build payload between STX and ETX
body := []byte{STX}
for _, f := range fields {
body = append(body, separator)
body = append(body, []byte(f)...)
}
body = append(body, separator)
body = append(body, ETX)
// wrap with STX/ETX
msg := append([]byte{STX}, []byte(body)...)
msg = append(msg, ETX)
// append LRC (XOR of everything after STX through ETX)
lrc := calculateLRC(body[1:])
body = append(body, lrc)
// compute LRC over everything *after* STX up to and including ETX
lrc := calculateLRC(msg[1:]) // skip STX
msg = append(msg, lrc)
lock.command = msg
lock.command = body
return nil
}
// Checks heart beat of the Assa Abloy lock server and perform key encoding
// LockSequence performs the full ENQ/ACK handshake and command exchange
func (lock *SaltoLockServer) LockSequence(conn net.Conn) error {
const funcName = "SaltoLockServer.LockSequence"
log.Infof("Sending command: %q", string(lock.command))
// Step 1: ENQ to check availability
respStr, err := sendAndReceive(conn, []byte{ENQ})
if err != nil {
return fmt.Errorf("[%s] failed sending ENQ: %w", funcName, err)
}
resp := []byte(respStr)
const timeout = 10 * time.Second
var (
err error
resp []byte
)
reader := bufio.NewReader(conn)
if len(resp) != 1 || resp[0] != ACK {
return fmt.Errorf("[%s] expected ACK (0x06) after ENQ, got: %q (hex: % X)", funcName, respStr, resp)
// 1. Send ENQ
if _, e := conn.Write([]byte{ENQ}); e != nil {
return fmt.Errorf("failed to send ENQ: %w", e)
}
// Step 2: Send actual command
respStr, err = sendAndReceive(conn, lock.command)
if err != nil {
return fmt.Errorf("[%s] failed sending command: %w", funcName, err)
}
resp = []byte(respStr)
if len(resp) == 1 && resp[0] == NAK {
return fmt.Errorf("[%s] command rejected by lock server (NAK)", funcName)
// 2. Expect ACK
conn.SetReadDeadline(time.Now().Add(timeout))
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)
}
log.Infof("Encoding response: %q", respStr)
return nil
// 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))
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. Expect STX
conn.SetReadDeadline(time.Now().Add(timeout))
stx, e := reader.ReadByte()
if e != nil {
return fmt.Errorf("error reading STX: %w", e)
}
resp = append(resp, stx)
if stx != STX {
err = fmt.Errorf("expected STX, got 0x%X", stx)
}
// 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, 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 {
break
}
}
// 9. Optional: read trailing byte (LRC or CR)
conn.SetReadDeadline(time.Now().Add(timeout))
if lrc, e := reader.ReadByte(); e == nil {
resp = append(resp, lrc)
} else {
log.Warnf("LockSequence: failed to read trailing LRC/CR: %v", e)
}
log.Infof("LockSequence: received response: %q", string(resp))
return err
}
+6 -13
View File
@@ -30,7 +30,7 @@ import (
)
const (
buildVersion = "1.0.4"
buildVersion = "1.0.8"
serviceName = "hardlink"
customLayout = "2006-01-02 15:04:05 -0700"
transactionUrl = "http://127.0.0.1:18181/start-transaction/"
@@ -46,15 +46,7 @@ type configRec struct {
DispenserAdrr string `yaml:"dispensAddr"`
PrinterName string `yaml:"printerName"`
LogDir string `yaml:"logdir"`
isPayment bool `yaml:"isPayment"`
}
// DoorCardRequest is the JSON payload for /issue-door-card.
type DoorCardRequest struct {
RoomField string `json:"roomField"`
CheckinTime string `json:"checkinTime"`
CheckoutTime string `json:"checkoutTime"`
FollowStr string `json:"followStr"`
IsPayment bool `yaml:"isPayment"`
}
// App holds shared resources.
@@ -121,7 +113,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()
@@ -179,6 +171,7 @@ func main() {
}
// Create App and wire routes
// dispHandle := &serial.Port{} // Placeholder, replace with actual dispenser handle
app := newApp(dispHandle, lockConn, config)
mux := http.NewServeMux()
@@ -323,7 +316,7 @@ func (app *App) startTransaction(w http.ResponseWriter, r *http.Request) {
func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
const op = logging.Op("issueDoorCard")
var (
doorReq DoorCardRequest
doorReq lockserver.DoorCardRequest
theResponse cmstypes.StatusRec
)
@@ -384,7 +377,7 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
}
// build lock server command
app.lockserver.BuildCommand(doorReq.RoomField, checkIn, checkOut)
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
// lock server sequence
err = app.lockserver.LockSequence(app.lockConn)
+14 -3
View File
@@ -2,9 +2,20 @@
builtVersion is a const in main.go
#### 1.0.1 - 22 July 2024
added salto lock server and implemented workflow for Salto
#### 1.0.8 - 1 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
#### 1.0.5 - 24 July 2024
added encoding keycard copy for Salto locks
#### 1.0.4 - 22 July 2024
added salto lock server and implemented workflow for Salto
#### 1.0.0 - 30 June 2024
added creditcall payment method