Browse Source

雷达、环境传感、单灯控制器数据处理、串口监听等

chengqian 2 weeks ago
parent
commit
1659f56d6d

+ 6 - 0
.idea/inspectionProfiles/Project_Default.xml

@@ -0,0 +1,6 @@
+<component name="InspectionProjectProfileManager">
+  <profile version="1.0">
+    <option name="myName" value="Project Default" />
+    <inspection_tool class="LanguageDetectionInspection" enabled="false" level="WARNING" enabled_by_default="false" />
+  </profile>
+</component>

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
+</project>

+ 3 - 0
build.bat

@@ -0,0 +1,3 @@
+set GOARCH=amd64
+set GOOS=windows
+go build -o build/smart_tunnel.exe ./

+ 10 - 5
config/config.yaml

@@ -10,8 +10,13 @@ mqtt:
   id: "local_test"
   user: "admin"
   password: "admin"
-  
-device:
-  informant: "5b6d335d"
-  speech_speed: "5b73355d"
-  speech_volume: "5b7631305d"
+
+nums:
+  envNum: 1 #环境传感器的数量
+  optNum: 1 #光传感器的数量
+
+policy:
+  id: 1 #1代表随环境变化改变光照 2代表根据来车改变光照 3代表根据时间改变光照
+  control: "regulateLight" #regulateLight表示调光 regulateSwitch表示开关模组
+  startTime: ""
+  endTime: ""

+ 3 - 15
config/serial.json

@@ -3,24 +3,12 @@
     "1":{
       "Code":1,
       "Interface":"RS485_1",
-      "Address":"/dev/ttymxc4",
+      "Address":"COM3",
       "BaudRate":9600,
       "DataBits":8,
       "StopBits":1,
-      "Parity":"N",
-      "Timeout":3000,
-      "ProtocolType":0
-    },
-    "2":{
-      "Code":2,
-      "Interface":"RS485_2",
-      "Address":"/dev/ttymxc6",
-      "BaudRate":9600,
-      "DataBits":8,
-      "StopBits":1,
-      "Parity":"N",
-      "Timeout":3000,
-      "ProtocolType":1
+      "Parity":"E",
+      "Timeout":3000
     }
   }
 }

+ 29 - 0
dev/devs.json

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

+ 0 - 15
dev/environmentalSensor.json

@@ -1,15 +0,0 @@
-{
-  "dev": [
-    {
-      "Code": 1,
-      "DevID": 1,
-      "DevCode": "B542100015",
-      "TID": 4,
-      "Name": "环境传感器",
-      "SendCloud":5000,
-      "WaitTime": 1000,
-      "ProtocolType": 0,
-      "DevType": 5
-    }
-  ]
-}

+ 0 - 15
dev/opticalSensor.json

@@ -1,15 +0,0 @@
-{
-  "dev": [
-    {
-      "Code": 1,
-      "DevID": 1,
-      "DevCode": "B542100015",
-      "TID": 4,
-      "Name": "光传感器",
-      "SendCloud":5000,
-      "WaitTime": 1000,
-      "ProtocolType": 0,
-      "DevType": 5
-    }
-  ]
-}

+ 4 - 23
go.mod

@@ -7,47 +7,28 @@ require (
 	github.com/eclipse/paho.mqtt.golang v1.5.0
 	github.com/google/uuid v1.2.0
 	github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f
+	github.com/robfig/cron v1.2.0
 	github.com/sirupsen/logrus v1.9.3
+	github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
+	github.com/valyala/bytebufferpool v1.0.0
 	gopkg.in/yaml.v3 v3.0.1
 )
 
 require (
-	github.com/bytedance/sonic v1.11.6 // indirect
-	github.com/bytedance/sonic/loader v0.1.1 // indirect
-	github.com/cloudwego/base64x v0.1.4 // indirect
-	github.com/cloudwego/iasm v0.2.0 // indirect
 	github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect
 	github.com/fogleman/gg v1.3.0 // indirect
-	github.com/gabriel-vasile/mimetype v1.4.3 // indirect
-	github.com/gin-contrib/sse v0.1.0 // indirect
-	github.com/gin-gonic/gin v1.10.0 // indirect
-	github.com/go-playground/locales v0.14.1 // indirect
-	github.com/go-playground/universal-translator v0.18.1 // indirect
-	github.com/go-playground/validator/v10 v10.20.0 // indirect
-	github.com/goccy/go-json v0.10.2 // indirect
 	github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
 	github.com/gorilla/websocket v1.5.3 // indirect
 	github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect
 	github.com/jonboulle/clockwork v0.5.0 // indirect
-	github.com/json-iterator/go v1.1.12 // indirect
-	github.com/klauspost/cpuid/v2 v2.2.7 // indirect
-	github.com/leodido/go-urn v1.4.0 // indirect
 	github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570 // indirect
 	github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 // indirect
-	github.com/mattn/go-isatty v0.0.20 // indirect
-	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
-	github.com/modern-go/reflect2 v1.0.2 // indirect
-	github.com/pelletier/go-toml/v2 v2.2.2 // indirect
 	github.com/pkg/errors v0.9.1 // indirect
+	github.com/stretchr/testify v1.9.0 // indirect
 	github.com/tebeka/strftime v0.1.5 // indirect
-	github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
-	github.com/ugorji/go/codec v1.2.12 // indirect
-	golang.org/x/arch v0.8.0 // indirect
 	golang.org/x/crypto v0.25.0 // indirect
 	golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d // indirect
 	golang.org/x/net v0.27.0 // indirect
 	golang.org/x/sync v0.7.0 // indirect
 	golang.org/x/sys v0.22.0 // indirect
-	golang.org/x/text v0.16.0 // indirect
-	google.golang.org/protobuf v1.34.1 // indirect
 )

+ 7 - 57
go.sum

@@ -1,11 +1,3 @@
-github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
-github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
-github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
-github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
-github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
-github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
-github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
-github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -17,24 +9,9 @@ github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 h1:Ghm4eQYC0nEPnSJ
 github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239/go.mod h1:Gdwt2ce0yfBxPvZrHkprdPPTTS3N5rwmLE8T22KBXlw=
 github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
 github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
-github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
-github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
-github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
-github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
-github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
-github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
-github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
-github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
-github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
-github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
-github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
-github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
-github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
-github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
 github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
 github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
 github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
-github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
 github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
 github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
 github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
@@ -43,57 +20,37 @@ github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 h1:IPJ3dvxmJ4uc
 github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869/go.mod h1:cJ6Cj7dQo+O6GJNiMx+Pa94qKj+TG8ONdKHgMNIyyag=
 github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I=
 github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
-github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
-github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
-github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
-github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
-github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
-github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
-github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
-github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
 github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570 h1:0iQektZGS248WXmGIYOwRXSQhD4qn3icjMpuxwO7qlo=
 github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570/go.mod h1:BLt8L9ld7wVsvEWQbuLrUZnCMnUmLZ+CGDzKtclrTlE=
 github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f h1:sgUSP4zdTUZYZgAGGtN5Lxk92rK+JUFOwf+FT99EEI4=
 github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f/go.mod h1:UGmTpUd3rjbtfIpwAPrcfmGf/Z1HS95TATB+m57TPB8=
 github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 h1:Bvq8AziQ5jFF4BHGAEDSqwPW1NJS3XshxbRCxtjFAZc=
 github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042/go.mod h1:TPpsiPUEh0zFL1Snz4crhMlBe60PYxRHr5oFF3rRYg0=
-github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
-github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
-github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
-github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
-github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
-github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
-github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
 github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
 github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
 github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ=
+github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
 github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
 github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
 github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
 github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
 github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
-github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
-github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
 github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
-github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
 github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
 github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07 h1:UyzmZLoiDWMRywV4DUYb9Fbt8uiOSooupjTq10vpvnU=
+github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
 github.com/tebeka/strftime v0.1.5 h1:1NQKN1NiQgkqd/2moD6ySP/5CoZQsKa1d3ZhJ44Jpmg=
 github.com/tebeka/strftime v0.1.5/go.mod h1:29/OidkoWHdEKZqzyDLUyC+LmgDgdHo4WAFCDT7D/Ig=
-github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
-github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
-github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
-github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
+github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
+github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
 github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
-golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
-golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
-golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
 golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
 golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
 golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
@@ -133,7 +90,6 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
 golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
@@ -158,7 +114,6 @@ golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
 golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
 golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
 golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
-golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
 golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
 golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
 golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
@@ -167,13 +122,8 @@ golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
 golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
 golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
 golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
-google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
-google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
 gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
 gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
-rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

+ 2 - 0
log/info.20250310.log

@@ -0,0 +1,2 @@
+{"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"}

+ 1 - 0
log/info.20250313.log

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

+ 4 - 0
log/info.20250314.log

@@ -0,0 +1,4 @@
+{"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"}

+ 30 - 2
main.go

@@ -1,9 +1,37 @@
 package main
 
-import "smart_tunnel_edge/util/logger"
+import (
+	"fmt"
+	"smart_tunnel_edge/util"
+	"smart_tunnel_edge/util/config"
+	"smart_tunnel_edge/util/logger"
+)
 
 func main() {
-
 	logger.InitLog() //初始化日志
 
+	err := config.LoadSerialConfig()
+	if err != nil {
+		logger.Logger.Errorf("加载串口配置失败: %v", err)
+		return
+	}
+	//打开串口并监听
+	if err := util.OpenSerialPort(config.SerialConfig.SerialMap); err != nil {
+		fmt.Printf("处理串口时发生错误: %v", err)
+		return
+	}
+	//初始化设备
+	err = config.LoadDevConfig()
+	if err != nil {
+		logger.Logger.Errorf("加载设备配置失败: %v", err)
+		return
+	}
+	for _, dev := range config.DevConfig.EnvDevs { //循环设备制定采集任务
+		go util.StartDeviceCollection(dev)
+	}
+
+	go util.TimeTasks()
+
+	select {}
+
 }

+ 9 - 0
protocol/envSensor/model.go

@@ -0,0 +1,9 @@
+package envSensor
+
+type DataPack struct {
+	Address  string //地址码
+	Function byte   //功能码
+	Start    []byte //寄存器起始地址
+	DataLen  []byte //控制指令长度
+	Crc      uint16 //Crc校验码
+}

+ 35 - 0
protocol/envSensor/service.go

@@ -0,0 +1,35 @@
+package envSensor
+
+import (
+	"encoding/hex"
+	"github.com/valyala/bytebufferpool"
+)
+
+func (x DataPack) GetEnvGatherCommand() *bytebufferpool.ByteBuffer {
+	buf := bytebufferpool.Get()
+	x.Function = 0x03
+	decodeAddress, _ := hex.DecodeString(x.Address)
+	buf.Write(decodeAddress)
+	buf.WriteByte(x.Function)
+	buf.Write(x.Start)
+	buf.Write(x.DataLen)
+	x.Crc = calculateCRC16Modbus(buf.Bytes())
+	buf.Write([]byte{byte(x.Crc & 0xFF), byte(x.Crc >> 8)})
+	return buf
+}
+
+func calculateCRC16Modbus(data []byte) uint16 {
+	var crc uint16 = 0xFFFF // CRC-16 初始化值
+	for _, byteVal := range data {
+		crc ^= uint16(byteVal) // 对字节进行异或操作
+		for i := 0; i < 8; i++ {
+			if crc&0x0001 != 0 {
+				crc >>= 1
+				crc ^= 0xA001 // 多项式 0xA001
+			} else {
+				crc >>= 1
+			}
+		}
+	}
+	return crc
+}

+ 12 - 0
protocol/lampControl/model.go

@@ -0,0 +1,12 @@
+package lampControl
+
+type DataPack struct {
+	Start   byte   //帧起始符,恒为0x68,1字节
+	Addr    string //地址域,6字节,整数,大端传输
+	Start2  byte   //帧起始符,恒为0x68,1字节
+	Ctl     uint8  //控制码,1字节
+	DataLen uint8  //数据域长度,1字节
+	Data    []byte //数据域
+	Cs      uint8  //Start到Cs之前的所有字节模256
+	End     byte   //结束符号,恒为0x16,1字节
+}

+ 107 - 0
protocol/lampControl/service.go

@@ -0,0 +1,107 @@
+package lampControl
+
+import (
+	"encoding/hex"
+	"fmt"
+	"github.com/valyala/bytebufferpool"
+	"strconv"
+)
+
+func (o DataPack) GetLampTurnOnOffCommand() *bytebufferpool.ByteBuffer {
+	//初始化成员
+	o.Start = 0x68
+	o.Addr = o.Addr
+	o.Start2 = 0x68
+	o.Ctl = 0x1E
+	o.Data = append([]byte{0x00, 0x00, 0x60, 0x07, 0x01}, o.Data...) //按路开关灯
+	o.DataLen = uint8(len(o.Data))
+	o.End = 0x16
+	//addr
+	tmpAddr := EncodeAddr(o.Addr)
+	if tmpAddr == nil {
+		return nil
+	}
+	//序列化
+	buf := bytebufferpool.Get()
+	buf.WriteByte(o.Start)
+	buf.Write(tmpAddr)
+	buf.WriteByte(o.Start2)
+	buf.WriteByte(o.Ctl)
+	buf.WriteByte(o.DataLen)
+
+	if o.DataLen > 0 {
+		TmpData := make([]byte, o.DataLen)
+		for i, b := range o.Data {
+			TmpData[i] = b + 0x33
+		}
+		buf.Write(TmpData)
+	}
+
+	//计算校验码
+	o.Cs = CheckSum(buf.Bytes())
+	buf.WriteByte(o.Cs)
+	buf.WriteByte(o.End)
+	return buf
+}
+
+func (o DataPack) GetLampSetBrightCommand(brightness int) *bytebufferpool.ByteBuffer {
+	//初始化成员
+	o.Start = 0x68
+	o.Addr = o.Addr
+	o.Start2 = 0x68
+	o.Ctl = 0x1E
+	hexValue := fmt.Sprintf("%02x", brightness)
+	decodeString, _ := hex.DecodeString(hexValue)
+	o.Data = append([]byte{0x00, 0x00, 0x60, 0x09, 0x01}, decodeString...) //按路调光照度
+	o.DataLen = uint8(len(o.Data))
+	o.End = 0x16
+	//addr
+	tmpAddr := EncodeAddr(o.Addr)
+	if tmpAddr == nil {
+		return nil
+	}
+	//序列化
+	buf := bytebufferpool.Get()
+	buf.WriteByte(o.Start)
+	buf.Write(tmpAddr)
+	buf.WriteByte(o.Start2)
+	buf.WriteByte(o.Ctl)
+	buf.WriteByte(o.DataLen)
+
+	if o.DataLen > 0 {
+		TmpData := make([]byte, o.DataLen)
+		for i, b := range o.Data {
+			TmpData[i] = b + 0x33
+		}
+		buf.Write(TmpData)
+	}
+
+	//计算校验码
+	o.Cs = CheckSum(buf.Bytes())
+	buf.WriteByte(o.Cs)
+	buf.WriteByte(o.End)
+	return buf
+}
+
+func CheckSum(data []byte) uint8 {
+	var sum uint64
+	for _, c := range data {
+		sum += uint64(c)
+	}
+	return uint8(sum % 256)
+}
+
+func EncodeAddr(Addr string) []byte {
+	var bytes []byte
+	for i := 0; i < len(Addr); i += 2 {
+		// 直接解析并添加到字节数组中
+		if b, err := strconv.ParseUint(Addr[i:i+2], 16, 8); err == nil {
+			bytes = append(bytes, byte(b))
+		}
+	}
+	// 反转字节顺序
+	for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
+		bytes[i], bytes[j] = bytes[j], bytes[i]
+	}
+	return bytes
+}

+ 1 - 0
protocol/switchRelay/model.go

@@ -0,0 +1 @@
+package switchRelay

+ 5 - 0
protocol/switchRelay/service.go

@@ -0,0 +1,5 @@
+package switchRelay
+
+//开指令
+
+//关指令

+ 58 - 0
radar_test.go

@@ -0,0 +1,58 @@
+package main
+
+import (
+	"encoding/hex"
+	"fmt"
+	"smart_tunnel_edge/protocol/envSensor"
+	"testing"
+)
+
+func Test_verify(t *testing.T) {
+
+	//Name := "光传感器"
+	//decodeAddress, _ := hex.DecodeString("01")
+	//dataPack := envSensor.DataPack{Address: decodeAddress, Start: []byte{0x01, 0xF8}, DataLen: []byte{0x00, 0x08}}
+	//
+	//if Name == "光传感器" {
+	//	dataPack = envSensor.DataPack{Address: decodeAddress, Start: []byte{0x00, 0x06}, DataLen: []byte{0x00, 0x01}}
+	//}
+	//buffer := dataPack.GetEnvGatherCommand()
+	//fmt.Println("++++++++", hex.EncodeToString(buffer.Bytes()))
+	//
+	//xxx := "010310030900ba012c000000000000000100016324" //42 14
+	//
+	//gz, _ := strconv.ParseInt(xxx[30:38], 16, 0)
+	////s := xxx[30:38]
+	//fmt.Println("截取: ", gz)
+
+	//hexStr := "7830303940790d0a"
+	//// 调用解析函数
+	//
+	//hex.EncodeToString([]byte{})
+	//result := parseHexString(hexStr)
+	//// 输出结果
+	//fmt.Println(result)
+
+	//xxx := "7830313940790d0a"
+	//char := parseHexString("7830313940790d0a")
+	//fmt.Println("+++++++", char)
+	//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()))
+
+}
+
+func parseHexString(hexStr string) string {
+	// 将十六进制字符串转换为字节数组
+	bytes, err := hex.DecodeString(hexStr)
+	if err != nil {
+		fmt.Println("错误: 十六进制字符串解析失败", err)
+		return ""
+	}
+
+	// 将字节数组转换为对应的字符
+	return string(bytes)
+}

+ 1 - 1
service/mqtt_handle.go

@@ -37,7 +37,7 @@ func GetHandler() *MqttHandler {
 }
 
 func (o *MqttHandler) SubscribeTopics() {
-	mqtt.GetMQTTMgr().Subscribe("smart_intersection/#", mqtt.AtLeastOnce, o.HandlerData)
+	mqtt.GetMQTTMgr().Subscribe("smart_tunnel/#", mqtt.AtLeastOnce, o.HandlerData)
 }
 
 func (o *MqttHandler) HandlerData(m mqtt.Message) {

BIN
smart_tunnel_edge.exe


+ 85 - 7
util/config/config.go

@@ -1,14 +1,19 @@
 package config
 
 import (
+	"encoding/json"
+	"fmt"
 	"gopkg.in/yaml.v3"
+	"io/ioutil"
 	"os"
 	"sync"
 )
 
 var (
-	instance *config
-	once     sync.Once
+	instance     *config
+	once         sync.Once
+	SerialConfig Serial
+	DevConfig    Devs
 )
 
 func init() {
@@ -35,7 +40,8 @@ func Instance() *config {
 type config struct {
 	Logger logger `yaml:"logger"`
 	Mqtt   mqtt   `yaml:"mqtt"`
-	Device device `yaml:"device"`
+	Nums   nums   `yaml:"nums"`
+	Policy policy `yaml:"policy"`
 }
 
 type logger struct {
@@ -51,8 +57,80 @@ type mqtt struct {
 	Password string `yaml:"password"`
 }
 
-type device struct {
-	Informant    string `yaml:"informant"`
-	SpeechSpeed  string `yaml:"speech_speed"`
-	SpeechVolume string `yaml:"speech_volume"`
+type nums struct {
+	EnvNum int `yaml:"envNum"`
+	OptNum int `yaml:"optNum"`
+}
+
+type policy struct {
+	Id        int    `json:"id"`
+	Control   string `json:"control"`
+	StartTime string `json:"startTime"`
+	EndTime   string `json:"endTime"`
+}
+
+func LoadSerialConfig() error {
+	// 读取配置文件
+	data, err := ioutil.ReadFile("./config/serial.json")
+	if err != nil {
+		return fmt.Errorf("读取配置文件失败: %v", err)
+	}
+
+	// 解析 JSON 数据到结构体
+	if err := json.Unmarshal(data, &SerialConfig); err != nil {
+		return fmt.Errorf("解析 JSON 配置失败: %v", err)
+	}
+	return nil
+}
+
+type Serial struct {
+	SerialMap map[int8]*SerialPort `json:"serial"`
+}
+
+type SerialPort struct {
+	Code      int8   `json:"code"`
+	Interface string `json:"interface"`
+	Address   string `json:"address"`
+	BaudRate  int    `json:"baudRate"`
+	DataBits  uint8  `json:"dataBits"`
+	StopBits  uint   `json:"stopBits"`
+	Parity    string `json:"parity"`
+	Timeout   uint   `json:"timeout"`
+}
+
+func LoadDevConfig() error {
+	fmt.Println("加载配置...")
+	// 读取配置文件
+	data, err := ioutil.ReadFile("./dev/devs.json")
+	if err != nil {
+		return fmt.Errorf("读取配置文件失败: %v", err)
+	}
+
+	// 解析 JSON 数据到结构体
+	if err := json.Unmarshal(data, &DevConfig); err != nil {
+		return fmt.Errorf("解析 JSON 配置失败: %v", err)
+	}
+	return nil
+}
+
+type Devs struct {
+	EnvDevs  []*EnvDev  `json:"envDev"`
+	LampDevs []*LampDev `json:"lampDev"`
+}
+
+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
+}
+
+type LampDev struct {
+	Sn       string `json:"sn"`       //设备SN
+	Address  string `json:"address"`  //设备地址
+	Name     string `json:"name"`     //设备名称
+	RadarId  int    `json:"radarId"`  //雷达id(用于在雷达监测到来车后,控制雷达在的那一路的单灯控制器)
+	SerialId int8   `json:"serialId"` // 串口id
 }

+ 49 - 0
util/devmgr.go

@@ -0,0 +1,49 @@
+package util
+
+import (
+	"smart_tunnel_edge/protocol/envSensor"
+	"smart_tunnel_edge/util/config"
+	"smart_tunnel_edge/util/logger"
+	"sync"
+	"time"
+)
+
+var mu sync.Mutex
+
+func StartDeviceCollection(dev *config.EnvDev) {
+	coverTime := dev.TaskTime
+	ticker := time.NewTicker(time.Duration(coverTime) * time.Minute)
+	defer ticker.Stop()
+
+	for {
+		select {
+		case <-ticker.C:
+			if dev.WaitTime > 0 {
+				time.Sleep(time.Duration(dev.WaitTime) * time.Second)
+			}
+			//获取指令
+			dataPack := envSensor.DataPack{Address: dev.DevAddress, 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}}
+			}
+			buffer := dataPack.GetEnvGatherCommand()
+			mu.Lock()
+			port, err := GetSerialPort(dev.SerialId)
+			if err != nil {
+				logger.Logger.Infof(err.Error())
+				continue
+			}
+			write, err := port.Write(buffer.Bytes())
+			mu.Unlock()
+			if write < 0 && err != nil {
+				logger.Logger.Errorf("设备:%v采集数据失败,错误:%v", dev.Sn, err)
+				continue
+			}
+		}
+	}
+}
+
+// 采集方法
+//func EnvGather(address string) {
+//
+//}

+ 25 - 0
util/serialQueue.go

@@ -0,0 +1,25 @@
+package util
+
+import "sync"
+
+type SerialQueue struct {
+	items [][]byte
+	lock  sync.Mutex
+}
+
+func (q *SerialQueue) Enqueue(item []byte) {
+	q.lock.Lock()
+	defer q.lock.Unlock()
+	q.items = append(q.items, item)
+}
+
+func (q *SerialQueue) Dequeue() ([]byte, bool) {
+	q.lock.Lock()
+	defer q.lock.Unlock()
+	if len(q.items) == 0 {
+		return nil, false
+	}
+	item := q.items[0]
+	q.items = q.items[1:]
+	return item, true
+}

+ 172 - 0
util/serialmgr.go

@@ -0,0 +1,172 @@
+package util
+
+import (
+	"encoding/hex"
+	"errors"
+	"fmt"
+	"github.com/tarm/serial"
+	"log"
+	"smart_tunnel_edge/util/config"
+	"smart_tunnel_edge/util/logger"
+	"strconv"
+	"time"
+)
+
+var (
+	parity = map[string]serial.Parity{
+		"N": serial.ParityNone,  // 无校验
+		"E": serial.ParityEven,  // 偶校验
+		"O": serial.ParityOdd,   // 奇校验
+		"M": serial.ParityMark,  // 标记校验
+		"S": serial.ParitySpace, // 空格校验
+	}
+	serialPort = make(map[int8]*serial.Port)
+	env        = make(map[string]int64) //存储环境传感器光照的切片
+	opt        = make(map[string]int64) //存储光照传感器光照的切片
+)
+
+var (
+	isLightOperate bool              // 标记是否进行开灯或调节亮度操作
+	timer          *time.Timer       // 用于延时关闭灯的计时器
+	lastCarTime    time.Time         // 记录上次来车的时间
+	lightDuration  = 2 * time.Minute // 灯亮的持续时间(2分钟)
+)
+
+const (
+	RegulateLight  = "regulateLight"
+	RegulateSwitch = "regulateSwitch"
+)
+
+func GetSerialPort(serialID int8) (*serial.Port, error) {
+	port, exists := serialPort[serialID]
+	if !exists {
+		return nil, errors.New("serial port not found")
+	}
+	return port, nil
+}
+
+func OpenSerialPort(portMap map[int8]*config.SerialPort) error {
+	fmt.Println("打开串口...")
+	var lastError error
+	// 遍历串口配置
+	for _, port := range portMap {
+		// 串口配置
+		c := &serial.Config{
+			Name:        port.Address,
+			Baud:        port.BaudRate,
+			Size:        port.DataBits,
+			StopBits:    serial.StopBits(port.StopBits),
+			Parity:      parity[port.Parity],
+			ReadTimeout: time.Duration(port.Timeout),
+		}
+		// 打开串口
+		pt, err := serial.OpenPort(c)
+
+		serialPort[port.Code] = pt
+
+		if err != nil {
+			logger.Logger.Errorf("无法打开串口 %s: %v", port.Address, err)
+			if lastError == nil {
+				lastError = err
+			}
+			continue
+		}
+
+		go listenPort(port.Code, pt) //开启线程监听串口
+	}
+	return lastError
+}
+
+func listenPort(portCode int8, port *serial.Port) {
+	fmt.Println("监听串口...")
+	buf := make([]byte, 128)
+	for {
+		// 读取数据
+		n, err := port.Read(buf)
+		if err != nil {
+			log.Printf("读取串口数据失败: %v", err)
+			continue
+		}
+		if n > 0 {
+			dataString := hex.EncodeToString(buf[:n])
+			fmt.Println("数据:", dataString)
+			switch {
+			case len(dataString) == 42 && dataString[2:6] == "0310": //环境传感器数据
+				fmt.Print("环境传感:")
+				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 将采集数据上报
+
+			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 将采集数据上报
+
+			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 { //没操作,就去操作
+
+						}
+					} else {
+						//开关模组
+					}
+					lastCarTime = now //更新最后来车时间
+				}
+				continue
+				//default:
+				//	// 其他情况可以处理默认数据
+				//	fmt.Printf("错误数据: %s \n", dataString)
+			}
+			if config.Instance().Nums.EnvNum == len(env) && config.Instance().Nums.OptNum == len(opt) {
+
+				envAverage := calculateAverage(env)
+				optAverage := calculateAverage(opt)
+
+				fmt.Println("环境平均值:", envAverage)
+				fmt.Println("光照平均值:", optAverage)
+
+				//TODO 作比较,进行灯控操作并清空切片
+
+				env = make(map[string]int64)
+				opt = make(map[string]int64)
+			}
+		}
+
+		time.Sleep(100 * time.Millisecond) // 设置延迟,避免CPU占用过高
+	}
+}
+
+func calculateAverage(data map[string]int64) float64 {
+	var sum int64
+	for _, value := range data {
+		sum += value
+	}
+	if len(data) == 0 {
+		return 0 // 防止除以零
+	}
+	return float64(sum) / float64(len(data))
+}

+ 38 - 0
util/task.go

@@ -0,0 +1,38 @@
+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)
+
+func TimeTasks() {
+	c := cron.New()
+	//每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())
+			}
+		}
+	})
+	c.Start()
+}