c_cloud.go 10 KB

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