myData.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. package initialize
  2. import (
  3. "encoding/hex"
  4. "log"
  5. "net"
  6. "os"
  7. "runtime"
  8. "runtime/debug"
  9. "server/dao"
  10. "server/logger"
  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. logger.Get().Println(err)
  38. } else {
  39. logger.Get().Println(lis)
  40. model.InductanceTCP = lis
  41. logger.Get().Println("inductanceTCP启动成功")
  42. }
  43. go StartInductanceTCP()
  44. }
  45. func StartInductanceTCP() {
  46. logger.Get().Println("进入StartInductanceTCP")
  47. handler := GetHandler()
  48. for {
  49. logger.Get().Println("进入InductanceTCP循环")
  50. conn, err := model.InductanceTCP.Accept()
  51. if err != nil {
  52. log.Println(err)
  53. }
  54. remoteAddr := conn.RemoteAddr().String()
  55. logger.Get().Printf("lis Accept conn = %s\n", remoteAddr)
  56. model.Mutex.Lock()
  57. deviceId, err := GetDeviceId(conn)
  58. if err != nil {
  59. log.Println("Error getting device ID:", err)
  60. //conn.Close()
  61. model.Mutex.Unlock()
  62. continue
  63. }
  64. model.ConnectionMap1.Store(deviceId, conn)
  65. model.Mutex.Unlock()
  66. // 使用 Load 方法尝试获取连接
  67. if conn1, ok := model.ConnectionMap1.Load(deviceId); ok {
  68. // 成功找到连接
  69. netConn := conn1.(net.Conn)
  70. // 在这里处理 netConn
  71. go handler.ReadAndHandle(netConn, deviceId)
  72. go handler.Handler()
  73. } else {
  74. // 没有找到对应的连接
  75. log.Printf("Connection for key %s not found", deviceId)
  76. }
  77. }
  78. }
  79. func GetDeviceId(conn net.Conn) (id string, err error) {
  80. // 发送 Modbus RTU 帧
  81. //FE 04 03 EE 00 08 85 B2
  82. data, err := utils.WriteAndReadDevice(modbus.ReadDeviceId, conn, 9, 2)
  83. if err != nil {
  84. return
  85. }
  86. return string(data), err
  87. }
  88. func (o *ModbusHandler) ReadAndHandle(conn net.Conn, deviceId string) {
  89. for {
  90. buffer := make([]byte, 1024)
  91. n, err := conn.Read(buffer)
  92. if err != nil {
  93. if isConnReset(err) {
  94. logger.Get().Error("连接被远程主机强制关闭")
  95. } else if os.IsTimeout(err) {
  96. logger.Get().Error("读取操作超时")
  97. } else {
  98. // 处理其他类型的错误
  99. logger.Get().Errorf("读取错误: %s\n", err)
  100. }
  101. return
  102. }
  103. queueData := model.QueueData{
  104. Id: deviceId,
  105. Value: buffer[:n],
  106. }
  107. ok, cnt := o.queue.Put(&queueData)
  108. if ok {
  109. continue
  110. } else {
  111. logger.Get().Errorf("HandlerData:查询队列失败,队列消息数量:%d", cnt)
  112. runtime.Gosched()
  113. }
  114. }
  115. }
  116. func isConnReset(err error) bool {
  117. if opErr, ok := err.(*net.OpError); ok {
  118. if opErr.Err == syscall.ECONNRESET {
  119. return true // Unix-like 系统上的 ECONNRESET
  120. } else if runtime.GOOS == "windows" {
  121. // Windows 上的 WSAECONNRESET 通常是通过错误消息识别的
  122. if se, ok := opErr.Err.(*os.SyscallError); ok {
  123. if errno, ok := se.Err.(syscall.Errno); ok {
  124. if errno == 10054 { // 10054 对应 WSAECONNRESET
  125. return true
  126. }
  127. }
  128. } else if strings.Contains(opErr.Err.Error(), "WSAECONNRESET") {
  129. // 如果错误消息包含 WSAECONNRESET,也认为是连接被重置
  130. return true
  131. }
  132. }
  133. }
  134. return false
  135. }
  136. func (o *ModbusHandler) Handler() interface{} {
  137. defer func() {
  138. if err := recover(); err != nil {
  139. go GetHandler().Handler()
  140. logger.Get().Errorf("MqttHandler.Handler:发生异常:%s", string(debug.Stack()))
  141. }
  142. }()
  143. for {
  144. msg, ok, quantity := o.queue.Get()
  145. if !ok {
  146. time.Sleep(10 * time.Millisecond)
  147. continue
  148. } else if quantity > 1000 {
  149. logger.Get().Errorf("数据队列累积过多,请注意优化,当前队列条数:%d", quantity)
  150. }
  151. queueData, ok := msg.(*model.QueueData)
  152. if !ok {
  153. logger.Get().Errorln("Type assertion failed: msg is not of type model.QueueDat")
  154. return nil
  155. }
  156. // 信息处理返回
  157. parseData(queueData)
  158. // 对数据进行修改
  159. }
  160. }
  161. func parseData(data *model.QueueData) {
  162. reg, dev, err := utils.GetDataByDeviceId(data.Id)
  163. if err != nil {
  164. logger.Get().Errorln("Error getting register and device:", err)
  165. return
  166. }
  167. toString := hex.EncodeToString(data.Value)
  168. logger.Get().Infof("deviceId: %s, value: %s", data.Id, toString)
  169. switch toString[0:2] {
  170. case "fe":
  171. switch toString[2:8] { // 开关灯
  172. case "050000", "050001", "050002", "050003", "050004", "050005", "050006", "050007":
  173. relyId, _ := strconv.Atoi(toString[7:8])
  174. logger.Get().Error(dev.DeviceLoops[relyId])
  175. if toString[8:12] == "0000" {
  176. dev.DeviceLoops[relyId].State = 0
  177. } else if toString[8:12] == "ff00" {
  178. dev.DeviceLoops[relyId].State = 1
  179. }
  180. for i, device := range reg.Devices {
  181. if device.Sn == data.Id {
  182. reg.Devices[i] = dev
  183. }
  184. }
  185. regions, err := utils.SaveRegionOnData(reg)
  186. err = service.SaveData(regions)
  187. if err != nil {
  188. logger.Get().Errorln("设备回路状态" + err.Error())
  189. return
  190. }
  191. case "0f0000":
  192. OperationCommand := hex.EncodeToString(modbus.OperationCommand)
  193. logger.Get().Infof("deviceId: %s, value: %s", data.Id, OperationCommand)
  194. if OperationCommand[14:16] == "00" {
  195. for i, loop := range dev.DeviceLoops {
  196. loop.State = 0
  197. dev.DeviceLoops[i] = loop
  198. }
  199. } else if OperationCommand[14:16] == "ff" {
  200. for i, loop := range dev.DeviceLoops {
  201. loop.State = 1
  202. dev.DeviceLoops[i] = loop
  203. }
  204. }
  205. for i, device := range reg.Devices {
  206. if device.Sn == data.Id {
  207. reg.Devices[i] = dev
  208. }
  209. }
  210. regions, err := utils.SaveRegionOnData(reg)
  211. err = service.SaveData(regions)
  212. if err != nil {
  213. logger.Get().Errorln("设备回路状态" + err.Error())
  214. return
  215. }
  216. }
  217. switch toString[2:6] {
  218. case "0101":
  219. for i, device := range reg.Devices {
  220. if device.Sn == data.Id {
  221. reg.Devices[i].State = 1
  222. reg.Devices[i].OnlineTime = time.Now()
  223. }
  224. for i2, _ := range device.DeviceLoops {
  225. if toString[6:8] == "ff" || toString[6:8] == "0f" {
  226. device.DeviceLoops[i2].State = 1
  227. } else if toString[6:8] == "00" {
  228. device.DeviceLoops[i2].State = 0
  229. }
  230. }
  231. }
  232. regions, err := utils.SaveRegionOnData(reg)
  233. err = service.SaveData(regions)
  234. if err != nil {
  235. logger.Get().Errorln("设备回路状态" + err.Error())
  236. return
  237. }
  238. }
  239. case "11":
  240. switch toString[2:6] {
  241. case "0336":
  242. batteryVoltage, _ := strconv.ParseInt(toString[6:10], 16, 64)
  243. batteryCurrent, _ := strconv.ParseInt(toString[10:14], 16, 64)
  244. batteryPlateVoltage, _ := strconv.ParseInt(toString[38:42], 16, 64)
  245. sun := dao.Sun{
  246. DeviceId: dev.Sn,
  247. BatteryVoltage: float64(batteryVoltage) / 100,
  248. BatteryCurrent: int(batteryCurrent),
  249. BatteryPlateVoltage: float64(batteryPlateVoltage) / 100,
  250. }
  251. for i, device := range reg.Devices {
  252. if device.Sn == dev.Sn {
  253. reg.Devices[i].Sun = sun
  254. }
  255. }
  256. regions, err := utils.SaveRegionOnData(reg)
  257. err = service.SaveData(regions)
  258. if err != nil {
  259. logger.Get().Println("太阳能数据保存" + err.Error())
  260. return
  261. }
  262. //电池
  263. if float64(batteryVoltage)/100 < 5 {
  264. data1 := modbus.DeviceSwitch(8, 1)
  265. if conn1, ok := model.ConnectionMap1.Load(data.Id); ok {
  266. // 成功找到连接
  267. netConn := conn1.(net.Conn)
  268. utils.WriteDevice(data1, netConn)
  269. } else {
  270. // 没有找到对应的连接
  271. logger.Get().Printf("Connection for key %s not found", data.Id)
  272. }
  273. } else {
  274. data1 := modbus.DeviceSwitch(8, 0)
  275. if conn1, ok := model.ConnectionMap1.Load(data.Id); ok {
  276. // 成功找到连接
  277. netConn := conn1.(net.Conn)
  278. utils.WriteDevice(data1, netConn)
  279. } else {
  280. // 没有找到对应的连接
  281. logger.Get().Printf("Connection for key %s not found", data.Id)
  282. }
  283. }
  284. }
  285. }
  286. switch toString[0:4] {
  287. case "4c43":
  288. bytes, err := hex.DecodeString(toString[4:])
  289. if err != nil {
  290. logger.Get().Errorln("Error decoding bytes:", err)
  291. return
  292. }
  293. for i, device := range reg.Devices {
  294. if device.Sn == string(bytes) {
  295. reg.Devices[i].State = 1
  296. reg.Devices[i].OnlineTime = time.Now()
  297. }
  298. }
  299. regions, err := utils.SaveRegionOnData(reg)
  300. err = service.SaveData(regions)
  301. if err != nil {
  302. logger.Get().Errorln("心跳" + err.Error())
  303. return
  304. }
  305. }
  306. }