myData.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. package initialize
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "log"
  6. "net"
  7. "os"
  8. "runtime"
  9. "runtime/debug"
  10. "server/dao"
  11. "server/modbus"
  12. "server/model"
  13. "server/service"
  14. "server/utils"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "syscall"
  19. "time"
  20. )
  21. type ModbusHandler struct {
  22. queue *modbus.MlQueue
  23. }
  24. var _handlerOnce sync.Once
  25. var _handlerSingle *ModbusHandler
  26. func GetHandler() *ModbusHandler {
  27. _handlerOnce.Do(func() {
  28. _handlerSingle = &ModbusHandler{
  29. queue: modbus.NewQueue(10000),
  30. }
  31. })
  32. return _handlerSingle
  33. }
  34. func InitInductanceTCP() {
  35. lis, err := net.Listen("tcp", ":60001")
  36. if err != nil {
  37. fmt.Println(err)
  38. } else {
  39. fmt.Println(lis)
  40. model.InductanceTCP = lis
  41. fmt.Println("inductanceTCP启动成功")
  42. }
  43. go StartInductanceTCP()
  44. }
  45. func StartInductanceTCP() {
  46. fmt.Println("进入StartInductanceTCP")
  47. handler := GetHandler()
  48. for {
  49. log.Println("进入InductanceTCP循环")
  50. conn, err := model.InductanceTCP.Accept()
  51. if err != nil {
  52. log.Println(err)
  53. }
  54. remoteAddr := conn.RemoteAddr().String()
  55. log.Printf("lis Accept conn = %s\n", remoteAddr)
  56. model.Mutex.Lock()
  57. if _, exists := model.ConnectionMap[remoteAddr]; exists {
  58. log.Printf("Connection from %s already exists, closing new connection\n", remoteAddr)
  59. conn.Close()
  60. model.Mutex.Unlock()
  61. continue
  62. }
  63. fmt.Println(conn)
  64. deviceId, err := GetDeviceId(conn)
  65. if err != nil {
  66. log.Println("Error getting device ID:", err)
  67. conn.Close()
  68. model.Mutex.Unlock()
  69. continue
  70. }
  71. model.ConnectionMap[deviceId] = conn
  72. model.Mutex.Unlock()
  73. //用新的协程处理新的连接
  74. go handler.ReadAndHandle(conn, deviceId)
  75. go handler.Handler()
  76. }
  77. }
  78. func GetDeviceId(conn net.Conn) (id string, err error) {
  79. // 发送 Modbus RTU 帧
  80. //FE 04 03 EE 00 08 85 B2
  81. data, err := utils.WriteAndReadDevice(modbus.ReadDeviceId, conn, 9, 2)
  82. if err != nil {
  83. return
  84. }
  85. return string(data), err
  86. }
  87. func (o *ModbusHandler) ReadAndHandle(conn net.Conn, deviceId string) {
  88. for {
  89. buffer := make([]byte, 1024)
  90. n, err := conn.Read(buffer)
  91. //if err != nil {
  92. // log.Println("Error reading from connection:", err)
  93. // return
  94. //}
  95. if err != nil {
  96. if isConnReset(err) {
  97. fmt.Println("连接被远程主机强制关闭")
  98. } else if os.IsTimeout(err) {
  99. fmt.Println("读取操作超时")
  100. } else {
  101. // 处理其他类型的错误
  102. fmt.Printf("读取错误: %s\n", err)
  103. }
  104. return
  105. }
  106. queueData := model.QueueData{
  107. Id: deviceId,
  108. Value: buffer[:n],
  109. }
  110. ok, cnt := o.queue.Put(&queueData)
  111. if ok {
  112. continue
  113. } else {
  114. fmt.Printf("HandlerData:查询队列失败,队列消息数量:%d", cnt)
  115. runtime.Gosched()
  116. }
  117. }
  118. }
  119. func isConnReset(err error) bool {
  120. if opErr, ok := err.(*net.OpError); ok {
  121. if opErr.Err == syscall.ECONNRESET {
  122. return true // Unix-like 系统上的 ECONNRESET
  123. } else if runtime.GOOS == "windows" {
  124. // Windows 上的 WSAECONNRESET 通常是通过错误消息识别的
  125. if se, ok := opErr.Err.(*os.SyscallError); ok {
  126. if errno, ok := se.Err.(syscall.Errno); ok {
  127. if errno == 10054 { // 10054 对应 WSAECONNRESET
  128. return true
  129. }
  130. }
  131. } else if strings.Contains(opErr.Err.Error(), "WSAECONNRESET") {
  132. // 如果错误消息包含 WSAECONNRESET,也认为是连接被重置
  133. return true
  134. }
  135. }
  136. }
  137. return false
  138. }
  139. func (o *ModbusHandler) Handler() interface{} {
  140. defer func() {
  141. if err := recover(); err != nil {
  142. go GetHandler().Handler()
  143. fmt.Printf("MqttHandler.Handler:发生异常:%s", string(debug.Stack()))
  144. }
  145. }()
  146. for {
  147. msg, ok, quantity := o.queue.Get()
  148. if !ok {
  149. time.Sleep(10 * time.Millisecond)
  150. continue
  151. } else if quantity > 1000 {
  152. fmt.Printf("数据队列累积过多,请注意优化,当前队列条数:%d", quantity)
  153. }
  154. queueData, ok := msg.(*model.QueueData)
  155. if !ok {
  156. fmt.Println("Type assertion failed: msg is not of type model.QueueDat")
  157. return nil
  158. }
  159. // 信息处理返回
  160. parseData(queueData)
  161. // 对数据进行修改
  162. }
  163. }
  164. func parseData(data *model.QueueData) {
  165. reg, dev, err := utils.GetDataByDeviceId(data.Id)
  166. if err != nil {
  167. fmt.Println("Error getting register and device:", err)
  168. return
  169. }
  170. toString := hex.EncodeToString(data.Value)
  171. fmt.Println(data.Id + "----" + toString)
  172. switch toString[0:2] {
  173. case "fe":
  174. switch toString[4:8] { // 开关灯
  175. case "0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007":
  176. if toString[8:12] == "0000" {
  177. for i, loop := range dev.DeviceLoops {
  178. loop.State = 0
  179. dev.DeviceLoops[i] = loop
  180. }
  181. } else if toString[8:12] == "ff00" {
  182. for i, loop := range dev.DeviceLoops {
  183. loop.State = 1
  184. dev.DeviceLoops[i] = loop
  185. }
  186. }
  187. }
  188. switch toString[2:6] {
  189. case "0101":
  190. for i, device := range reg.Devices {
  191. if device.Sn == data.Id {
  192. reg.Devices[i].State = 1
  193. reg.Devices[i].OnlineTime = time.Now()
  194. }
  195. }
  196. regions, err := utils.SaveRegionOnData(reg)
  197. fmt.Println(regions)
  198. err = service.SaveData(regions)
  199. if err != nil {
  200. fmt.Println(err)
  201. return
  202. }
  203. }
  204. case "11":
  205. switch toString[2:6] {
  206. case "0336":
  207. batteryVoltage, _ := strconv.ParseInt(toString[6:10], 16, 64)
  208. batteryCurrent, _ := strconv.ParseInt(toString[10:14], 16, 64)
  209. batteryPlateVoltage, _ := strconv.ParseInt(toString[38:42], 16, 64)
  210. sun := dao.Sun{
  211. DeviceId: dev.Sn,
  212. BatteryVoltage: float64(batteryVoltage) / 100,
  213. BatteryCurrent: int(batteryCurrent),
  214. BatteryPlateVoltage: float64(batteryPlateVoltage) / 100,
  215. }
  216. for i, device := range reg.Devices {
  217. if device.Sn == dev.Sn {
  218. reg.Devices[i].Sun = sun
  219. }
  220. }
  221. regions, err := utils.SaveRegionOnData(reg)
  222. err = service.SaveData(regions)
  223. if err != nil {
  224. fmt.Println(err)
  225. return
  226. }
  227. //电池
  228. if float64(batteryVoltage)/100 < 5 {
  229. data1 := modbus.DeviceSwitch(8, 1)
  230. utils.WriteDevice(data1, model.ConnectionMap[data.Id])
  231. } else {
  232. data1 := modbus.DeviceSwitch(8, 0)
  233. utils.WriteDevice(data1, model.ConnectionMap[data.Id])
  234. }
  235. }
  236. }
  237. switch toString[0:4] {
  238. case "4c43":
  239. bytes, err := hex.DecodeString(toString[4:])
  240. if err != nil {
  241. fmt.Println("Error decoding bytes:", err)
  242. return
  243. }
  244. for i, device := range reg.Devices {
  245. if device.Sn == string(bytes) {
  246. reg.Devices[i].State = 1
  247. reg.Devices[i].OnlineTime = time.Now()
  248. }
  249. }
  250. regions, err := utils.SaveRegionOnData(reg)
  251. err = service.SaveData(regions)
  252. if err != nil {
  253. fmt.Println(err)
  254. return
  255. }
  256. }
  257. }