c_cloud.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package config
  2. import (
  3. "cicv-data-closedloop/common/config/c_log"
  4. "cicv-data-closedloop/common/util"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/gorilla/websocket"
  9. "gopkg.in/yaml.v3"
  10. "net/url"
  11. "os"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. type MonitorStruct struct {
  17. Url string `yaml:"url"`
  18. }
  19. type platform struct {
  20. UrlDeviceAuth string `yaml:"url-device-auth"`
  21. UrlTaskPoll string `yaml:"url-task-poll"`
  22. UrlTask string `yaml:"url-task"`
  23. }
  24. type rosbagStruct struct {
  25. Path string `yaml:"path"`
  26. Envs []string `yaml:"envs"`
  27. }
  28. type hostStruct struct {
  29. Name string `yaml:"name"`
  30. Ip string `yaml:"ip"`
  31. Topics []string `yaml:"topics"`
  32. Rosbag rosbagStruct `yaml:"rosbag"`
  33. }
  34. type ros struct {
  35. MasterAddress string `yaml:"master-address"`
  36. Nodes []string `yaml:"nodes"`
  37. }
  38. type disk struct {
  39. Name string `yaml:"name"`
  40. Used uint64 `yaml:"used"`
  41. Path []string `yaml:"path"`
  42. }
  43. type trigger struct {
  44. Label string `yaml:"label"`
  45. Topics []string `yaml:"topics"`
  46. }
  47. type CollectNumPlusStruct struct {
  48. Url string `yaml:"url"`
  49. }
  50. type CollectLimitStruct struct {
  51. Url string `yaml:"url"`
  52. Flag int `yaml:"flag"`
  53. Day int `yaml:"day"`
  54. Week int `yaml:"week"`
  55. Month int `yaml:"month"`
  56. Year int `yaml:"year"`
  57. }
  58. type CollectWindowStruct struct {
  59. Flag int `yaml:"flag"`
  60. Days []string `yaml:"days,omitempty"`
  61. Start string `yaml:"start_time"`
  62. End string `yaml:"end_time"`
  63. StartTime time.Time
  64. EndTime time.Time
  65. }
  66. type cloudConfig struct {
  67. CollectLimit CollectLimitStruct `yaml:"collect-limit"`
  68. CollectWindow CollectWindowStruct `yaml:"collect-window"`
  69. CollectNumPlus CollectNumPlusStruct `yaml:"collect-num-plus"`
  70. HasOneMsgTopic bool `yaml:"has-one-msg-topic"` // 是否存在只发单帧的话题
  71. FullCollect bool `yaml:"full-collect"`
  72. ConfigRefreshInterval int `yaml:"config-refresh-interval"` // 配置刷新时间间隔
  73. BagNumber int `yaml:"bag-number"`
  74. TimeWindowSendGap int `yaml:"time-window-send-gap"` // 主节点向从节点发送窗口的最小时间间隔
  75. BagDataDir string `yaml:"bag-data-dir"`
  76. BagCopyDir string `yaml:"bag-copy-dir"`
  77. TriggersDir string `yaml:"triggers-dir"`
  78. RpcPort string `yaml:"rpc-port"`
  79. Triggers []trigger `yaml:"triggers"`
  80. Hosts []hostStruct `yaml:"hosts"`
  81. Ros ros `yaml:"ros"`
  82. Platform platform `yaml:"platform"`
  83. Disk disk `yaml:"disk"`
  84. Monitor MonitorStruct `yaml:"monitor"`
  85. }
  86. //// Request 结构体定义
  87. //type Request struct {
  88. // Type string `json:"type"`
  89. // UUID string `json:"uuid"`
  90. // CommandID string `json:"commandId"`
  91. // Parameter interface{} `json:"parameter"`
  92. //}
  93. //
  94. //// Response 结构体定义
  95. //type Response struct {
  96. // CommandID string `json:"commandId"`
  97. // ErrorCode string `json:"errorCode"`
  98. // Results map[string]string `json:"results"`
  99. // Status string `json:"status"`
  100. // Time int64 `json:"time"`
  101. // Type string `json:"type"`
  102. // UUID string `json:"uuid"`
  103. //}
  104. var (
  105. CloudConfig cloudConfig
  106. CloudConfigMutex sync.RWMutex
  107. )
  108. // InitCloudConfig 初始化业务配置
  109. func InitCloudConfig() {
  110. // history20240401:朴津机器人额外加一个获取sn码
  111. var snCode string
  112. for {
  113. time.Sleep(time.Duration(2) * time.Second)
  114. snCode, err := getSnCode()
  115. if err != nil {
  116. c_log.GlobalLogger.Error("获取sn码失败:", err.Error())
  117. continue
  118. }
  119. LocalConfig.SecretKey = snCode
  120. LocalConfig.EquipmentNo = "pjibot-" + snCode
  121. break
  122. }
  123. c_log.GlobalLogger.Info("本地机器人sn码为:", snCode)
  124. c_log.GlobalLogger.Info("初始化OSS配置文件 - 开始。")
  125. // 获取文件的目录
  126. _ = util.CreateParentDir(LocalConfig.CloudConfigLocalPath)
  127. // 3 ------- 获取 yaml 字符串 -------
  128. cloudConfigObjectKey := LocalConfig.OssBasePrefix + LocalConfig.EquipmentNo + "/" + LocalConfig.CloudConfigFilename
  129. // 判断文件是否存在。如果不存在则使用默认的
  130. isExist, err := OssBucket.IsObjectExist(cloudConfigObjectKey)
  131. if err != nil {
  132. c_log.GlobalLogger.Errorf("判断配置文件是否存在失败,错误信息为:%v", err)
  133. }
  134. if isExist {
  135. c_log.GlobalLogger.Info("使用机器人自定义配置文件:", cloudConfigObjectKey)
  136. } else {
  137. cloudConfigObjectKey = LocalConfig.OssBasePrefix + LocalConfig.CloudConfigFilename // 默认配置文件路径
  138. c_log.GlobalLogger.Info("使用机器人默认配置文件:", cloudConfigObjectKey)
  139. }
  140. for {
  141. OssMutex.Lock()
  142. err := OssBucket.GetObjectToFile(cloudConfigObjectKey, LocalConfig.CloudConfigLocalPath)
  143. OssMutex.Unlock()
  144. if err != nil {
  145. c_log.GlobalLogger.Error("下载 OSS 上的配置文件 "+cloudConfigObjectKey+" 失败,请尽快在 OSS 上传配置文件。", err)
  146. time.Sleep(time.Duration(2) * time.Second)
  147. continue
  148. }
  149. break
  150. }
  151. content, err := os.ReadFile(LocalConfig.CloudConfigLocalPath)
  152. if err != nil {
  153. c_log.GlobalLogger.Error("程序崩溃,配置文件 ", LocalConfig.CloudConfigLocalPath, " 读取失败:", err)
  154. os.Exit(-1)
  155. }
  156. // 4 ------- 解析YAML内容 -------
  157. var newCloudConfig cloudConfig
  158. err = yaml.Unmarshal(content, &newCloudConfig)
  159. if err != nil {
  160. c_log.GlobalLogger.Error("程序崩溃,配置文件 ", LocalConfig.CloudConfigLocalPath, " 解析失败:", err)
  161. os.Exit(-1)
  162. }
  163. cw := time.Now()
  164. loc := cw.Location()
  165. // 单独解析采集时间
  166. startTime, err := time.ParseInLocation("15:04", newCloudConfig.CollectWindow.Start, loc)
  167. if err != nil {
  168. c_log.GlobalLogger.Error("云端配置文件解析采集时间【startTime】失败 ", err, "取默认值【00:00】")
  169. newCloudConfig.CollectWindow.StartTime, _ = time.ParseInLocation("15:04", "00:00", loc)
  170. }
  171. newCloudConfig.CollectWindow.StartTime = startTime
  172. endTime, err := time.ParseInLocation("15:04", newCloudConfig.CollectWindow.End, loc)
  173. if err != nil {
  174. c_log.GlobalLogger.Error("云端配置文件解析采集时间【endTime】失败 ", err, "取默认值【23:59】")
  175. newCloudConfig.CollectWindow.EndTime, _ = time.ParseInLocation("15:04", "23:59", loc)
  176. }
  177. newCloudConfig.CollectWindow.EndTime = endTime
  178. if len(newCloudConfig.CollectWindow.Days) == 0 {
  179. // 默认设置为每天
  180. newCloudConfig.CollectWindow.Days = []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
  181. }
  182. // 5 ------- 校验 yaml -------
  183. if checkCloudConfig(newCloudConfig) {
  184. CloudConfigMutex.RLock()
  185. CloudConfig = newCloudConfig
  186. CloudConfigMutex.RUnlock()
  187. } else {
  188. c_log.GlobalLogger.Error("程序崩溃,配置文件格式错误:", newCloudConfig)
  189. os.Exit(-1)
  190. }
  191. c_log.GlobalLogger.Info("初始化OSS配置文件 - 成功。")
  192. util.CreateDir(CloudConfig.BagDataDir)
  193. util.CreateDir(CloudConfig.BagCopyDir)
  194. }
  195. // 更新业务配置
  196. func refreshCloudConfig() {
  197. // 获取文件的目录
  198. _ = util.CreateParentDir(LocalConfig.CloudConfigLocalPath)
  199. // 3 ------- 获取 yaml 字符串 -------
  200. var content []byte
  201. cloudConfigObjectKey := LocalConfig.OssBasePrefix + LocalConfig.EquipmentNo + "/" + LocalConfig.CloudConfigFilename
  202. isExist, err := OssBucket.IsObjectExist(cloudConfigObjectKey)
  203. if err != nil {
  204. c_log.GlobalLogger.Errorf("判断配置文件是否存在失败,错误信息为:%v", err)
  205. return
  206. }
  207. if !isExist {
  208. cloudConfigObjectKey = LocalConfig.OssBasePrefix + LocalConfig.CloudConfigFilename // 默认配置文件路径
  209. }
  210. OssMutex.Lock()
  211. err = OssBucket.GetObjectToFile(cloudConfigObjectKey, LocalConfig.CloudConfigLocalPath)
  212. OssMutex.Unlock()
  213. if err != nil {
  214. c_log.GlobalLogger.Error("下载oss上的配置文件"+cloudConfigObjectKey+"失败。", err)
  215. return
  216. }
  217. content, err = os.ReadFile(LocalConfig.CloudConfigLocalPath)
  218. if err != nil {
  219. c_log.GlobalLogger.Error("配置文件 ", LocalConfig.CloudConfigLocalPath, " 读取失败:", err)
  220. return
  221. }
  222. // 4 ------- 解析YAML内容 -------
  223. var newCloudConfig cloudConfig
  224. err = yaml.Unmarshal(content, &newCloudConfig)
  225. if err != nil {
  226. c_log.GlobalLogger.Error("配置文件 ", LocalConfig.CloudConfigLocalPath, " 解析失败:", err)
  227. return
  228. }
  229. // 5 ------- 校验 yaml -------
  230. if checkCloudConfig(newCloudConfig) {
  231. CloudConfigMutex.RLock()
  232. CloudConfig = newCloudConfig
  233. CloudConfigMutex.RUnlock()
  234. } else {
  235. c_log.GlobalLogger.Error("配置文件格式错误:", newCloudConfig)
  236. return
  237. }
  238. util.CreateDir(CloudConfig.BagDataDir)
  239. util.CreateDir(CloudConfig.BagCopyDir)
  240. }
  241. // RefreshCloudConfig 轮询oss上的配置文件更新到本地
  242. func RefreshCloudConfig() {
  243. for {
  244. time.Sleep(time.Duration(CloudConfig.ConfigRefreshInterval) * time.Second)
  245. refreshCloudConfig()
  246. }
  247. }
  248. // CheckConfig 校验 cfg.yaml 文件
  249. func checkCloudConfig(check cloudConfig) bool {
  250. if len(check.Hosts) != 1 {
  251. c_log.GlobalLogger.Error("cloud-config.yaml中配置的hosts必须为1。")
  252. os.Exit(-1)
  253. }
  254. return true
  255. }
  256. func getSnCode() (string, error) {
  257. var command []string
  258. command = append(command, "get")
  259. command = append(command, "sn")
  260. _, snOutput, err := util.ExecuteSync(LocalConfig.RosparamPath, command...)
  261. if err != nil {
  262. return "", errors.New("执行获取sn码命令" + util.ToString(command) + "出错:" + util.ToString(err))
  263. }
  264. c_log.GlobalLogger.Info("执行获取sn码命令", command, "成功,结果为:", snOutput)
  265. snCode := strings.Replace(strings.Replace(snOutput, " ", "", -1), "\n", "", -1)
  266. return snCode, nil
  267. }
  268. // SendWebsocketRequest 发送WebSocket请求并返回sn字段的值
  269. func SendWebsocketRequest(serverURL, path string, request Request) (string, error) {
  270. // 构建WebSocket连接URL
  271. u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
  272. // 创建一个Dialer实例,用于建立WebSocket连接
  273. dialer := websocket.Dialer{
  274. ReadBufferSize: 1024,
  275. WriteBufferSize: 1024,
  276. // 可选:设置超时等
  277. HandshakeTimeout: 5 * time.Second,
  278. }
  279. // 建立WebSocket连接
  280. conn, _, err := dialer.Dial(u.String(), nil)
  281. if err != nil {
  282. return "", fmt.Errorf("dial: %w", err)
  283. }
  284. defer conn.Close()
  285. // 将请求JSON编码为字节
  286. requestJSON, err := json.Marshal(request)
  287. if err != nil {
  288. return "", fmt.Errorf("marshal request: %w", err)
  289. }
  290. // 发送WebSocket消息
  291. err = conn.WriteMessage(websocket.TextMessage, requestJSON)
  292. if err != nil {
  293. return "", fmt.Errorf("write: %w", err)
  294. }
  295. // 读取WebSocket响应
  296. _, responseBytes, err := conn.ReadMessage()
  297. if err != nil {
  298. return "", fmt.Errorf("read: %w", err)
  299. }
  300. // 将响应字节解码为JSON
  301. var response Response
  302. err = json.Unmarshal(responseBytes, &response)
  303. if err != nil {
  304. return "", fmt.Errorf("unmarshal response: %w", err)
  305. }
  306. // 返回sn字段的值
  307. return response.Results["sn"], nil
  308. }