myTool.go 13 KB

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