myTool.go 16 KB

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