c_cloud.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 PlatformStruct 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 RosStruct struct {
  35. MasterAddress string `yaml:"master-address"`
  36. Nodes []string `yaml:"nodes"`
  37. }
  38. type DiskStruct struct {
  39. Name string `yaml:"name"`
  40. Used uint64 `yaml:"used"`
  41. }
  42. type TriggerStruct struct {
  43. Label string `yaml:"label"`
  44. Topics []string `yaml:"topics"`
  45. }
  46. type CollectLimitStruct struct {
  47. Url string `yaml:"url"`
  48. Day int `yaml:"day"`
  49. Week int `yaml:"week"`
  50. Month int `yaml:"month"`
  51. Year int `yaml:"year"`
  52. }
  53. type DataDirStruct struct {
  54. Src string `yaml:"src"`
  55. Dest string `yaml:"dest"`
  56. Exclude []string `yaml:"exclude"`
  57. }
  58. type cloudConfig struct {
  59. CollectLimit CollectLimitStruct `yaml:"collect-limit"`
  60. DataDir DataDirStruct `yaml:"data-dir"`
  61. MapBufFiles []string `yaml:"map-buf-files"`
  62. FullCollect bool `yaml:"full-collect"`
  63. ConfigRefreshInterval int `yaml:"config-refresh-interval"` // 配置刷新时间间隔
  64. BagNumber int `yaml:"bag-number"`
  65. TimeWindowSendGap int `yaml:"time-window-send-gap"` // 主节点向从节点发送窗口的最小时间间隔
  66. MapBagPath string `yaml:"map-bag-path"`
  67. TfstaticBagPath string `yaml:"tfstatic-bag-path"`
  68. CostmapBagPath string `yaml:"costmap-bag-path"`
  69. BagDataDir string `yaml:"bag-data-dir"`
  70. BagCopyDir string `yaml:"bag-copy-dir"`
  71. TriggersDir string `yaml:"triggers-dir"`
  72. RpcPort string `yaml:"rpc-port"`
  73. Triggers []TriggerStruct `yaml:"triggers"`
  74. Hosts []HostStruct `yaml:"hosts"`
  75. Ros RosStruct `yaml:"ros"`
  76. Platform PlatformStruct `yaml:"platform"`
  77. Disk DiskStruct `yaml:"disk"`
  78. Monitor MonitorStruct `yaml:"monitor"`
  79. }
  80. // Request 结构体定义
  81. type Request struct {
  82. Type string `json:"type"`
  83. UUID string `json:"uuid"`
  84. CommandID string `json:"commandId"`
  85. Parameter interface{} `json:"parameter"`
  86. }
  87. // Response 结构体定义
  88. type Response struct {
  89. CommandID string `json:"commandId"`
  90. ErrorCode string `json:"errorCode"`
  91. Results map[string]string `json:"results"`
  92. Status string `json:"status"`
  93. Time int64 `json:"time"`
  94. Type string `json:"type"`
  95. UUID string `json:"uuid"`
  96. }
  97. var (
  98. CloudConfig cloudConfig
  99. CloudConfigMutex sync.RWMutex
  100. )
  101. // InitCloudConfig 初始化业务配置
  102. func InitCloudConfig() {
  103. // history20240401:朴津机器人额外加一个获取sn码
  104. var snCode string
  105. for {
  106. time.Sleep(time.Duration(2) * time.Second)
  107. snCode, err := getSnCode()
  108. if err != nil {
  109. c_log.GlobalLogger.Error("获取sn码失败:", err.Error())
  110. continue
  111. }
  112. LocalConfig.SecretKey = snCode
  113. LocalConfig.EquipmentNo = "pjibot-" + snCode
  114. break
  115. }
  116. c_log.GlobalLogger.Info("本地机器人sn码为:", snCode)
  117. c_log.GlobalLogger.Info("初始化OSS配置文件 - 开始。")
  118. // 获取文件的目录
  119. _ = util.CreateParentDir(LocalConfig.CloudConfigLocalPath)
  120. // 3 ------- 获取 yaml 字符串 -------
  121. cloudConfigObjectKey := LocalConfig.OssBasePrefix + LocalConfig.EquipmentNo + "/" + LocalConfig.CloudConfigFilename
  122. // 判断文件是否存在。如果不存在则使用默认的
  123. isExist, err := OssBucket.IsObjectExist(cloudConfigObjectKey)
  124. if err != nil {
  125. c_log.GlobalLogger.Errorf("判断配置文件是否存在失败,错误信息为:%v", err)
  126. }
  127. if isExist {
  128. c_log.GlobalLogger.Info("使用机器人自定义配置文件:", cloudConfigObjectKey)
  129. } else {
  130. cloudConfigObjectKey = LocalConfig.OssBasePrefix + LocalConfig.CloudConfigFilename // 默认配置文件路径
  131. c_log.GlobalLogger.Info("使用机器人默认配置文件:", cloudConfigObjectKey)
  132. }
  133. for {
  134. OssMutex.Lock()
  135. err := OssBucket.GetObjectToFile(cloudConfigObjectKey, LocalConfig.CloudConfigLocalPath)
  136. OssMutex.Unlock()
  137. if err != nil {
  138. c_log.GlobalLogger.Error("下载 OSS 上的配置文件 "+cloudConfigObjectKey+" 失败,请尽快在 OSS 上传配置文件。", err)
  139. time.Sleep(time.Duration(2) * time.Second)
  140. continue
  141. }
  142. break
  143. }
  144. content, err := os.ReadFile(LocalConfig.CloudConfigLocalPath)
  145. if err != nil {
  146. c_log.GlobalLogger.Error("程序崩溃,配置文件 ", LocalConfig.CloudConfigLocalPath, " 读取失败:", err)
  147. os.Exit(-1)
  148. }
  149. // 4 ------- 解析YAML内容 -------
  150. var newCloudConfig cloudConfig
  151. err = yaml.Unmarshal(content, &newCloudConfig)
  152. if err != nil {
  153. c_log.GlobalLogger.Error("程序崩溃,配置文件 ", LocalConfig.CloudConfigLocalPath, " 解析失败:", err)
  154. os.Exit(-1)
  155. }
  156. // 5 ------- 校验 yaml -------
  157. if checkCloudConfig(newCloudConfig) {
  158. CloudConfigMutex.RLock()
  159. CloudConfig = newCloudConfig
  160. CloudConfigMutex.RUnlock()
  161. } else {
  162. c_log.GlobalLogger.Error("程序崩溃,配置文件格式错误:", newCloudConfig)
  163. os.Exit(-1)
  164. }
  165. c_log.GlobalLogger.Info("初始化OSS配置文件 - 成功。")
  166. util.CreateDir(CloudConfig.BagDataDir)
  167. util.CreateDir(CloudConfig.BagCopyDir)
  168. }
  169. // 更新业务配置
  170. func refreshCloudConfig() {
  171. // 获取文件的目录
  172. _ = util.CreateParentDir(LocalConfig.CloudConfigLocalPath)
  173. // 3 ------- 获取 yaml 字符串 -------
  174. var content []byte
  175. cloudConfigObjectKey := LocalConfig.OssBasePrefix + LocalConfig.EquipmentNo + "/" + LocalConfig.CloudConfigFilename
  176. isExist, err := OssBucket.IsObjectExist(cloudConfigObjectKey)
  177. if err != nil {
  178. c_log.GlobalLogger.Errorf("判断配置文件是否存在失败,错误信息为:%v", err)
  179. return
  180. }
  181. if !isExist {
  182. cloudConfigObjectKey = LocalConfig.OssBasePrefix + LocalConfig.CloudConfigFilename // 默认配置文件路径
  183. }
  184. OssMutex.Lock()
  185. err = OssBucket.GetObjectToFile(cloudConfigObjectKey, LocalConfig.CloudConfigLocalPath)
  186. OssMutex.Unlock()
  187. if err != nil {
  188. c_log.GlobalLogger.Error("下载oss上的配置文件"+cloudConfigObjectKey+"失败。", err)
  189. }
  190. content, err = os.ReadFile(LocalConfig.CloudConfigLocalPath)
  191. if err != nil {
  192. c_log.GlobalLogger.Error("配置文件 ", LocalConfig.CloudConfigLocalPath, " 读取失败:", err)
  193. return
  194. }
  195. // 4 ------- 解析YAML内容 -------
  196. var newCloudConfig cloudConfig
  197. err = yaml.Unmarshal(content, &newCloudConfig)
  198. if err != nil {
  199. c_log.GlobalLogger.Error("配置文件 ", LocalConfig.CloudConfigLocalPath, " 解析失败:", err)
  200. return
  201. }
  202. // 5 ------- 校验 yaml -------
  203. if checkCloudConfig(newCloudConfig) {
  204. CloudConfigMutex.RLock()
  205. CloudConfig = newCloudConfig
  206. CloudConfigMutex.RUnlock()
  207. } else {
  208. c_log.GlobalLogger.Error("配置文件格式错误:", newCloudConfig)
  209. return
  210. }
  211. util.CreateDir(CloudConfig.BagDataDir)
  212. util.CreateDir(CloudConfig.BagCopyDir)
  213. }
  214. // RefreshCloudConfig 轮询oss上的配置文件更新到本地
  215. func RefreshCloudConfig() {
  216. for {
  217. time.Sleep(time.Duration(CloudConfig.ConfigRefreshInterval) * time.Second)
  218. refreshCloudConfig()
  219. }
  220. }
  221. // CheckConfig 校验 cfg.yaml 文件
  222. func checkCloudConfig(check cloudConfig) bool {
  223. if len(check.Hosts) != 1 {
  224. c_log.GlobalLogger.Error("cloud-config.yaml中配置的hosts必须为1。")
  225. os.Exit(-1)
  226. }
  227. return true
  228. }
  229. func getSnCode() (string, error) {
  230. var command []string
  231. command = append(command, "get")
  232. command = append(command, "sn")
  233. _, snOutput, err := util.ExecuteSync(LocalConfig.RosparamPath, command...)
  234. if err != nil {
  235. return "", errors.New("执行获取sn码命令" + util.ToString(command) + "出错:" + util.ToString(err))
  236. }
  237. c_log.GlobalLogger.Info("执行获取sn码命令", command, "成功,结果为:", snOutput)
  238. snCode := strings.Replace(strings.Replace(snOutput, " ", "", -1), "\n", "", -1)
  239. return snCode, nil
  240. }
  241. // SendWebsocketRequest 发送WebSocket请求并返回sn字段的值
  242. func SendWebsocketRequest(serverURL, path string, request Request) (string, error) {
  243. // 构建WebSocket连接URL
  244. u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
  245. // 创建一个Dialer实例,用于建立WebSocket连接
  246. dialer := websocket.Dialer{
  247. ReadBufferSize: 1024,
  248. WriteBufferSize: 1024,
  249. // 可选:设置超时等
  250. HandshakeTimeout: 5 * time.Second,
  251. }
  252. // 建立WebSocket连接
  253. conn, _, err := dialer.Dial(u.String(), nil)
  254. if err != nil {
  255. return "", fmt.Errorf("dial: %w", err)
  256. }
  257. defer conn.Close()
  258. // 将请求JSON编码为字节
  259. requestJSON, err := json.Marshal(request)
  260. if err != nil {
  261. return "", fmt.Errorf("marshal request: %w", err)
  262. }
  263. // 发送WebSocket消息
  264. err = conn.WriteMessage(websocket.TextMessage, requestJSON)
  265. if err != nil {
  266. return "", fmt.Errorf("write: %w", err)
  267. }
  268. // 读取WebSocket响应
  269. _, responseBytes, err := conn.ReadMessage()
  270. if err != nil {
  271. return "", fmt.Errorf("read: %w", err)
  272. }
  273. // 将响应字节解码为JSON
  274. var response Response
  275. err = json.Unmarshal(responseBytes, &response)
  276. if err != nil {
  277. return "", fmt.Errorf("unmarshal response: %w", err)
  278. }
  279. // 返回sn字段的值
  280. return response.Results["sn"], nil
  281. }