netmgrd.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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, httpTime := 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. netOK := tcpOK || pingOK
  70. if netOK {
  71. isOnline.Store(true)
  72. offlineStartTs.Store(0)
  73. if isSyncNTPTimeOK.Load() && time.Since(lastSyncNTPTime) < (time.Duration(60)*time.Minute) {
  74. t.Reset(interval2)
  75. continue
  76. }
  77. var err error
  78. if !httpTime.IsZero() { // 优先使用HTTP时间, 实测速度快且精度高
  79. err = SetSystemTime(httpTime)
  80. }
  81. if httpTime.IsZero() || err != nil {
  82. err = SyncNTPTime() //// 同步HTTP时间失败, 则尝试同步标准时间
  83. }
  84. if err == nil {
  85. isSyncNTPTimeOK.Store(true)
  86. baseapp.Logger.Infof("[%s] ✅ 系统时间已同步: %s", MODULE_NAME, time.Now().Format("2006-01-02 15:04:05"))
  87. lastSyncNTPTime = time.Now()
  88. t.Reset(interval2)
  89. continue
  90. } else {
  91. isSyncNTPTimeOK.Store(false)
  92. baseapp.Logger.Errorf("[%s] 同步系统时间时有错误发生: %v!!", MODULE_NAME, err)
  93. t.Reset(interval1)
  94. continue
  95. }
  96. }
  97. // 3.4, 联网失败-离线时
  98. if isOnline.Load() { // 状态由"1"变为"0"
  99. isOnline.Store(false)
  100. offlineStartTs.Store(time.Now().UnixNano()) // 记录离线开始时间
  101. }
  102. if offlineDuration() >= (time.Duration(60) * time.Second) {
  103. baseapp.Logger.Warnf("[%s] 网络长时间的断开, 尝试重新激活...", MODULE_NAME)
  104. switch curModemType {
  105. case Air720U: //重启合宙4G调制解调器
  106. modem1.ModuleExit()
  107. modem1.ModuleInit(true)
  108. case EC200U: // 重启移远4G调制解调器
  109. modem2.ModuleExit()
  110. modem2.ModuleInit(true)
  111. }
  112. openNetwork()
  113. offlineStartTs.Store(time.Now().UnixNano()) // 重置离线开始时间
  114. }
  115. t.Reset(interval1)
  116. case <-baseapp.IsExit2():
  117. return
  118. } // select end
  119. } // for end
  120. }
  121. // 返回联网状态
  122. func IsInetAvailable() bool {
  123. return isOnline.Load()
  124. }
  125. // 时间是否同步
  126. func IsSyncedNtpTime() bool {
  127. return isSyncNTPTimeOK.Load()
  128. }
  129. // 等待所有成功
  130. func WaitAllOK(timeout time.Duration) bool {
  131. deadline := time.Now().Add(timeout)
  132. tick := 50 * time.Millisecond
  133. for {
  134. if IsInetAvailable() && IsSyncedNtpTime() {
  135. return true
  136. }
  137. remaining := time.Until(deadline)
  138. if remaining <= 0 {
  139. return false
  140. }
  141. sleep := min(tick, remaining)
  142. time.Sleep(sleep)
  143. }
  144. }
  145. // 返回断网时长
  146. func offlineDuration() time.Duration {
  147. if IsInetAvailable() {
  148. return 0
  149. }
  150. ts := offlineStartTs.Load()
  151. if ts == 0 {
  152. offlineStartTs.Store(time.Now().UnixNano())
  153. ts = offlineStartTs.Load()
  154. }
  155. return time.Since(time.Unix(0, ts))
  156. }
  157. // 打开有线网络
  158. func openEth0Net() bool {
  159. mu1.Lock()
  160. defer mu1.Unlock()
  161. if isRunning1 {
  162. return true
  163. }
  164. killAllUdhcpc()
  165. err := disable4GInterfaces()
  166. if err != nil {
  167. baseapp.Logger.Errorf("[%s] 错误: %v!!", MODULE_NAME, err)
  168. return false
  169. }
  170. bExists, _ := udhcpcEth0Exists()
  171. if bExists {
  172. killEth0Udhcpc()
  173. }
  174. err = dialupEth0()
  175. if err != nil {
  176. baseapp.Logger.Errorf("[%s] 拨号连接\"eth0\"时发生错误: %v!!", MODULE_NAME, err)
  177. return false
  178. }
  179. ipv4, mask, err := getEth0Addr()
  180. if err != nil {
  181. baseapp.Logger.Errorf("[%s] 读取\"eth0\"地址时发生错误: %v!!", MODULE_NAME, err)
  182. return false
  183. }
  184. baseapp.Logger.Infof("[%s] \"eth0\"分配的地址: %s/%s", MODULE_NAME, ipv4, mask)
  185. exitCh1 = make(chan struct{})
  186. wg1.Add(1)
  187. go func() { // 启动携程守护"eth0"网卡上的 "udhcpc"后台服务进程
  188. defer wg1.Done()
  189. monitorEth0Udhcpc(exitCh1)
  190. }()
  191. isRunning1 = true
  192. return isRunning1
  193. }
  194. // 断开有线网络
  195. func closeEth0Net() {
  196. mu1.Lock()
  197. defer mu1.Unlock()
  198. if !isRunning1 {
  199. return
  200. }
  201. close(exitCh1)
  202. wg1.Wait() // 等待守护"eth0"网卡上的 "udhcpc"后台服务进程的携程退出
  203. bExists, _ := udhcpcEth0Exists()
  204. if bExists {
  205. killEth0Udhcpc()
  206. }
  207. isRunning1 = false
  208. }
  209. // 打开连接网络
  210. func openNetwork() {
  211. closeEth0Net()
  212. switch curModemType {
  213. case Air720U: //合宙4G调制解调器
  214. modem1.Stop4GNetwork()
  215. case EC200U: // 移远4G调制解调器
  216. modem2.Stop4GNetwork()
  217. }
  218. eth0CableOK, _ := isEth0CableConnected()
  219. if eth0CableOK && openEth0Net() {
  220. curNetType = NetEth
  221. baseapp.Logger.Infof("[%s] ✅ 有线网络已连接", MODULE_NAME)
  222. return
  223. }
  224. if curNetType == NetLTE && IsInetAvailable() { // 当前已是蜂窝网络且联网正常
  225. return
  226. }
  227. start4GNetwork := func() bool {
  228. startOK := false
  229. switch curModemType {
  230. case Air720U: //合宙4G调制解调器
  231. if eth2CableOK, _ := modem1.Is4GCableConnected(); eth2CableOK {
  232. startOK = modem1.Start4GNetwork()
  233. time.Sleep(time.Duration(500) * time.Millisecond)
  234. enableEth0() // 恢复有线网口
  235. }
  236. case EC200U: // 移远4G调制解调器
  237. if usb0CableOK, _ := modem2.Is4GCableConnected(); usb0CableOK {
  238. startOK = modem2.Start4GNetwork()
  239. time.Sleep(time.Duration(500) * time.Millisecond)
  240. enableEth0() // 恢复有线网口
  241. }
  242. }
  243. return startOK
  244. }
  245. if start4GNetwork() {
  246. curNetType = NetLTE
  247. baseapp.Logger.Infof("[%s] ✅ 蜂窝网络已连接(%s)", MODULE_NAME, curModemType.String())
  248. return
  249. }
  250. curNetType = NetNone
  251. baseapp.Logger.Warnf("[%s] 当前无可用网络接口(有线/蜂窝均不可用)!", MODULE_NAME)
  252. }
  253. // 得到当前联网类型: 有线、蜂窝
  254. func GetCurrentNetType() NetType {
  255. return curNetType
  256. }
  257. //export RTU_IsInetAvailable
  258. func RTU_IsInetAvailable() C.int {
  259. if IsInetAvailable() {
  260. return 1
  261. }
  262. return 0
  263. }
  264. //export RTU_IsSyncedNtpTime
  265. func RTU_IsSyncedNtpTime() C.int {
  266. if IsSyncedNtpTime() {
  267. return 1
  268. }
  269. return 0
  270. }