myData.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. for {
  80. buffer := make([]byte, 1024)
  81. n, err := conn.Read(buffer)
  82. if err != nil && err != io.EOF {
  83. if isConnReset(err) {
  84. logger.Get().Error("连接被远程主机强制关闭")
  85. } else if os.IsTimeout(err) {
  86. logger.Get().Error("读取操作超时")
  87. } else {
  88. // 处理其他类型的错误
  89. logger.Get().Errorf("读取错误: %s\n", err)
  90. }
  91. defer conn.Close()
  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. logger.Get().Errorf("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. logger.Get().Errorf("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. logger.Get().Errorf("数据队列累积过多,请注意优化,当前队列条数:%d", quantity)
  141. }
  142. queueData, ok := msg.(*model.QueueData)
  143. if !ok {
  144. logger.Get().Errorln("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. reg, dev, err := utils.GetDataByDeviceIP(data.Ip)
  154. if err != nil {
  155. logger.Get().Errorln("Error getting register and device:", err)
  156. return
  157. }
  158. toString := hex.EncodeToString(data.Value)
  159. logger.Get().Infof("deviceIP: %s, value: %s", data.Ip, toString)
  160. switch toString[0:2] {
  161. case "fe":
  162. switch toString[2:8] { // 开关灯
  163. case "050000", "050001", "050002", "050003", "050004", "050005", "050006", "050007":
  164. relyId, _ := strconv.Atoi(toString[7:8])
  165. logger.Get().Error(dev.DeviceLoops[relyId])
  166. if toString[8:12] == "0000" {
  167. dev.DeviceLoops[relyId].State = 0
  168. } else if toString[8:12] == "ff00" {
  169. dev.DeviceLoops[relyId].State = 1
  170. }
  171. for i, device := range reg.Devices {
  172. if device.Ip == data.Ip {
  173. reg.Devices[i] = dev
  174. }
  175. }
  176. regions, err := utils.SaveRegionOnData(reg)
  177. err = service.SaveData(regions)
  178. if err != nil {
  179. logger.Get().Errorln("设备回路状态" + err.Error())
  180. return
  181. }
  182. case "0f0000":
  183. OperationCommand := hex.EncodeToString(modbus.OperationCommand)
  184. logger.Get().Infof("deviceId: %s, value: %s", data.Ip, OperationCommand)
  185. if OperationCommand[14:16] == "00" {
  186. for i, loop := range dev.DeviceLoops {
  187. loop.State = 0
  188. dev.DeviceLoops[i] = loop
  189. }
  190. } else if OperationCommand[14:16] == "ff" {
  191. for i, loop := range dev.DeviceLoops {
  192. loop.State = 1
  193. dev.DeviceLoops[i] = loop
  194. }
  195. }
  196. for i, device := range reg.Devices {
  197. if device.Sn == data.Ip {
  198. reg.Devices[i] = dev
  199. }
  200. }
  201. regions, err := utils.SaveRegionOnData(reg)
  202. err = service.SaveData(regions)
  203. if err != nil {
  204. logger.Get().Errorln("设备回路状态" + err.Error())
  205. return
  206. }
  207. }
  208. switch toString[2:6] {
  209. case "0101":
  210. // 将16进制字符串解码为字节切片
  211. bytes, err := hex.DecodeString(toString[6:8])
  212. if err != nil {
  213. logger.Get().Errorln("解码失败:", err)
  214. return
  215. }
  216. // 转换为二进制字符串
  217. binStr := ""
  218. for _, b := range bytes {
  219. // 使用fmt.Sprintf将每个字节转换为8位的二进制字符串
  220. binStr += fmt.Sprintf("%08b", b)
  221. }
  222. for i, device := range reg.Devices {
  223. if device.Ip == data.Ip {
  224. reg.Devices[i].State = 1
  225. reg.Devices[i].OnlineTime = time.Now()
  226. if len(device.DeviceLoops) == 8 {
  227. for j := len(device.DeviceLoops) - 1; j >= 0; j-- {
  228. reg.Devices[i].DeviceLoops[7-j].State = int(binStr[j] - '0')
  229. }
  230. } else {
  231. for j := len(device.DeviceLoops) - 1; j >= 0; j-- {
  232. reg.Devices[i].DeviceLoops[3-j].State = int(binStr[j+4] - '0')
  233. }
  234. }
  235. }
  236. }
  237. regions, err := utils.SaveRegionOnData(reg)
  238. err = service.SaveData(regions)
  239. if err != nil {
  240. logger.Get().Errorln("设备回路状态" + err.Error())
  241. return
  242. }
  243. }
  244. case "11":
  245. switch toString[2:6] {
  246. case "0336":
  247. batteryVoltage, _ := strconv.ParseInt(toString[6:10], 16, 64)
  248. batteryCurrent, _ := strconv.ParseInt(toString[10:14], 16, 64)
  249. batteryPlateVoltage, _ := strconv.ParseInt(toString[38:42], 16, 64)
  250. sun := dao.Sun{
  251. DeviceId: dev.Sn,
  252. BatteryVoltage: float64(batteryVoltage) / 100,
  253. BatteryCurrent: int(batteryCurrent),
  254. BatteryPlateVoltage: float64(batteryPlateVoltage) / 100,
  255. }
  256. for i, device := range reg.Devices {
  257. if device.Sn == dev.Sn {
  258. reg.Devices[i].Sun = sun
  259. }
  260. }
  261. regions, err := utils.SaveRegionOnData(reg)
  262. err = service.SaveData(regions)
  263. if err != nil {
  264. logger.Get().Println("太阳能数据保存" + err.Error())
  265. return
  266. }
  267. //电池
  268. if float64(batteryVoltage)/100 < 5 {
  269. data1 := modbus.DeviceSwitch(8, 1)
  270. if conn1, ok := model.ConnectionMap1.Load(data.Ip); ok {
  271. // 成功找到连接
  272. netConn := conn1.(net.Conn)
  273. err := utils.WriteDevice(data1, netConn)
  274. if err != nil {
  275. logger.Get().Errorf("电池符合控制 写命令错误: %s -- conn: %v", err, netConn.RemoteAddr().String())
  276. return
  277. }
  278. } else {
  279. // 没有找到对应的连接
  280. logger.Get().Printf("电池符合控制Connection for key %s not found", data.Ip)
  281. }
  282. } else {
  283. data1 := modbus.DeviceSwitch(8, 0)
  284. if conn1, ok := model.ConnectionMap1.Load(data.Ip); ok {
  285. // 成功找到连接
  286. netConn := conn1.(net.Conn)
  287. err := utils.WriteDevice(data1, netConn)
  288. if err != nil {
  289. logger.Get().Errorf("电池符合控制 写命令错误: %s -- conn: %v", err, netConn.RemoteAddr().String())
  290. return
  291. }
  292. } else {
  293. // 没有找到对应的连接
  294. logger.Get().Printf("电池符合控制Connection for key %s not found", data.Ip)
  295. }
  296. }
  297. }
  298. }
  299. switch toString[0:4] {
  300. case "4c43":
  301. bytes, err := hex.DecodeString(toString[4:])
  302. if err != nil {
  303. logger.Get().Errorln("Error decoding bytes:", err)
  304. return
  305. }
  306. for i, device := range reg.Devices {
  307. if device.Sn == string(bytes) {
  308. reg.Devices[i].State = 1
  309. reg.Devices[i].OnlineTime = time.Now()
  310. }
  311. }
  312. regions, err := utils.SaveRegionOnData(reg)
  313. err = service.SaveData(regions)
  314. if err != nil {
  315. logger.Get().Errorln("心跳" + err.Error())
  316. return
  317. }
  318. }
  319. }