package service import ( "fmt" "server/dao" "server/logger" "server/modbus" "server/model" "server/utils" ) func SaveData(data []dao.Region) error { if len(data) == 0 { return fmt.Errorf("数据不能为空") } err := utils.SaveData("static/data.json", data) if err != nil { return err } // Remove the redundant return err statement. return nil // Return nil to indicate success } func DeviceLoopSwitch(deviceLoop dao.DeviceLoop) error { data := modbus.DeviceLoopSwitch(deviceLoop.ID, deviceLoop.State) if model.ConnectionMap[deviceLoop.DeviceId] == nil { return fmt.Errorf("设备连接丢失") } _, dev, _ := utils.GetDataByDeviceId(deviceLoop.DeviceId) if dev.State == 0 { return fmt.Errorf("设备离线无法操作") } err := utils.WriteDevice(dev.Sn, data, model.ConnectionMap[deviceLoop.DeviceId]) if err != nil { fmt.Printf("Write device error: %v\n", err) return err } return nil } func DeviceSwitch(req model.DeviceRequest) error { data := modbus.DeviceSwitch(req.Device.LoopNumber, req.State) if model.ConnectionMap[req.Device.Sn] == nil { return fmt.Errorf("设备连接丢失") } err := utils.WriteDevice(req.Device.Sn, data, model.ConnectionMap[req.Device.Sn]) if err != nil { logger.Get().Errorf("Write device error: %v\n", err) return err } return nil } func DeviceBatchSwitch(req model.DevicesRequest) error { for _, device := range req.Devices { if device.State == 0 { continue } data := modbus.DeviceSwitch(device.LoopNumber, req.State) if model.ConnectionMap[device.Sn] == nil { return fmt.Errorf("设备连接丢失") } err := utils.WriteDevice(device.Sn, data, model.ConnectionMap[device.Sn]) if err != nil { fmt.Printf("Write device error: %v\n", err) return err } } return nil } // GetOnlineDevice 获取在线设备 总共设备 在线率 func GetOnlineDevice() (total, online int) { devices, err := utils.GetOnlineDevices() if err != nil { logger.Get().Errorf("GetOnlineDevices err = %s\n", err.Error()) return } allDevices, err := utils.GetAllDevices() if err != nil { logger.Get().Errorf("GetAllDevices err = %s\n", err.Error()) return } return len(allDevices), len(devices) } func GetSunDevices() (devices []dao.Device, err error) { allDevices, err := utils.GetAllDevices() if err != nil { return nil, err } for _, device := range allDevices { if device.IsSun { devices = append(devices, device) } } return } func UpdateRegisterAddress(deviceId string) error { err := utils.WriteDevice(deviceId, modbus.UpdateRegisterAddress(), model.ConnectionMap[deviceId]) if err != nil { logger.Get().Errorf("UpdateRegisterAddress error: %v\n", err) return err } return nil }