完成授书游戏节点功能

This commit is contained in:
2024-11-21 17:23:07 +08:00
parent 4ea0af5bd7
commit 88f7d55930
11 changed files with 240 additions and 123 deletions

View File

@@ -1,24 +1,44 @@
package play
import (
"context"
"encoding/json"
"game-driver/config"
"game-driver/internal/middleware"
"game-driver/internal/routes/play/card_device"
"game-driver/internal/schema"
"game-driver/leaf"
"game-driver/pkg/utils"
"github.com/eclipse/paho.golang/paho"
"go.uber.org/zap"
"sync"
"time"
)
func PushCard() leaf.HandlerFunc {
device, err := card_device.New("gpiochip0")
if err != nil {
zap.S().Panicln("初始化发卡器失败: ", err)
type ResponseBody struct {
Empty int `json:"empty"`
Error int `json:"error"`
OutOk int `json:"out_ok"`
num int
}
func PushCard(ctx context.Context) leaf.HandlerFunc {
devices := make([]*card_device.Device, 0)
for _, group := range config.C.Game.CardGroups {
gv, _ := json.Marshal(group)
zap.S().Info("发卡指针初始化:", string(gv))
device, err := card_device.New("gpiochip0", group)
if err != nil {
zap.S().Panicln("初始化发卡器失败: ", err)
}
devices = append(devices, device)
}
go func() {
<-utils.GlobalMqttClient.Done()
device.Close()
<-ctx.Done()
for _, device := range devices {
device.Close()
}
}()
return func(c *leaf.Context) {
@@ -26,7 +46,9 @@ func PushCard() leaf.HandlerFunc {
var action time.Duration
if a, ok := payload.Game["action"]; ok {
action = time.Duration(a.(float64))
if v, ok := a.(float64); ok {
action = time.Duration(v)
}
}
// 等待组
@@ -44,7 +66,25 @@ func PushCard() leaf.HandlerFunc {
select {
case <-a:
case <-time.After(action * time.Second):
device.PushCard()
body := &ResponseBody{}
for _, device := range devices {
body.Empty += device.GetEmpty()
body.Error += device.GetError()
}
for i, device := range devices {
if device.GetEmpty() == 0 && device.GetError() == 0 && device.GetOutOk() == 0 {
body.num = i + 1
device.PushCard()
break
}
}
// 延迟1秒获取结果并发送消息
time.AfterFunc(time.Second, func() {
if body.num != 0 {
body.OutOk += devices[body.num-1].GetOutOk()
}
publishBody(ctx, c.Properties.ResponseTopic, body)
})
}
}()
@@ -52,3 +92,15 @@ func PushCard() leaf.HandlerFunc {
Default(c)
}
}
// 发布消息
func publishBody(ctx context.Context, topic string, body *ResponseBody) {
if topic != "" {
bytes, _ := json.Marshal(body)
utils.GlobalMqttClient.Publish(ctx, &paho.Publish{
Topic: topic,
Payload: bytes,
QoS: 1,
})
}
}