myData.go 9.1 KB

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