netmgrd.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package netmgrd
  2. import "C"
  3. import (
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "hnyfkj.com.cn/rtu/linux/baseapp"
  8. modem1 "hnyfkj.com.cn/rtu/linux/air720u" // 合宙4G调制解调器
  9. modem2 "hnyfkj.com.cn/rtu/linux/ec200u" // 移远4G调制解调器
  10. )
  11. const MODULE_NAME = "NetworkManager"
  12. var (
  13. isOnline atomic.Bool // 标记是否联网
  14. offlineStartTs atomic.Int64 // 离线开始时间
  15. isSyncNTPTimeOK atomic.Bool // 标记本地时间是否已同步成功
  16. lastSyncNTPTime time.Time // 记录同步网络时间成功的时间
  17. curNetType NetType // 当前的网络类型: 有线、蜂窝
  18. mu1 sync.Mutex
  19. isRunning1 bool
  20. exitCh1 chan struct{}
  21. wg1 sync.WaitGroup
  22. )
  23. type NetType int
  24. const (
  25. NetNone NetType = iota
  26. NetEth // 有线网络, 注册网卡名为"eth0"
  27. NetLTE // 蜂窝网络
  28. )
  29. func (n NetType) String() string {
  30. switch n {
  31. case NetEth:
  32. return "有线"
  33. case NetLTE:
  34. return "蜂窝"
  35. default:
  36. return "未知"
  37. }
  38. }
  39. const (
  40. interval1 = time.Duration(1) * time.Second
  41. interval2 = time.Duration(5) * time.Second
  42. )
  43. func ModuleInit() {
  44. go serviceRun()
  45. }
  46. // 联网保持服务
  47. func serviceRun() {
  48. // 1, 首次打开网络
  49. openNetwork()
  50. // 2, 监控联网状态
  51. t := time.NewTimer(interval1)
  52. defer t.Stop()
  53. for {
  54. select {
  55. case <-t.C:
  56. // 3.1 切换网络-看情况
  57. eth0CableOK, _ := isEth0CableConnected()
  58. if eth0CableOK && curNetType != NetEth { // 有线插入 && 当前不是有线
  59. baseapp.Logger.Warnf("[%s] 检测到有线接入,切换到有线网络...", MODULE_NAME)
  60. openNetwork()
  61. } else if !eth0CableOK && curNetType == NetEth { // 有线拔出 && 当前还是有线
  62. baseapp.Logger.Warnf("[%s] 检测到有线断开,切换到蜂窝网络...", MODULE_NAME)
  63. openNetwork()
  64. }
  65. // 3.2, 联网检测-看结果
  66. dnsOK, pingOK, tcpOK, httpOK := CheckNetwork()
  67. baseapp.Logger.Infof("[%s] 联网类型: %s; 检测结果: DNS OK=%v, PING OK=%v, TCP OK=%v, HTTP OK=%v", MODULE_NAME, curNetType.String(), dnsOK, pingOK, tcpOK, httpOK)
  68. // 3.3, 联网成功-在线时
  69. if dnsOK && pingOK && tcpOK {
  70. isOnline.Store(true)
  71. offlineStartTs.Store(0)
  72. if isSyncNTPTimeOK.Load() {
  73. if time.Since(lastSyncNTPTime) >= (time.Duration(60) * time.Minute) { // 1小时后需要再次同步NTP时间
  74. isSyncNTPTimeOK.Store(false)
  75. } else {
  76. t.Reset(interval2)
  77. continue
  78. }
  79. }
  80. err := SyncNTPTime()
  81. if err == nil {
  82. isSyncNTPTimeOK.Store(true)
  83. baseapp.Logger.Infof("[%s] NTP时间已同步", MODULE_NAME)
  84. lastSyncNTPTime = time.Now()
  85. t.Reset(interval2)
  86. continue
  87. } else {
  88. baseapp.Logger.Errorf("[%s] 同步NTP时间时有错误发生: %v!!", MODULE_NAME, err)
  89. t.Reset(interval1)
  90. continue
  91. }
  92. }
  93. // 3.4, 联网失败-离线时
  94. if isOnline.Load() { // 状态由"1"变为"0"
  95. isOnline.Store(false)
  96. offlineStartTs.Store(time.Now().UnixNano()) // 记录离线开始时间
  97. }
  98. if offlineDuration() >= (time.Duration(60) * time.Second) {
  99. baseapp.Logger.Warnf("[%s] 网络长时间的断开, 尝试重新激活...", MODULE_NAME)
  100. switch curModemType {
  101. case Air720U: //重启合宙4G调制解调器
  102. modem1.ModuleExit()
  103. modem1.ModuleInit(true)
  104. case EC200U: // 重启移远4G调制解调器
  105. modem2.ModuleExit()
  106. modem2.ModuleInit(true)
  107. }
  108. openNetwork()
  109. offlineStartTs.Store(time.Now().UnixNano()) // 重置离线开始时间
  110. }
  111. t.Reset(interval1)
  112. case <-baseapp.IsExit2():
  113. return
  114. } // select end
  115. } // for end
  116. }
  117. // 返回联网状态
  118. func IsInetAvailable() bool {
  119. return isOnline.Load()
  120. }
  121. // 时间是否同步
  122. func IsSyncedNtpTime() bool {
  123. return isSyncNTPTimeOK.Load()
  124. }
  125. // 等待所有成功
  126. func WaitAllOK(timeout time.Duration) bool {
  127. deadline := time.Now().Add(timeout)
  128. tick := 50 * time.Millisecond
  129. for {
  130. if IsInetAvailable() && IsSyncedNtpTime() {
  131. return true
  132. }
  133. remaining := time.Until(deadline)
  134. if remaining <= 0 {
  135. return false
  136. }
  137. sleep := min(tick, remaining)
  138. time.Sleep(sleep)
  139. }
  140. }
  141. // 返回断网时长
  142. func offlineDuration() time.Duration {
  143. if IsInetAvailable() {
  144. return 0
  145. }
  146. ts := offlineStartTs.Load()
  147. if ts == 0 {
  148. offlineStartTs.Store(time.Now().UnixNano())
  149. ts = offlineStartTs.Load()
  150. }
  151. return time.Since(time.Unix(0, ts))
  152. }
  153. // 打开有线网络
  154. func openEth0Net() bool {
  155. mu1.Lock()
  156. defer mu1.Unlock()
  157. if isRunning1 {
  158. return true
  159. }
  160. killAllUdhcpc()
  161. err := disable4GInterfaces()
  162. if err != nil {
  163. baseapp.Logger.Errorf("[%s] 错误: %v!!", MODULE_NAME, err)
  164. return false
  165. }
  166. bExists, _ := udhcpcEth0Exists()
  167. if bExists {
  168. killEth0Udhcpc()
  169. }
  170. err = dialupEth0()
  171. if err != nil {
  172. baseapp.Logger.Errorf("[%s] 拨号连接\"eth0\"时发生错误: %v!!", MODULE_NAME, err)
  173. return false
  174. }
  175. ipv4, mask, err := getEth0Addr()
  176. if err != nil {
  177. baseapp.Logger.Errorf("[%s] 读取\"eth0\"地址时发生错误: %v!!", MODULE_NAME, err)
  178. return false
  179. }
  180. baseapp.Logger.Infof("[%s] \"eth0\"分配的地址: %s/%s", MODULE_NAME, ipv4, mask)
  181. exitCh1 = make(chan struct{})
  182. wg1.Add(1)
  183. go func() { // 启动携程守护"eth0"网卡上的 "udhcpc"后台服务进程
  184. defer wg1.Done()
  185. monitorEth0Udhcpc(exitCh1)
  186. }()
  187. isRunning1 = true
  188. return isRunning1
  189. }
  190. // 断开有线网络
  191. func closeEth0Net() {
  192. mu1.Lock()
  193. defer mu1.Unlock()
  194. if !isRunning1 {
  195. return
  196. }
  197. close(exitCh1)
  198. wg1.Wait() // 等待守护"eth0"网卡上的 "udhcpc"后台服务进程的携程退出
  199. bExists, _ := udhcpcEth0Exists()
  200. if bExists {
  201. killEth0Udhcpc()
  202. }
  203. isRunning1 = false
  204. }
  205. // 打开连接网络
  206. func openNetwork() {
  207. closeEth0Net()
  208. switch curModemType {
  209. case Air720U: //合宙4G调制解调器
  210. modem1.Stop4GNetwork()
  211. case EC200U: // 移远4G调制解调器
  212. modem2.Stop4GNetwork()
  213. }
  214. eth0CableOK, _ := isEth0CableConnected()
  215. if eth0CableOK && openEth0Net() {
  216. curNetType = NetEth
  217. baseapp.Logger.Infof("[%s] ✅ 有线网络已连接", MODULE_NAME)
  218. return
  219. }
  220. start4GNetwork := func() bool {
  221. startOK := false
  222. switch curModemType {
  223. case Air720U: //合宙4G调制解调器
  224. if eth2CableOK, _ := modem1.Is4GCableConnected(); eth2CableOK {
  225. startOK = modem1.Start4GNetwork()
  226. time.Sleep(time.Duration(500) * time.Millisecond)
  227. enableEth0() // 恢复有线网口
  228. }
  229. case EC200U: // 移远4G调制解调器
  230. if usb0CableOK, _ := modem2.Is4GCableConnected(); usb0CableOK {
  231. startOK = modem2.Start4GNetwork()
  232. time.Sleep(time.Duration(500) * time.Millisecond)
  233. enableEth0() // 恢复有线网口
  234. }
  235. }
  236. return startOK
  237. }
  238. if start4GNetwork() {
  239. curNetType = NetLTE
  240. baseapp.Logger.Infof("[%s] ✅ 蜂窝网络已连接(%s)", MODULE_NAME, curModemType.String())
  241. return
  242. }
  243. curNetType = NetNone
  244. baseapp.Logger.Warnf("[%s] 当前无可用网络接口(有线/蜂窝均不可用)!", MODULE_NAME)
  245. }
  246. // 得到当前联网类型: 有线、蜂窝
  247. func GetCurrentNetType() NetType {
  248. return curNetType
  249. }
  250. //export RTU_IsInetAvailable
  251. func RTU_IsInetAvailable() C.int {
  252. if IsInetAvailable() {
  253. return 1
  254. }
  255. return 0
  256. }
  257. //export RTU_IsSyncedNtpTime
  258. func RTU_IsSyncedNtpTime() C.int {
  259. if IsSyncedNtpTime() {
  260. return 1
  261. }
  262. return 0
  263. }