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 state *dto.IotServiceState } func (s *IotQcServer) start() error { startMqttClient() // 注册服务请求处理 s.registerReqHandlers() // 启动服务状态发布定时任务 iqcs.tasks = append(iqcs.tasks, service.NewScheduledTask(pubServerState, 1*time.Second)) return nil } func (s *IotQcServer) stateMonitor() *dto.IotServiceState { if s.qcMappingService != nil { if err := s.qcMappingService.ReportError(); err != nil { // slog.Error("Modbus驱采映射服务报错", "err", err) return &dto.IotServiceState{ State: dto.ServiceState_Error, ErrMsg: err.Error(), } } } return &dto.IotServiceState{ State: dto.ServiceState_Normal, } } 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{}, state: &dto.IotServiceState{ State: dto.ServiceState_Normal, }, } iqcs.start() } func pubServerState() { state := iqcs.stateMonitor() mqtt.PubIotServiceState(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) } }