myTool.go 13 KB

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