myTool.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package utils
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "server/dao"
  10. "server/logger"
  11. "strings"
  12. "time"
  13. )
  14. const dataFilePath = "static/data.json"
  15. // LoadData 从文件中加载 Region 数据。
  16. func LoadData() ([]dao.Region, error) {
  17. data, err := os.ReadFile(dataFilePath)
  18. datafb, err := os.ReadFile("static/data-fb.json")
  19. var regionsfb []dao.Region
  20. if err := json.Unmarshal(datafb, &regionsfb); err != nil {
  21. // 提供更多的上下文信息来帮助调试
  22. return nil, fmt.Errorf("解析 JSON 失败: %v, 原始数据: %s", err, string(data))
  23. }
  24. if err != nil {
  25. if os.IsNotExist(err) {
  26. return regionsfb, nil // 文件不存在时返回空数组
  27. }
  28. return nil, fmt.Errorf("读取文件失败: %v", err)
  29. }
  30. // 检查文件是否为空
  31. if len(data) == 0 {
  32. return regionsfb, nil // 如果文件为空,返回空数组
  33. }
  34. var regions []dao.Region
  35. if err := json.Unmarshal(data, &regions); err != nil {
  36. // 提供更多的上下文信息来帮助调试
  37. return nil, fmt.Errorf("解析 JSON 失败: %v, 原始数据: %s", err, string(data))
  38. }
  39. return regions, nil
  40. }
  41. func GetOnlineDevices() (devices []dao.Device, err error) {
  42. regions, err := LoadData()
  43. if err != nil {
  44. return nil, err
  45. }
  46. for _, region := range regions {
  47. for _, device := range region.Devices {
  48. if device.State == 0 {
  49. continue
  50. }
  51. devices = append(devices, device)
  52. }
  53. }
  54. return devices, err
  55. }
  56. func GetAllDevices() (devices []dao.Device, err error) {
  57. regions, err := LoadData()
  58. if err != nil {
  59. return nil, err
  60. }
  61. for _, region := range regions {
  62. for _, device := range region.Devices {
  63. devices = append(devices, device)
  64. }
  65. }
  66. return devices, err
  67. }
  68. // GetDataByDeviceId 按设备id获取信息 地区+设备
  69. func GetDataByDeviceId(deviceId string) (reg dao.Region, dev dao.Device, err error) {
  70. regions, err := LoadData()
  71. if err != nil {
  72. return reg, dev, err
  73. }
  74. for _, region := range regions {
  75. for _, device := range region.Devices {
  76. if device.Sn == deviceId {
  77. return region, device, nil
  78. }
  79. }
  80. }
  81. return reg, dev, fmt.Errorf("设备%s未找到", deviceId)
  82. }
  83. func SaveRegionOnData(data dao.Region) ([]dao.Region, error) {
  84. regions, err := LoadData()
  85. if err != nil {
  86. return regions, err
  87. }
  88. for i, region := range regions {
  89. if region.Name == data.Name {
  90. regions[i] = data
  91. }
  92. }
  93. return regions, nil
  94. }
  95. // SaveData 保存数据到文件
  96. func SaveData(path string, parameter interface{}) error {
  97. // 如果 parameter 是 nil 或者是空的结构体/切片,可以选择不写入文件或返回错误。
  98. if parameter == nil {
  99. return fmt.Errorf("无法保存 nil 数据")
  100. }
  101. // 序列化数据
  102. data, err := json.MarshalIndent(parameter, "", " ")
  103. if err != nil {
  104. return fmt.Errorf("JSON 序列化失败: %v", err)
  105. }
  106. // 创建临时文件用于原子写入
  107. tempFile, err := ioutil.TempFile(filepath.Dir(path), "tmp-")
  108. if err != nil {
  109. return fmt.Errorf("创建临时文件失败: %v", err)
  110. }
  111. defer os.Remove(tempFile.Name()) // 确保即使出错也能清理临时文件
  112. // 写入临时文件
  113. if _, err := tempFile.Write(data); err != nil {
  114. tempFile.Close()
  115. return fmt.Errorf("写入临时文件失败: %v", err)
  116. }
  117. // 确保所有数据都写入磁盘
  118. if err := tempFile.Sync(); err != nil {
  119. tempFile.Close()
  120. return fmt.Errorf("同步临时文件失败: %v", err)
  121. }
  122. // 关闭临时文件
  123. if err := tempFile.Close(); err != nil {
  124. return fmt.Errorf("关闭临时文件失败: %v", err)
  125. }
  126. // 使用原子操作替换原始文件
  127. if err := os.Rename(tempFile.Name(), path); err != nil {
  128. return fmt.Errorf("替换文件失败: %v", err)
  129. }
  130. return nil
  131. }
  132. const (
  133. maxRetries = 3 // 最大重试次数
  134. writeTimeout = 5 * time.Second // 写入超时时间
  135. reconnectWait = 2 * time.Second // 重连等待时间
  136. )
  137. func WriteDevice(frame []byte, conn net.Conn) error {
  138. for attempts := 0; attempts < maxRetries; attempts++ {
  139. if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
  140. logger.Get().Errorf("Set write deadline failed: %v", err)
  141. return err
  142. }
  143. _, err := conn.Write(frame)
  144. if err == nil {
  145. return nil
  146. }
  147. // 检查是否是对端强制关闭连接的错误
  148. if ne, ok := err.(*net.OpError); ok && (strings.Contains(ne.Err.Error(), "forcibly closed") || strings.Contains(ne.Err.Error(), "broken pipe") || strings.Contains(ne.Err.Error(), "connection reset")) {
  149. logger.Get().Warnf("Connection forcibly closed by peer, retrying (%d/%d)", attempts+1, maxRetries)
  150. // 关闭旧连接
  151. if err := conn.Close(); err != nil {
  152. logger.Get().Errorf("Failed to close connection: %v", err)
  153. }
  154. // 尝试重新建立连接
  155. var newConn net.Conn
  156. remoteAddr := conn.RemoteAddr().String()
  157. // 解析原始连接的远程地址和网络接口
  158. addr, networkInterface, err := parseRemoteAddr(remoteAddr)
  159. if err != nil {
  160. logger.Get().Errorf("Failed to parse remote address: %v", err)
  161. continue // 继续下一次重试
  162. }
  163. newConn, err = net.Dial("tcp", fmt.Sprintf("%s%%%s", addr, networkInterface))
  164. if err != nil {
  165. logger.Get().Errorf("Reconnect failed: %v", err)
  166. time.Sleep(reconnectWait) // 等待一段时间后重试
  167. continue // 继续下一次重试
  168. }
  169. conn = newConn
  170. continue // 重试写入
  171. }
  172. // 如果不是对端强制关闭连接的错误,则直接返回错误
  173. logger.Get().Errorf("Write failed: %v", err)
  174. return fmt.Errorf("write failed after %d retries: %v", attempts+1, err)
  175. }
  176. return fmt.Errorf("failed to write after %d retries", maxRetries)
  177. }
  178. // 解析远程地址,提取 IP 地址和网络接口名称
  179. func parseRemoteAddr(addr string) (string, string, error) {
  180. parts := strings.Split(addr, "%")
  181. if len(parts) != 2 {
  182. return "", "", fmt.Errorf("invalid remote address format: %s", addr)
  183. }
  184. return parts[0], parts[1], nil
  185. }
  186. func WriteAndReadDevice(frame []byte, conn net.Conn, former, after int) (data []byte, err error) {
  187. // 发送 Modbus RTU 帧
  188. n, err := conn.Write(frame)
  189. if err != nil {
  190. logger.Get().Errorln("Error writing to connection:", err)
  191. return
  192. }
  193. // 等待一段时间以接收响应
  194. time.Sleep(1000 * time.Millisecond)
  195. // 读取响应
  196. buffer := make([]byte, 1024)
  197. n, err = conn.Read(buffer)
  198. if err != nil {
  199. logger.Get().Errorln("Error reading from connection:", err)
  200. return
  201. }
  202. // 检查读取的字节数是否足够
  203. if n < former+after {
  204. err = fmt.Errorf("not enough bytes read to satisfy the slice range")
  205. return
  206. }
  207. // 返回子切片
  208. return buffer[former : n-after], err
  209. }