myTool.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. var regions []dao.Region
  18. // 尝试从主数据文件读取数据
  19. data, err := os.ReadFile(dataFilePath)
  20. if err != nil {
  21. if !os.IsNotExist(err) {
  22. return nil, fmt.Errorf("读取文件失败: %v", err)
  23. }
  24. // 如果主数据文件不存在,则尝试从备份文件读取
  25. } else {
  26. // 检查文件是否为空
  27. if len(data) > 0 {
  28. if err := json.Unmarshal(data, &regions); err != nil {
  29. return nil, fmt.Errorf("解析 JSON 失败 (主文件): %v, 原始数据: %s", err, string(data))
  30. }
  31. }
  32. }
  33. return regions, nil
  34. }
  35. func GetOnlineDevices() (devices []dao.Device, err error) {
  36. regions, err := LoadData()
  37. if err != nil {
  38. return nil, err
  39. }
  40. for _, region := range regions {
  41. for _, device := range region.Devices {
  42. if device.State == 0 {
  43. continue
  44. }
  45. devices = append(devices, device)
  46. }
  47. }
  48. return devices, err
  49. }
  50. func GetAllDevices() (devices []dao.Device, err error) {
  51. regions, err := LoadData()
  52. if err != nil {
  53. return nil, err
  54. }
  55. for _, region := range regions {
  56. for _, device := range region.Devices {
  57. devices = append(devices, device)
  58. }
  59. }
  60. return devices, err
  61. }
  62. // GetDataByDeviceId 按设备id获取信息 地区+设备
  63. func GetDataByDeviceId(deviceId string) (reg dao.Region, dev dao.Device, err error) {
  64. regions, err := LoadData()
  65. if err != nil {
  66. return reg, dev, err
  67. }
  68. for _, region := range regions {
  69. for _, device := range region.Devices {
  70. if device.Sn == deviceId {
  71. return region, device, nil
  72. }
  73. }
  74. }
  75. return reg, dev, fmt.Errorf("设备%s未找到", deviceId)
  76. }
  77. func SaveRegionOnData(data dao.Region) ([]dao.Region, error) {
  78. regions, err := LoadData()
  79. if err != nil {
  80. return regions, err
  81. }
  82. for i, region := range regions {
  83. if region.Name == data.Name {
  84. regions[i] = data
  85. break
  86. }
  87. }
  88. return regions, nil
  89. }
  90. // SaveData 保存数据到文件
  91. func SaveData(path string, newData []dao.Region) error {
  92. // 加载当前数据
  93. currentRegions, err := LoadData()
  94. if err != nil {
  95. return err
  96. }
  97. // 创建一个映射以便快速查找
  98. regionMap := make(map[string]dao.Region)
  99. for _, region := range currentRegions {
  100. regionMap[region.Name] = region
  101. }
  102. // 遍历传入的新数据,进行版本控制检查
  103. for _, newRegion := range newData {
  104. existingRegion, exists := regionMap[newRegion.Name]
  105. if exists {
  106. if existingRegion.Version != newRegion.Version {
  107. return fmt.Errorf("版本冲突: 区域 '%s' 的当前版本=%d, 提交版本=%d", newRegion.Name, existingRegion.Version, newRegion.Version)
  108. }
  109. // 更新版本号
  110. newRegion.Version++
  111. regionMap[newRegion.Name] = newRegion
  112. } else {
  113. // 如果区域不存在,则直接添加(假设这是新增的区域)
  114. newRegion.Version = 1 // 新增区域的初始版本号设为1
  115. regionMap[newRegion.Name] = newRegion
  116. }
  117. }
  118. // 将 map 转换回 slice
  119. updatedRegions := make([]dao.Region, 0, len(regionMap))
  120. for _, region := range regionMap {
  121. updatedRegions = append(updatedRegions, region)
  122. }
  123. // 序列化数据
  124. data, err := json.MarshalIndent(updatedRegions, "", " ")
  125. if err != nil {
  126. return fmt.Errorf("JSON 序列化失败: %v", err)
  127. }
  128. // 创建临时文件用于原子写入
  129. tempFile, err := ioutil.TempFile(filepath.Dir(path), "tmp-")
  130. if err != nil {
  131. return fmt.Errorf("创建临时文件失败: %v", err)
  132. }
  133. defer os.Remove(tempFile.Name()) // 确保即使出错也能清理临时文件
  134. // 写入临时文件
  135. if _, err := tempFile.Write(data); err != nil {
  136. tempFile.Close()
  137. return fmt.Errorf("写入临时文件失败: %v", err)
  138. }
  139. // 确保所有数据都写入磁盘
  140. if err := tempFile.Sync(); err != nil {
  141. tempFile.Close()
  142. return fmt.Errorf("同步临时文件失败: %v", err)
  143. }
  144. // 关闭临时文件
  145. if err := tempFile.Close(); err != nil {
  146. return fmt.Errorf("关闭临时文件失败: %v", err)
  147. }
  148. // 使用原子操作替换原始文件
  149. if err := os.Rename(tempFile.Name(), path); err != nil {
  150. return fmt.Errorf("替换文件失败: %v", err)
  151. }
  152. return nil
  153. }
  154. const (
  155. maxRetries = 3 // 最大重试次数
  156. readTimeout = 5 * time.Second // 读取超时时间
  157. writeTimeout = 5 * time.Second // 写入超时时间
  158. reconnectWait = 2 * time.Second // 重连等待时间
  159. )
  160. // checkConnection 检查连接是否仍然有效
  161. func checkConnection(conn net.Conn) error {
  162. probe := []byte{}
  163. _, err := conn.Write(probe)
  164. return err
  165. }
  166. // checkAndReconnect 检查是否需要重连,并在必要时执行重连
  167. func checkAndReconnect(conn net.Conn) (net.Conn, error) {
  168. remoteAddr := conn.RemoteAddr().String()
  169. // 关闭旧连接
  170. if err := conn.Close(); err != nil {
  171. logger.Get().Errorf("Failed to close connection: %v", err)
  172. return nil, err
  173. }
  174. // 解析原始连接的远程地址和网络接口
  175. addr, networkInterface, err := parseRemoteAddr(remoteAddr)
  176. if err != nil {
  177. logger.Get().Errorf("Failed to parse remote address: %v", err)
  178. return nil, err
  179. }
  180. // 尝试重新建立连接
  181. newConn, err := net.Dial("tcp", fmt.Sprintf("%s%%%s", addr, networkInterface))
  182. if err != nil {
  183. logger.Get().Errorf("Reconnect failed: %v", err)
  184. return nil, err
  185. }
  186. logger.Get().Warnf("Successfully reconnected to %s", remoteAddr)
  187. return newConn, nil
  188. }
  189. // isConnectionClosedError 检查错误是否表明连接被对端强制关闭或已关闭
  190. func isConnectionClosedError(err error) bool {
  191. if ne, ok := err.(*net.OpError); ok {
  192. return strings.Contains(ne.Err.Error(), "forcibly closed") ||
  193. strings.Contains(ne.Err.Error(), "broken pipe") ||
  194. strings.Contains(ne.Err.Error(), "connection reset") ||
  195. strings.Contains(ne.Err.Error(), "use of closed network connection")
  196. }
  197. return false
  198. }
  199. // setDeadlineWithRetry 使用重试机制设置读写截止时间
  200. func setDeadlineWithRetry(conn net.Conn, timeout time.Duration, operation string) error {
  201. for attempts := 0; attempts < maxRetries; attempts++ {
  202. var err error
  203. switch operation {
  204. case "read":
  205. err = conn.SetReadDeadline(time.Now().Add(timeout))
  206. case "write":
  207. err = conn.SetWriteDeadline(time.Now().Add(timeout))
  208. default:
  209. return fmt.Errorf("invalid operation: %s", operation)
  210. }
  211. if err == nil {
  212. return nil
  213. }
  214. if isConnectionClosedError(err) {
  215. logger.Get().Warnf("Set %s deadline failed due to closed connection, retrying (%d/%d)", operation, attempts+1, maxRetries)
  216. var newConn net.Conn
  217. var reconnErr error
  218. newConn, reconnErr = checkAndReconnect(conn)
  219. if reconnErr != nil {
  220. time.Sleep(reconnectWait) // 等待一段时间后重试
  221. continue // 继续下一次重试
  222. }
  223. conn = newConn
  224. continue // 重试设置截止时间
  225. }
  226. logger.Get().Errorf("Set %s deadline failed: %v", operation, err)
  227. return fmt.Errorf("set %s deadline failed after %d retries: %v", operation, attempts+1, err)
  228. }
  229. return fmt.Errorf("failed to set %s deadline after %d retries", operation, maxRetries)
  230. }
  231. // readWithRetry 使用重试机制进行读取操作
  232. func readWithRetry(buffer []byte, conn net.Conn) (int, error) {
  233. for attempts := 0; attempts < maxRetries; attempts++ {
  234. if err := setDeadlineWithRetry(conn, readTimeout, "read"); err != nil {
  235. return 0, err
  236. }
  237. // 检查连接是否仍然有效
  238. if err := checkConnection(conn); err != nil {
  239. if isConnectionClosedError(err) {
  240. logger.Get().Warnf("Connection check failed due to closed connection, retrying (%d/%d)", attempts+1, maxRetries)
  241. var newConn net.Conn
  242. var reconnErr error
  243. newConn, reconnErr = checkAndReconnect(conn)
  244. if reconnErr != nil {
  245. time.Sleep(reconnectWait) // 等待一段时间后重试
  246. continue // 继续下一次重试
  247. }
  248. conn = newConn
  249. continue // 重试读取
  250. }
  251. logger.Get().Errorf("Connection check failed: %v", err)
  252. return 0, fmt.Errorf("connection check failed after %d retries: %v", attempts+1, err)
  253. }
  254. n, err := conn.Read(buffer)
  255. if err == nil {
  256. return n, nil
  257. }
  258. if isConnectionClosedError(err) {
  259. logger.Get().Warnf("Read failed due to closed connection, retrying (%d/%d)", attempts+1, maxRetries)
  260. var newConn net.Conn
  261. var reconnErr error
  262. newConn, reconnErr = checkAndReconnect(conn)
  263. if reconnErr != nil {
  264. time.Sleep(reconnectWait) // 等待一段时间后重试
  265. continue // 继续下一次重试
  266. }
  267. conn = newConn
  268. continue // 重试读取
  269. }
  270. logger.Get().Errorf("Read failed: %v", err)
  271. return 0, fmt.Errorf("read failed after %d retries: %v", attempts+1, err)
  272. }
  273. return 0, fmt.Errorf("failed to read after %d retries", maxRetries)
  274. }
  275. // writeWithRetry 使用重试机制进行写入操作
  276. func writeWithRetry(frame []byte, conn net.Conn) error {
  277. for attempts := 0; attempts < maxRetries; attempts++ {
  278. if err := setDeadlineWithRetry(conn, writeTimeout, "write"); err != nil {
  279. return err
  280. }
  281. // 检查连接是否仍然有效
  282. if err := checkConnection(conn); err != nil {
  283. if isConnectionClosedError(err) {
  284. logger.Get().Warnf("Connection check failed due to closed connection, retrying (%d/%d)", attempts+1, maxRetries)
  285. var newConn net.Conn
  286. var reconnErr error
  287. newConn, reconnErr = checkAndReconnect(conn)
  288. if reconnErr != nil {
  289. time.Sleep(reconnectWait) // 等待一段时间后重试
  290. continue // 继续下一次重试
  291. }
  292. conn = newConn
  293. continue // 重试写入
  294. }
  295. logger.Get().Errorf("Connection check failed: %v", err)
  296. return fmt.Errorf("connection check failed after %d retries: %v", attempts+1, err)
  297. }
  298. _, err := conn.Write(frame)
  299. if err == nil {
  300. return nil
  301. }
  302. if isConnectionClosedError(err) {
  303. logger.Get().Warnf("Write failed due to closed connection, retrying (%d/%d)", attempts+1, maxRetries)
  304. var newConn net.Conn
  305. var reconnErr error
  306. newConn, reconnErr = checkAndReconnect(conn)
  307. if reconnErr != nil {
  308. time.Sleep(reconnectWait) // 等待一段时间后重试
  309. continue // 继续下一次重试
  310. }
  311. conn = newConn
  312. continue // 重试写入
  313. }
  314. logger.Get().Errorf("Write failed: %v", err)
  315. return fmt.Errorf("write failed after %d retries: %v", attempts+1, err)
  316. }
  317. return fmt.Errorf("failed to write after %d retries", maxRetries)
  318. }
  319. // ReadDevice 从设备读取数据
  320. func ReadDevice(buffer []byte, conn net.Conn) (int, error) {
  321. return readWithRetry(buffer, conn)
  322. }
  323. // WriteDevice1 向设备写入数据
  324. func WriteDevice1(frame []byte, conn net.Conn) error {
  325. return writeWithRetry(frame, conn)
  326. }
  327. func WriteDevice(frame []byte, conn net.Conn) error {
  328. for attempts := 0; attempts < maxRetries; attempts++ {
  329. if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
  330. logger.Get().Errorf("Set write deadline failed: %v", err)
  331. return err
  332. }
  333. _, err := conn.Write(frame)
  334. if err == nil {
  335. return nil
  336. }
  337. // 检查是否是对端强制关闭连接的错误
  338. 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")) {
  339. logger.Get().Warnf("Connection forcibly closed by peer, retrying (%d/%d)", attempts+1, maxRetries)
  340. // 关闭旧连接
  341. if err := conn.Close(); err != nil {
  342. logger.Get().Errorf("Failed to close connection: %v", err)
  343. }
  344. // 尝试重新建立连接
  345. var newConn net.Conn
  346. remoteAddr := conn.RemoteAddr().String()
  347. // 解析原始连接的远程地址和网络接口
  348. addr, networkInterface, err := parseRemoteAddr(remoteAddr)
  349. if err != nil {
  350. logger.Get().Errorf("Failed to parse remote address: %v", err)
  351. continue // 继续下一次重试
  352. }
  353. newConn, err = net.Dial("tcp", fmt.Sprintf("%s%%%s", addr, networkInterface))
  354. if err != nil {
  355. logger.Get().Errorf("Reconnect failed: %v", err)
  356. time.Sleep(reconnectWait) // 等待一段时间后重试
  357. continue // 继续下一次重试
  358. }
  359. conn = newConn
  360. continue // 重试写入
  361. }
  362. // 如果不是对端强制关闭连接的错误,则直接返回错误
  363. logger.Get().Errorf("Write failed: %v", err)
  364. return fmt.Errorf("write failed after %d retries: %v", attempts+1, err)
  365. }
  366. return fmt.Errorf("failed to write after %d retries", maxRetries)
  367. }
  368. // 解析远程地址,提取 IP 地址和网络接口名称
  369. func parseRemoteAddr(addr string) (string, string, error) {
  370. parts := strings.Split(addr, "%")
  371. if len(parts) != 2 {
  372. return "", "", fmt.Errorf("invalid remote address format: %s", addr)
  373. }
  374. return parts[0], parts[1], nil
  375. }
  376. func WriteAndReadDevice(frame []byte, conn net.Conn, former, after int) (data []byte, err error) {
  377. // 发送 Modbus RTU 帧
  378. n, err := conn.Write(frame)
  379. if err != nil {
  380. logger.Get().Errorln("Error writing to connection:", err)
  381. return
  382. }
  383. // 等待一段时间以接收响应
  384. time.Sleep(1000 * time.Millisecond)
  385. // 读取响应
  386. buffer := make([]byte, 1024)
  387. n, err = conn.Read(buffer)
  388. if err != nil {
  389. logger.Get().Errorln("Error reading from connection:", err)
  390. return
  391. }
  392. // 检查读取的字节数是否足够
  393. if n < former+after {
  394. err = fmt.Errorf("not enough bytes read to satisfy the slice range")
  395. return
  396. }
  397. // 返回子切片
  398. return buffer[former : n-after], err
  399. }