Browse Source

mqtt对接,yaml配置文件修改,单灯控制器对接,环境传感采集数据上报等

chengqian 5 days ago
parent
commit
86458f4ac6

+ 14 - 18
config/config.yaml

@@ -1,22 +1,18 @@
-
-# Logger configurations.
 logger:
-  path: "./log"
-  level: "info"
-  name: "info"
-
+    level: info
+    name: info
+    path: ./log
 mqtt:
-  server: "tcp://106.52.134.22:1883"
-  id: "local_test"
-  user: "admin"
-  password: "admin"
-
+    id: smart_tunnel_edge
+    password: admin
+    server: tcp://118.253.180.18:1883
+    user: admin
 nums:
-  envNum: 1 #环境传感器的数量
-  optNum: 1 #光传感器的数量
-
+    envNum: 1
+    optNum: 1
 policy:
-  id: 1 #1代表随环境变化改变光照 2代表根据来车改变光照 3代表根据时间改变光照
-  control: "regulateLight" #regulateLight表示调光 regulateSwitch表示开关模组
-  startTime: ""
-  endTime: ""
+    control: regulateLight
+    endTime: "00:50"
+    id: 1
+    startTime: "00:50"
+tunnelId: LC12312312

+ 3 - 3
dev/devs.json

@@ -2,7 +2,7 @@
   "envDev": [
     {
       "Sn": "ddd",
-      "DevAddress": "01",
+      "Address": "01",
       "Name": "环境传感器",
       "TaskTime":5,
       "WaitTime": 0,
@@ -10,7 +10,7 @@
     },
     {
       "Sn": "xxx",
-      "DevAddress": "02",
+      "Address": "02",
       "Name": "光传感器",
       "TaskTime":5,
       "WaitTime":10,
@@ -19,7 +19,7 @@
   ],
   "lampDev": [
     {
-      "sn": "yyy",
+      "Sn": "yyy",
       "Address": "160000007012",
       "Name": "单灯控制器",
       "RadarId": 1,

+ 0 - 2
log/info.20250310.log

@@ -1,2 +0,0 @@
-{"level":"error","msg":"无法打开串口 COM: The system cannot find the file specified.","time":"2025-03-10 15:23:41.162"}
-{"level":"error","msg":"无法打开串口 COM3: The system cannot find the file specified.","time":"2025-03-10 16:47:14.422"}

+ 0 - 1
log/info.20250313.log

@@ -1 +0,0 @@
-{"level":"error","msg":"加载设备配置失败: 读取配置文件失败: open ./config/devs.json: The system cannot find the file specified.","time":"2025-03-13 17:06:14.181"}

+ 0 - 4
log/info.20250314.log

@@ -1,4 +0,0 @@
-{"level":"error","msg":"无法打开串口 COM223: The system cannot find the file specified.","time":"2025-03-14 09:07:33.767"}
-{"level":"error","msg":"无法打开串口 COM3: The system cannot find the file specified.","time":"2025-03-14 09:08:10.925"}
-{"level":"error","msg":"无法打开串口 COM3: Access is denied.","time":"2025-03-14 16:43:24.565"}
-{"level":"error","msg":"无法打开串口 COM3: Access is denied.","time":"2025-03-14 16:57:30.811"}

+ 4 - 0
log/info.20250324.log

@@ -0,0 +1,4 @@
+{"level":"info","msg":"MClient.OnConnectHandler:MQTT连接成功","time":"2025-03-24 16:16:29.607"}
+{"level":"error","msg":"parseTopic err","time":"2025-03-24 16:16:41.159"}
+{"level":"info","msg":"MClient.OnConnectHandler:MQTT连接成功","time":"2025-03-24 16:17:32.628"}
+{"level":"info","msg":"MClient.OnConnectHandler:MQTT连接成功","time":"2025-03-24 17:04:39.512"}

+ 3 - 0
log/info.20250326.log

@@ -0,0 +1,3 @@
+{"level":"info","msg":"MClient.OnConnectHandler:MQTT连接成功","time":"2025-03-26 09:25:14.630"}
+{"level":"info","msg":"MClient.OnConnectHandler:MQTT连接成功","time":"2025-03-26 16:27:34.081"}
+{"level":"info","msg":"MClient.OnConnectHandler:MQTT连接成功","time":"2025-03-26 17:07:35.499"}

File diff suppressed because it is too large
+ 67 - 0
log/info.20250327.log


+ 3 - 0
main.go

@@ -2,6 +2,7 @@ package main
 
 import (
 	"fmt"
+	"smart_tunnel_edge/mqtt"
 	"smart_tunnel_edge/util"
 	"smart_tunnel_edge/util/config"
 	"smart_tunnel_edge/util/logger"
@@ -10,6 +11,8 @@ import (
 func main() {
 	logger.InitLog() //初始化日志
 
+	mqtt.InitMqtt() //初始化mqtt
+
 	err := config.LoadSerialConfig()
 	if err != nil {
 		logger.Logger.Errorf("加载串口配置失败: %v", err)

+ 149 - 0
mqtt/mqtt_handle.go

@@ -0,0 +1,149 @@
+package mqtt
+
+import (
+	"encoding/json"
+	"errors"
+	"fmt"
+	"runtime"
+	"runtime/debug"
+	"smart_tunnel_edge/util/config"
+	"smart_tunnel_edge/util/logger"
+	"strconv"
+	"strings"
+	"sync"
+	"time"
+)
+
+func InitMqtt() {
+	MqttService = GetHandler()
+	MqttService.SubscribeTopics()
+	go MqttService.Handler()
+}
+
+var MqttService *MqttHandler
+
+type MqttHandler struct {
+	queue *MlQueue
+}
+
+var _handlerOnce sync.Once
+var _handlerSingle *MqttHandler
+
+func GetHandler() *MqttHandler {
+	_handlerOnce.Do(func() {
+		_handlerSingle = &MqttHandler{
+			queue: NewQueue(10000),
+		}
+	})
+	return _handlerSingle
+}
+
+func (o *MqttHandler) SubscribeTopics() {
+	GetMQTTMgr().Subscribe("smart_tunnel/#", AtLeastOnce, o.HandlerData)
+}
+
+func (o *MqttHandler) HandlerData(m Message) {
+	for {
+		ok, cnt := o.queue.Put(&m)
+		if ok {
+			break
+		} else {
+			logger.Logger.Errorf("HandlerData:查询队列失败,队列消息数量:%d", cnt)
+			runtime.Gosched()
+		}
+	}
+}
+
+func (o *MqttHandler) Handler() interface{} {
+	defer func() {
+		if err := recover(); err != nil {
+			go GetHandler().Handler()
+			logger.Logger.Errorf("MqttHandler.Handler:发生异常:%s", string(debug.Stack()))
+		}
+	}()
+	for {
+		msg, ok, quantity := o.queue.Get()
+		if !ok {
+			time.Sleep(10 * time.Millisecond)
+			continue
+		} else if quantity > 1000 {
+			logger.Logger.Warnf("数据队列累积过多,请注意优化,当前队列条数:%d", quantity)
+		}
+		m, ok := msg.(*Message)
+		fmt.Println("主题:", m.Topic())
+		if !ok {
+			continue
+		}
+		_, topic, err := ParseTopic(m.Topic())
+		if err != nil {
+			logger.Logger.Errorf("parseTopic err")
+			continue
+		}
+
+		switch topic {
+		case TopicLampControl:
+
+		case TopicTunnelTactics:
+			// 修改策略
+			num, _ := strconv.Atoi(m.PayloadString())
+			updates := map[string]interface{}{
+				"id": num,
+			}
+			if !updateConfigAndReload(updates) {
+				continue
+			}
+
+		case TopicTunnelTiming:
+			// 修改时控
+			var data map[string]interface{}
+			if err := json.Unmarshal([]byte(m.PayloadString()), &data); err != nil {
+				logger.Logger.Errorf("Error unmarshalling JSON: %v", err)
+				continue
+			}
+
+			updates := map[string]interface{}{
+				"startTime": data["startTime"],
+				"endTime":   data["endTime"],
+			}
+			if !updateConfigAndReload(updates) {
+				continue
+			}
+		}
+	}
+}
+
+func (o *MqttHandler) Publish(topic string, data interface{}) error {
+	return GetMQTTMgr().Publish(topic, data, AtLeastOnce)
+}
+
+func (o *MqttHandler) GetTopic(operation string) string {
+	tunnelId := config.Instance().TunnelId
+	return fmt.Sprintf("smart_tunnel/%s/%s", tunnelId, operation)
+}
+
+func ParseTopic(topic string) (sn string, operate string, err error) {
+	strList := strings.Split(topic, "/")
+	sn = strList[1]
+	operate = strList[2]
+	if len(strList) != 3 {
+		return "", "", errors.New("不支持的topic")
+	}
+	return
+}
+
+func updateConfigAndReload(updates map[string]interface{}) bool {
+	if err := config.UpdateYAMLConfig(updates); err != nil {
+		logger.Logger.Errorf("修改yaml失败 err: %v", err)
+		return false
+	}
+	config.ReloadConfig()
+	return true
+}
+
+const (
+	TopicGatherDataEnv = "gatherDataEnv"
+	TopicGatherDataOpt = "gatherDataOpt"
+	TopicTunnelTactics = "tunnelTactics"
+	TopicTunnelTiming  = "tunnelTiming"
+	TopicLampControl   = "lampControl"
+)

+ 16 - 4
radar_test.go

@@ -3,7 +3,7 @@ package main
 import (
 	"encoding/hex"
 	"fmt"
-	"smart_tunnel_edge/protocol/envSensor"
+	"smart_tunnel_edge/util/config"
 	"testing"
 )
 
@@ -39,9 +39,19 @@ func Test_verify(t *testing.T) {
 	//fmt.Println("len++", len(xxx))
 	//fmt.Println(",,,", xxx[0:2], xxx[8:16])
 
-	dataPack := envSensor.DataPack{Address: "02", Start: []byte{0x00, 0x06}, DataLen: []byte{0x00, 0x01}}
-	command := dataPack.GetEnvGatherCommand()
-	fmt.Println("+++++", hex.EncodeToString(command.Bytes()))
+	//dataPack := envSensor.DataPack{Address: "02", Start: []byte{0x00, 0x06}, DataLen: []byte{0x00, 0x01}}
+	//command := dataPack.GetEnvGatherCommand()
+	//fmt.Println("+++++", hex.EncodeToString(command.Bytes()))
+
+	updates := map[string]interface{}{
+		"id":        1,
+		"startTime": "00:30",
+		"endTime":   "00:20",
+	}
+	err := config.UpdateYAMLConfig(updates)
+	if err != nil {
+		fmt.Println(err)
+	}
 
 }
 
@@ -56,3 +66,5 @@ func parseHexString(hexStr string) string {
 	// 将字节数组转换为对应的字符
 	return string(bytes)
 }
+
+// UpdateYAMLConfig 用于更新 YAML 配置文件中的多个值

+ 0 - 104
service/mqtt_handle.go

@@ -1,104 +0,0 @@
-package service
-
-import (
-	"errors"
-	"fmt"
-	"runtime"
-	"runtime/debug"
-	"smart_tunnel_edge/mqtt"
-	"smart_tunnel_edge/util/logger"
-	"strings"
-	"sync"
-	"time"
-)
-
-func InitMqtt() {
-	MqttService = GetHandler()
-	MqttService.SubscribeTopics()
-	go MqttService.Handler()
-}
-
-var MqttService *MqttHandler
-
-type MqttHandler struct {
-	queue *mqtt.MlQueue
-}
-
-var _handlerOnce sync.Once
-var _handlerSingle *MqttHandler
-
-func GetHandler() *MqttHandler {
-	_handlerOnce.Do(func() {
-		_handlerSingle = &MqttHandler{
-			queue: mqtt.NewQueue(10000),
-		}
-	})
-	return _handlerSingle
-}
-
-func (o *MqttHandler) SubscribeTopics() {
-	mqtt.GetMQTTMgr().Subscribe("smart_tunnel/#", mqtt.AtLeastOnce, o.HandlerData)
-}
-
-func (o *MqttHandler) HandlerData(m mqtt.Message) {
-	for {
-		ok, cnt := o.queue.Put(&m)
-		if ok {
-			break
-		} else {
-			logger.Logger.Errorf("HandlerData:查询队列失败,队列消息数量:%d", cnt)
-			runtime.Gosched()
-		}
-	}
-}
-
-func (o *MqttHandler) Handler() interface{} {
-	defer func() {
-		if err := recover(); err != nil {
-			go GetHandler().Handler()
-			logger.Logger.Errorf("MqttHandler.Handler:发生异常:%s", string(debug.Stack()))
-		}
-	}()
-	for {
-		msg, ok, quantity := o.queue.Get()
-		if !ok {
-			time.Sleep(10 * time.Millisecond)
-			continue
-		} else if quantity > 1000 {
-			logger.Logger.Warnf("数据队列累积过多,请注意优化,当前队列条数:%d", quantity)
-		}
-		m, ok := msg.(*mqtt.Message)
-		if !ok {
-			continue
-		}
-
-		_, topic, err := parseTopic(m.Topic())
-		if err != nil {
-			logger.Logger.Errorf("parseTopic err")
-			continue
-		}
-		switch topic {
-		case TopicDeviceGateway:
-
-		case TopicDeviceCamera:
-
-		default:
-			fmt.Println("我是主题:::", topic)
-		}
-	}
-}
-
-func parseTopic(topic string) (string, string, error) {
-	strList := strings.Split(topic, "/")
-	if len(strList) < 4 {
-		return "", "", errors.New("不支持的topic")
-	}
-	topic = strings.Join(strList[2:], "/")
-	return strList[1], topic, nil
-}
-
-const (
-	TopicDeviceGateway = "device/gateway"
-	TopicDeviceCamera  = "device/camera"
-	TopicDeviceScreens = "device/screens"
-)

+ 70 - 25
util/config/config.go

@@ -16,20 +16,31 @@ var (
 	DevConfig    Devs
 )
 
+// 初始化配置,确保只初始化一次
 func init() {
 	once.Do(func() {
-		var conf config
-		filePath := "./config/config.yaml"
-		if f, err := os.Open(filePath); err != nil {
+		loadConfig() // 加载配置文件
+	})
+}
+
+// 重新加载配置文件
+func ReloadConfig() {
+	loadConfig() // 加载配置文件
+}
+
+// 加载配置文件
+func loadConfig() {
+	var conf config
+	filePath := "./config/config.yaml"
+	if f, err := os.Open(filePath); err != nil {
+		panic(err)
+	} else {
+		err := yaml.NewDecoder(f).Decode(&conf)
+		if err != nil {
 			panic(err)
-		} else {
-			err := yaml.NewDecoder(f).Decode(&conf)
-			if err != nil {
-				panic(err)
-			}
 		}
-		instance = &conf
-	})
+	}
+	instance = &conf
 }
 
 // 获取配置文档实例
@@ -38,10 +49,11 @@ func Instance() *config {
 }
 
 type config struct {
-	Logger logger `yaml:"logger"`
-	Mqtt   mqtt   `yaml:"mqtt"`
-	Nums   nums   `yaml:"nums"`
-	Policy policy `yaml:"policy"`
+	TunnelId string `yaml:"tunnelId"`
+	Logger   logger `yaml:"logger"`
+	Mqtt     mqtt   `yaml:"mqtt"`
+	Nums     nums   `yaml:"nums"`
+	Policy   policy `yaml:"policy"`
 }
 
 type logger struct {
@@ -63,10 +75,10 @@ type nums struct {
 }
 
 type policy struct {
-	Id        int    `json:"id"`
-	Control   string `json:"control"`
-	StartTime string `json:"startTime"`
-	EndTime   string `json:"endTime"`
+	Id        int    `yaml:"id"`
+	Control   string `yaml:"control"`
+	StartTime string `yaml:"startTime"`
+	EndTime   string `yaml:"endTime"`
 }
 
 func LoadSerialConfig() error {
@@ -119,18 +131,51 @@ type Devs struct {
 }
 
 type EnvDev struct {
-	Sn         string `json:"sn"`         //设备SN
-	DevAddress string `json:"devAddress"` //设备地址
-	Name       string `json:"name"`       //设备名称
-	TaskTime   uint   `json:"taskTime"`   //设备采集周期,单位分钟
-	WaitTime   uint   `json:"waitTime"`   //等待时间,单位秒
-	SerialId   int8   `json:"serialId"`   //串口id
+	Sn       string `json:"sn"`       //设备SN
+	Address  string `json:"address"`  //设备地址
+	Name     string `json:"name"`     //设备名称
+	TaskTime uint   `json:"taskTime"` //设备采集周期,单位分钟
+	WaitTime uint   `json:"waitTime"` //等待时间,单位秒
+	SerialId int8   `json:"serialId"` //串口id
 }
 
 type LampDev struct {
 	Sn       string `json:"sn"`       //设备SN
 	Address  string `json:"address"`  //设备地址
 	Name     string `json:"name"`     //设备名称
-	RadarId  int    `json:"radarId"`  //雷达id(用于在雷达监测到来车后,控制雷达在的那一路的单灯控制器)
+	RadarId  int8   `json:"radarId"`  //雷达id(用于在雷达监测到来车后,控制雷达在的那一路的单灯控制器)
 	SerialId int8   `json:"serialId"` // 串口id
 }
+
+// 读取、更新并保存配置的统一方法
+func UpdateYAMLConfig(updates map[string]interface{}) error {
+	data, err := ioutil.ReadFile("./config/config.yaml")
+	if err != nil {
+		return fmt.Errorf("读取文件时出错: %w", err)
+	}
+
+	var yamlData map[string]interface{}
+	err = yaml.Unmarshal(data, &yamlData)
+	if err != nil {
+		return fmt.Errorf("解析 YAML 数据时出错: %w", err)
+	}
+
+	pl, ok := yamlData["policy"].(map[string]interface{})
+	if !ok {
+		return fmt.Errorf("找不到 'policy' 字段")
+	}
+
+	for key, value := range updates {
+		pl[key] = value
+	}
+	updatedData, err := yaml.Marshal(yamlData)
+	if err != nil {
+		return fmt.Errorf("编码 YAML 数据时出错: %w", err)
+	}
+	err = ioutil.WriteFile("./config/config.yaml", updatedData, 0644)
+	if err != nil {
+		return fmt.Errorf("写入文件时出错: %w", err)
+	}
+
+	return nil
+}

+ 47 - 3
util/devmgr.go

@@ -2,6 +2,7 @@ package util
 
 import (
 	"smart_tunnel_edge/protocol/envSensor"
+	"smart_tunnel_edge/protocol/lampControl"
 	"smart_tunnel_edge/util/config"
 	"smart_tunnel_edge/util/logger"
 	"sync"
@@ -10,6 +11,11 @@ import (
 
 var mu sync.Mutex
 
+const (
+	RegulateLight  = "regulateLight"
+	RegulateSwitch = "regulateSwitch"
+)
+
 func StartDeviceCollection(dev *config.EnvDev) {
 	coverTime := dev.TaskTime
 	ticker := time.NewTicker(time.Duration(coverTime) * time.Minute)
@@ -22,9 +28,9 @@ func StartDeviceCollection(dev *config.EnvDev) {
 				time.Sleep(time.Duration(dev.WaitTime) * time.Second)
 			}
 			//获取指令
-			dataPack := envSensor.DataPack{Address: dev.DevAddress, Start: []byte{0x01, 0xF8}, DataLen: []byte{0x00, 0x08}}
+			dataPack := envSensor.DataPack{Address: dev.Address, Start: []byte{0x01, 0xF8}, DataLen: []byte{0x00, 0x08}}
 			if dev.Name == "光传感器" {
-				dataPack = envSensor.DataPack{Address: dev.DevAddress, Start: []byte{0x00, 0x06}, DataLen: []byte{0x00, 0x01}}
+				dataPack = envSensor.DataPack{Address: dev.Address, Start: []byte{0x00, 0x06}, DataLen: []byte{0x00, 0x01}}
 			}
 			buffer := dataPack.GetEnvGatherCommand()
 			mu.Lock()
@@ -35,7 +41,7 @@ func StartDeviceCollection(dev *config.EnvDev) {
 			}
 			write, err := port.Write(buffer.Bytes())
 			mu.Unlock()
-			if write < 0 && err != nil {
+			if write < 0 || err != nil {
 				logger.Logger.Errorf("设备:%v采集数据失败,错误:%v", dev.Sn, err)
 				continue
 			}
@@ -47,3 +53,41 @@ func StartDeviceCollection(dev *config.EnvDev) {
 //func EnvGather(address string) {
 //
 //}
+
+func OperationLampSwitchJudge(radarId int8, brightness int) {
+	if config.Instance().Policy.Control == RegulateLight {
+		SetLampBright(radarId, brightness)
+	}
+}
+
+// 单灯控制器调光方法
+func SetLampBright(radarId int8, brightness int) {
+	var wg sync.WaitGroup
+	for _, dev := range config.DevConfig.LampDevs {
+		if dev.RadarId != radarId {
+			continue
+		}
+		wg.Add(1)
+		newDev := dev
+		go func() {
+			defer wg.Done()
+			// 获取对应的串口
+			port, err := GetSerialPort(newDev.SerialId)
+			if err != nil {
+				logger.Logger.Infof("获取串口失败,设备编号:%v,错误:%v", newDev.Sn, err)
+				return
+			}
+			buffer := lampControl.DataPack{Addr: newDev.Address}.GetLampSetBrightCommand(brightness)
+
+			mu.Lock() // 锁定串口操作
+			write, err := port.Write(buffer.Bytes())
+			mu.Unlock()
+
+			if write < 0 || err != nil {
+				logger.Logger.Errorf("单灯:%v操作失败,错误:%v", newDev.Sn, err)
+				return
+			}
+		}()
+	}
+	wg.Wait()
+}

+ 13 - 0
util/model.go

@@ -0,0 +1,13 @@
+package util
+
+type EnvData struct {
+	Sn          string  `json:"sn"`
+	Temperature float64 `json:"temperature"`
+	Humidity    float64 `json:"humidity"`
+	Illuminance int64   `json:"illuminance"`
+}
+
+type OpticalData struct {
+	Sn          string `json:"sn"`
+	Illuminance int64  `json:"illuminance"`
+}

+ 55 - 25
util/serialmgr.go

@@ -2,10 +2,12 @@ package util
 
 import (
 	"encoding/hex"
+	"encoding/json"
 	"errors"
 	"fmt"
 	"github.com/tarm/serial"
 	"log"
+	"smart_tunnel_edge/mqtt"
 	"smart_tunnel_edge/util/config"
 	"smart_tunnel_edge/util/logger"
 	"strconv"
@@ -32,11 +34,6 @@ var (
 	lightDuration  = 2 * time.Minute // 灯亮的持续时间(2分钟)
 )
 
-const (
-	RegulateLight  = "regulateLight"
-	RegulateSwitch = "regulateSwitch"
-)
-
 func GetSerialPort(serialID int8) (*serial.Port, error) {
 	port, exists := serialPort[serialID]
 	if !exists {
@@ -96,52 +93,80 @@ func listenPort(portCode int8, port *serial.Port) {
 				shiDu, _ := strconv.ParseInt(dataString[6:10], 16, 0)
 				wenDu, _ := strconv.ParseInt(dataString[10:14], 16, 0)
 				gz, _ := strconv.ParseInt(dataString[30:38], 16, 0)
-				fmt.Printf("湿度 :%v %%RH", float64(shiDu)/10.0)
-				fmt.Printf("温度 :%v ℃", float64(wenDu)/10.0)
-				fmt.Printf("光照度 :%v Lux \n", gz)
-
 				if _, exists := env[dataString[0:2]]; !exists {
 					env[dataString[0:2]] = gz
 				}
 
-				//TODO 将采集数据上报
+				data := EnvData{Temperature: float64(wenDu) / 10.0, Humidity: float64(shiDu) / 10.0, Illuminance: gz}
+				for _, dev := range config.DevConfig.EnvDevs {
+					if dev.Address == dataString[0:2] {
+						data.Sn = dev.Sn
+						break
+					}
+				}
+
+				jsonData, _ := json.Marshal(data)
+				topic := mqtt.MqttService.GetTopic(mqtt.TopicGatherDataEnv)
+				err := mqtt.MqttService.Publish(topic, jsonData)
+				if err != nil {
+					logger.Logger.Errorf("MQTT Publish err = %s", err.Error())
+					continue
+				}
 
 			case len(dataString) == 14 && dataString[2:6] == "0302": //光照传感器数据
 				fmt.Printf("光传感:")
 				gz, _ := strconv.ParseInt(dataString[6:10], 16, 0)
-				fmt.Printf("光照度 :%v Lux \n", gz)
 
 				if _, exists := env[dataString[0:2]]; !exists {
 					opt[dataString[0:2]] = gz
 				}
 
-				//TODO 将采集数据上报
+				data := OpticalData{Illuminance: gz}
+				for _, dev := range config.DevConfig.EnvDevs {
+					if dev.Address == dataString[0:2] {
+						data.Sn = dev.Sn
+						break
+					}
+				}
+
+				jsonData, _ := json.Marshal(data)
+				topic := mqtt.MqttService.GetTopic(mqtt.TopicGatherDataOpt)
+				err := mqtt.MqttService.Publish(topic, jsonData)
+				if err != nil {
+					logger.Logger.Errorf("MQTT Publish err = %s", err.Error())
+					continue
+				}
 
 			case len(dataString) == 16 && dataString[0:2] == "78" && dataString[8:16] == "40790d0a": //雷达数据
 				dataBytes, _ := hex.DecodeString(dataString)
 				speed, _ := strconv.Atoi(string(dataBytes)[1:4])
-				if speed > 5 && config.Instance().Policy.Id == 2 { //速度大于5且策略为根据来车调光(2代表根据来车改变光照)
-					now := time.Now()
-					if config.Instance().Policy.Control == RegulateLight { //判断操作策略
-						//调光
-						if isLightOperate { //如果已经操作
-							if now.Sub(lastCarTime) <= lightDuration { // 并且两分钟内再来车,延长计时
-								timer.Reset(lightDuration)
-							}
-						} else { //没操作,就去操作
-
+				// 配置实例
+				policy := config.Instance().Policy
+				if speed > 5 && policy.Id == 2 { // 速度大于5且策略为根据来车调光(2代表根据来车改变光照)
+					now := time.Now() // 记录来车时间
+					// 如果已经操作过灯
+					if isLightOperate {
+						// 如果在两分钟内再来车,延长计时
+						if now.Sub(lastCarTime) <= lightDuration {
+							timer.Reset(lightDuration)
 						}
 					} else {
-						//开关模组
+						OperationLampSwitchJudge(portCode, 100)
+						isLightOperate = true
+						timer = time.AfterFunc(lightDuration, func() {
+							OperationLampSwitchJudge(portCode, 20)
+							isLightOperate = false
+						})
 					}
-					lastCarTime = now //更新最后来车时间
+					// 更新最后来车时间
+					lastCarTime = now
 				}
 				continue
 				//default:
 				//	// 其他情况可以处理默认数据
 				//	fmt.Printf("错误数据: %s \n", dataString)
 			}
-			if config.Instance().Nums.EnvNum == len(env) && config.Instance().Nums.OptNum == len(opt) {
+			if config.Instance().Policy.Id == 1 && config.Instance().Nums.EnvNum == len(env) && config.Instance().Nums.OptNum == len(opt) {
 
 				envAverage := calculateAverage(env)
 				optAverage := calculateAverage(opt)
@@ -150,6 +175,11 @@ func listenPort(portCode int8, port *serial.Port) {
 				fmt.Println("光照平均值:", optAverage)
 
 				//TODO 作比较,进行灯控操作并清空切片
+				if envAverage-6 >= 0 {
+
+				} else {
+
+				}
 
 				env = make(map[string]int64)
 				opt = make(map[string]int64)

+ 36 - 22
util/task.go

@@ -1,12 +1,7 @@
 package util
 
 import (
-	"encoding/hex"
-	"fmt"
 	"github.com/robfig/cron"
-	"smart_tunnel_edge/protocol/lampControl"
-	"smart_tunnel_edge/util/config"
-	"smart_tunnel_edge/util/logger"
 )
 
 var commandQueue = make(chan []byte, 5)
@@ -16,23 +11,42 @@ func TimeTasks() {
 	//每3分钟监测状态
 	//_ = c.AddFunc("0 0/5 * * * ? ", func() {
 	_ = c.AddFunc("0/5 * * * * ?", func() {
-		for _, dev := range config.DevConfig.LampDevs {
-			pack := lampControl.DataPack{Addr: dev.Address, Data: []byte{0x00}}
-			command := pack.GetLampTurnOnOffCommand()
-			//dataPack := lampControl.DataPack{Addr: dev.Address}
-			//command := dataPack.GetLampSetBrightCommand(10)
-			fmt.Println("命令:", hex.EncodeToString(command.Bytes()))
-			port, err := GetSerialPort(dev.SerialId)
-			if err != nil {
-				logger.Logger.Infof(err.Error())
-				continue
-			}
-			write, err := port.Write(command.Bytes())
-			fmt.Println("write.....,", write)
-			if err != nil {
-				fmt.Println(err.Error())
-			}
-		}
+		//for _, dev := range config.DevConfig.LampDevs {
+		//	pack := lampControl.DataPack{Addr: dev.Address, Data: []byte{0x01}}
+		//	command := pack.GetLampTurnOnOffCommand()
+		//	//dataPack := lampControl.DataPack{Addr: dev.Address}
+		//	//command := dataPack.GetLampSetBrightCommand(10)
+		//	fmt.Println("命令:", hex.EncodeToString(command.Bytes()))
+		//	port, err := GetSerialPort(dev.SerialId)
+		//	if err != nil {
+		//		logger.Logger.Infof(err.Error())
+		//		continue
+		//	}
+		//	write, err := port.Write(command.Bytes())
+		//	fmt.Println("write.....,", write)
+		//	if err != nil {
+		//		fmt.Println(err.Error())
+		//	}
+		//}
+		//data := EnvData{Temperature: float64(98) / 10.0, Humidity: float64(345) / 10.0, Illuminance: 666}
+		//
+		//jsonData, _ := json.Marshal(data)
+		//topic := mqtt.MqttService.GetTopic(mqtt.TopicGatherDataEnv)
+		//err := mqtt.MqttService.Publish(topic, jsonData)
+		//if err != nil {
+		//	logger.Logger.Errorf("MQTT Publish err = %s", err.Error())
+		//}
+		//parseTopic, s, _ := mqtt.ParseTopic("smart_tunnel/xyzSuiDao/gatherDataEnv")
+		//fmt.Println("====", parseTopic)
+		//fmt.Println("====", s)
+		//
+		//fmt.Println("主题:", topic)
+
+		//fmt.Println("实时更新。。。", config.Instance().Policy.StartTime)
+		//fmt.Println("实时更新。。。", config.Instance().Mqtt.Server)
+		//config.ReloadConfig()
+		//fmt.Println(config.Instance().Policy.Id == 2)
+		//fmt.Println(config.Instance().Policy.Control == "regulateSwitch")
 	})
 	c.Start()
 }