Compare commits

..
25 Commits
Author SHA1 Message Date
Yurii a4885be458 added route for taking preauthorization payment 2025-12-10 11:12:39 +00:00
Yurii 89dfa28e6f return masked card number and expiry date in the payment success URL 2025-12-08 13:31:21 +00:00
Yurii bb526a248d improved logging for creditcall payment processing 2025-11-13 16:06:31 +00:00
Yurii f4f44da541 moved handlers from main.go to handlers/handlers.go 2025-11-13 15:16:06 +00:00
Yurii 7993a2360d added testmode to config file 2025-11-12 13:14:56 +00:00
Yurii c15ceba78f increased timeout for Salto lock server connection to 40 seconds 2025-10-20 19:41:07 +02:00
Yurii 04c664294d removed minutes from the start and expiry time in Salto lock command 2025-10-06 15:36:02 +01:00
Yurii da5cafe031 allowed to continue if the connection to the lock server fails at startup 2025-09-10 13:20:54 +01:00
Yurii efa415e631 increased timeout for TLJ lock server connection to 30 seconds 2025-09-04 14:54:50 +01:00
Yurii f1dc0ccce4 added functionality to commit transactions 2025-08-30 23:03:39 +01:00
Yurii 1bceb55285 fixed TCP/IP connection to the lock server 2025-08-27 17:14:40 +01:00
Yurii bb8cdb1d84 fixed issue in creditcall payment processing where error description was not properly set 2025-08-26 16:13:21 +01:00
Yurii 251afd6aeb TCP/IP connection to the lock server is now established before encoding the keycard and closed after the encoding is done 2025-08-21 19:26:42 +01:00
Yurii e6ff292706 added delay before checking dispenser status 2025-08-11 18:10:53 +01:00
Yurii b4d16f9021 updated Salto key encoding workflow 2025-08-11 14:57:33 +01:00
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
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
Yurii b303721a92 added salto lock server and implemented workflow for Salto 2025-07-23 11:46:26 +01:00
Yurii dc91a9ae63 removed db connection 2025-07-04 13:04:05 +01:00
Yurii b303481b5f removed insertion of transaction into db 2025-07-04 12:46:50 +01:00
Yurii 41cf71a253 made url parametrs hexadecimal encoded 2025-07-01 11:21:34 +01:00
12 changed files with 1107 additions and 483 deletions
+1
View File
@@ -28,6 +28,7 @@ Checkin.code-workspace
_obj _obj
_test _test
.vscode/ .vscode/
ChipDNAClient/
# Architecture specific extensions/prefixes # Architecture specific extensions/prefixes
*.[568vq] *.[568vq]
+4
View File
@@ -251,6 +251,8 @@ func CardToEncoderPosition(port *serial.Port) (string, error) {
return "", fmt.Errorf("error sending ENQ to prompt device: %v", err) return "", fmt.Errorf("error sending ENQ to prompt device: %v", err)
} }
time.Sleep(delay)
//Check card position status //Check card position status
status, err := CheckDispenserStatus(port) status, err := CheckDispenserStatus(port)
if err != nil { if err != nil {
@@ -281,6 +283,8 @@ func CardOutOfMouth(port *serial.Port) (string, error) {
return "", fmt.Errorf("error sending ENQ to prompt device: %v", err) return "", fmt.Errorf("error sending ENQ to prompt device: %v", err)
} }
time.Sleep(delay)
//Check card position status //Check card position status
status, err := CheckDispenserStatus(port) status, err := CheckDispenserStatus(port)
if err != nil { if err != nil {
+390
View File
@@ -0,0 +1,390 @@
package handlers
import (
"bytes"
"encoding/json"
"encoding/xml"
"io"
"net/http"
"strings"
"time"
"github.com/tarm/serial"
"gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/hardlink/dispenser"
"gitea.futuresens.co.uk/futuresens/hardlink/lockserver"
"gitea.futuresens.co.uk/futuresens/hardlink/payment"
"gitea.futuresens.co.uk/futuresens/hardlink/printer"
"gitea.futuresens.co.uk/futuresens/logging"
log "github.com/sirupsen/logrus"
)
const (
customLayout = "2006-01-02 15:04:05 -0700"
takePreauthorizationUrl = "http://127.0.0.1:18181/start-transaction/"
takePaymentUrl = "http://127.0.0.1:18181/start-and-confirm-transaction/"
)
type App struct {
dispPort *serial.Port
lockserver lockserver.LockServer
isPayment bool
}
func NewApp(dispPort *serial.Port, lockType, encoderAddress string, isPayment bool) *App {
return &App{
isPayment: isPayment,
dispPort: dispPort,
lockserver: lockserver.NewLockServer(lockType, encoderAddress, FatalError),
}
}
func (app *App) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/issuedoorcard", app.issueDoorCard)
mux.HandleFunc("/printroomticket", app.printRoomTicket)
mux.HandleFunc("/takepreauth", app.takePreauthorization)
mux.HandleFunc("/takepayment", app.takePayment)
}
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
const op = logging.Op("takePreauthorization")
var (
theResponse cmstypes.ResponseRec
cardholderReceipt string
theRequest cmstypes.TransactionRec
trResult payment.TransactionResultXML
)
theResponse.Status.Code = http.StatusInternalServerError
theResponse.Status.Message = "500 Internal server error"
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Content-Type", "application/json")
if !app.isPayment {
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Payment processing is disabled")
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
return
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
log.Println("takePreauthorization called")
if r.Method != http.MethodPost {
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Method not allowed; use POST")
writeTransactionResult(w, http.StatusMethodNotAllowed, theResponse)
return
}
defer r.Body.Close()
if ct := r.Header.Get("Content-Type"); ct != "text/xml" {
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Content-Type must be text/xml")
writeTransactionResult(w, http.StatusUnsupportedMediaType, theResponse)
return
}
body, _ := io.ReadAll(r.Body)
err := xml.Unmarshal(body, &theRequest)
if err != nil {
logging.Error(serviceName, err.Error(), "ReadXML", string(op), "", "", 0)
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Invalid XML payload")
writeTransactionResult(w, http.StatusBadRequest, theResponse)
return
}
log.Printf("Transaction payload: Amount=%s, Type=%s", theRequest.AmountMinorUnits, theRequest.TransactionType)
client := &http.Client{Timeout: 300 * time.Second}
response, err := client.Post(takePreauthorizationUrl, "text/xml", bytes.NewBuffer(body))
if err != nil {
logging.Error(serviceName, err.Error(), "Payment processing error", string(op), "", "", 0)
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "No response from payment processor")
writeTransactionResult(w, http.StatusBadGateway, theResponse)
return
}
defer response.Body.Close()
body, err = io.ReadAll(response.Body)
if err != nil {
logging.Error(serviceName, err.Error(), "Read response body error", string(op), "", "", 0)
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Failed to read response body")
writeTransactionResult(w, http.StatusInternalServerError, theResponse)
return
}
if err := trResult.ParseTransactionResult(body); err != nil {
logging.Error(serviceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
}
// Compose JSON from responseEntries
result := make(map[string]string)
for _, e := range trResult.Entries {
switch e.Key {
case payment.ReceiptData, payment.ReceiptDataMerchant:
// ignore these
case payment.ReceiptDataCardholder:
cardholderReceipt = e.Value
case payment.TransactionResult:
theResponse.Status.Message = e.Value
theResponse.Status.Code = http.StatusOK
result[e.Key] = e.Value
default:
result[e.Key] = e.Value
}
}
if err := printer.PrintCardholderReceipt(cardholderReceipt); err != nil {
log.Errorf("PrintCardholderReceipt error: %v", err)
}
theResponse.Data = payment.BuildPreauthRedirectURL(result)
writeTransactionResult(w, http.StatusOK, theResponse)
}
func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
const op = logging.Op("takePayment")
var (
theResponse cmstypes.ResponseRec
cardholderReceipt string
theRequest cmstypes.TransactionRec
trResult payment.TransactionResultXML
)
theResponse.Status.Code = http.StatusInternalServerError
theResponse.Status.Message = "500 Internal server error"
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Content-Type", "application/json")
if !app.isPayment {
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Payment processing is disabled")
writeTransactionResult(w, http.StatusServiceUnavailable, theResponse)
return
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
log.Println("takePayment called")
if r.Method != http.MethodPost {
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Method not allowed; use POST")
writeTransactionResult(w, http.StatusMethodNotAllowed, theResponse)
return
}
defer r.Body.Close()
if ct := r.Header.Get("Content-Type"); ct != "text/xml" {
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Content-Type must be text/xml")
writeTransactionResult(w, http.StatusUnsupportedMediaType, theResponse)
return
}
body, _ := io.ReadAll(r.Body)
err := xml.Unmarshal(body, &theRequest)
if err != nil {
logging.Error(serviceName, err.Error(), "ReadXML", string(op), "", "", 0)
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Invalid XML payload")
writeTransactionResult(w, http.StatusBadRequest, theResponse)
return
}
log.Printf("Transaction payload: Amount=%s, Type=%s", theRequest.AmountMinorUnits, theRequest.TransactionType)
client := &http.Client{Timeout: 300 * time.Second}
response, err := client.Post(takePaymentUrl, "text/xml", bytes.NewBuffer(body))
if err != nil {
logging.Error(serviceName, err.Error(), "Payment processing error", string(op), "", "", 0)
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "No response from payment processor")
writeTransactionResult(w, http.StatusBadGateway, theResponse)
return
}
defer response.Body.Close()
body, err = io.ReadAll(response.Body)
if err != nil {
logging.Error(serviceName, err.Error(), "Read response body error", string(op), "", "", 0)
theResponse.Data = payment.BuildFailureURL(payment.ResultError, "Failed to read response body")
writeTransactionResult(w, http.StatusInternalServerError, theResponse)
return
}
if err := trResult.ParseTransactionResult(body); err != nil {
logging.Error(serviceName, err.Error(), "Parse transaction result error", string(op), "", "", 0)
}
// Compose JSON from responseEntries
result := make(map[string]string)
for _, e := range trResult.Entries {
switch e.Key {
case payment.ReceiptData, payment.ReceiptDataMerchant:
// ignore these
case payment.ReceiptDataCardholder:
cardholderReceipt = e.Value
case payment.TransactionResult:
theResponse.Status.Message = e.Value
theResponse.Status.Code = http.StatusOK
result[e.Key] = e.Value
default:
result[e.Key] = e.Value
}
}
if err := printer.PrintCardholderReceipt(cardholderReceipt); err != nil {
log.Errorf("PrintCardholderReceipt error: %v", err)
}
theResponse.Data = payment.BuildPaymentRedirectURL(result)
writeTransactionResult(w, http.StatusOK, theResponse)
}
func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
const op = logging.Op("issueDoorCard")
var (
doorReq lockserver.DoorCardRequest
theResponse cmstypes.StatusRec
)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
log.Println("issueDoorCard called")
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
return
}
defer r.Body.Close()
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json")
return
}
if err := json.NewDecoder(r.Body).Decode(&doorReq); err != nil {
logging.Error(serviceName, err.Error(), "ReadJSON", string(op), "", "", 0)
writeError(w, http.StatusBadRequest, "Invalid JSON payload: "+err.Error())
return
}
// parse times
checkIn, err := time.Parse(customLayout, doorReq.CheckinTime)
if err != nil {
logging.Error(serviceName, err.Error(), "Invalid checkinTime format", string(op), "", "", 0)
writeError(w, http.StatusBadRequest, "Invalid checkinTime format: "+err.Error())
return
}
checkOut, err := time.Parse(customLayout, doorReq.CheckoutTime)
if err != nil {
logging.Error(serviceName, err.Error(), "Invalid checkoutTime format", string(op), "", "", 0)
writeError(w, http.StatusBadRequest, "Invalid checkoutTime format: "+err.Error())
return
}
// dispenser sequence
if status, err := dispenser.DispenserSequence(app.dispPort); err != nil {
if status != "" {
logging.Error(serviceName, status, "Dispense error", string(op), "", "", 0)
writeError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
} else {
logging.Error(serviceName, err.Error(), "Dispense error", string(op), "", "", 0)
writeError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error()+"; check card stock")
}
return
} else {
log.Info(status)
}
// build lock server command
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
// lock server sequence
err = app.lockserver.LockSequence()
if err != nil {
logging.Error(serviceName, err.Error(), "Key encoding", string(op), "", "", 0)
writeError(w, http.StatusBadGateway, err.Error())
dispenser.CardOutOfMouth(app.dispPort)
return
}
// final dispenser steps
if status, err := dispenser.CardOutOfMouth(app.dispPort); err != nil {
logging.Error(serviceName, err.Error(), "Dispenser eject error", string(op), "", "", 0)
writeError(w, http.StatusServiceUnavailable, "Dispenser eject error: "+err.Error())
return
} else {
log.Info(status)
}
theResponse.Code = http.StatusOK
theResponse.Message = "Card issued successfully"
// success! return 200 and any data you like
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(theResponse)
}
func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
const op = logging.Op("printRoomTicket")
var roomDetails printer.RoomDetailsRec
// Allow CORS preflight if needed
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
log.Println("printRoomTicket called")
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
return
}
if ct := r.Header.Get("Content-Type"); !strings.Contains(ct, "xml") {
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/xml")
return
}
defer r.Body.Close()
if err := xml.NewDecoder(r.Body).Decode(&roomDetails); err != nil {
logging.Error(serviceName, err.Error(), "ReadXML", string(op), "", "", 0)
writeError(w, http.StatusBadRequest, "Invalid XML payload: "+err.Error())
return
}
data, err := printer.BuildRoomTicket(roomDetails)
if err != nil {
logging.Error(serviceName, err.Error(), "BuildRoomTicket", string(op), "", "", 0)
writeError(w, http.StatusInternalServerError, "BuildRoomTicket failed: "+err.Error())
return
}
// Send to the Windows Epson TM-T82II via the printer package
if err := printer.SendToPrinter(data); err != nil {
logging.Error(serviceName, err.Error(), "printRoomTicket", "printRoomTicket", "", "", 0)
writeError(w, http.StatusInternalServerError, "Print failed: "+err.Error())
return
}
// Success
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(cmstypes.StatusRec{
Code: http.StatusOK,
Message: "Print job sent successfully",
})
}
+41
View File
@@ -0,0 +1,41 @@
package handlers
import (
"encoding/json"
"fmt"
"net/http"
"os"
"gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/logging"
log "github.com/sirupsen/logrus"
)
const serviceName = "hardlink"
// writeError is a helper to send a JSON error and HTTP status in one go.
func writeError(w http.ResponseWriter, status int, msg string) {
theResponse := cmstypes.StatusRec{
Code: status,
Message: msg,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(theResponse)
}
func writeTransactionResult(w http.ResponseWriter, status int, theResponse cmstypes.ResponseRec) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(theResponse); err != nil {
logging.Error(serviceName, err.Error(), "JSON encode error", "startTransaction", "", "", 0)
}
}
func FatalError(err error) {
fmt.Println(err.Error())
log.Errorf(err.Error())
fmt.Println(". Press Enter to exit...")
fmt.Scanln()
os.Exit(1)
}
+10 -3
View File
@@ -10,17 +10,24 @@ 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
} }
// Checks heart beat of the Assa Abloy lock server and perform key encoding // Checks heart beat of the Assa Abloy lock server and perform key encoding
func (lock *AssaLockServer) LockSequence(conn net.Conn) error { func (lock *AssaLockServer) LockSequence() error {
const funcName = "AssaLockServer.LockSequence" const funcName = "AssaLockServer.LockSequence"
conn, err := InitializeServerConnection(LockServerURL)
if err != nil {
return err
}
defer conn.Close()
resp, err := sendHeartbeatToServer(conn) resp, err := sendHeartbeatToServer(conn)
if err != nil { if err != nil {
return fmt.Errorf("[%s] heartbeat failed: %v", funcName, err) return fmt.Errorf("[%s] heartbeat failed: %v", funcName, err)
+35 -11
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() 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
} }
+10 -3
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)
} }
@@ -53,8 +53,15 @@ func (lock *OmniLockServer) BuildCommand(lockId string, checkIn, checkOut time.T
} }
// Starts link to the Omnitec lock server and perform key encoding // Starts link to the Omnitec lock server and perform key encoding
func (lock *OmniLockServer) LockSequence(conn net.Conn) error { func (lock *OmniLockServer) LockSequence() error {
const funcName = "OmniLockServer.LockSequence" const funcName = "OmniLockServer.LockSequence"
conn, err := InitializeServerConnection(LockServerURL)
if err != nil {
return err
}
defer conn.Close()
// Start the link with the lock server // Start the link with the lock server
regs, err := lock.linkStart(conn) regs, err := lock.linkStart(conn)
if err != nil { if err != nil {
+226
View File
@@ -0,0 +1,226 @@
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",
t.Hour(), 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
}
// readFrame consumes a full frame starting with firstByte (expected STX).
// It reads up to ETX and then attempts to read a trailing LRC (or CR). timeout controls read deadlines.
func (lock *SaltoLockServer) readFrame(conn net.Conn, reader *bufio.Reader, firstByte byte, timeout time.Duration) ([]byte, error) {
frame := []byte{firstByte}
for {
conn.SetReadDeadline(time.Now().Add(timeout))
b, e := reader.ReadByte()
if e != nil {
return frame, fmt.Errorf("error reading frame body: %w", e)
}
frame = append(frame, b)
if b == ETX {
break
}
}
// read trailing LRC (or CR) if present (non-blocking w/ timeout)
conn.SetReadDeadline(time.Now().Add(timeout))
if lrc, e := reader.ReadByte(); e == nil {
frame = append(frame, lrc)
} else {
// Not fatal: some devices might omit LRC/CR — just log
log.Warnf("readFrame: no trailing LRC/CR: %v", e)
}
return frame, nil
}
// waitForAck waits for ACK or NAK. If STX frames are encountered they are drained
// using readFrame. drainedCount (if non-nil) accumulates the number of drained frames.
func (lock *SaltoLockServer) waitForAck(conn net.Conn, reader *bufio.Reader, timeout time.Duration, drainedCount *int) error {
deadline := time.Now().Add(timeout)
for {
conn.SetReadDeadline(time.Now().Add(time.Until(deadline)))
b, e := reader.ReadByte()
if e != nil {
return fmt.Errorf("error waiting for ACK/NAK: %w", e)
}
switch b {
case ACK:
return nil
case NAK:
return fmt.Errorf("received NAK")
case STX:
// stale or queued full response: consume it and continue waiting
frame, fe := lock.readFrame(conn, reader, b, timeout)
if fe != nil {
// if we can't consume frame, consider it an error
return fmt.Errorf("failed to consume queued STX frame: %w", fe)
}
if drainedCount != nil {
*drainedCount++
log.Infof("Drained queued frame #%d (while waiting for ACK): %q", *drainedCount, string(frame))
} else {
log.Infof("Drained queued frame (while waiting for ACK): %q", string(frame))
}
// loop to keep waiting for ACK
default:
// Unexpected byte while waiting for ACK. Log and continue reading.
log.Warnf("waitForAck: unexpected byte 0x%X while waiting for ACK; ignoring", b)
// keep looping until timeout or ACK/NAK
}
}
}
// LockSequence performs the full ENQ/ACK handshake and command exchange
func (lock *SaltoLockServer) LockSequence() error {
const timeout = 20 * time.Second
var (
resp []byte
drained = 0 // count of stale frames consumed across waits
)
conn, err := InitializeServerConnection(LockServerURL)
if err != nil {
return err
}
defer conn.Close()
reader := bufio.NewReader(conn)
// 1. Send ENQ
log.Infof("Sending ENQ")
if _, e := conn.Write([]byte{ENQ}); e != nil {
return fmt.Errorf("failed to send ENQ: %w", e)
}
// 2. Expect ACK (but drain any queued STX frames first)
if e := lock.waitForAck(conn, reader, timeout, &drained); e != nil {
return fmt.Errorf("error awaiting ACK to ENQ: %w", e)
}
// 3. Send command frame
log.Infof("Sending encoding command: %q", string(lock.command))
if _, e := conn.Write(lock.command); e != nil {
return fmt.Errorf("failed to send command frame: %w", e)
}
// 4. Expect ACK to command (again drain any queued frames that might precede it)
if e := lock.waitForAck(conn, reader, timeout, &drained); e != nil {
return fmt.Errorf("error awaiting ACK to command: %w", e)
}
// 5. Now read the *next* STX frame which should be the response to our command.
for {
conn.SetReadDeadline(time.Now().Add(40 * time.Second))
b, e := reader.ReadByte()
if e != nil {
return fmt.Errorf("error reading response start: %w", e)
}
if b != STX {
// If anything else arrives, it might be another control byte or noise;
// log and keep consuming until we find STX.
log.Warnf("expected STX to start response but got 0x%X; ignoring", b)
continue
}
// consume full response frame
frame, fe := lock.readFrame(conn, reader, b, timeout)
if fe != nil {
return fmt.Errorf("error reading response frame: %w", fe)
}
resp = append(resp, frame...)
break
}
// parse the command code within response frame
if len(resp) >= 4 {
// The command bytes are usually at indices 2 and 3 if separator is at index 1
sepIndex := 1
b1 := resp[sepIndex+1]
b2 := resp[sepIndex+2]
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): %q", string(resp))
return fmt.Errorf("lock response indicates room does not exist: %q", string(resp))
default:
log.Warnf("LockSequence: unexpected command response %q", string(resp))
return fmt.Errorf("error encoding keycard, unexpected response: %q", string(resp))
}
} else {
log.Warnf("LockSequence: response too short: %q", string(resp))
return fmt.Errorf("response too short")
}
log.Infof("LockSequence: received response: %q", string(resp))
return nil
}
+70
View File
@@ -0,0 +1,70 @@
package lockserver
import (
"encoding/json"
"fmt"
"io/ioutil"
"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() error {
log.Infof("Sending command: %q", lock.command)
client := &http.Client{Timeout: 30 * 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
}
+136 -404
View File
@@ -1,12 +1,8 @@
package main package main
import ( import (
"database/sql"
"encoding/json"
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"io"
"net"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
@@ -21,19 +17,14 @@ import (
yaml "gopkg.in/yaml.v3" yaml "gopkg.in/yaml.v3"
"gitea.futuresens.co.uk/futuresens/hardlink/dispenser" "gitea.futuresens.co.uk/futuresens/hardlink/dispenser"
"gitea.futuresens.co.uk/futuresens/hardlink/handlers"
"gitea.futuresens.co.uk/futuresens/hardlink/lockserver" "gitea.futuresens.co.uk/futuresens/hardlink/lockserver"
"gitea.futuresens.co.uk/futuresens/hardlink/payment"
"gitea.futuresens.co.uk/futuresens/hardlink/printer" "gitea.futuresens.co.uk/futuresens/hardlink/printer"
"gitea.futuresens.co.uk/futuresens/cmstypes"
"gitea.futuresens.co.uk/futuresens/logging"
) )
const ( const (
buildVersion = "1.0.0" buildVersion = "1.0.26"
serviceName = "hardlink" serviceName = "hardlink"
customLayout = "2006-01-02 15:04:05 -0700"
transactionUrl = "http://127.0.0.1:18181/start-transaction/"
) )
// configRec holds values from config.yml. // configRec holds values from config.yml.
@@ -42,47 +33,23 @@ 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 TestMode bool `yaml:"testMode"`
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.
type App struct {
dispPort *serial.Port
lockConn net.Conn
lockserver lockserver.LockServer
db *sql.DB
}
func newApp(dispPort *serial.Port, lockConn net.Conn, config configRec, db *sql.DB) *App {
return &App{
dispPort: dispPort,
lockConn: lockConn,
lockserver: lockserver.NewLockServer(config.LockType, config.EncoderAddress, fatalError),
db: db,
}
} }
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
lockserver.Cert = config.Cert
lockserver.LockServerURL = config.LockserverUrl
dispHandle := &serial.Port{}
// Setup logging and get file handle // Setup logging and get file handle
logFile, err := setupLogging(config.LogDir) logFile, err := setupLogging(config.LogDir)
@@ -92,45 +59,145 @@ func main() {
defer logFile.Close() defer logFile.Close()
// Initialize dispenser // Initialize dispenser
dispenser.SerialPort = config.DispenserPort if !config.TestMode {
dispenser.Address = []byte(config.DispenserAdrr) dispenser.SerialPort = config.DispenserPort
dispHandle, err := dispenser.InitializeDispenser() dispenser.Address = []byte(config.DispenserAdrr)
if err != nil { dispHandle, err = dispenser.InitializeDispenser()
fatalError(err) if err != nil {
} handlers.FatalError(err)
defer dispHandle.Close() }
defer dispHandle.Close()
status, err := dispenser.CheckDispenserStatus(dispHandle) status, err := dispenser.CheckDispenserStatus(dispHandle)
if err != nil { if err != nil {
if len(status) == 0 { if len(status) == 0 {
err = fmt.Errorf("%s; wrong dispenser address: %s", err, config.DispenserAdrr) err = fmt.Errorf("%s; wrong dispenser address: %s", err, config.DispenserAdrr)
fatalError(err) handlers.FatalError(err)
} else { } else {
fmt.Println(status) fmt.Println(status)
fmt.Println(err.Error())
}
}
log.Infof("Dispenser initialized on port %s, %s", config.DispenserPort, status)
}
// Test lock-server connection
switch strings.ToLower(config.LockType) {
case lockserver.TLJ:
default:
lockConn, err := lockserver.InitializeServerConnection(config.LockserverUrl)
if err != nil {
fmt.Println(err.Error()) fmt.Println(err.Error())
log.Errorf(err.Error())
} else {
fmt.Printf("Connected to the lock server successfuly at %s\n", config.LockserverUrl)
log.Infof("Connected to the lock server successfuly at %s", config.LockserverUrl)
lockConn.Close()
} }
} }
log.Infof("Dispenser initialized on port %s, %s", config.DispenserPort, status)
// Initialize lock-server connection once if config.IsPayment {
lockConn, err := lockserver.InitializeServerConnection(config.LockserverUrl) fmt.Println("Payment processing is enabled")
if err != nil { log.Info("Payment processing is enabled")
fatalError(err) startChipDnaClient()
} else {
fmt.Println("Payment processing is disabled")
log.Info("Payment processing is disabled")
} }
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) // Create App and wire routes
if err != nil { app := handlers.NewApp(dispHandle, config.LockType, config.EncoderAddress, config.IsPayment)
fatalError(fmt.Errorf("DB init failed: %v", err))
mux := http.NewServeMux()
app.RegisterRoutes(mux)
addr := fmt.Sprintf(":%d", config.Port)
log.Infof("Starting HTTP server on http://localhost%s", addr)
fmt.Printf("Starting HTTP server on http://localhost%s", addr)
if err := http.ListenAndServe(addr, mux); err != nil {
handlers.FatalError(err)
} }
defer db.Close() }
// setupLogging ensures log directory, opens log file, and configures logrus.
// Returns the *os.File so caller can defer its Close().
func setupLogging(logDir string) (*os.File, error) {
fileName := logDir + serviceName + ".log"
f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return nil, fmt.Errorf("open log file: %w", err)
}
log.SetOutput(f)
log.SetFormatter(&log.JSONFormatter{
TimestampFormat: time.RFC3339,
})
log.SetLevel(log.InfoLevel)
log.WithFields(log.Fields{
"buildVersion": buildVersion,
}).Info("Logging initialized")
return f, nil
}
// readConfig reads config.yml and applies defaults.
func readConfig() configRec {
var cfg configRec
const configName = "config.yml"
defaultPort := 9091
sep := string(os.PathSeparator)
data, err := os.ReadFile(configName)
if err != nil {
log.Warnf("ReadConfig %s: %v", configName, err)
} else if err := yaml.Unmarshal(data, &cfg); err != nil {
log.Warnf("Unmarshal config: %v", err)
}
if cfg.Port == 0 {
cfg.Port = defaultPort
}
if cfg.LockType == "" {
err = fmt.Errorf("LockType is required in %s", configName)
handlers.FatalError(err)
}
cfg.LockType = strings.ToLower(cfg.LockType)
if cfg.LogDir == "" {
cfg.LogDir = "./logs" + sep
} else if !strings.HasSuffix(cfg.LogDir, sep) {
cfg.LogDir += sep
}
return cfg
}
func readTicketLayout() printer.LayoutOptions {
const layoutName = "TicketLayout.xml"
var layout printer.LayoutOptions
// 1) Read the file
data, err := os.ReadFile(layoutName)
if err != nil {
handlers.FatalError(fmt.Errorf("failed to read %s: %v", layoutName, err))
}
// 2) Unmarshal into your struct
if err := xml.Unmarshal(data, &layout); err != nil {
handlers.FatalError(fmt.Errorf("failed to parse %s: %v", layoutName, err))
}
return layout
}
func startChipDnaClient() {
startClient := func() (*exec.Cmd, error) { startClient := func() (*exec.Cmd, error) {
cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe") cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe")
err := cmd.Start() err := cmd.Start()
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to start ChipDnaClient: %v", err) return nil, fmt.Errorf("failed to start ChipDnaClient: %v", err)
} }
log.Infof("ChipDnaClient started with PID %d", cmd.Process.Pid) log.Infof("ChipDnaClient started with PID %d", cmd.Process.Pid)
return cmd, nil return cmd, nil
@@ -138,7 +205,7 @@ func main() {
cmd, err := startClient() cmd, err := startClient()
if err != nil { if err != nil {
fatalError(err) handlers.FatalError(err)
} }
// Restart loop // Restart loop
@@ -180,339 +247,4 @@ func main() {
} }
os.Exit(0) os.Exit(0)
}() }()
// Create App and wire routes
app := newApp(dispHandle, lockConn, config, db)
mux := http.NewServeMux()
setUpRoutes(app, mux)
addr := fmt.Sprintf(":%d", config.Port)
log.Infof("Starting HTTP server on http://localhost%s", addr)
fmt.Printf("Starting HTTP server on http://localhost%s", addr)
if err := http.ListenAndServe(addr, mux); err != nil {
fatalError(err)
}
}
func setUpRoutes(app *App, mux *http.ServeMux) {
mux.HandleFunc("/issuedoorcard", app.issueDoorCard)
mux.HandleFunc("/printroomticket", app.printRoomTicket)
mux.HandleFunc("/starttransaction", app.startTransaction)
}
func fatalError(err error) {
fmt.Println(err.Error())
log.Errorf(err.Error())
fmt.Println(". Press Enter to exit...")
fmt.Scanln()
os.Exit(1)
}
// setupLogging ensures log directory, opens log file, and configures logrus.
// Returns the *os.File so caller can defer its Close().
func setupLogging(logDir string) (*os.File, error) {
fileName := logDir + serviceName + ".log"
f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return nil, fmt.Errorf("open log file: %w", err)
}
log.SetOutput(f)
log.SetFormatter(&log.JSONFormatter{
TimestampFormat: time.RFC3339,
})
log.SetLevel(log.InfoLevel)
log.WithFields(log.Fields{
"buildVersion": buildVersion,
}).Info("Logging initialized")
return f, nil
}
// writeError is a helper to send a JSON error and HTTP status in one go.
func writeError(w http.ResponseWriter, status int, msg string) {
theResponse := cmstypes.StatusRec{
Code: status,
Message: msg,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(theResponse)
}
func (app *App) startTransaction(w http.ResponseWriter, r *http.Request) {
const op = logging.Op("startTransaction")
var (
theResponse cmstypes.ResponseRec
cardholderReceipt string
)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
log.Println("startTransaction called")
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
return
}
defer r.Body.Close()
if ct := r.Header.Get("Content-Type"); ct != "text/xml" {
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be text/xml")
return
}
client := &http.Client{Timeout: 90 * time.Second}
response, err := client.Post(transactionUrl, "text/xml", r.Body)
if err != nil {
logging.Error(serviceName, err.Error(), "Payment processing error", string(op), "", "", 0)
writeError(w, http.StatusInternalServerError, "Payment processing failed: "+err.Error())
return
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
logging.Error(serviceName, err.Error(), "Read response body error", string(op), "", "", 0)
writeError(w, http.StatusInternalServerError, "Failed to read response body: "+err.Error())
return
}
responseEntries, _ := payment.ParseTransactionResult(body)
// Compose JSON from responseEntries
result := make(map[string]string)
for _, e := range responseEntries {
switch e.Key {
case "RECEIPT_DATA", "RECEIPT_DATA_MERCHANT":
case "RECEIPT_DATA_CARDHOLDER":
cardholderReceipt = e.Value
case "TRANSACTION_RESULT":
theResponse.Status.Message = e.Value
theResponse.Status.Code = http.StatusOK
result[e.Key] = e.Value
default:
result[e.Key] = e.Value
}
}
if err := printer.PrintCardholderReceipt(cardholderReceipt); err != nil {
log.Errorf("PrintCardholderReceipt error: %v", err)
}
// Insert into DB
if err := payment.InsertTransactionRecord(r.Context(), app.db, result); err != nil {
log.Errorf("DB insert error: %v", err)
}
theResponse.Data = payment.BuildRedirectURL(result)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(theResponse); err != nil {
logging.Error(serviceName, err.Error(), "JSON encode error", string(op), "", "", 0)
}
}
func (app *App) issueDoorCard(w http.ResponseWriter, r *http.Request) {
const op = logging.Op("issueDoorCard")
var (
doorReq DoorCardRequest
theResponse cmstypes.StatusRec
)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
log.Println("issueDoorCard called")
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
return
}
defer r.Body.Close()
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json")
return
}
if err := json.NewDecoder(r.Body).Decode(&doorReq); err != nil {
logging.Error(serviceName, err.Error(), "ReadJSON", string(op), "", "", 0)
writeError(w, http.StatusBadRequest, "Invalid JSON payload: "+err.Error())
return
}
// parse times
checkIn, err := time.Parse(customLayout, doorReq.CheckinTime)
if err != nil {
logging.Error(serviceName, err.Error(), "Invalid checkinTime format", string(op), "", "", 0)
writeError(w, http.StatusBadRequest, "Invalid checkinTime format: "+err.Error())
return
}
checkOut, err := time.Parse(customLayout, doorReq.CheckoutTime)
if err != nil {
logging.Error(serviceName, err.Error(), "Invalid checkoutTime format", string(op), "", "", 0)
writeError(w, http.StatusBadRequest, "Invalid checkoutTime format: "+err.Error())
return
}
// dispenser sequence
if status, err := dispenser.DispenserSequence(app.dispPort); err != nil {
if status != "" {
logging.Error(serviceName, status, "Dispense error", string(op), "", "", 0)
writeError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
} else {
logging.Error(serviceName, err.Error(), "Dispense error", string(op), "", "", 0)
writeError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error()+"; check card stock")
}
return
} else {
log.Info(status)
}
// build lock server command
app.lockserver.BuildCommand(doorReq.RoomField, checkIn, checkOut)
// lock server sequence
err = app.lockserver.LockSequence(app.lockConn)
if err != nil {
logging.Error(serviceName, err.Error(), "Key encoding", string(op), "", "", 0)
writeError(w, http.StatusBadGateway, err.Error())
dispenser.CardOutOfMouth(app.dispPort)
return
}
// final dispenser steps
if status, err := dispenser.CardOutOfMouth(app.dispPort); err != nil {
logging.Error(serviceName, err.Error(), "Dispenser eject error", string(op), "", "", 0)
writeError(w, http.StatusServiceUnavailable, "Dispenser eject error: "+err.Error())
return
} else {
log.Info(status)
}
theResponse.Code = http.StatusOK
theResponse.Message = "Card issued successfully"
// success! return 200 and any data you like
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(theResponse)
}
func (app *App) printRoomTicket(w http.ResponseWriter, r *http.Request) {
const op = logging.Op("printRoomTicket")
var roomDetails printer.RoomDetailsRec
// Allow CORS preflight if needed
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
log.Println("printRoomTicket called")
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
return
}
if ct := r.Header.Get("Content-Type"); !strings.Contains(ct, "xml") {
writeError(w, http.StatusUnsupportedMediaType, "Content-Type must be application/xml")
return
}
defer r.Body.Close()
if err := xml.NewDecoder(r.Body).Decode(&roomDetails); err != nil {
logging.Error(serviceName, err.Error(), "ReadXML", string(op), "", "", 0)
writeError(w, http.StatusBadRequest, "Invalid XML payload: "+err.Error())
return
}
data, err := printer.BuildRoomTicket(roomDetails)
if err != nil {
logging.Error(serviceName, err.Error(), "BuildRoomTicket", string(op), "", "", 0)
writeError(w, http.StatusInternalServerError, "BuildRoomTicket failed: "+err.Error())
return
}
// Send to the Windows Epson TM-T82II via the printer package
if err := printer.SendToPrinter(data); err != nil {
logging.Error(serviceName, err.Error(), "printRoomTicket", "printRoomTicket", "", "", 0)
writeError(w, http.StatusInternalServerError, "Print failed: "+err.Error())
return
}
// Success
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(cmstypes.StatusRec{
Code: http.StatusOK,
Message: "Print job sent successfully",
})
}
// readConfig reads config.yml and applies defaults.
func readConfig() configRec {
var cfg configRec
const configName = "config.yml"
defaultPort := 9091
sep := string(os.PathSeparator)
data, err := os.ReadFile(configName)
if err != nil {
log.Warnf("ReadConfig %s: %v", configName, err)
} else if err := yaml.Unmarshal(data, &cfg); err != nil {
log.Warnf("Unmarshal config: %v", err)
}
if cfg.Port == 0 {
cfg.Port = defaultPort
}
if cfg.LockType == "" {
err = fmt.Errorf("LockType is required in %s", configName)
fatalError(err)
}
cfg.LockType = strings.ToLower(cfg.LockType)
if cfg.LogDir == "" {
cfg.LogDir = "./logs" + sep
} else if !strings.HasSuffix(cfg.LogDir, sep) {
cfg.LogDir += sep
}
return cfg
}
func readTicketLayout() printer.LayoutOptions {
const layoutName = "TicketLayout.xml"
var layout printer.LayoutOptions
// 1) Read the file
data, err := os.ReadFile(layoutName)
if err != nil {
fatalError(fmt.Errorf("failed to read %s: %v", layoutName, err))
}
// 2) Unmarshal into your struct
if err := xml.Unmarshal(data, &layout); err != nil {
fatalError(fmt.Errorf("failed to parse %s: %v", layoutName, err))
}
return layout
} }
+115 -59
View File
@@ -3,6 +3,7 @@ package payment
import ( import (
"context" "context"
"database/sql" "database/sql"
"encoding/hex"
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"net/url" "net/url"
@@ -15,6 +16,11 @@ import (
) )
const ( const (
// Transaction types
SaleTransactionType = "sale"
AccountVerificationType = "account verification"
// Transaction results
ResultApproved = "approved" ResultApproved = "approved"
ResultDeclined = "declined" ResultDeclined = "declined"
ResultCancelled = "cancelled" ResultCancelled = "cancelled"
@@ -22,6 +28,26 @@ const (
ResultError = "error" ResultError = "error"
CheckinSuccessfulEndpoint = "/successful" // Endpoint to send guest to after successful payment CheckinSuccessfulEndpoint = "/successful" // Endpoint to send guest to after successful payment
CheckinUnsuccessfulEndpoint = "/unsuccessful" CheckinUnsuccessfulEndpoint = "/unsuccessful"
// Response map keys
CardReference = "CARD_REFERENCE"
CardHash = "CARD_HASH"
Errors = "ERRORS"
ReceiptData = "RECEIPT_DATA"
ReceiptDataMerchant = "RECEIPT_DATA_MERCHANT"
ReceiptDataCardholder = "RECEIPT_DATA_CARDHOLDER"
Reference = "REFERENCE"
PAN_MASKED = "PAN_MASKED"
EXPIRY_DATE = "EXPIRY_DATE"
TransactionResult = "TRANSACTION_RESULT"
TransactionType = "TRANSACTION_TYPE"
ConfirmResult = "CONFIRM_RESULT"
ConfirmErrors = "CONFIRM_ERRORS"
// Log field keys
LogFieldError = "error"
LogFieldDescription = "description"
LogResult = "transactionResult"
) )
// XML parsing structs // XML parsing structs
@@ -41,15 +67,22 @@ type (
Key string `xml:"Key"` Key string `xml:"Key"`
Value string `xml:"Value"` Value string `xml:"Value"`
} }
TransactionConfirmation struct {
XMLName xml.Name `xml:"TransactionConfirmation"`
Result string `xml:"Result"`
Errors string `xml:"Errors"`
ErrorDescription string `xml:"ErrorDescription"`
ReceiptDataCardholder string `xml:"ReceiptDataCardholder"`
}
) )
// ParseTransactionResult parses the XML into entries. // ParseTransactionResult parses the XML into entries.
func ParseTransactionResult(data []byte) ([]EntryXML, error) { func (tr *TransactionResultXML) ParseTransactionResult(data []byte) error {
var tr TransactionResultXML
if err := xml.Unmarshal(data, &tr); err != nil { if err := xml.Unmarshal(data, &tr); err != nil {
return nil, fmt.Errorf("XML unmarshal: %w", err) return fmt.Errorf("XML unmarshal: %w", err)
} }
return tr.Entries, nil return nil
} }
// initMSSQL opens and pings the SQL Server instance localhost\SQLEXPRESS // initMSSQL opens and pings the SQL Server instance localhost\SQLEXPRESS
@@ -216,65 +249,88 @@ func nullableFloatArg(nf sql.NullFloat64) interface{} {
return nil return nil
} }
func BuildRedirectURL(result map[string]string) string { // BuildRedirectURL builds the redirect URL to send the guest to after payment.
// 1) normalize the result code func BuildPaymentRedirectURL(result map[string]string) string {
res := strings.ToLower(result["TRANSACTION_RESULT"]) res := result[TransactionResult]
// 2) pick base path and optional error params // Transaction approved?
var basePath string if strings.EqualFold(res, ResultApproved) {
var msgType, description string // Transaction confirmed?
if strings.EqualFold(result[ConfirmResult], ResultApproved) {
log.WithField(LogResult, result[ConfirmResult]).
Info("Transaction approved and confirmed")
switch res { return buildSuccessURL(result)
case ResultApproved: }
basePath = CheckinSuccessfulEndpoint
case ResultDeclined: // Not confirmed
basePath = CheckinUnsuccessfulEndpoint log.WithFields(log.Fields{LogFieldError: result[ConfirmResult], LogFieldDescription: result[ConfirmErrors]}).
msgType = "declined" Error("Transaction approved but not confirmed")
description = "payment declined"
case ResultCancelled: return BuildFailureURL(result[ConfirmResult], result[ConfirmErrors])
basePath = CheckinUnsuccessfulEndpoint
msgType = "cancelled"
description = "payment cancelled by customer"
case ResultPending:
// you could choose to treat pending as unsuccessful or special-case it
basePath = CheckinUnsuccessfulEndpoint
msgType = "pending"
description = "payment pending"
case ResultError:
basePath = CheckinUnsuccessfulEndpoint
msgType = "error"
description = result["ERROR"]
default:
basePath = CheckinUnsuccessfulEndpoint
msgType = "error"
description = "unknown transaction result"
} }
if msgType != "" { // Not approved
log.Warnf("Transaction %s: %s - %s", res, msgType, description) return BuildFailureURL(res, result[Errors])
} }
// 3) build query params func BuildPreauthRedirectURL(result map[string]string) string {
q := url.Values{} res := result[TransactionResult]
q.Set("TxnReference", result["REFERENCE"]) tType := result[TransactionType]
q.Set("CardHash", result["CARD_HASH"])
q.Set("CardReference", result["CARD_REFERENCE"]) // Transaction approved?
if strings.EqualFold(res, ResultApproved) {
// only append these when non-approved switch {
if msgType != "" { // Transaction type AccountVerification?
q.Set("MsgType", msgType) case strings.EqualFold(tType, AccountVerificationType):
q.Set("Description", description) log.WithField(LogResult, result[TransactionResult]).
} Info("Account verification approved")
// 4) assemble final URL return buildSuccessURL(result)
// note: url.URL automatically escapes values in RawQuery
u := url.URL{ // Transaction type Sale?
Path: basePath, case strings.EqualFold(tType, SaleTransactionType):
RawQuery: q.Encode(), // Transaction confirmed?
} log.WithField(LogResult, result[ConfirmResult]).
return u.String() Info("Amount preauthorized successfully")
return buildSuccessURL(result)
}
}
// Not approved
return BuildFailureURL(res, result[Errors])
}
func buildSuccessURL(result map[string]string) string {
q := url.Values{}
q.Set("CardNumber", hex.EncodeToString([]byte(result[PAN_MASKED])))
q.Set("ExpiryDate", hex.EncodeToString([]byte(result[EXPIRY_DATE])))
q.Set("TxnReference", result[Reference])
q.Set("CardHash", hex.EncodeToString([]byte(result[CardHash])))
q.Set("CardReference", hex.EncodeToString([]byte(result[CardReference])))
return (&url.URL{
Path: CheckinSuccessfulEndpoint,
RawQuery: q.Encode(),
}).String()
}
func BuildFailureURL(msgType, description string) string {
q := url.Values{}
if msgType != "" {
description = fmt.Sprintf("Transaction %s", strings.ToLower(msgType))
}
if description != "" {
msgType = ResultError
}
log.WithFields(log.Fields{LogFieldError: msgType, LogFieldDescription: description}).
Error("Transaction failed")
q.Set("MsgType", msgType)
q.Set("Description", description)
return (&url.URL{
Path: CheckinUnsuccessfulEndpoint,
RawQuery: q.Encode(),
}).String()
} }
+69 -3
View File
@@ -2,14 +2,80 @@
builtVersion is a const in main.go builtVersion is a const in main.go
#### 1.0.0 - 30 Jun 2024 #### 1.0.26 - 10 December 2025
added route for taking preauthorization payment
#### 1.0.25 - 08 December 2025
return masked card number and expiry date in the payment success URL
#### 1.0.24 - 13 November 2025
improved logging for creditcall payment processing
#### 1.0.23 - 13 November 2025
moved handlers from main.go to handlers/handlers.go
#### 1.0.22 - 13 November 2025
added test mode into config file to allow testing without connecting to the dispenser
#### 1.0.21 - 20 October 2025
increased timeout for Salto lock server connection to 40 seconds
#### 1.0.20 - 06 October 2025
removed minutes from the start and expiry time in Salto lock command
#### 1.0.19 - 10 September 2025
allowed to continue if the connection to the lock server fails at startup
#### 1.0.18 - 04 September 2025
increased timeout for TLJ lock server connection to 30 seconds
#### 1.0.17 - 30 August 2025
added functionality to commit transactions
#### 1.0.15 - 27 August 2025
fixed TCP/IP connection to the lock server
#### 1.0.14 - 21 August 2025
fixed issue in creditcall payment processing where error description was not properly set
#### 1.0.13 - 21 August 2025
TCP/IP connection to the lock server is now established before encoding the keycard and closedafter the encoding is done.
#### 1.0.12 - 11 August 2025
added delay before checking dispenser status
#### 1.0.11 - 11 August 2025
updated Salto key encoding workflow
#### 1.0.10 - 08 August 2025
updated logging for TLJ locks
#### 1.0.9 - 08 August 2025
added TLJ lock server and implemented workflow for TLJ locks
#### 1.0.8 - 01 August 2025
improved error handling and logging in Salto
#### 1.0.7 - 25 July 2025
added check if the room exists
#### 1.0.6 - 25 July 2025
updated workflow for Salto locks
#### 1.0.5 - 24 July 2025
added encoding keycard copy for Salto locks
#### 1.0.4 - 22 July 2025
added salto lock server and implemented workflow for Salto
#### 1.0.0 - 30 June 2025
added creditcall payment method added creditcall payment method
`/starttransaction` - API payment endpoint to start a transaction `/starttransaction` - API payment endpoint to start a transaction
#### 0.9.1 - 22 May 2024 #### 0.9.1 - 22 May 2025
added lockserver interface and implemented workflow for Omnitec added lockserver interface and implemented workflow for Omnitec
#### 0.9.0 - 22 May 2024 #### 0.9.0 - 22 May 2025
The new API has two new endpoints: The new API has two new endpoints:
- `/issuedoorcard` - encoding the door card for the room. - `/issuedoorcard` - encoding the door card for the room.
- `/printroomticket` - printing the room ticket. - `/printroomticket` - printing the room ticket.