myTool.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package utils
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net"
  9. "os"
  10. "path/filepath"
  11. "server/dao"
  12. "server/logger"
  13. "server/model"
  14. "strings"
  15. "time"
  16. )
  17. const dataFilePath = "static/data.json"
  18. // LoadData 从文件中加载 Region 数据。
  19. func LoadData() ([]dao.Region, error) {
  20. data, err := os.ReadFile(dataFilePath)
  21. datafb, err := os.ReadFile("static/data-fb.json")
  22. var regionsfb []dao.Region
  23. if err := json.Unmarshal(datafb, &regionsfb); err != nil {
  24. // 提供更多的上下文信息来帮助调试
  25. return nil, fmt.Errorf("解析 JSON 失败: %v, 原始数据: %s", err, string(data))
  26. }
  27. if err != nil {
  28. if os.IsNotExist(err) {
  29. return regionsfb, nil // 文件不存在时返回空数组
  30. }
  31. return nil, fmt.Errorf("读取文件失败: %v", err)
  32. }
  33. // 检查文件是否为空
  34. if len(data) == 0 {
  35. return regionsfb, nil // 如果文件为空,返回空数组
  36. }
  37. var regions []dao.Region
  38. if err := json.Unmarshal(data, &regions); err != nil {
  39. // 提供更多的上下文信息来帮助调试
  40. return nil, fmt.Errorf("解析 JSON 失败: %v, 原始数据: %s", err, string(data))
  41. }
  42. return regions, nil
  43. }
  44. func GetOnlineDevices() (devices []dao.Device, err error) {
  45. regions, err := LoadData()
  46. if err != nil {
  47. return nil, err
  48. }
  49. for _, region := range regions {
  50. for _, device := range region.Devices {
  51. if device.State == 0 {
  52. continue
  53. }
  54. devices = append(devices, device)
  55. }
  56. }
  57. return devices, err
  58. }
  59. func GetAllDevices() (devices []dao.Device, err error) {
  60. regions, err := LoadData()
  61. if err != nil {
  62. return nil, err
  63. }
  64. for _, region := range regions {
  65. for _, device := range region.Devices {
  66. devices = append(devices, device)
  67. }
  68. }
  69. return devices, err
  70. }
  71. // GetDataByDeviceId 按设备id获取信息 地区+设备
  72. func GetDataByDeviceId(deviceId string) (reg dao.Region, dev dao.Device, err error) {
  73. regions, err := LoadData()
  74. if err != nil {
  75. return reg, dev, err
  76. }
  77. for _, region := range regions {
  78. for _, device := range region.Devices {
  79. if device.Sn == deviceId {
  80. return region, device, nil
  81. }
  82. }
  83. }
  84. return reg, dev, fmt.Errorf("设备%s未找到", deviceId)
  85. }
  86. func SaveRegionOnData(data dao.Region) ([]dao.Region, error) {
  87. regions, err := LoadData()
  88. if err != nil {
  89. return regions, err
  90. }
  91. for i, region := range regions {
  92. if region.Name == data.Name {
  93. regions[i] = data
  94. }
  95. }
  96. return regions, nil
  97. }
  98. // SaveData 保存数据到文件
  99. func SaveData(path string, parameter interface{}) error {
  100. // 参数验证
  101. if parameter == nil {
  102. return fmt.Errorf("无法保存 nil 数据")
  103. }
  104. // 序列化数据
  105. data, err := json.MarshalIndent(parameter, "", " ")
  106. if err != nil {
  107. return fmt.Errorf("JSON 序列化失败: %v", err)
  108. }
  109. // 创建临时文件用于原子写入
  110. tempFile, err := os.CreateTemp(filepath.Dir(path), "tmp-*.json")
  111. if err != nil {
  112. return fmt.Errorf("创建临时文件失败: %v", err)
  113. }
  114. defer os.Remove(tempFile.Name()) // 确保即使出错也能清理临时文件
  115. // 写入临时文件
  116. if _, err := io.Copy(tempFile, bytes.NewReader(data)); err != nil {
  117. return fmt.Errorf("写入临时文件失败: %v", err)
  118. }
  119. // 确保所有数据都写入磁盘
  120. if err := tempFile.Sync(); err != nil {
  121. return fmt.Errorf("同步临时文件失败: %v", err)
  122. }
  123. // 关闭临时文件(这里其实可以省略错误处理,因为defer会确保文件被关闭)
  124. if err := tempFile.Close(); err != nil {
  125. // 通常不需要处理这个错误,因为defer已经确保了关闭操作
  126. // 但如果你想记录这个错误,可以在这里做
  127. }
  128. // 使用原子操作替换原始文件
  129. if err := os.Rename(tempFile.Name(), path); err != nil {
  130. // 将结构体转换为JSON字节切片
  131. jsonBytes, err := json.Marshal(parameter)
  132. if err != nil {
  133. return fmt.Errorf("Error marshalling to JSON: %v\n", err)
  134. }
  135. // 将字节切片转换为字符串
  136. jsonString := string(jsonBytes)
  137. // 打开或创建文件,并设置标志以覆盖原有内容
  138. file, err := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  139. if err != nil {
  140. fmt.Printf("无法打开或创建文件: %v\n", err)
  141. }
  142. defer file.Close() // 确保在main函数结束时关闭文件
  143. // 写入数据到文件
  144. _, err = file.WriteString(string(jsonString))
  145. if err != nil {
  146. fmt.Printf("写入文件失败: %v\n", err)
  147. }
  148. //return fmt.Errorf("替换文件失败,直接写入: %v", err)
  149. }
  150. return nil
  151. }
  152. const (
  153. maxRetries = 3 // 最大重试次数
  154. writeTimeout = 5 * time.Second // 写入超时时间
  155. reconnectWait = 2 * time.Second // 重连等待时间
  156. )
  157. func WriteDevice(deviceId string, frame []byte, conn net.Conn) error {
  158. for attempts := 0; attempts < maxRetries; attempts++ {
  159. if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
  160. // 捕捉 "use of closed network connection" 错误
  161. if ne, ok := err.(*net.OpError); ok && strings.Contains(strings.ToLower(ne.Err.Error()), "use of closed network connection") {
  162. logger.Get().Warnf("Connection is closed, retrying (%d/%d)", attempts+1, maxRetries)
  163. if attempts == 3 {
  164. delete(model.ConnectionMap, deviceId)
  165. }
  166. // 关闭旧连接(尽管这里认为连接已关闭)
  167. if err := conn.Close(); err != nil {
  168. logger.Get().Errorf("Failed to close connection: %v", err)
  169. delete(model.ConnectionMap, deviceId)
  170. }
  171. // 尝试重新建立连接
  172. var newConn net.Conn
  173. remoteAddr := conn.RemoteAddr().String()
  174. // 解析原始连接的远程地址和网络接口
  175. addr, networkInterface, err := parseRemoteAddr(remoteAddr)
  176. if err != nil {
  177. logger.Get().Errorf("Failed to parse remote address: %v", err)
  178. continue // 继续下一次重试
  179. }
  180. newConn, err = net.Dial("tcp", fmt.Sprintf("%s%%%s", addr, networkInterface))
  181. if err != nil {
  182. logger.Get().Errorf("Reconnect failed: %v", err)
  183. time.Sleep(reconnectWait) // 等待一段时间后重试
  184. continue // 继续下一次重试
  185. }
  186. conn = newConn
  187. continue // 重试写入
  188. } else {
  189. // 如果是其他类型的错误,则直接返回
  190. logger.Get().Errorf("Set write deadline failed: %v", err)
  191. return err
  192. }
  193. }
  194. _, err := conn.Write(frame)
  195. if err == nil {
  196. return nil
  197. }
  198. // 检查是否是对端强制关闭连接的错误
  199. 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")) {
  200. logger.Get().Warnf("Connection forcibly closed by peer, retrying (%d/%d)", attempts+1, maxRetries)
  201. // 关闭旧连接
  202. if err := conn.Close(); err != nil {
  203. logger.Get().Errorf("Failed to close connection: %v", err)
  204. }
  205. // 尝试重新建立连接
  206. var newConn net.Conn
  207. remoteAddr := conn.RemoteAddr().String()
  208. // 解析原始连接的远程地址和网络接口
  209. addr, networkInterface, err := parseRemoteAddr(remoteAddr)
  210. if err != nil {
  211. logger.Get().Errorf("Failed to parse remote address: %v", err)
  212. continue // 继续下一次重试
  213. }
  214. newConn, err = net.Dial("tcp", fmt.Sprintf("%s%%%s", addr, networkInterface))
  215. if err != nil {
  216. logger.Get().Errorf("Reconnect failed: %v", err)
  217. time.Sleep(reconnectWait) // 等待一段时间后重试
  218. continue // 继续下一次重试
  219. }
  220. conn = newConn
  221. continue // 重试写入
  222. }
  223. // 如果不是对端强制关闭连接的错误,则直接返回错误
  224. logger.Get().Errorf("Write failed: %v", err)
  225. return fmt.Errorf("write failed after %d retries: %v", attempts+1, err)
  226. }
  227. return fmt.Errorf("failed to write after %d retries", maxRetries)
  228. }
  229. // 解析远程地址,提取 IP 地址和网络接口名称
  230. func parseRemoteAddr(addr string) (string, string, error) {
  231. parts := strings.Split(addr, "%")
  232. if len(parts) != 2 {
  233. return "", "", fmt.Errorf("invalid remote address format: %s", addr)
  234. }
  235. return parts[0], parts[1], nil
  236. }
  237. func WriteAndReadDevice(frame []byte, conn net.Conn, former, after int) (data []byte, err error) {
  238. // 发送 Modbus RTU 帧
  239. n, err := conn.Write(frame)
  240. if err != nil {
  241. logger.Get().Errorln("Error writing to connection:", err)
  242. return
  243. }
  244. // 等待一段时间以接收响应
  245. time.Sleep(1000 * time.Millisecond)
  246. // 读取响应
  247. buffer := make([]byte, 1024)
  248. n, err = conn.Read(buffer)
  249. if err != nil {
  250. logger.Get().Errorln("Error reading from connection:", err)
  251. return
  252. }
  253. // 检查读取的字节数是否足够
  254. if n < former+after {
  255. err = fmt.Errorf("not enough bytes read to satisfy the slice range")
  256. return
  257. }
  258. // 返回子切片
  259. return buffer[former : n-after], err
  260. }
  261. func SixteenTurnsTwo(val string) (string, error) {
  262. // 将16进制字符串解码为字节切片
  263. byte16, err := hex.DecodeString(val)
  264. if err != nil {
  265. fmt.Println("解码失败:", err)
  266. return "", nil
  267. }
  268. // 转换为二进制字符串
  269. binStr := ""
  270. for _, b := range byte16 {
  271. // 使用fmt.Sprintf将每个字节转换为8位的二进制字符串
  272. binStr += fmt.Sprintf("%08b", b)
  273. }
  274. return binStr, err
  275. }