71 lines
1.9 KiB
Go
71 lines
1.9 KiB
Go
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
|
|
}
|