87 lines
2.3 KiB
Go
87 lines
2.3 KiB
Go
package server
|
|
|
|
import (
|
|
"log/slog"
|
|
"os"
|
|
"time"
|
|
|
|
"joylink.club/iot/config"
|
|
"joylink.club/iot/dto"
|
|
"joylink.club/iot/mqtt"
|
|
"joylink.club/iot/service"
|
|
)
|
|
|
|
var iqcs *IotQcServer
|
|
|
|
type IotQcServer struct {
|
|
qcMappingService service.IotQcMappingService
|
|
tasks []service.IScheduledTask
|
|
}
|
|
|
|
func (s *IotQcServer) start() error {
|
|
startMqttClient()
|
|
// 注册服务请求处理
|
|
s.registerReqHandlers()
|
|
// 启动服务状态发布定时任务
|
|
iqcs.tasks = append(iqcs.tasks, service.NewScheduledTask(pubServerState, 1*time.Second))
|
|
return nil
|
|
}
|
|
|
|
func (s *IotQcServer) registerReqHandlers() {
|
|
mqtt.RegIotQcServiceStartReqHandler(s.startIotQcMappingService)
|
|
mqtt.RegIotQcServiceStopReqHandler(s.stopIotQcMappingService)
|
|
mqtt.RegIotLogReqHandler(GetIotLog)
|
|
}
|
|
|
|
func (s *IotQcServer) startIotQcMappingService(req *dto.IotQcServiceStartReq) *dto.IotQcServiceCommonResp {
|
|
mqcs, err := service.NewModbusQcService(req.Config)
|
|
if err != nil {
|
|
slog.Error("创建Modbus驱采映射服务失败", "err", err)
|
|
return &dto.IotQcServiceCommonResp{Code: 1, Msg: err.Error()}
|
|
}
|
|
s.qcMappingService = mqcs
|
|
return &dto.IotQcServiceCommonResp{Code: 0, Msg: "成功"}
|
|
}
|
|
|
|
func (s *IotQcServer) stopIotQcMappingService(req *dto.IotQcServiceStopReq) *dto.IotQcServiceCommonResp {
|
|
if err := s.qcMappingService.Stop(); err != nil {
|
|
slog.Error("停止Modbus驱采映射服务失败", "err", err)
|
|
return &dto.IotQcServiceCommonResp{Code: 1, Msg: err.Error()}
|
|
}
|
|
return &dto.IotQcServiceCommonResp{Code: 0, Msg: "成功"}
|
|
}
|
|
|
|
func StartIotQcServer() {
|
|
iqcs = &IotQcServer{
|
|
tasks: []service.IScheduledTask{},
|
|
}
|
|
iqcs.start()
|
|
}
|
|
|
|
func pubServerState() {
|
|
state := dto.ServiceState_Normal
|
|
mqtt.PubIotServiceState(&dto.IotServiceState{
|
|
State: state,
|
|
})
|
|
}
|
|
|
|
func startMqttClient() {
|
|
config.LoadConfig()
|
|
mqttcfg := config.Cfg.Mqtt
|
|
cmc := &mqtt.IotMqttConfig{
|
|
AppId: mqttcfg.Topic.App,
|
|
BrokerUrl: mqttcfg.Address,
|
|
ClientId: mqttcfg.ClientId,
|
|
Username: mqttcfg.Username,
|
|
Password: mqttcfg.Password,
|
|
KeepAlive: mqttcfg.KeepAlive,
|
|
ConnectRetryDelay: mqttcfg.ConnectRetryDelay,
|
|
ConnectTimeout: mqttcfg.ConnectTimeout,
|
|
}
|
|
err := mqtt.Start(cmc)
|
|
if err != nil {
|
|
slog.Error("启动MQTT客户端失败", "error", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|