Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aeea755045 | ||
|
|
ebe50b17a9 | ||
|
|
4a255c06ed | ||
|
|
9f0a9c939f | ||
|
|
7f6262b470 | ||
|
|
895849376e | ||
|
|
43f1e8787f | ||
|
|
7941e2065e | ||
|
|
b59d77a373 | ||
|
|
a4885be458 | ||
|
|
89dfa28e6f | ||
|
|
bb526a248d | ||
|
|
f4f44da541 | ||
|
|
7993a2360d | ||
|
|
c15ceba78f | ||
|
|
04c664294d | ||
|
|
da5cafe031 | ||
|
|
efa415e631 | ||
|
|
f1dc0ccce4 | ||
|
|
1bceb55285 | ||
|
|
bb8cdb1d84 | ||
|
|
251afd6aeb | ||
|
|
e6ff292706 | ||
|
|
b4d16f9021 | ||
|
|
c8f6c57983 | ||
|
|
61b089fe55 | ||
|
|
8b0e7df582 | ||
|
|
25eab0dc75 | ||
|
|
fc91f2c0f2 | ||
|
|
5ce9fdcf0b | ||
|
|
b303721a92 | ||
|
|
dc91a9ae63 | ||
|
|
b303481b5f | ||
|
|
41cf71a253 | ||
|
|
5e99453eeb |
@@ -28,6 +28,7 @@ Checkin.code-workspace
|
||||
_obj
|
||||
_test
|
||||
.vscode/
|
||||
ChipDNAClient/
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// internal/bootstrap/db.go
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/db"
|
||||
)
|
||||
|
||||
func OpenDB(cfg *config.ConfigRec) (*sql.DB, error) {
|
||||
return db.InitMSSQL(
|
||||
cfg.Dbport,
|
||||
cfg.Dbuser,
|
||||
cfg.Dbpassword,
|
||||
cfg.Dbname,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/errorhandlers"
|
||||
log "github.com/sirupsen/logrus"
|
||||
yaml "gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// configRec holds values from config.yml.
|
||||
type ConfigRec struct {
|
||||
Port int `yaml:"port"`
|
||||
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"`
|
||||
Dbport int `yaml:"dbport"` // Port for the database connection
|
||||
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
|
||||
IsPayment bool `yaml:"isPayment"`
|
||||
TestMode bool `yaml:"testMode"`
|
||||
}
|
||||
|
||||
// ReadConfig reads config.yml and applies defaults.
|
||||
func ReadHardlinkConfig() 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)
|
||||
errorhandlers.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
|
||||
}
|
||||
|
||||
if cfg.Dbport <= 0 || cfg.Dbuser == "" || cfg.Dbname == "" || cfg.Dbpassword == "" {
|
||||
err = fmt.Errorf("Database config (dbport, dbuser, dbname, dbpassword) are required in %s", configName)
|
||||
log.Warnf(err.Error())
|
||||
}
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
func ReadPreauthReleaserConfig() ConfigRec {
|
||||
var cfg ConfigRec
|
||||
const configName = "config.yml"
|
||||
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.Dbport <= 0 || cfg.Dbuser == "" || cfg.Dbname == "" || cfg.Dbpassword == "" {
|
||||
err = fmt.Errorf("Database config (dbport, dbuser, dbname, dbpassword) are required in %s", configName)
|
||||
errorhandlers.FatalError(err)
|
||||
}
|
||||
|
||||
if cfg.LogDir == "" {
|
||||
cfg.LogDir = "./logs" + sep
|
||||
} else if !strings.HasSuffix(cfg.LogDir, sep) {
|
||||
cfg.LogDir += sep
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mssqldb "github.com/denisenkom/go-mssqldb" // for error inspection
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
)
|
||||
|
||||
// InitMSSQL opens and pings the SQL Server instance (keeps your original behaviour)
|
||||
func InitMSSQL(port int, user, password, database string) (*sql.DB, error) {
|
||||
if port <= 0 || user == "" || database == "" {
|
||||
return nil, errors.New("incomplete database configuration")
|
||||
}
|
||||
|
||||
dsn := fmt.Sprintf(
|
||||
"sqlserver://%s:%s@%s:%d?database=%s&encrypt=disable",
|
||||
user, password, "localhost", port, database,
|
||||
)
|
||||
|
||||
db, err := sql.Open("sqlserver", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := db.QueryRowContext(ctx, "SELECT 1").Scan(new(int)); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
log.Info("Database connection established")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func parseDateOnly(s string) (time.Time, error) {
|
||||
parsed, err := time.Parse(types.CustomLayout, s)
|
||||
if err == nil {
|
||||
// construct midnight in local timezone, then convert to UTC for storage consistency
|
||||
localMidnight := time.Date(parsed.Year(), parsed.Month(), parsed.Day(), 0, 0, 0, 0, time.Local)
|
||||
return localMidnight.UTC(), nil
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("parseDateOnly error: parsing %q: %w", s, err)
|
||||
}
|
||||
|
||||
// InsertPreauth stores a preauthorization record. It is idempotent: duplicate TxnReference is ignored.
|
||||
func InsertPreauth(ctx context.Context, db *sql.DB, m map[string]string, checkoutDate string) error {
|
||||
const funcName = "InsertPreauth"
|
||||
|
||||
totalMinorUnits := m[types.TotalAmount]
|
||||
txnReference := m[types.Reference]
|
||||
if txnReference == "" {
|
||||
return fmt.Errorf("%s: missing REFERENCE", funcName)
|
||||
}
|
||||
if totalMinorUnits == "" {
|
||||
return fmt.Errorf("%s: missing TotalAmount", funcName)
|
||||
}
|
||||
|
||||
// parse minor units, fallback to 0 on parse error but report it
|
||||
amountInt, err := strconv.ParseInt(totalMinorUnits, 10, 64)
|
||||
if err != nil {
|
||||
log.WithFields(log.Fields{
|
||||
"func": funcName,
|
||||
"value": totalMinorUnits,
|
||||
"error": err,
|
||||
}).Warnf("parsing TotalAmount, defaulting to 0")
|
||||
amountInt = 0
|
||||
}
|
||||
totalAmount := float64(amountInt) / 100.0
|
||||
|
||||
txnTime := time.Now().UTC()
|
||||
|
||||
// parse departure / checkout date and compute release date (48h after departure)
|
||||
checkOutDate, err := parseDateOnly(checkoutDate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("InsertPreauth: parsing checkoutDate %q: %w", checkoutDate, err)
|
||||
}
|
||||
releaseDate := checkOutDate.Add(48 * time.Hour)
|
||||
|
||||
const stmt = `
|
||||
INSERT INTO dbo.Preauthorizations
|
||||
(TxnReference, TotalMinorUnits, TotalAmount, TxnDateTime, DepartureDate, ReleaseDate)
|
||||
VALUES
|
||||
(@TxnReference, @TotalMinorUnits, @TotalAmount, @TxnDateTime, @DepartureDate, @ReleaseDate);
|
||||
`
|
||||
_, err = db.ExecContext(ctx, stmt,
|
||||
sql.Named("TxnReference", txnReference),
|
||||
sql.Named("TotalMinorUnits", totalMinorUnits),
|
||||
sql.Named("TotalAmount", totalAmount),
|
||||
sql.Named("TxnDateTime", txnTime),
|
||||
sql.Named("DepartureDate", checkOutDate),
|
||||
sql.Named("ReleaseDate", releaseDate),
|
||||
)
|
||||
if err != nil {
|
||||
// handle duplicate-key (unique constraint) gracefully: SQL Server error numbers 2601/2627
|
||||
var sqlErr mssqldb.Error
|
||||
if errors.As(err, &sqlErr) {
|
||||
if sqlErr.Number == 2627 || sqlErr.Number == 2601 {
|
||||
log.Infof("InsertPreauth: preauth %s already exists (duplicate key) - ignoring", txnReference)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("InsertPreauth exec: %w", err)
|
||||
}
|
||||
|
||||
log.Infof("Inserted preauth %s amount=%s minorUnits release=%s", txnReference, totalMinorUnits, releaseDate.Format(time.RFC3339))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetDuePreauths returns preauths with ReleaseDate <= now where Released = 0.
|
||||
// If limit > 0, the query uses TOP(limit) to bound results at DB level.
|
||||
func GetDuePreauths(ctx context.Context, db *sql.DB, now time.Time, limit int) ([]types.PreauthRec, error) {
|
||||
baseQuery := `
|
||||
SELECT Id, TxnReference, TotalMinorUnits, TotalAmount, TxnDateTime, DepartureDate, ReleaseDate, Released, ReleasedAt
|
||||
FROM dbo.Preauthorizations
|
||||
WHERE Released = 0 AND ReleaseDate <= @Now
|
||||
ORDER BY ReleaseDate ASC
|
||||
`
|
||||
query := baseQuery
|
||||
if limit > 0 {
|
||||
// embed TOP to keep DB from returning everything; limit is controlled by the caller.
|
||||
query = strings.Replace(baseQuery, "SELECT", fmt.Sprintf("SELECT TOP (%d)", limit), 1)
|
||||
}
|
||||
|
||||
rows, err := db.QueryContext(ctx, query, sql.Named("Now", now))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GetDuePreauths query: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []types.PreauthRec
|
||||
for rows.Next() {
|
||||
var r types.PreauthRec
|
||||
var departure sql.NullTime
|
||||
var releasedAt sql.NullTime
|
||||
// Note: adjust scanning targets if types.PreauthRec fields differ
|
||||
if err := rows.Scan(
|
||||
&r.Id,
|
||||
&r.TxnReference,
|
||||
&r.TotalMinorUnits,
|
||||
&r.TotalAmount,
|
||||
&r.TxnDateTime,
|
||||
&departure,
|
||||
&r.ReleaseDate,
|
||||
&r.Released,
|
||||
&releasedAt,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("GetDuePreauths scan: %w", err)
|
||||
}
|
||||
|
||||
if departure.Valid {
|
||||
r.DepartureDate = departure.Time
|
||||
} else {
|
||||
r.DepartureDate = time.Time{}
|
||||
}
|
||||
r.ReleasedAt = releasedAt
|
||||
|
||||
out = append(out, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("GetDuePreauths rows: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// MarkPreauthReleased sets Released=1 and stores the timestamp. Returns error if no rows updated.
|
||||
func MarkPreauthReleased(ctx context.Context, db *sql.DB, txnReference string, releasedAt time.Time) error {
|
||||
const stmt = `
|
||||
UPDATE dbo.Preauthorizations
|
||||
SET Released = 1, ReleasedAt = @ReleasedAt
|
||||
WHERE TxnReference = @TxnReference AND Released = 0;
|
||||
`
|
||||
res, err := db.ExecContext(ctx, stmt, sql.Named("ReleasedAt", releasedAt), sql.Named("TxnReference", txnReference))
|
||||
if err != nil {
|
||||
return fmt.Errorf("MarkPreauthReleased exec: %w", err)
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return fmt.Errorf("MarkPreauthReleased RowsAffected: %w", err)
|
||||
}
|
||||
if n == 0 {
|
||||
return fmt.Errorf("no rows updated for %s (maybe already released)", txnReference)
|
||||
}
|
||||
log.Infof("Marked preauth %s released at %s", txnReference, releasedAt.Format(time.RFC3339))
|
||||
return nil
|
||||
}
|
||||
|
||||
+141
-146
@@ -1,9 +1,8 @@
|
||||
package dispenser
|
||||
|
||||
import (
|
||||
// "encoding/hex"
|
||||
"fmt"
|
||||
// "log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -20,29 +19,25 @@ const (
|
||||
space = 0x00 // Space character
|
||||
baudRate = 9600 // Baud rate for serial communication
|
||||
delay = 500 * time.Millisecond // Delay for processing commands
|
||||
)
|
||||
|
||||
// type (
|
||||
// configRec struct {
|
||||
// SerialPort string `yaml:"port"`
|
||||
// Address string `yaml:"addr"`
|
||||
// }
|
||||
// )
|
||||
// cache freshness for "continuous status" reads (tune as you wish)
|
||||
defaultStatusTTL = 1500 * time.Millisecond
|
||||
)
|
||||
|
||||
var (
|
||||
SerialPort string
|
||||
Address []byte
|
||||
commandFC7 = []byte{ETX, 0x46, 0x43, 0x37} // "FC7" command dispense card at read card position
|
||||
commandFC0 = []byte{ETX, 0x46, 0x43, 0x30} // "FC0" command dispense card out of card mouth command
|
||||
|
||||
commandFC7 = []byte{ETX, 0x46, 0x43, 0x37} // "FC7"
|
||||
commandFC0 = []byte{ETX, 0x46, 0x43, 0x30} // "FC0"
|
||||
|
||||
statusPos0 = map[byte]string{
|
||||
0x38: "Keep",
|
||||
0x34: "Command cannot execute",
|
||||
0x32: "Preparing card fails",
|
||||
0x31: "Preparing card",
|
||||
0x30: "Normal", // Default if none of the above
|
||||
0x30: "Normal",
|
||||
}
|
||||
|
||||
statusPos1 = map[byte]string{
|
||||
0x38: "Dispensing card",
|
||||
0x34: "Capturing card",
|
||||
@@ -50,7 +45,6 @@ var (
|
||||
0x31: "Capture card error",
|
||||
0x30: "Normal",
|
||||
}
|
||||
|
||||
statusPos2 = map[byte]string{
|
||||
0x38: "No captured card",
|
||||
0x34: "Card overlapped",
|
||||
@@ -58,7 +52,6 @@ var (
|
||||
0x31: "Card pre-empty",
|
||||
0x30: "Normal",
|
||||
}
|
||||
|
||||
statusPos3 = map[byte]string{
|
||||
0x38: "Card empty",
|
||||
0x34: "Card ready position",
|
||||
@@ -69,48 +62,77 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
func checkStatus(statusResp []byte) (string, error) {
|
||||
if len(statusResp) > 3 {
|
||||
statusBytes := statusResp[7:11] // Extract the relevant bytes from the response
|
||||
// For each position, get the ASCII character, hex value, and mapped meaning.
|
||||
posStatus := []struct {
|
||||
pos int
|
||||
value byte
|
||||
mapper map[byte]string
|
||||
}{
|
||||
{pos: 1, value: statusBytes[0], mapper: statusPos0},
|
||||
{pos: 2, value: statusBytes[1], mapper: statusPos1},
|
||||
{pos: 3, value: statusBytes[2], mapper: statusPos2},
|
||||
{pos: 4, value: statusBytes[3], mapper: statusPos3},
|
||||
}
|
||||
// --------------------
|
||||
// Status helpers
|
||||
// --------------------
|
||||
|
||||
result := ""
|
||||
for _, p := range posStatus {
|
||||
statusMsg, exists := p.mapper[p.value]
|
||||
if !exists {
|
||||
statusMsg = "Unknown status"
|
||||
}
|
||||
if p.value != 0x30 {
|
||||
result += fmt.Sprintf("Status: %s; ", statusMsg)
|
||||
}
|
||||
if p.pos == 4 && p.value == 0x38 {
|
||||
return result, fmt.Errorf("Card well empty")
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
func logStatus(statusBytes []byte) {
|
||||
if len(statusBytes) < 4 {
|
||||
log.Infof("Dispenser status: <invalid len=%d>", len(statusBytes))
|
||||
return
|
||||
}
|
||||
|
||||
} else {
|
||||
if len(statusResp) == 3 && statusResp[0] == ACK && statusResp[1] == Address[0] && statusResp[2] == Address[1] {
|
||||
return "active;", nil
|
||||
} else if len(statusResp) > 0 && statusResp[0] == NAK {
|
||||
return "", fmt.Errorf("negative response from dispenser")
|
||||
} else {
|
||||
return "", fmt.Errorf("unexpected response status: % X", statusResp)
|
||||
posStatus := []struct {
|
||||
pos int
|
||||
value byte
|
||||
mapper map[byte]string
|
||||
}{
|
||||
{pos: 1, value: statusBytes[0], mapper: statusPos0},
|
||||
{pos: 2, value: statusBytes[1], mapper: statusPos1},
|
||||
{pos: 3, value: statusBytes[2], mapper: statusPos2},
|
||||
{pos: 4, value: statusBytes[3], mapper: statusPos3},
|
||||
}
|
||||
|
||||
var result strings.Builder
|
||||
for _, p := range posStatus {
|
||||
statusMsg, exists := p.mapper[p.value]
|
||||
if !exists {
|
||||
statusMsg = fmt.Sprintf("Unknown status 0x%X at position %d", p.value, p.pos)
|
||||
}
|
||||
if p.value != 0x30 {
|
||||
result.WriteString(statusMsg + "; ")
|
||||
}
|
||||
}
|
||||
log.Infof("Dispenser status: %s", result.String())
|
||||
}
|
||||
|
||||
// calculateBCC computes the Block Check Character (BCC) as the XOR of all bytes from STX to ETX.
|
||||
func isAtEncoderPosition(statusBytes []byte) bool {
|
||||
return len(statusBytes) >= 4 && statusBytes[3] == 0x33
|
||||
}
|
||||
|
||||
func stockTake(statusBytes []byte) string {
|
||||
if len(statusBytes) < 4 {
|
||||
return ""
|
||||
}
|
||||
status := ""
|
||||
if statusBytes[2] != 0x30 {
|
||||
status = statusPos2[statusBytes[2]]
|
||||
}
|
||||
if statusBytes[3] == 0x38 {
|
||||
status = statusPos3[statusBytes[3]]
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func isCardWellEmpty(statusBytes []byte) bool {
|
||||
return len(statusBytes) >= 4 && statusBytes[3] == 0x38
|
||||
}
|
||||
|
||||
func checkACK(statusResp []byte) error {
|
||||
if len(statusResp) == 3 &&
|
||||
statusResp[0] == ACK &&
|
||||
len(Address) >= 2 &&
|
||||
statusResp[1] == Address[0] &&
|
||||
statusResp[2] == Address[1] {
|
||||
return nil
|
||||
}
|
||||
if len(statusResp) > 0 && statusResp[0] == NAK {
|
||||
return fmt.Errorf("negative response from dispenser")
|
||||
}
|
||||
return fmt.Errorf("unexpected response status: % X", statusResp)
|
||||
}
|
||||
|
||||
// calculateBCC computes BCC as XOR of all bytes from STX to ETX.
|
||||
func calculateBCC(data []byte) byte {
|
||||
var bcc byte
|
||||
for _, b := range data {
|
||||
@@ -121,8 +143,8 @@ func calculateBCC(data []byte) byte {
|
||||
|
||||
func createPacket(address []byte, command []byte) []byte {
|
||||
packet := []byte{STX}
|
||||
packet = append(packet, address...) // Address bytes
|
||||
packet = append(packet, space) // Space character
|
||||
packet = append(packet, address...)
|
||||
packet = append(packet, space)
|
||||
packet = append(packet, command...)
|
||||
packet = append(packet, ETX)
|
||||
bcc := calculateBCC(packet)
|
||||
@@ -130,161 +152,134 @@ func createPacket(address []byte, command []byte) []byte {
|
||||
return packet
|
||||
}
|
||||
|
||||
func buildCheckRF(address []byte) []byte {
|
||||
return createPacket(address, []byte{STX, 0x52, 0x46})
|
||||
}
|
||||
|
||||
func buildCheckAP(address []byte) []byte {
|
||||
return createPacket(address, []byte{STX, 0x41, 0x50})
|
||||
}
|
||||
func buildCheckAP(address []byte) []byte { return createPacket(address, []byte{STX, 0x41, 0x50}) }
|
||||
|
||||
func sendAndReceive(port *serial.Port, packet []byte, delay time.Duration) ([]byte, error) {
|
||||
n, err := port.Write(packet)
|
||||
_, err := port.Write(packet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error writing to port: %w", err)
|
||||
}
|
||||
// log.Printf("TX %d bytes: % X", n, packet[:n])
|
||||
|
||||
time.Sleep(delay) // Wait for the dispenser to process the command
|
||||
time.Sleep(delay)
|
||||
|
||||
buf := make([]byte, 128)
|
||||
n, err = port.Read(buf)
|
||||
n, err := port.Read(buf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error reading from port: %w", err)
|
||||
}
|
||||
resp := buf[:n]
|
||||
// log.Printf("RX %d bytes: % X", n, buf[:n])
|
||||
return resp, nil
|
||||
return buf[:n], nil
|
||||
}
|
||||
|
||||
// --------------------
|
||||
// Serial init (3 attempts)
|
||||
// --------------------
|
||||
|
||||
func InitializeDispenser() (*serial.Port, error) {
|
||||
const funcName = "initializeDispenser"
|
||||
const (
|
||||
funcName = "InitializeDispenser"
|
||||
maxRetries = 3
|
||||
retryDelay = 2 * time.Second
|
||||
)
|
||||
|
||||
if SerialPort == "" {
|
||||
return nil, fmt.Errorf("%s: SerialPort is empty", funcName)
|
||||
}
|
||||
if len(Address) < 2 {
|
||||
return nil, fmt.Errorf("%s: Address must be at least 2 bytes", funcName)
|
||||
}
|
||||
|
||||
serialConfig := &serial.Config{
|
||||
Name: SerialPort,
|
||||
Baud: baudRate,
|
||||
ReadTimeout: time.Second * 2,
|
||||
ReadTimeout: 2 * time.Second,
|
||||
}
|
||||
port, err := serial.OpenPort(serialConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error opening dispenser COM port: %w", err)
|
||||
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= maxRetries; attempt++ {
|
||||
port, err := serial.OpenPort(serialConfig)
|
||||
if err == nil {
|
||||
log.Infof("%s: dispenser opened on %s (attempt %d/%d)", funcName, SerialPort, attempt, maxRetries)
|
||||
return port, nil
|
||||
}
|
||||
|
||||
lastErr = err
|
||||
log.Warnf("%s: failed to open dispenser on %s (attempt %d/%d): %v", funcName, SerialPort, attempt, maxRetries, err)
|
||||
if attempt < maxRetries {
|
||||
time.Sleep(retryDelay)
|
||||
}
|
||||
}
|
||||
return port, nil
|
||||
|
||||
return nil, fmt.Errorf("%s: failed to open dispenser on %s after %d attempts: %w", funcName, SerialPort, maxRetries, lastErr)
|
||||
}
|
||||
|
||||
func DispenserSequence(port *serial.Port) (string, error) {
|
||||
const funcName = "dispenserSequence"
|
||||
var result string
|
||||
// --------------------
|
||||
// Internal (port-owner only) operations
|
||||
// --------------------
|
||||
|
||||
// Check dispenser status
|
||||
status, err := CheckDispenserStatus(port)
|
||||
if err != nil {
|
||||
return status, fmt.Errorf("[%s] error checking dispenser status: %v", funcName, err)
|
||||
}
|
||||
result += status
|
||||
|
||||
// Send card to encoder position
|
||||
status, err = CardToEncoderPosition(port)
|
||||
if err != nil {
|
||||
return status, fmt.Errorf("[%s] error sending card to encoder position: %v", funcName, err)
|
||||
}
|
||||
result += "; " + status
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// if dispenser is not responding, I should repeat the command
|
||||
func CheckDispenserStatus(port *serial.Port) (string, error) {
|
||||
const funcName = "checkDispenserStatus"
|
||||
var result string
|
||||
// checkDispenserStatus talks to the device and returns the 4 status bytes [pos0..pos3].
|
||||
func checkDispenserStatus(port *serial.Port) ([]byte, error) {
|
||||
checkCmd := buildCheckAP(Address)
|
||||
enq := append([]byte{ENQ}, Address...)
|
||||
|
||||
// Send check command (AP)
|
||||
statusResp, err := sendAndReceive(port, checkCmd, delay)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error sending check command: %v", err)
|
||||
return nil, fmt.Errorf("error sending check command: %w", err)
|
||||
}
|
||||
if len(statusResp) == 0 {
|
||||
return "", fmt.Errorf("no response from dispenser")
|
||||
return nil, fmt.Errorf("no response from dispenser")
|
||||
}
|
||||
status, err := checkStatus(statusResp)
|
||||
if err != nil {
|
||||
return status, err
|
||||
if err := checkACK(statusResp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result += "; " + status
|
||||
|
||||
// Send ENQ+ADDR to prompt device to execute the command.
|
||||
statusResp, err = sendAndReceive(port, enq, delay)
|
||||
if err != nil {
|
||||
log.Errorf("error sending ENQ: %v", err)
|
||||
return nil, fmt.Errorf("error sending ENQ: %w", err)
|
||||
}
|
||||
if len(statusResp) == 0 {
|
||||
return "", fmt.Errorf("no response from dispenser")
|
||||
if len(statusResp) < 13 {
|
||||
return nil, fmt.Errorf("incomplete status response from dispenser: % X", statusResp)
|
||||
}
|
||||
status, err = checkStatus(statusResp)
|
||||
if err != nil {
|
||||
return status, err
|
||||
}
|
||||
result += status
|
||||
return result, nil
|
||||
return statusResp[7:11], nil
|
||||
}
|
||||
|
||||
func CardToEncoderPosition(port *serial.Port) (string, error) {
|
||||
const funcName = "cartToEncoderPosition"
|
||||
func cardToEncoderPosition(port *serial.Port) error {
|
||||
enq := append([]byte{ENQ}, Address...)
|
||||
|
||||
//Send Dispense card to encoder position (FC7) ---
|
||||
dispenseCmd := createPacket(Address, commandFC7)
|
||||
log.Println("Send card to encoder position")
|
||||
|
||||
statusResp, err := sendAndReceive(port, dispenseCmd, delay)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error sending card to encoder position: %v", err)
|
||||
return fmt.Errorf("error sending card to encoder position: %w", err)
|
||||
}
|
||||
_, err = checkStatus(statusResp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
if err := checkACK(statusResp); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
//Send ENQ to prompt device ---
|
||||
_, err = port.Write(enq)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error sending ENQ to prompt device: %v", err)
|
||||
return fmt.Errorf("error sending ENQ to prompt device: %w", err)
|
||||
}
|
||||
|
||||
//Check card position status
|
||||
status, err := CheckDispenserStatus(port)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return status, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func CardOutOfMouth(port *serial.Port) (string, error) {
|
||||
const funcName = "CardOutOfMouth"
|
||||
func cardOutOfMouth(port *serial.Port) error {
|
||||
enq := append([]byte{ENQ}, Address...)
|
||||
|
||||
// Send card out of card mouth (FC0) ---
|
||||
dispenseCmd := createPacket(Address, commandFC0)
|
||||
log.Println("Send card to out mouth position")
|
||||
|
||||
statusResp, err := sendAndReceive(port, dispenseCmd, delay)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error sending out of mouth command: %v", err)
|
||||
return fmt.Errorf("error sending out of mouth command: %w", err)
|
||||
}
|
||||
_, err = checkStatus(statusResp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
if err := checkACK(statusResp); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
//Send ENQ to prompt device ---
|
||||
_, err = port.Write(enq)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error sending ENQ to prompt device: %v", err)
|
||||
return fmt.Errorf("error sending ENQ to prompt device: %w", err)
|
||||
}
|
||||
|
||||
//Check card position status
|
||||
status, err := CheckDispenserStatus(port)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return status, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
// --------------------
|
||||
// Queue-based client (single owner of port)
|
||||
// --------------------
|
||||
package dispenser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tarm/serial"
|
||||
)
|
||||
|
||||
type cmdType int
|
||||
|
||||
const (
|
||||
cmdStatus cmdType = iota
|
||||
cmdToEncoder
|
||||
cmdOutOfMouth
|
||||
)
|
||||
|
||||
type cmdReq struct {
|
||||
typ cmdType
|
||||
ctx context.Context
|
||||
respCh chan cmdResp
|
||||
}
|
||||
|
||||
type cmdResp struct {
|
||||
status []byte
|
||||
err error
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
port *serial.Port
|
||||
|
||||
reqCh chan cmdReq
|
||||
done chan struct{}
|
||||
|
||||
// status cache
|
||||
mu sync.RWMutex
|
||||
lastStatus []byte
|
||||
lastStatusT time.Time
|
||||
statusTTL time.Duration
|
||||
|
||||
// published "stock/cardwell" cache + callback
|
||||
lastStockMu sync.RWMutex
|
||||
lastStock string
|
||||
onStock func(string)
|
||||
}
|
||||
|
||||
// NewClient starts the worker that owns the serial port.
|
||||
func NewClient(port *serial.Port, queueSize int) *Client {
|
||||
if queueSize <= 0 {
|
||||
queueSize = 16
|
||||
}
|
||||
c := &Client{
|
||||
port: port,
|
||||
reqCh: make(chan cmdReq, queueSize),
|
||||
done: make(chan struct{}),
|
||||
statusTTL: defaultStatusTTL,
|
||||
}
|
||||
go c.loop()
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
select {
|
||||
case <-c.done:
|
||||
return
|
||||
default:
|
||||
close(c.done)
|
||||
}
|
||||
}
|
||||
|
||||
// Optional: tune cache TTL (how "fresh" cached status must be)
|
||||
func (c *Client) SetStatusTTL(d time.Duration) {
|
||||
c.mu.Lock()
|
||||
c.statusTTL = d
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// OnStockUpdate registers a callback called whenever polling (or status reads) produce a stock status string.
|
||||
func (c *Client) OnStockUpdate(fn func(string)) {
|
||||
c.lastStockMu.Lock()
|
||||
c.onStock = fn
|
||||
c.lastStockMu.Unlock()
|
||||
}
|
||||
|
||||
// LastStock returns the most recently computed stock/card-well status string.
|
||||
func (c *Client) LastStock() string {
|
||||
c.lastStockMu.RLock()
|
||||
defer c.lastStockMu.RUnlock()
|
||||
return c.lastStock
|
||||
}
|
||||
|
||||
func (c *Client) setStock(statusBytes []byte) {
|
||||
stock := stockTake(statusBytes)
|
||||
|
||||
c.lastStockMu.Lock()
|
||||
c.lastStock = stock
|
||||
fn := c.onStock
|
||||
c.lastStockMu.Unlock()
|
||||
|
||||
// call outside lock
|
||||
if fn != nil {
|
||||
fn(stock)
|
||||
}
|
||||
}
|
||||
|
||||
// StartPolling performs a periodic status refresh.
|
||||
// It will NOT interrupt commands: it enqueues only when queue is idle.
|
||||
func (c *Client) StartPolling(interval time.Duration) {
|
||||
if interval <= 0 {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
t := time.NewTicker(interval)
|
||||
defer t.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-c.done:
|
||||
return
|
||||
case <-t.C:
|
||||
// enqueue only if idle to avoid delaying real commands
|
||||
if len(c.reqCh) != 0 {
|
||||
continue
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_, err := c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
log.Debugf("dispenser polling: %v", err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (c *Client) loop() {
|
||||
for {
|
||||
select {
|
||||
case <-c.done:
|
||||
return
|
||||
case req := <-c.reqCh:
|
||||
c.handle(req)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) handle(req cmdReq) {
|
||||
select {
|
||||
case <-req.ctx.Done():
|
||||
req.respCh <- cmdResp{err: req.ctx.Err()}
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
switch req.typ {
|
||||
case cmdStatus:
|
||||
st, err := checkDispenserStatus(c.port)
|
||||
if err == nil && len(st) == 4 {
|
||||
c.mu.Lock()
|
||||
c.lastStatus = append([]byte(nil), st...)
|
||||
c.lastStatusT = time.Now()
|
||||
c.mu.Unlock()
|
||||
|
||||
// publish stock/cardwell
|
||||
c.setStock(st)
|
||||
}
|
||||
req.respCh <- cmdResp{status: st, err: err}
|
||||
|
||||
case cmdToEncoder:
|
||||
err := cardToEncoderPosition(c.port)
|
||||
req.respCh <- cmdResp{err: err}
|
||||
|
||||
case cmdOutOfMouth:
|
||||
err := cardOutOfMouth(c.port)
|
||||
req.respCh <- cmdResp{err: err}
|
||||
|
||||
default:
|
||||
req.respCh <- cmdResp{err: fmt.Errorf("unknown command")}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) do(ctx context.Context, typ cmdType) ([]byte, error) {
|
||||
rch := make(chan cmdResp, 1)
|
||||
req := cmdReq{typ: typ, ctx: ctx, respCh: rch}
|
||||
|
||||
select {
|
||||
case c.reqCh <- req:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
select {
|
||||
case r := <-rch:
|
||||
return r.status, r.err
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// CheckStatus returns cached status if fresh, otherwise enqueues a device status read.
|
||||
func (c *Client) CheckStatus(ctx context.Context) ([]byte, error) {
|
||||
c.mu.RLock()
|
||||
ttl := c.statusTTL
|
||||
st := append([]byte(nil), c.lastStatus...)
|
||||
ts := c.lastStatusT
|
||||
c.mu.RUnlock()
|
||||
|
||||
if len(st) == 4 && time.Since(ts) <= ttl {
|
||||
// even when returning cached, keep stock in sync
|
||||
c.setStock(st)
|
||||
return st, nil
|
||||
}
|
||||
return c.do(ctx, cmdStatus)
|
||||
}
|
||||
|
||||
func (c *Client) ToEncoder(ctx context.Context) error {
|
||||
_, err := c.do(ctx, cmdToEncoder)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) OutOfMouth(ctx context.Context) error {
|
||||
_, err := c.do(ctx, cmdOutOfMouth)
|
||||
return err
|
||||
}
|
||||
|
||||
// --------------------
|
||||
// Public sequences updated to use Client (queue)
|
||||
// --------------------
|
||||
|
||||
// DispenserPrepare: check status; if empty => ok; else ensure at encoder.
|
||||
func (c *Client) DispenserPrepare(ctx context.Context) (string, error) {
|
||||
const funcName = "DispenserPrepare"
|
||||
stockStatus := ""
|
||||
|
||||
status, err := c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] check status: %w", funcName, err)
|
||||
}
|
||||
|
||||
logStatus(status)
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
|
||||
if isCardWellEmpty(status) {
|
||||
return stockStatus, nil
|
||||
}
|
||||
if isAtEncoderPosition(status) {
|
||||
return stockStatus, nil
|
||||
}
|
||||
|
||||
if err := c.ToEncoder(ctx); err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
status, err = c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] re-check status: %w", funcName, err)
|
||||
}
|
||||
logStatus(status)
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
|
||||
return stockStatus, nil
|
||||
}
|
||||
|
||||
func (c *Client) DispenserStart(ctx context.Context) (string, error) {
|
||||
const funcName = "DispenserStart"
|
||||
stockStatus := ""
|
||||
|
||||
status, err := c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] check status: %w", funcName, err)
|
||||
}
|
||||
|
||||
logStatus(status)
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
|
||||
if isCardWellEmpty(status) {
|
||||
return stockStatus, fmt.Errorf(stockStatus)
|
||||
}
|
||||
if isAtEncoderPosition(status) {
|
||||
return stockStatus, nil
|
||||
}
|
||||
|
||||
if err := c.ToEncoder(ctx); err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
status, err = c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] re-check status: %w", funcName, err)
|
||||
}
|
||||
logStatus(status)
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
|
||||
return stockStatus, nil
|
||||
}
|
||||
|
||||
func (c *Client) DispenserFinal(ctx context.Context) (string, error) {
|
||||
const funcName = "DispenserFinal"
|
||||
stockStatus := ""
|
||||
|
||||
if err := c.OutOfMouth(ctx); err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] out of mouth: %w", funcName, err)
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
status, err := c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] check status: %w", funcName, err)
|
||||
}
|
||||
logStatus(status)
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
|
||||
time.Sleep(delay)
|
||||
if err := c.ToEncoder(ctx); err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] to encoder: %w", funcName, err)
|
||||
}
|
||||
|
||||
time.Sleep(delay)
|
||||
status, err = c.CheckStatus(ctx)
|
||||
if err != nil {
|
||||
return stockStatus, fmt.Errorf("[%s] re-check status: %w", funcName, err)
|
||||
}
|
||||
logStatus(status)
|
||||
stockStatus = stockTake(status)
|
||||
c.setStock(status)
|
||||
|
||||
return stockStatus, nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package errorhandlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
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 FatalError(err error) {
|
||||
fmt.Println(err.Error())
|
||||
log.Errorf(err.Error())
|
||||
fmt.Println(". Press Enter to exit...")
|
||||
fmt.Scanln()
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -3,13 +3,19 @@ module gitea.futuresens.co.uk/futuresens/hardlink
|
||||
go 1.23.2
|
||||
|
||||
require (
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.171
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.190
|
||||
gitea.futuresens.co.uk/futuresens/logging v1.0.9
|
||||
github.com/alexbrainman/printer v0.0.0-20200912035444-f40f26f0bdeb
|
||||
github.com/denisenkom/go-mssqldb v0.12.3
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
|
||||
golang.org/x/image v0.27.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require golang.org/x/sys v0.32.0 // indirect
|
||||
require (
|
||||
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe // indirect
|
||||
github.com/golang-sql/sqlexp v0.1.0 // indirect
|
||||
golang.org/x/crypto v0.3.0 // indirect
|
||||
golang.org/x/sys v0.32.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.171 h1:/WM3mG5i4VYspeLaGFwjuvQJHM/Pks/dN3RjhrmYaN0=
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.171/go.mod h1:ABMUkdm+3VGrkuoCJsXMfPPud9GHDOwBb1NiifFqxes=
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.190 h1:OxP911wT8HQqBJ20KIZcBxi898rsYHhhCkne2u45p1A=
|
||||
gitea.futuresens.co.uk/futuresens/cmstypes v1.0.190/go.mod h1:ABMUkdm+3VGrkuoCJsXMfPPud9GHDOwBb1NiifFqxes=
|
||||
gitea.futuresens.co.uk/futuresens/fscrypto v0.0.0-20221125125050-9acaffd21362 h1:MnhYo7XtsECCU+5yVMo3tZZOOSOKGkl7NpOvTAieBTo=
|
||||
gitea.futuresens.co.uk/futuresens/fscrypto v0.0.0-20221125125050-9acaffd21362/go.mod h1:p95ouVfK4qyC20D3/k9QLsWSxD2pdweWiY6vcYi9hpM=
|
||||
gitea.futuresens.co.uk/futuresens/logging v1.0.9 h1:uvCQq/plecB0z/bUWOhFhwyYUWGPkTBZHsYNL+3RFvI=
|
||||
gitea.futuresens.co.uk/futuresens/logging v1.0.9/go.mod h1:pepS4+sreKTXJUp1Dq2RunpvQ0oY3vU2AuYjMTZzVQo=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.11.0/go.mod h1:HcM1YX14R7CJcghJGOYCgdezslRSVzqwLf/q+4Y2r/0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8=
|
||||
github.com/alexbrainman/printer v0.0.0-20200912035444-f40f26f0bdeb h1:OzF7h5OJLiB2QvpxfFdUFdSedYYsEKAXnE8BwsWQPmY=
|
||||
github.com/alexbrainman/printer v0.0.0-20200912035444-f40f26f0bdeb/go.mod h1:aeB9oSJ1VNJXxBkCz6Krw3aW8lPx6rkWnW/hXcoujR4=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/denisenkom/go-mssqldb v0.12.3 h1:pBSGx9Tq67pBOTLmxNuirNTeB8Vjmf886Kx+8Y+8shw=
|
||||
github.com/denisenkom/go-mssqldb v0.12.3/go.mod h1:k0mtMFOnU+AihqFxPMiF05rtiDrorD1Vrm1KEz5hxDo=
|
||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
||||
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY=
|
||||
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
|
||||
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
|
||||
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
|
||||
github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8=
|
||||
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
@@ -19,16 +31,34 @@ github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKs
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07 h1:UyzmZLoiDWMRywV4DUYb9Fbt8uiOSooupjTq10vpvnU=
|
||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.3.0 h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A=
|
||||
golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
|
||||
golang.org/x/image v0.27.0 h1:C8gA4oWU/tKkdCfYT6T2u4faJu3MeNS5O8UPWlPF61w=
|
||||
golang.org/x/image v0.27.0/go.mod h1:xbdrClrAUway1MUTEZDq9mz/UpRwYAkFFNUslZtcB+g=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/db"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type preauthSpoolRecord struct {
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
CheckoutDate string `json:"checkoutDate"` // keep as received
|
||||
Fields map[string]string `json:"fields"` // ChipDNA result.Fields
|
||||
}
|
||||
|
||||
func (app *App) getDB(ctx context.Context) (*sql.DB, error) {
|
||||
app.dbMu.Lock()
|
||||
defer app.dbMu.Unlock()
|
||||
|
||||
// Fast path: db exists and is alive
|
||||
if app.db != nil {
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := app.db.PingContext(pingCtx); err == nil {
|
||||
return app.db, nil
|
||||
}
|
||||
|
||||
// stale handle
|
||||
_ = app.db.Close()
|
||||
app.db = nil
|
||||
}
|
||||
|
||||
// Reconnect once, bounded
|
||||
dialCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dbConn, err := db.InitMSSQL(
|
||||
app.cfg.Dbport,
|
||||
app.cfg.Dbuser,
|
||||
app.cfg.Dbpassword,
|
||||
app.cfg.Dbname,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pingCtx, cancel2 := context.WithTimeout(dialCtx, 1*time.Second)
|
||||
defer cancel2()
|
||||
|
||||
if err := dbConn.PingContext(pingCtx); err != nil {
|
||||
_ = dbConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
app.db = dbConn
|
||||
return app.db, nil
|
||||
}
|
||||
|
||||
func (app *App) spoolPath() string {
|
||||
// keep it near logs; adjust if you prefer a dedicated dir
|
||||
// ensure LogDir ends with separator in your config loader
|
||||
return filepath.Join(app.cfg.LogDir, "preauth_spool.ndjson")
|
||||
}
|
||||
|
||||
// persistPreauth tries DB first; if DB is down or insert fails, it spools to file.
|
||||
// It never returns an error to the caller (so your HTTP flow stays simple),
|
||||
// but it logs failures.
|
||||
func (app *App) persistPreauth(ctx context.Context, fields map[string]string, checkoutDate string) {
|
||||
// First, try DB (with your reconnect logic inside getDB)
|
||||
dbConn, err := app.getDB(ctx)
|
||||
if err == nil && dbConn != nil {
|
||||
if err := db.InsertPreauth(ctx, dbConn, fields, checkoutDate); err == nil {
|
||||
// opportunistic drain once DB is alive
|
||||
go app.drainPreauthSpool(context.Background())
|
||||
return
|
||||
} else {
|
||||
log.WithError(err).Warn("DB insert failed; will spool preauth")
|
||||
}
|
||||
} else {
|
||||
log.WithError(err).Warn("DB unavailable; will spool preauth")
|
||||
}
|
||||
|
||||
// Fallback: spool to file
|
||||
rec := preauthSpoolRecord{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
CheckoutDate: checkoutDate,
|
||||
Fields: fields,
|
||||
}
|
||||
if spErr := app.spoolPreauth(rec); spErr != nil {
|
||||
log.WithError(spErr).Error("failed to spool preauth")
|
||||
}
|
||||
}
|
||||
|
||||
// append one line JSON (NDJSON)
|
||||
func (app *App) spoolPreauth(rec preauthSpoolRecord) error {
|
||||
p := app.spoolPath()
|
||||
|
||||
f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open spool file: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
b, err := json.Marshal(rec)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal spool record: %w", err)
|
||||
}
|
||||
|
||||
if _, err := f.Write(append(b, '\n')); err != nil {
|
||||
return fmt.Errorf("write spool record: %w", err)
|
||||
}
|
||||
|
||||
return f.Sync() // ensure it's on disk
|
||||
}
|
||||
|
||||
// Drain spool into DB.
|
||||
// Strategy: read all lines, insert each; keep failures in a temp file; then replace original.
|
||||
func (app *App) drainPreauthSpool(ctx context.Context) {
|
||||
dbConn, err := app.getDB(ctx)
|
||||
if err != nil {
|
||||
return // still down, nothing to do
|
||||
}
|
||||
|
||||
spool := app.spoolPath()
|
||||
in, err := os.Open(spool)
|
||||
if err != nil {
|
||||
// no spool is fine
|
||||
return
|
||||
}
|
||||
defer in.Close()
|
||||
|
||||
tmp := spool + ".tmp"
|
||||
out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
|
||||
if err != nil {
|
||||
log.WithError(err).Warn("drain spool: open tmp failed")
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
sc := bufio.NewScanner(in)
|
||||
// allow long lines if receipts ever sneak in (shouldn't, but safe)
|
||||
buf := make([]byte, 0, 64*1024)
|
||||
sc.Buffer(buf, 2*1024*1024)
|
||||
|
||||
var (
|
||||
okCount int
|
||||
failCount int
|
||||
)
|
||||
|
||||
for sc.Scan() {
|
||||
line := sc.Bytes()
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
var rec preauthSpoolRecord
|
||||
if err := json.Unmarshal(line, &rec); err != nil {
|
||||
// malformed line: keep it so we don't lose evidence
|
||||
_, _ = out.Write(append(line, '\n'))
|
||||
failCount++
|
||||
continue
|
||||
}
|
||||
|
||||
// attempt insert
|
||||
if err := db.InsertPreauth(ctx, dbConn, rec.Fields, rec.CheckoutDate); err != nil {
|
||||
// DB still flaky or data issue: keep it for later retry
|
||||
_, _ = out.Write(append(line, '\n'))
|
||||
failCount++
|
||||
continue
|
||||
}
|
||||
|
||||
okCount++
|
||||
}
|
||||
|
||||
if err := sc.Err(); err != nil {
|
||||
log.WithError(err).Warn("drain spool: scanner error")
|
||||
// best effort; do not replace spool
|
||||
return
|
||||
}
|
||||
|
||||
_ = out.Sync()
|
||||
|
||||
// Replace original spool with temp (atomic on Windows is best-effort; still OK here)
|
||||
_ = in.Close()
|
||||
_ = out.Close()
|
||||
|
||||
if err := os.Rename(tmp, spool); err != nil {
|
||||
log.WithError(err).Warn("drain spool: rename failed")
|
||||
return
|
||||
}
|
||||
|
||||
if okCount > 0 || failCount > 0 {
|
||||
log.WithFields(log.Fields{
|
||||
"inserted": okCount,
|
||||
"remaining": failCount,
|
||||
}).Info("preauth spool drained")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/dispenser"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/errorhandlers"
|
||||
"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/types"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
disp *dispenser.Client
|
||||
lockserver lockserver.LockServer
|
||||
isPayment bool
|
||||
db *sql.DB
|
||||
cfg *config.ConfigRec
|
||||
dbMu sync.Mutex
|
||||
cardWellMu sync.RWMutex
|
||||
cardWellStatus string
|
||||
}
|
||||
|
||||
func NewApp(disp *dispenser.Client, lockType, encoderAddress, cardWellStatus string, db *sql.DB, cfg *config.ConfigRec) *App {
|
||||
app := &App{
|
||||
isPayment: cfg.IsPayment,
|
||||
disp: disp,
|
||||
lockserver: lockserver.NewLockServer(lockType, encoderAddress, errorhandlers.FatalError),
|
||||
db: db,
|
||||
cfg: cfg,
|
||||
}
|
||||
app.SetCardWellStatus(cardWellStatus)
|
||||
return app
|
||||
}
|
||||
|
||||
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)
|
||||
mux.HandleFunc("/dispenserstatus", app.reportDispenserStatus)
|
||||
}
|
||||
|
||||
func (app *App) takePreauthorization(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("takePreauthorization")
|
||||
var (
|
||||
theResponse cmstypes.ResponseRec
|
||||
theRequest cmstypes.TransactionRec
|
||||
trResult payment.TransactionResultXML
|
||||
result payment.PaymentResult
|
||||
save bool
|
||||
)
|
||||
|
||||
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(types.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(types.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(types.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(types.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(types.LinkTakePreauthorization, "text/xml", bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Payment processing error", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.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(types.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.FillFromTransactionResult(trResult)
|
||||
|
||||
if err := printer.PrintCardholderReceipt(result.CardholderReceipt); err != nil {
|
||||
log.Errorf("PrintCardholderReceipt error: %v", err)
|
||||
}
|
||||
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data, save = payment.BuildPreauthRedirectURL(result.Fields)
|
||||
if save {
|
||||
go app.persistPreauth(context.Background(), result.Fields, theRequest.CheckoutDate)
|
||||
}
|
||||
|
||||
writeTransactionResult(w, http.StatusOK, theResponse)
|
||||
}
|
||||
|
||||
func (app *App) takePayment(w http.ResponseWriter, r *http.Request) {
|
||||
const op = logging.Op("takePayment")
|
||||
var (
|
||||
theResponse cmstypes.ResponseRec
|
||||
theRequest cmstypes.TransactionRec
|
||||
trResult payment.TransactionResultXML
|
||||
result payment.PaymentResult
|
||||
)
|
||||
|
||||
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(types.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(types.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(types.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(types.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(types.LinkTakePayment, "text/xml", bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Payment processing error", string(op), "", "", 0)
|
||||
theResponse.Data = payment.BuildFailureURL(types.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(types.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.FillFromTransactionResult(trResult)
|
||||
|
||||
if err := printer.PrintCardholderReceipt(result.CardholderReceipt); err != nil {
|
||||
log.Errorf("PrintCardholderReceipt error: %v", err)
|
||||
}
|
||||
|
||||
theResponse.Status = result.Status
|
||||
theResponse.Data = payment.BuildPaymentRedirectURL(result.Fields)
|
||||
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 {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/json" {
|
||||
errorhandlers.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)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid JSON payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// parse times
|
||||
checkIn, err := time.Parse(types.CustomLayout, doorReq.CheckinTime)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Invalid checkinTime format", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid checkinTime format: "+err.Error())
|
||||
return
|
||||
}
|
||||
checkOut, err := time.Parse(types.CustomLayout, doorReq.CheckoutTime)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Invalid checkoutTime format", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusBadRequest, "Invalid checkoutTime format: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure dispenser ready (card at encoder) BEFORE we attempt encoding.
|
||||
// With queued dispenser ops, this will not clash with polling.
|
||||
status, err := app.disp.DispenserStart(r.Context())
|
||||
app.SetCardWellStatus(status)
|
||||
if err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Dispense error", string(op), "", "", 0)
|
||||
errorhandlers.WriteError(w, http.StatusServiceUnavailable, "Dispense error: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Always attempt to finalize after we have moved a card / started an issuance flow.
|
||||
// This guarantees we eject and prepare the next card even on lock failures.
|
||||
finalize := func() {
|
||||
if app.disp == nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
status, ferr := app.disp.DispenserFinal(ctx)
|
||||
if ferr != nil {
|
||||
logging.Error(serviceName, ferr.Error(), "Dispenser final error", string(op), "", "", 0)
|
||||
return
|
||||
}
|
||||
app.SetCardWellStatus(status)
|
||||
}
|
||||
|
||||
// build lock server command
|
||||
app.lockserver.BuildCommand(doorReq, checkIn, checkOut)
|
||||
|
||||
// lock server sequence
|
||||
if err := app.lockserver.LockSequence(); err != nil {
|
||||
logging.Error(serviceName, err.Error(), "Key encoding", string(op), "", "", 0)
|
||||
finalize()
|
||||
errorhandlers.WriteError(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// final dispenser steps
|
||||
finalize()
|
||||
|
||||
theResponse.Code = http.StatusOK
|
||||
theResponse.Message = "Card issued successfully"
|
||||
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 {
|
||||
errorhandlers.WriteError(w, http.StatusMethodNotAllowed, "Method not allowed; use POST")
|
||||
return
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); !strings.Contains(ct, "xml") {
|
||||
errorhandlers.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)
|
||||
errorhandlers.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)
|
||||
errorhandlers.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)
|
||||
errorhandlers.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",
|
||||
})
|
||||
}
|
||||
|
||||
func (app *App) reportDispenserStatus(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(cmstypes.StatusRec{
|
||||
Code: http.StatusOK,
|
||||
Message: app.CardWellStatus(),
|
||||
})
|
||||
}
|
||||
|
||||
func (app *App) SetCardWellStatus(s string) {
|
||||
app.cardWellMu.Lock()
|
||||
app.cardWellStatus = s
|
||||
app.cardWellMu.Unlock()
|
||||
}
|
||||
|
||||
func (app *App) CardWellStatus() string {
|
||||
app.cardWellMu.RLock()
|
||||
defer app.cardWellMu.RUnlock()
|
||||
return app.cardWellStatus
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
)
|
||||
|
||||
const serviceName = "hardlink"
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// cmd/hardlink-preauth-release/main.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/bootstrap"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/logging"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/payment"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
buildVersion = "1.0.2"
|
||||
serviceName = "preauth-release"
|
||||
)
|
||||
|
||||
func main() {
|
||||
config := config.ReadPreauthReleaserConfig()
|
||||
// Setup logging and get file handle
|
||||
logFile, err := logging.SetupLogging(config.LogDir, serviceName, buildVersion)
|
||||
if err != nil {
|
||||
log.Printf("Failed to set up logging: %v\n", err)
|
||||
}
|
||||
defer logFile.Close()
|
||||
database, err := bootstrap.OpenDB(&config)
|
||||
if err != nil {
|
||||
log.WithError(err).Fatal("DB init failed")
|
||||
}
|
||||
defer database.Close()
|
||||
|
||||
if err := payment.ReleasePreauthorizations(database); err != nil {
|
||||
log.Error(err)
|
||||
fmt.Println(err)
|
||||
} else {
|
||||
log.Info("Task completed successfully")
|
||||
fmt.Println("Task completed successfully")
|
||||
}
|
||||
|
||||
for i := 20; i > 0; i-- {
|
||||
fmt.Printf("\rExiting in %2d seconds... ", i)
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
fmt.Println("\rExiting now. ")
|
||||
os.Exit(0)
|
||||
}
|
||||
@@ -10,17 +10,24 @@ 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
|
||||
}
|
||||
|
||||
// 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"
|
||||
|
||||
conn, err := InitializeServerConnection(LockServerURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
resp, err := sendHeartbeatToServer(conn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("[%s] heartbeat failed: %v", funcName, err)
|
||||
|
||||
@@ -12,34 +12,63 @@ 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"
|
||||
Salto = "salto"
|
||||
TLJ = "tlj"
|
||||
)
|
||||
|
||||
var (
|
||||
Cert string
|
||||
LockServerURL string
|
||||
)
|
||||
|
||||
type (
|
||||
LockServer interface {
|
||||
BuildCommand(lockId string, checkIn, checkOut time.Time) error
|
||||
LockSequence(conn net.Conn) error
|
||||
BuildCommand(doorReq DoorCardRequest, checkIn, checkOut time.Time) error
|
||||
LockSequence() error
|
||||
}
|
||||
|
||||
AssaLockServer struct {
|
||||
encoderAddr string
|
||||
command string
|
||||
encoderAddr string
|
||||
command string
|
||||
}
|
||||
|
||||
OmniLockServer struct {
|
||||
encoderAddr string // Encoder address for the lock server
|
||||
command []byte // Command to be sent to the lock server
|
||||
encoderAddr string // Encoder unit address
|
||||
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 {
|
||||
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
|
||||
@@ -84,8 +113,3 @@ func sendAndReceive(conn net.Conn, command []byte) (string, error) {
|
||||
response := buf[:n]
|
||||
return string(response), nil
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
func (lock *OmniLockServer) LockSequence(conn net.Conn) error {
|
||||
func (lock *OmniLockServer) LockSequence() error {
|
||||
const funcName = "OmniLockServer.LockSequence"
|
||||
|
||||
conn, err := InitializeServerConnection(LockServerURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// Start the link with the lock server
|
||||
regs, err := lock.linkStart(conn)
|
||||
if err != nil {
|
||||
|
||||
@@ -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("LockSequence: 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("LockSequence: 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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// setupLogging ensures log directory, opens log file, and configures logrus.
|
||||
// Returns the *os.File so caller can defer its Close().
|
||||
func SetupLogging(logDir, serviceName, buildVersion 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
|
||||
}
|
||||
@@ -1,348 +1,146 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/tarm/serial"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
yaml "gopkg.in/yaml.v3"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/bootstrap"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/config"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/dispenser"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/errorhandlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/handlers"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/lockserver"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/logging"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/printer"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/logging"
|
||||
)
|
||||
|
||||
const (
|
||||
buildVersion = "0.9.2"
|
||||
serviceName = "hardlink"
|
||||
customLayout = "2006-01-02 15:04:05 -0700"
|
||||
buildVersion = "1.1.2"
|
||||
serviceName = "hardlink"
|
||||
pollingFrequency = 8 * time.Second
|
||||
)
|
||||
|
||||
// configRec holds values from config.yml.
|
||||
type configRec struct {
|
||||
Port int `yaml:"port"`
|
||||
LockserverUrl string `yaml:"lockservUrl"`
|
||||
LockType string `yaml:"lockType"`
|
||||
EncoderAddress string `yaml:"encoderAddr"`
|
||||
DispenserPort string `yaml:"dispensPort"`
|
||||
DispenserAdrr string `yaml:"dispensAddr"`
|
||||
PrinterName string `yaml:"printerName"`
|
||||
LogDir string `yaml:"logdir"`
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
func newApp(dispPort *serial.Port, lockConn net.Conn, config configRec) *App {
|
||||
return &App{
|
||||
dispPort: dispPort,
|
||||
lockConn: lockConn,
|
||||
lockserver: lockserver.NewLockServer(config.LockType, config.EncoderAddress, fatalError),
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Load config
|
||||
config := readConfig()
|
||||
|
||||
cfg := config.ReadHardlinkConfig()
|
||||
printer.Layout = readTicketLayout()
|
||||
printer.PrinterName = config.PrinterName
|
||||
printer.PrinterName = cfg.PrinterName
|
||||
lockserver.Cert = cfg.Cert
|
||||
lockserver.LockServerURL = cfg.LockserverUrl
|
||||
|
||||
var (
|
||||
dispPort *serial.Port
|
||||
disp *dispenser.Client
|
||||
cardWellStatus string
|
||||
)
|
||||
|
||||
// Setup logging and get file handle
|
||||
logFile, err := setupLogging(config.LogDir)
|
||||
logFile, err := logging.SetupLogging(cfg.LogDir, serviceName, buildVersion)
|
||||
if err != nil {
|
||||
log.Printf("Failed to set up logging: %v\n", err)
|
||||
}
|
||||
defer logFile.Close()
|
||||
|
||||
// Initialize dispenser
|
||||
dispenser.SerialPort = config.DispenserPort
|
||||
dispenser.Address = []byte(config.DispenserAdrr)
|
||||
dispHandle, err := dispenser.InitializeDispenser()
|
||||
if err != nil {
|
||||
fatalError(err)
|
||||
}
|
||||
defer dispHandle.Close()
|
||||
if !cfg.TestMode {
|
||||
dispenser.SerialPort = cfg.DispenserPort
|
||||
dispenser.Address = []byte(cfg.DispenserAdrr)
|
||||
|
||||
status, err := dispenser.CheckDispenserStatus(dispHandle)
|
||||
if err != nil {
|
||||
if len(status) == 0 {
|
||||
err = fmt.Errorf("%s; wrong dispenser address: %s", err, config.DispenserAdrr)
|
||||
fatalError(err)
|
||||
} else {
|
||||
fmt.Println(status)
|
||||
dispPort, err = dispenser.InitializeDispenser()
|
||||
if err != nil {
|
||||
errorhandlers.FatalError(err)
|
||||
}
|
||||
defer dispPort.Close()
|
||||
|
||||
// Start queued dispenser client (single goroutine owns the serial port)
|
||||
disp = dispenser.NewClient(dispPort, 32)
|
||||
defer disp.Close()
|
||||
|
||||
// Prepare dispenser (ensures card at encoder position unless empty)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cardWellStatus, err = disp.DispenserPrepare(ctx)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("%s; wrong dispenser address: %s", err, cfg.DispenserAdrr)
|
||||
errorhandlers.FatalError(err)
|
||||
}
|
||||
fmt.Println(cardWellStatus)
|
||||
}
|
||||
|
||||
// Test lock-server connection
|
||||
switch strings.ToLower(cfg.LockType) {
|
||||
case lockserver.TLJ:
|
||||
// TLJ uses HTTP - skip TCP probe here (as you did before)
|
||||
default:
|
||||
lockConn, err := lockserver.InitializeServerConnection(cfg.LockserverUrl)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
log.Errorf(err.Error())
|
||||
} else {
|
||||
fmt.Printf("Connected to the lock server successfuly at %s\n", cfg.LockserverUrl)
|
||||
log.Infof("Connected to the lock server successfuly at %s", cfg.LockserverUrl)
|
||||
lockConn.Close()
|
||||
}
|
||||
}
|
||||
log.Infof("Dispenser initialized on port %s, %s", config.DispenserPort, status)
|
||||
|
||||
// Initialize lock-server connection once
|
||||
lockConn, err := lockserver.InitializeServerConnection(config.LockserverUrl)
|
||||
database, err := bootstrap.OpenDB(&cfg)
|
||||
if err != nil {
|
||||
fatalError(err)
|
||||
log.Warnf("DB init failed: %v", err)
|
||||
}
|
||||
defer database.Close()
|
||||
|
||||
if cfg.IsPayment {
|
||||
fmt.Println("Payment processing is enabled")
|
||||
log.Info("Payment processing is enabled")
|
||||
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)
|
||||
|
||||
// Create App and wire routes
|
||||
app := newApp(dispHandle, lockConn, config)
|
||||
// NOTE: change handlers.NewApp signature to accept *dispenser.Client instead of *serial.Port
|
||||
app := handlers.NewApp(disp, cfg.LockType, cfg.EncoderAddress, cardWellStatus, database, &cfg)
|
||||
|
||||
// Update cardWellStatus when dispenser status changes
|
||||
if !cfg.TestMode {
|
||||
// Set initial cardWellStatus
|
||||
app.SetCardWellStatus(cardWellStatus)
|
||||
|
||||
// Set up callback to update cardWellStatus when dispenser status changes
|
||||
disp.OnStockUpdate(func(stock string) {
|
||||
app.SetCardWellStatus(stock)
|
||||
})
|
||||
|
||||
// Start polling for dispenser status every 10 seconds
|
||||
disp.StartPolling(pollingFrequency)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
setUpRoutes(app, mux)
|
||||
app.RegisterRoutes(mux)
|
||||
|
||||
addr := fmt.Sprintf(":%d", config.Port)
|
||||
addr := fmt.Sprintf(":%d", cfg.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)
|
||||
errorhandlers.FatalError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func setUpRoutes(app *App, mux *http.ServeMux) {
|
||||
mux.HandleFunc("/issuedoorcard", app.issueDoorCard)
|
||||
mux.HandleFunc("/printroomticket", app.printRoomTicket)
|
||||
}
|
||||
|
||||
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) 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
|
||||
@@ -350,13 +148,70 @@ func readTicketLayout() printer.LayoutOptions {
|
||||
// 1) Read the file
|
||||
data, err := os.ReadFile(layoutName)
|
||||
if err != nil {
|
||||
fatalError(fmt.Errorf("failed to read %s: %v", layoutName, err))
|
||||
errorhandlers.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))
|
||||
errorhandlers.FatalError(fmt.Errorf("failed to parse %s: %v", layoutName, err))
|
||||
}
|
||||
|
||||
return layout
|
||||
}
|
||||
|
||||
func startChipDnaClient() {
|
||||
startClient := func() (*exec.Cmd, error) {
|
||||
cmd := exec.Command("./ChipDNAClient/ChipDnaClient.exe")
|
||||
err := cmd.Start()
|
||||
if err != nil {
|
||||
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 {
|
||||
errorhandlers.FatalError(err)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}()
|
||||
}
|
||||
|
||||
+172
-31
@@ -1,42 +1,183 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/cmstypes"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
_ "github.com/denisenkom/go-mssqldb"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// StartTransaction sends a start transaction XML to ChipDNA Server
|
||||
func (pc *PaymentClient) StartTransaction(amountMinorUnits int, reference string) (string, error) {
|
||||
conn, err := net.Dial("tcp", pc.Addr)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to connect: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// Set timeout
|
||||
conn.SetDeadline(time.Now().Add(15 * time.Second))
|
||||
|
||||
// Format XML request
|
||||
request := fmt.Sprintf(`
|
||||
<StartTransaction>
|
||||
<Amount>%d</Amount>
|
||||
<AmountType>Actual</AmountType>
|
||||
<Reference>%s</Reference>
|
||||
<TransactionType>Sale</TransactionType>
|
||||
</StartTransaction>`, amountMinorUnits, reference)
|
||||
|
||||
_, err = conn.Write([]byte(request))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to write to server: %w", err)
|
||||
// XML parsing structs
|
||||
type (
|
||||
TransactionRec struct {
|
||||
XMLName xml.Name `xml:"TransactionPayload"`
|
||||
AmountMinorUnits string `xml:"amount"`
|
||||
TransactionType string `xml:"transactionType"`
|
||||
}
|
||||
|
||||
// Read response
|
||||
buff := make([]byte, 4096)
|
||||
n, err := conn.Read(buff)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read from server: %w", err)
|
||||
TransactionResultXML struct {
|
||||
XMLName xml.Name `xml:"TransactionResult"`
|
||||
Entries []EntryXML `xml:"Entry"`
|
||||
}
|
||||
|
||||
return string(buff[:n]), nil
|
||||
EntryXML struct {
|
||||
Key string `xml:"Key"`
|
||||
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"`
|
||||
}
|
||||
|
||||
PaymentResult struct {
|
||||
Fields map[string]string
|
||||
CardholderReceipt string
|
||||
Status cmstypes.StatusRec
|
||||
}
|
||||
|
||||
TransactionInfo struct {
|
||||
transactionRes string
|
||||
transactionState string
|
||||
}
|
||||
)
|
||||
|
||||
// ParseTransactionResult parses the XML into entries.
|
||||
func (tr *TransactionResultXML) ParseTransactionResult(data []byte) error {
|
||||
if err := xml.Unmarshal(data, &tr); err != nil {
|
||||
return fmt.Errorf("XML unmarshal: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ti *TransactionInfo) FillFromTransactionResult(trResult TransactionResultXML) {
|
||||
for _, e := range trResult.Entries {
|
||||
switch e.Key {
|
||||
case types.TransactionResult:
|
||||
ti.transactionRes = e.Value
|
||||
case types.TransactionState:
|
||||
ti.transactionState = e.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PaymentResult) FillFromTransactionResult(trResult TransactionResultXML) {
|
||||
if r.Fields == nil {
|
||||
r.Fields = make(map[string]string)
|
||||
}
|
||||
|
||||
for _, e := range trResult.Entries {
|
||||
switch e.Key {
|
||||
|
||||
case types.ReceiptData, types.ReceiptDataMerchant:
|
||||
// intentionally ignored
|
||||
|
||||
case types.ReceiptDataCardholder:
|
||||
r.CardholderReceipt = e.Value
|
||||
|
||||
case types.TransactionResult:
|
||||
r.Status.Message = e.Value
|
||||
r.Status.Code = http.StatusOK
|
||||
r.Fields[e.Key] = e.Value
|
||||
|
||||
default:
|
||||
r.Fields[e.Key] = e.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BuildRedirectURL builds the redirect URL to send the guest to after payment.
|
||||
func BuildPaymentRedirectURL(result map[string]string) string {
|
||||
res := result[types.TransactionResult]
|
||||
|
||||
// Transaction approved?
|
||||
if strings.EqualFold(res, types.ResultApproved) {
|
||||
// Transaction confirmed?
|
||||
if strings.EqualFold(result[types.ConfirmResult], types.ResultApproved) {
|
||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
||||
Info("Transaction approved and confirmed")
|
||||
|
||||
return buildSuccessURL(result)
|
||||
}
|
||||
|
||||
// Not confirmed
|
||||
log.WithFields(log.Fields{types.LogFieldError: result[types.ConfirmResult], types.LogFieldDescription: result[types.ConfirmErrors]}).
|
||||
Error("Transaction approved but not confirmed")
|
||||
|
||||
return BuildFailureURL(result[types.ConfirmResult], result[types.ConfirmErrors])
|
||||
}
|
||||
|
||||
// Not approved
|
||||
return BuildFailureURL(res, result[types.Errors])
|
||||
}
|
||||
|
||||
func BuildPreauthRedirectURL(result map[string]string) (string, bool) {
|
||||
res := result[types.TransactionResult]
|
||||
tType := result[types.TransactionType]
|
||||
|
||||
// Transaction approved?
|
||||
if strings.EqualFold(res, types.ResultApproved) {
|
||||
switch {
|
||||
// Transaction type AccountVerification?
|
||||
case strings.EqualFold(tType, types.AccountVerificationType):
|
||||
log.WithField(types.LogResult, result[types.TransactionResult]).
|
||||
Info("Account verification approved")
|
||||
|
||||
return buildSuccessURL(result), false
|
||||
|
||||
// Transaction type Sale?
|
||||
case strings.EqualFold(tType, types.SaleTransactionType):
|
||||
// Transaction confirmed?
|
||||
log.WithField(types.LogResult, result[types.ConfirmResult]).
|
||||
Info("Amount preauthorized successfully")
|
||||
|
||||
return buildSuccessURL(result), true
|
||||
}
|
||||
}
|
||||
|
||||
// Not approved
|
||||
return BuildFailureURL(res, result[types.Errors]), false
|
||||
}
|
||||
|
||||
func buildSuccessURL(result map[string]string) string {
|
||||
q := url.Values{}
|
||||
q.Set("CardNumber", hex.EncodeToString([]byte(result[types.PAN_MASKED])))
|
||||
q.Set("ExpiryDate", hex.EncodeToString([]byte(result[types.EXPIRY_DATE])))
|
||||
q.Set("TxnReference", result[types.Reference])
|
||||
q.Set("CardHash", hex.EncodeToString([]byte(result[types.CardHash])))
|
||||
q.Set("CardReference", hex.EncodeToString([]byte(result[types.CardReference])))
|
||||
return (&url.URL{
|
||||
Path: types.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 = types.ResultError
|
||||
}
|
||||
|
||||
log.WithFields(log.Fields{types.LogFieldError: msgType, types.LogFieldDescription: description}).
|
||||
Error("Transaction failed")
|
||||
|
||||
q.Set("MsgType", msgType)
|
||||
q.Set("Description", description)
|
||||
return (&url.URL{
|
||||
Path: types.CheckinUnsuccessfulEndpoint,
|
||||
RawQuery: q.Encode(),
|
||||
}).String()
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/url"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PaymentClient holds connection data
|
||||
type PaymentClient struct {
|
||||
Addr string // e.g., "127.0.0.1:1869"
|
||||
}
|
||||
|
||||
func InitializeConnection(paymentrUrl string) (net.Conn, error) {
|
||||
const funcName = "InitializeServerConnection"
|
||||
// Parse the URL to extract host and port
|
||||
parsedUrl, err := url.Parse(paymentrUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[%s] failed to parse LockserverUrl: %v", funcName, err)
|
||||
}
|
||||
|
||||
// Remove any leading/trailing slashes just in case
|
||||
address := strings.Trim(parsedUrl.Host, "/")
|
||||
|
||||
// Establish a TCP connection to the Visionline server
|
||||
conn, err := net.Dial("tcp", address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to payment server: %v", err)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/db"
|
||||
"gitea.futuresens.co.uk/futuresens/hardlink/types"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
httpTimeout = 120 * time.Second
|
||||
)
|
||||
|
||||
/* ==============================
|
||||
Public Entry Point
|
||||
============================== */
|
||||
|
||||
func ReleasePreauthorizations(database *sql.DB) error {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
client := &http.Client{Timeout: httpTimeout}
|
||||
|
||||
preauths, err := fetchDuePreauths(ctx, database, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(preauths) == 0 {
|
||||
log.Info("No preauthorizations due for release")
|
||||
return nil
|
||||
} else {
|
||||
log.Infof("%d preauthorizations due for release", len(preauths))
|
||||
}
|
||||
|
||||
var failed []string
|
||||
var completed int
|
||||
for _, p := range preauths {
|
||||
if err := handlePreauthRelease(ctx, database, client, p, now); err != nil {
|
||||
log.Errorf("Preauth %s failed: %v", p.TxnReference, err)
|
||||
failed = append(failed, p.TxnReference)
|
||||
}
|
||||
completed++
|
||||
}
|
||||
log.Infof("Preauth release completed: %d processed, %d failed", completed, len(failed))
|
||||
|
||||
if len(failed) > 0 {
|
||||
return fmt.Errorf("preauth release incomplete, failed refs: %s", strings.Join(failed, ", "))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
Core Business Logic
|
||||
============================== */
|
||||
|
||||
func handlePreauthRelease(
|
||||
ctx context.Context,
|
||||
dbConn *sql.DB,
|
||||
client *http.Client,
|
||||
preauth types.PreauthRec,
|
||||
now time.Time,
|
||||
) error {
|
||||
|
||||
ref := preauth.TxnReference
|
||||
log.Infof("Evaluating preauth %s", ref)
|
||||
|
||||
info, err := fetchTransactionInfo(ctx, client, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infof("res=%s state=%s", info.transactionRes, info.transactionState)
|
||||
|
||||
// If already voided or declined → mark released
|
||||
if isAlreadyReleased(info) {
|
||||
return markReleased(ctx, dbConn, ref, now)
|
||||
}
|
||||
|
||||
// Only void approved + uncommitted
|
||||
if !isVoidable(info) {
|
||||
log.Infof("Preauth %s not eligible for void (res=%s state=%s)", ref, info.transactionRes, info.transactionState)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Void transaction
|
||||
if err := voidPreauth(ctx, client, ref); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify final state
|
||||
finalInfo, err := fetchTransactionInfo(ctx, client, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !isSuccessfullyVoided(finalInfo) {
|
||||
return fmt.Errorf("unexpected final state res=%s state=%s",
|
||||
finalInfo.transactionRes, finalInfo.transactionState)
|
||||
}
|
||||
|
||||
log.Infof("Preauth %s successfully voided", ref)
|
||||
return markReleased(ctx, dbConn, ref, now)
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
State Evaluation Helpers
|
||||
============================== */
|
||||
|
||||
func isVoidable(info TransactionInfo) bool {
|
||||
return strings.EqualFold(info.transactionRes, types.ResultApproved) &&
|
||||
strings.EqualFold(info.transactionState, types.ResultStateUncommitted)
|
||||
}
|
||||
|
||||
func isAlreadyReleased(info TransactionInfo) bool {
|
||||
return strings.EqualFold(info.transactionState, types.ResultStateVoided) ||
|
||||
strings.EqualFold(info.transactionRes, types.ResultDeclined)
|
||||
}
|
||||
|
||||
func isSuccessfullyVoided(info TransactionInfo) bool {
|
||||
return strings.EqualFold(info.transactionRes, types.ResultDeclined) &&
|
||||
strings.EqualFold(info.transactionState, types.ResultStateVoided)
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
External Operations
|
||||
============================== */
|
||||
|
||||
func fetchDuePreauths(
|
||||
ctx context.Context,
|
||||
dbConn *sql.DB,
|
||||
now time.Time,
|
||||
) ([]types.PreauthRec, error) {
|
||||
|
||||
return db.GetDuePreauths(ctx, dbConn, now, 0)
|
||||
}
|
||||
|
||||
func markReleased(
|
||||
ctx context.Context,
|
||||
dbConn *sql.DB,
|
||||
ref string,
|
||||
now time.Time,
|
||||
) error {
|
||||
|
||||
return db.MarkPreauthReleased(ctx, dbConn, ref, now)
|
||||
}
|
||||
|
||||
func fetchTransactionInfo(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
ref string,
|
||||
) (TransactionInfo, error) {
|
||||
|
||||
var tr TransactionResultXML
|
||||
var info TransactionInfo
|
||||
|
||||
payload, _ := xml.Marshal(types.TransactionReferenceRequest{
|
||||
TransactionReference: ref,
|
||||
})
|
||||
|
||||
body, err := postXML(ctx, client, types.LinkTransactionInformation, payload)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
if err := tr.ParseTransactionResult(body); err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
info.FillFromTransactionResult(tr)
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func voidPreauth(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
ref string,
|
||||
) error {
|
||||
|
||||
var tr TransactionResultXML
|
||||
var info TransactionInfo
|
||||
|
||||
payload, _ := xml.Marshal(types.TransactionReferenceRequest{
|
||||
TransactionReference: ref,
|
||||
})
|
||||
|
||||
body, err := postXML(ctx, client, types.LinkVoidTransaction, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tr.ParseTransactionResult(body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
info.FillFromTransactionResult(tr)
|
||||
|
||||
if !strings.EqualFold(info.transactionRes, types.ResultApproved) {
|
||||
return fmt.Errorf("void rejected: %s", info.transactionRes)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/* ==============================
|
||||
Low-level HTTP
|
||||
============================== */
|
||||
|
||||
func postXML(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
url string,
|
||||
payload []byte,
|
||||
) ([]byte, error) {
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/xml")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
+143
-12
@@ -5,13 +5,13 @@ import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"image"
|
||||
|
||||
"image/color"
|
||||
"image/draw"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/alexbrainman/printer"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -19,6 +19,21 @@ import (
|
||||
)
|
||||
|
||||
type (
|
||||
CardholderReceipt struct {
|
||||
XMLName xml.Name `xml:"ReceiptData"`
|
||||
ReceiptEntries struct {
|
||||
ReceiptEntry []ReceiptEntryXML `xml:"ReceiptEntry"`
|
||||
} `xml:"ReceiptEntries"`
|
||||
}
|
||||
|
||||
ReceiptEntryXML struct {
|
||||
ReceiptEntryId string `xml:"ReceiptEntryId"`
|
||||
Value string `xml:"Value"`
|
||||
Label string `xml:"Label"`
|
||||
ReceiptItemType string `xml:"ReceiptItemType"`
|
||||
Priority string `xml:"Priority"`
|
||||
}
|
||||
|
||||
RoomDetailsRec struct {
|
||||
XMLName xml.Name `xml:"roomdetails"`
|
||||
Name string `xml:"customername"`
|
||||
@@ -54,11 +69,30 @@ type (
|
||||
}
|
||||
)
|
||||
|
||||
const (
|
||||
ESC = 0x1B
|
||||
GS = 0x1D
|
||||
CENTER = 0x01
|
||||
BOLD_ON = 0x01
|
||||
BOLD_OFF = 0x00
|
||||
LARGE_FONT = 0x11
|
||||
WIDER_FONT = 0x10
|
||||
NORMAL_FONT = 0x00
|
||||
)
|
||||
|
||||
var (
|
||||
Layout LayoutOptions
|
||||
PrinterName string
|
||||
)
|
||||
|
||||
func ParseCardholderReceipt(data []byte) ([]ReceiptEntryXML, error) {
|
||||
var tr CardholderReceipt
|
||||
if err := xml.Unmarshal(data, &tr); err != nil {
|
||||
return nil, fmt.Errorf("XML unmarshal: %w", err)
|
||||
}
|
||||
return tr.ReceiptEntries.ReceiptEntry, nil
|
||||
}
|
||||
|
||||
func BuildRoomTicket(details RoomDetailsRec) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
@@ -66,17 +100,6 @@ func BuildRoomTicket(details RoomDetailsRec) ([]byte, error) {
|
||||
write := func(b []byte) { buf.Write(b) }
|
||||
writeStr := func(s string) { buf.WriteString(s) }
|
||||
|
||||
const (
|
||||
ESC = 0x1B
|
||||
GS = 0x1D
|
||||
CENTER = 0x01
|
||||
BOLD_ON = 0x01
|
||||
BOLD_OFF = 0x00
|
||||
LARGE_FONT = 0x11
|
||||
WIDER_FONT = 0x10
|
||||
NORMAL_FONT = 0x00
|
||||
)
|
||||
|
||||
// 0) Hotel logo at top
|
||||
logoBytes, err := printLogo(Layout.LogoPath)
|
||||
if err != nil {
|
||||
@@ -144,6 +167,114 @@ func BuildRoomTicket(details RoomDetailsRec) ([]byte, error) {
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func PrintCardholderReceipt(cardholderReceipt string) error {
|
||||
receiptEntries, err := ParseCardholderReceipt([]byte(cardholderReceipt))
|
||||
if err != nil {
|
||||
return fmt.Errorf("ParseCardholderReceipt: %w", err)
|
||||
}
|
||||
|
||||
data, err := BuildCardholderReceipt(receiptEntries)
|
||||
if err != nil {
|
||||
return fmt.Errorf("BuildCardholderReceipt: %w", err)
|
||||
}
|
||||
|
||||
// Send to the Windows Epson TM-T82II via the printer package
|
||||
if err := SendToPrinter(data); err != nil {
|
||||
return fmt.Errorf("SendToPrinter: %w", err)
|
||||
}
|
||||
log.Info("Cardholder receipt printed successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
func BuildCardholderReceipt(entries []ReceiptEntryXML) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
write := func(b []byte) { buf.Write(b) }
|
||||
// writeStr := func(s string) { buf.WriteString(s) }
|
||||
writeln := func(s string) {
|
||||
buf.WriteString(s)
|
||||
buf.WriteByte('\n')
|
||||
}
|
||||
|
||||
// Build a lookup map by ReceiptEntryId
|
||||
m := make(map[string]ReceiptEntryXML, len(entries))
|
||||
for _, e := range entries {
|
||||
m[e.ReceiptEntryId] = e
|
||||
}
|
||||
|
||||
// Utility to center text
|
||||
// center := func(s string) {
|
||||
// write([]byte{ESC, 'a', CENTER})
|
||||
// writeln(s)
|
||||
// write([]byte{ESC, 'a', 0})
|
||||
// }
|
||||
|
||||
// Utility for bold lines
|
||||
// boldOn := func() { write([]byte{GS, '!', WIDER_FONT}) }
|
||||
// boldOff := func() { write([]byte{GS, '!', NORMAL_FONT}) }
|
||||
|
||||
// boldOn()
|
||||
|
||||
// 1) Header: CARDHOLDER COPY
|
||||
writeln(m["Recipient"].Value)
|
||||
// writeStr("\n\n")
|
||||
// 2) Merchant name
|
||||
writeln(m["MerchantName"].Value)
|
||||
// writeStr("\n\n")
|
||||
// 3) AID
|
||||
writeln("AID: " + m["Aid"].Value)
|
||||
|
||||
// 4) Card scheme & pan
|
||||
writeln(fmt.Sprintf("%s Card: %s", m["CardScheme"].Value, m["PanMasked"].Value))
|
||||
|
||||
// 5) PAN Seq No
|
||||
writeln("PAN Seq No: " + m["PanSequence"].Value)
|
||||
|
||||
// 6) Transaction source
|
||||
writeln(m["TransactionSource"].Value)
|
||||
|
||||
// 7) Transaction type (Sale/Account Verification)
|
||||
writeln(m["TransactionType"].Value)
|
||||
|
||||
// 8) Total
|
||||
// assuming value like "GBP1.50" — insert space after currency
|
||||
total := m["TotalAmount"].Value
|
||||
if !strings.HasPrefix(total, "GBP") && len(total) > 3 {
|
||||
total = total[:3] + " " + total[3:]
|
||||
}
|
||||
writeln("TOTAL: " + total)
|
||||
|
||||
// 9) Cardholder verification
|
||||
writeln(m["CardholderVerification"].Value)
|
||||
|
||||
// 10) Approved/Declined
|
||||
writeln(m["TransactionResult"].Value)
|
||||
|
||||
// 11) Auth code
|
||||
writeln("Auth Code: " + m["AuthCode"].Value)
|
||||
|
||||
// 12) Reference
|
||||
writeln("Ref: " + m["AuthReference"].Value)
|
||||
|
||||
// 13) Merchant & terminal IDs
|
||||
writeln("MID: " + m["MerchantIdMasked"].Value)
|
||||
writeln("TID: " + m["TerminalIdMasked"].Value)
|
||||
|
||||
// 14) Date/time
|
||||
writeln(m["AuthDateTime"].Value)
|
||||
|
||||
// 15) Retention message
|
||||
writeln(m["RetentionMessage"].Value)
|
||||
|
||||
// boldOff()
|
||||
|
||||
// finally feed & cut
|
||||
write([]byte{ESC, 'd', 7}) // Feed 5 lines
|
||||
write([]byte{GS, 'V', 1})
|
||||
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func printLogo(path string) ([]byte, error) {
|
||||
const maxLogoWidth = 384
|
||||
f, err := os.Open(path)
|
||||
|
||||
+100
-2
@@ -2,10 +2,108 @@
|
||||
|
||||
builtVersion is a const in main.go
|
||||
|
||||
#### 0.9.1 - 22 May 2024
|
||||
#### 1.1.2 - 02 February 2026
|
||||
added logging for unknown dispenser status positions
|
||||
|
||||
#### 1.1.1 - 02 February 2026
|
||||
added contionuous polling of the dispenser status every 8 seconds to update the card well status
|
||||
|
||||
#### 1.1.0 - 26 January 2026
|
||||
divided `/starttransaction` endpoint into two separate endpoints:
|
||||
`/takepreauth` to request preauthorization payment
|
||||
`/takepayment` to request taking payment
|
||||
added preauth releaser functionality to release preauthorization payments after a defined time period
|
||||
added db connection check before adding a transaction to the database
|
||||
and reconnection functionality if the connection to the database is lost
|
||||
added `/dispenserstatus` endpoint
|
||||
key card always stays at encoder position
|
||||
|
||||
#### 1.0.30 - 09 January 2026
|
||||
improved logging for preauth releaser
|
||||
|
||||
#### 1.0.29 - 08 January 2026
|
||||
added count down before exiting the preauth releaser 20 seconds
|
||||
|
||||
#### 1.0.28 - 10 December 2025
|
||||
added preauth releaser
|
||||
|
||||
#### 1.0.27 - 10 December 2025
|
||||
updated handling AmountTooSmall response from creditcall
|
||||
|
||||
#### 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
|
||||
`/starttransaction` - API payment endpoint to start a transaction
|
||||
|
||||
#### 0.9.1 - 22 May 2025
|
||||
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:
|
||||
- `/issuedoorcard` - encoding the door card for the room.
|
||||
- `/printroomticket` - printing the room ticket.
|
||||
@@ -0,0 +1,71 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/xml"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
DateOnly = "2006-01-02"
|
||||
CustomLayout = "2006-01-02 15:04:05 -0700"
|
||||
LinkTakePreauthorization = "http://127.0.0.1:18181/start-transaction/"
|
||||
LinkTakePayment = "http://127.0.0.1:18181/start-and-confirm-transaction/"
|
||||
LinkTransactionInformation = "http://127.0.0.1:18181/transaction-information/"
|
||||
LinkVoidTransaction = "http://127.0.0.1:18181/void-transaction/"
|
||||
// Transaction types
|
||||
SaleTransactionType = "sale"
|
||||
AccountVerificationType = "account verification"
|
||||
|
||||
// Transaction results
|
||||
ResultApproved = "approved"
|
||||
ResultDeclined = "declined"
|
||||
ResultCancelled = "cancelled"
|
||||
ResultPending = "pending"
|
||||
ResultStateUncommitted = "uncommitted"
|
||||
ResultStateVoided = "voided"
|
||||
ResultError = "error"
|
||||
CheckinSuccessfulEndpoint = "/successful" // Endpoint to send guest to after successful payment
|
||||
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"
|
||||
TransactionState = "TRANSACTION_STATE"
|
||||
ConfirmResult = "CONFIRM_RESULT"
|
||||
ConfirmErrors = "CONFIRM_ERRORS"
|
||||
TotalAmount = "TOTAL_AMOUNT"
|
||||
|
||||
// Log field keys
|
||||
LogFieldError = "error"
|
||||
LogFieldDescription = "description"
|
||||
LogResult = "transactionResult"
|
||||
)
|
||||
|
||||
type (
|
||||
TransactionReferenceRequest struct {
|
||||
XMLName xml.Name `xml:"TransactionReferenceRequest"`
|
||||
TransactionReference string `xml:"TransactionReference"`
|
||||
}
|
||||
|
||||
PreauthRec struct {
|
||||
Id int64
|
||||
TxnReference string
|
||||
TotalMinorUnits int64
|
||||
TotalAmount float64
|
||||
TxnDateTime time.Time
|
||||
DepartureDate time.Time // date-only (00:00)
|
||||
ReleaseDate time.Time
|
||||
Released bool
|
||||
ReleasedAt sql.NullTime
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user