46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
package handler
|
||
|
||
import (
|
||
"crypto/rand"
|
||
"encoding/json"
|
||
"fmt"
|
||
"log"
|
||
"strings"
|
||
|
||
"github.com/qy/hw-ws-service/internal/connection"
|
||
)
|
||
|
||
// helloMessage 是硬件发来的 hello 握手消息。
|
||
type helloMessage struct {
|
||
MAC string `json:"mac"`
|
||
}
|
||
|
||
// HandleHello 处理硬件的 hello 握手消息。
|
||
// 校验 MAC 地址,分配 session_id,返回握手响应。
|
||
func HandleHello(conn *connection.Connection, raw []byte) error {
|
||
var msg helloMessage
|
||
if err := json.Unmarshal(raw, &msg); err != nil {
|
||
return fmt.Errorf("hello: invalid json: %w", err)
|
||
}
|
||
|
||
// MAC 地址与 URL 参数不一致时记录警告,但不拒绝连接
|
||
if msg.MAC != "" && !strings.EqualFold(msg.MAC, conn.DeviceID) {
|
||
log.Printf("[hello][%s] MAC mismatch: url=%s body=%s", conn.DeviceID, conn.DeviceID, msg.MAC)
|
||
}
|
||
|
||
sessionID := newSessionID()
|
||
conn.Handshake(sessionID)
|
||
|
||
return conn.SendJSON(map[string]string{
|
||
"type": "hello",
|
||
"status": "ok",
|
||
"session_id": sessionID,
|
||
})
|
||
}
|
||
|
||
func newSessionID() string {
|
||
b := make([]byte, 4)
|
||
rand.Read(b) //nolint:errcheck // crypto/rand.Read 在标准库中不会返回错误
|
||
return fmt.Sprintf("%x", b)
|
||
}
|