Compare commits

...
7 Commits
7 changed files with 396 additions and 85 deletions
+2 -2
View File
@@ -10,11 +10,11 @@ import (
) )
// Build key encoding request command for the Assa Abloy lock server. // 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") ci := checkIn.Format("200601021504")
co := checkOut.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 return nil
} }
+34 -10
View File
@@ -12,34 +12,63 @@ import (
log "github.com/sirupsen/logrus" 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 ( const (
AssaAbloy = "assaabloy" AssaAbloy = "assaabloy"
Omnitec = "omnitec" Omnitec = "omnitec"
Salto = "salto"
TLJ = "tlj"
)
var (
Cert string
LockServerURL string
) )
type ( type (
LockServer interface { LockServer interface {
BuildCommand(lockId string, checkIn, checkOut time.Time) error BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error
LockSequence(conn net.Conn) error LockSequence(conn net.Conn) error
} }
AssaLockServer struct { AssaLockServer struct {
encoderAddr string encoderAddr string
command string command string
} }
OmniLockServer struct { OmniLockServer struct {
encoderAddr string // Encoder unit address 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
}
TLJLockServer struct {
encoderAddr string
command string
} }
) )
func NewLockServer(lockType, encoderAddr string, fatalError func(error)) LockServer { func NewLockServer(lockType, encoderAddr string, fatalError func(error)) LockServer {
switch lockType { switch strings.ToLower(lockType) {
case AssaAbloy: case AssaAbloy:
return &AssaLockServer{encoderAddr: encoderAddr} return &AssaLockServer{encoderAddr: encoderAddr}
case Omnitec: case Omnitec:
return &OmniLockServer{encoderAddr: encoderAddr} return &OmniLockServer{encoderAddr: encoderAddr}
case Salto:
return &SaltoLockServer{encoderAddr: encoderAddr}
case TLJ:
return &TLJLockServer{encoderAddr: encoderAddr}
default: default:
fatalError(fmt.Errorf("unsupported LockType: %s; must be 'assaabloy' or 'omnitec'", lockType)) 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 return nil // This line will never be reached, but is needed to satisfy the compiler
@@ -84,8 +113,3 @@ func sendAndReceive(conn net.Conn, command []byte) (string, error) {
response := buf[:n] response := buf[:n]
return string(response), nil return string(response), nil
} }
+2 -2
View File
@@ -13,7 +13,7 @@ import (
) )
// Build key encoding request command for the Omnitec lock server. // 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" const funcName = "OmniLockServer.BuildCommand"
hostname, err := os.Hostname() hostname, err := os.Hostname()
if err != nil { 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 // Format lockId as 4-digit zero-padded string
idInt, err := strconv.Atoi(lockId) idInt, err := strconv.Atoi(doorReq.RoomField)
if err != nil { if err != nil {
return fmt.Errorf("[%s] failed to convert lockId to integer: %v", funcName, err) return fmt.Errorf("[%s] failed to convert lockId to integer: %v", funcName, err)
} }
+194
View File
@@ -0,0 +1,194 @@
package lockserver
import (
"bufio"
"fmt"
"net"
"time"
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
separator = 0xB3 // '│' character in ASCII (179 decimal)
)
// calculateLRC computes the Longitudinal Redundancy Check over data
func calculateLRC(data []byte) byte {
var lrc byte
for _, b := range data {
lrc ^= b
}
return lrc
}
// 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)
// command type
cmd := "CN"
if req.FollowStr == "1" {
cmd = "CC"
}
// fields 0–10
fields := []string{
cmd,
lock.encoderAddr,
"E",
req.RoomField,
"", // optional field 4
"", // 5
"", // 6
"", // 7
"", // 8
start,
expiry,
}
// 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)
// append LRC (XOR of everything after STX through ETX)
lrc := calculateLRC(body[1:])
body = append(body, lrc)
lock.command = body
return nil
}
// LockSequence performs the full ENQ/ACK handshake and command exchange
func (lock *SaltoLockServer) LockSequence(conn net.Conn) error {
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 _, 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))
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 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
}
+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
}
+71 -70
View File
@@ -30,7 +30,7 @@ import (
) )
const ( const (
buildVersion = "1.0.0" buildVersion = "1.0.10"
serviceName = "hardlink" serviceName = "hardlink"
customLayout = "2006-01-02 15:04:05 -0700" customLayout = "2006-01-02 15:04:05 -0700"
transactionUrl = "http://127.0.0.1:18181/start-transaction/" transactionUrl = "http://127.0.0.1:18181/start-transaction/"
@@ -42,22 +42,12 @@ type configRec struct {
LockserverUrl string `yaml:"lockservUrl"` LockserverUrl string `yaml:"lockservUrl"`
LockType string `yaml:"lockType"` LockType string `yaml:"lockType"`
EncoderAddress string `yaml:"encoderAddr"` EncoderAddress string `yaml:"encoderAddr"`
Cert string `yaml:"cert"`
DispenserPort string `yaml:"dispensPort"` DispenserPort string `yaml:"dispensPort"`
DispenserAdrr string `yaml:"dispensAddr"` DispenserAdrr string `yaml:"dispensAddr"`
PrinterName string `yaml:"printerName"` PrinterName string `yaml:"printerName"`
LogDir string `yaml:"logdir"` LogDir string `yaml:"logdir"`
dbport int `yaml:"dbport"` // Port for the database connection IsPayment bool `yaml:"isPayment"`
dbname string `yaml:"dbname"` // Database name for the connection
dbuser string `yaml:"dbuser"` // User for the database connection
dbpassword string `yaml:"dbpassword"` // Password for the database connection
}
// 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"`
} }
// App holds shared resources. // App holds shared resources.
@@ -78,10 +68,13 @@ func newApp(dispPort *serial.Port, lockConn net.Conn, config configRec) *App {
func main() { func main() {
// Load config // Load config
config := readConfig() config := readConfig()
printer.Layout = readTicketLayout() printer.Layout = readTicketLayout()
printer.PrinterName = config.PrinterName printer.PrinterName = config.PrinterName
var lockConn net.Conn
lockserver.Cert = config.Cert
lockserver.LockServerURL = config.LockserverUrl
// Setup logging and get file handle // Setup logging and get file handle
logFile, err := setupLogging(config.LogDir) logFile, err := setupLogging(config.LogDir)
if err != nil { if err != nil {
@@ -111,12 +104,17 @@ func main() {
log.Infof("Dispenser initialized on port %s, %s", config.DispenserPort, status) log.Infof("Dispenser initialized on port %s, %s", config.DispenserPort, status)
// Initialize lock-server connection once // Initialize lock-server connection once
lockConn, err := lockserver.InitializeServerConnection(config.LockserverUrl) switch strings.ToLower(config.LockType) {
if err != nil { case lockserver.TLJ:
fatalError(err)
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) // db, err := payment.InitMSSQL(config.dbport, config.dbname, config.dbuser, config.dbpassword)
// if err != nil { // if err != nil {
@@ -124,62 +122,65 @@ func main() {
// } // }
// defer db.Close() // defer db.Close()
startClient := func() (*exec.Cmd, error) { if config.IsPayment {
cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe") startClient := func() (*exec.Cmd, error) {
err := cmd.Start() cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe")
if err != nil { err := cmd.Start()
return nil, fmt.Errorf("Failed to start ChipDnaClient: %v", err)
}
log.Infof("ChipDnaClient started with PID %d", cmd.Process.Pid)
return cmd, nil
}
cmd, err := startClient()
if err != nil {
fatalError(err)
}
// Restart loop
go func() {
for {
err := cmd.Wait()
if err != nil { if err != nil {
log.Errorf("ChipDnaClient exited unexpectedly: %v", err) return nil, fmt.Errorf("failed to start ChipDnaClient: %v", err)
time.Sleep(2 * time.Second)
cmd, err = startClient()
if err != nil {
log.Errorf("Restart failed: %v", err)
return
}
log.Info("ChipDnaClient restarted successfully")
} }
log.Infof("ChipDnaClient started with PID %d", cmd.Process.Pid)
return cmd, nil
} }
}()
// Handle shutdown signals cmd, err := startClient()
sigs := make(chan os.Signal, 1) if err != nil {
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) fatalError(err)
go func() {
<-sigs
log.Info("Shutting down...")
if cmd.Process != nil {
log.Info("Sending SIGTERM to ChipDnaClient...")
_ = cmd.Process.Signal(syscall.SIGTERM)
// wait up to 5s for graceful shutdown
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
select {
case <-time.After(5 * time.Second):
log.Warn("ChipDnaClient did not exit in time, killing...")
_ = cmd.Process.Kill()
case err := <-done:
log.Infof("ChipDnaClient exited cleanly: %v", err)
}
} }
os.Exit(0)
}() // Restart loop
go func() {
for {
err := cmd.Wait()
if err != nil {
log.Errorf("ChipDnaClient exited unexpectedly: %v", err)
time.Sleep(2 * time.Second)
cmd, err = startClient()
if err != nil {
log.Errorf("Restart failed: %v", err)
return
}
log.Info("ChipDnaClient restarted successfully")
}
}
}()
// Handle shutdown signals
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
log.Info("Shutting down...")
if cmd.Process != nil {
log.Info("Sending SIGTERM to ChipDnaClient...")
_ = cmd.Process.Signal(syscall.SIGTERM)
// wait up to 5s for graceful shutdown
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
select {
case <-time.After(5 * time.Second):
log.Warn("ChipDnaClient did not exit in time, killing...")
_ = cmd.Process.Kill()
case err := <-done:
log.Infof("ChipDnaClient exited cleanly: %v", err)
}
}
os.Exit(0)
}()
}
// Create App and wire routes // Create App and wire routes
// dispHandle := &serial.Port{} // Placeholder, replace with actual dispenser handle
app := newApp(dispHandle, lockConn, config) app := newApp(dispHandle, lockConn, config)
mux := http.NewServeMux() mux := http.NewServeMux()
@@ -324,7 +325,7 @@ func (app *App) startTransaction(w http.ResponseWriter, r *http.Request) {
func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) { func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
const op = logging.Op("issueDoorCard") const op = logging.Op("issueDoorCard")
var ( var (
doorReq DoorCardRequest doorReq lockserver.DoorCardRequest
theResponse cmstypes.StatusRec theResponse cmstypes.StatusRec
) )
@@ -385,7 +386,7 @@ func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
} }
// build lock server command // build lock server command
app.lockserver.BuildCommand(doorReq.RoomField, checkIn, checkOut) app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
// lock server sequence // lock server sequence
err = app.lockserver.LockSequence(app.lockConn) err = app.lockserver.LockSequence(app.lockConn)
+22 -1
View File
@@ -2,7 +2,28 @@
builtVersion is a const in main.go builtVersion is a const in main.go
#### 1.0.0 - 30 Jun 2024 #### 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
#### 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 added creditcall payment method
`/starttransaction` - API payment endpoint to start a transaction `/starttransaction` - API payment endpoint to start a transaction