c_cloud.go 9.4 KB

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