myData.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package initialize
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "io"
  6. "net"
  7. "os"
  8. "runtime"
  9. "runtime/debug"
  10. "server/dao"
  11. "server/global"
  12. "server/modbus"
  13. "server/model"
  14. "server/service/item"
  15. "server/utils"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "syscall"
  20. "time"
  21. )
  22. type ModbusHandler struct {
  23. queue *modbus.MlQueue
  24. }
  25. var _handlerOnce sync.Once
  26. var _handlerSingle *ModbusHandler
  27. func GetHandler() *ModbusHandler {
  28. _handlerOnce.Do(func() {
  29. _handlerSingle = &ModbusHandler{
  30. queue: modbus.NewQueue(10000),
  31. }
  32. })
  33. return _handlerSingle
  34. }
  35. func InitInductanceTCP() {
  36. lis, err := net.Listen("tcp", ":60001")
  37. if err != nil {
  38. global.GVA_LOG.Error(err.Error())
  39. } else {
  40. model.InductanceTCP = lis
  41. global.GVA_LOG.Info(fmt.Sprintf("inductanceTCP启动成功 %v \n", lis))
  42. }
  43. go StartInductanceTCP()
  44. }
  45. func StartInductanceTCP() {
  46. global.GVA_LOG.Info("进入StartInductanceTCP")
  47. handler := GetHandler()
  48. for {
  49. global.GVA_LOG.Info("进入InductanceTCP循环")
  50. conn, err := model.InductanceTCP.Accept()
  51. if err != nil {
  52. global.GVA_LOG.Info(err.Error())
  53. }
  54. remoteAddr := conn.RemoteAddr().String()
  55. global.GVA_LOG.Info(fmt.Sprintf("lis Accept conn = %s\n", remoteAddr))
  56. // 解析远程地址
  57. addr, err := net.ResolveTCPAddr("tcp", remoteAddr)
  58. if err != nil {
  59. // 处理错误...
  60. global.GVA_LOG.Error(fmt.Sprintf("解析错误 conn = %s\n", addr.IP.String()))
  61. }
  62. model.ConnectionMap1.Store(addr.IP.String(), conn)
  63. //每次连接 进行设备重连操作
  64. item.DeviceAdjustment(addr.IP.String())
  65. // 使用 Load 方法尝试获取连接
  66. if conn1, ok := model.ConnectionMap1.Load(addr.IP.String()); ok {
  67. // 成功找到连接
  68. netConn := conn1.(net.Conn)
  69. // 在这里处理 netConn
  70. go handler.ReadAndHandle(netConn, addr.IP.String())
  71. go handler.Handler()
  72. } else {
  73. // 没有找到对应的连接
  74. global.GVA_LOG.Warn(fmt.Sprintf("启动 Connection for key %s not found", addr.IP.String()))
  75. }
  76. }
  77. }
  78. func (o *ModbusHandler) ReadAndHandle(conn net.Conn, remoteAddr string) {
  79. defer conn.Close()
  80. for {
  81. buffer := make([]byte, 1024)
  82. n, err := conn.Read(buffer)
  83. if err != nil && err != io.EOF {
  84. if isConnReset(err) {
  85. global.GVA_LOG.Error(fmt.Sprintf("连接被远程主机强制关闭conn: %s", conn.RemoteAddr().String()))
  86. } else if os.IsTimeout(err) {
  87. global.GVA_LOG.Error(fmt.Sprintf("读取操作超时conn: %s", conn.RemoteAddr().String()))
  88. } else {
  89. global.GVA_LOG.Error(fmt.Sprintf("读取错误: %s\n conn: %s", err, conn.RemoteAddr().String()))
  90. }
  91. model.ConnectionMap1.Delete(remoteAddr)
  92. return
  93. }
  94. queueData := model.QueueData{
  95. Ip: remoteAddr,
  96. Value: buffer[:n],
  97. }
  98. ok, cnt := o.queue.Put(&queueData)
  99. if ok {
  100. continue
  101. } else {
  102. global.GVA_LOG.Warn(fmt.Sprintf("HandlerData:查询队列失败,队列消息数量:%d", cnt))
  103. runtime.Gosched()
  104. }
  105. }
  106. }
  107. func isConnReset(err error) bool {
  108. if opErr, ok := err.(*net.OpError); ok {
  109. if opErr.Err == syscall.ECONNRESET {
  110. return true // Unix-like 系统上的 ECONNRESET
  111. } else if runtime.GOOS == "windows" {
  112. // Windows 上的 WSAECONNRESET 通常是通过错误消息识别的
  113. if se, ok := opErr.Err.(*os.SyscallError); ok {
  114. if errno, ok := se.Err.(syscall.Errno); ok {
  115. if errno == 10054 { // 10054 对应 WSAECONNRESET
  116. return true
  117. }
  118. }
  119. } else if strings.Contains(opErr.Err.Error(), "WSAECONNRESET") {
  120. // 如果错误消息包含 WSAECONNRESET,也认为是连接被重置
  121. return true
  122. }
  123. }
  124. }
  125. return false
  126. }
  127. func (o *ModbusHandler) Handler() interface{} {
  128. defer func() {
  129. if err := recover(); err != nil {
  130. go GetHandler().Handler()
  131. global.GVA_LOG.Error(fmt.Sprintf("MqttHandler.Handler:发生异常:%s", string(debug.Stack())))
  132. }
  133. }()
  134. for {
  135. msg, ok, quantity := o.queue.Get()
  136. if !ok {
  137. time.Sleep(10 * time.Millisecond)
  138. continue
  139. } else if quantity > 1000 {
  140. global.GVA_LOG.Error(fmt.Sprintf("数据队列累积过多,请注意优化,当前队列条数:%d", quantity))
  141. }
  142. queueData, ok := msg.(*model.QueueData)
  143. if !ok {
  144. global.GVA_LOG.Error("Type assertion failed: msg is not of type model.QueueDat")
  145. return nil
  146. }
  147. // 信息处理返回
  148. parseData(queueData)
  149. // 对数据进行修改
  150. }
  151. }
  152. func parseData(data *model.QueueData) {
  153. dev, err := dao.QueryDeviceByIp(data.Ip)
  154. if err != nil {
  155. global.GVA_LOG.Error(fmt.Sprintf("Error getting register and device: %s", err))
  156. return
  157. }
  158. toString := hex.EncodeToString(data.Value)
  159. switch toString[0:2] {
  160. case "fe":
  161. switch toString[2:8] { // 开关灯
  162. case "050000", "050001", "050002", "050003", "050004", "050005", "050006", "050007":
  163. relyId, _ := strconv.Atoi(toString[7:8])
  164. state := 0
  165. if toString[8:12] == "0000" {
  166. state = 0
  167. } else if toString[8:12] == "ff00" {
  168. state = 1
  169. }
  170. err := dao.UpdateDeviceLoopStateByDeviceIdAndRelayId(int(dev.ID), relyId+1, state)
  171. if err != nil {
  172. global.GVA_LOG.Error(fmt.Sprintf("Error updating device loop state: %s", err))
  173. }
  174. case "0f0000":
  175. OperationCommand := hex.EncodeToString(modbus.OperationCommand)
  176. state := 0
  177. if OperationCommand[14:16] == "00" {
  178. state = 0
  179. } else if OperationCommand[14:16] == "ff" {
  180. state = 1
  181. }
  182. err := dao.UpdateDeviceLoopStateByDeviceId(int(dev.ID), state)
  183. if err != nil {
  184. global.GVA_LOG.Error(fmt.Sprintf("Error updating device loop state: %s", err))
  185. }
  186. }
  187. switch toString[2:6] {
  188. case "0101":
  189. // 将16进制字符串解码为字节切片
  190. bytes, err := hex.DecodeString(toString[6:8])
  191. if err != nil {
  192. global.GVA_LOG.Error(fmt.Sprintf("解码失败: %s", err))
  193. return
  194. }
  195. // 转换为二进制字符串
  196. binStr := ""
  197. for _, b := range bytes {
  198. // 使用fmt.Sprintf将每个字节转换为8位的二进制字符串
  199. binStr += fmt.Sprintf("%08b", b)
  200. }
  201. // 转换为二进制字符串
  202. binStr = reverseString(binStr)
  203. data := map[string]interface{}{
  204. "state": 1,
  205. "online_time": time.Now(),
  206. }
  207. dao.UpdateDeviceByMapAndSn(data, dev.Sn)
  208. loopCount := dev.LoopNumber
  209. if loopCount > len(binStr) {
  210. loopCount = len(binStr)
  211. }
  212. // 回路ID从 1 开始
  213. for i := 0; i < loopCount; i++ {
  214. relayId := i + 1 // 回路 1、2、3、4...
  215. state := int(binStr[i] - '0')
  216. dao.UpdateDeviceLoopStateByDeviceIdAndRelayId(int(dev.ID), relayId, state)
  217. }
  218. //for i, device := range reg.Devices {
  219. // if device.Ip == data.Ip {
  220. // reg.Devices[i].State = 1
  221. // reg.Devices[i].OnlineTime = time.Now()
  222. // if len(device.DeviceLoops) == 8 {
  223. // for j := len(device.DeviceLoops) - 1; j >= 0; j-- {
  224. // reg.Devices[i].DeviceLoops[7-j].State = int(binStr[j] - '0')
  225. // }
  226. // } else {
  227. // for j := len(device.DeviceLoops) - 1; j >= 0; j-- {
  228. // reg.Devices[i].DeviceLoops[3-j].State = int(binStr[j+4] - '0')
  229. // }
  230. // }
  231. //
  232. // }
  233. //}
  234. }
  235. case "11":
  236. switch toString[2:6] {
  237. case "0336":
  238. batteryVoltage, _ := strconv.ParseInt(toString[6:10], 16, 64)
  239. batteryCurrent, _ := strconv.ParseInt(toString[10:14], 16, 64)
  240. batteryPlateVoltage, _ := strconv.ParseInt(toString[38:42], 16, 64)
  241. sun := dao.Sun{
  242. DeviceId: dev.Sn,
  243. BatteryVoltage: float64(batteryVoltage) / 100,
  244. BatteryCurrent: int(batteryCurrent),
  245. BatteryPlateVoltage: float64(batteryPlateVoltage) / 100,
  246. }
  247. err := sun.SaveSun()
  248. if err != nil {
  249. global.GVA_LOG.Error(fmt.Sprintf("电池信息保存失败: %s", err))
  250. return
  251. }
  252. //电池
  253. if float64(batteryVoltage)/100 < 5 {
  254. data1 := modbus.DeviceSwitch(8, 1)
  255. if conn1, ok := model.ConnectionMap1.Load(data.Ip); ok {
  256. // 成功找到连接
  257. netConn := conn1.(net.Conn)
  258. err := utils.WriteDevice(data1, netConn)
  259. if err != nil {
  260. global.GVA_LOG.Error(fmt.Sprintf("电池符合控制 写命令错误: %s -- conn: %v", err, netConn.RemoteAddr().String()))
  261. return
  262. }
  263. } else {
  264. // 没有找到对应的连接
  265. global.GVA_LOG.Warn(fmt.Sprintf("电池符合控制Connection for key %s not found", data.Ip))
  266. }
  267. } else {
  268. data1 := modbus.DeviceSwitch(8, 0)
  269. if conn1, ok := model.ConnectionMap1.Load(data.Ip); ok {
  270. // 成功找到连接
  271. netConn := conn1.(net.Conn)
  272. err := utils.WriteDevice(data1, netConn)
  273. if err != nil {
  274. global.GVA_LOG.Error(fmt.Sprintf("电池符合控制 写命令错误: %s -- conn: %v", err, netConn.RemoteAddr().String()))
  275. return
  276. }
  277. } else {
  278. // 没有找到对应的连接
  279. global.GVA_LOG.Warn(fmt.Sprintf("电池符合控制Connection for key %s not found", data.Ip))
  280. }
  281. }
  282. }
  283. }
  284. switch toString[0:4] {
  285. case "4c43":
  286. bytes, err := hex.DecodeString(toString[4:])
  287. if err != nil {
  288. global.GVA_LOG.Error(fmt.Sprintf("Error decoding bytes: %s", err))
  289. return
  290. }
  291. data := map[string]interface{}{
  292. "state": 1,
  293. "online_time": time.Now(),
  294. }
  295. err = dao.UpdateDeviceByMapAndSn(data, string(bytes))
  296. if err != nil {
  297. global.GVA_LOG.Error(fmt.Sprintf("修改设备状态失败: %s", err))
  298. }
  299. }
  300. }
  301. // 反转字符串
  302. func reverseString(s string) string {
  303. runes := []rune(s)
  304. for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
  305. runes[i], runes[j] = runes[j], runes[i]
  306. }
  307. return string(runes)
  308. }