c_cloud.go 9.3 KB

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