gateway.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. package gateway
  2. import (
  3. "bufio"
  4. "confrontation-training/common"
  5. "confrontation-training/constant"
  6. errors "confrontation-training/err"
  7. "confrontation-training/global"
  8. "confrontation-training/http"
  9. "confrontation-training/models"
  10. "confrontation-training/models/gateway"
  11. "confrontation-training/response"
  12. "encoding/hex"
  13. "encoding/json"
  14. "fmt"
  15. "github.com/gin-gonic/gin"
  16. log "github.com/sirupsen/logrus"
  17. "io"
  18. "io/ioutil"
  19. "os"
  20. "strconv"
  21. "strings"
  22. "time"
  23. )
  24. // ScanDevice
  25. // PingExample confrontation-training
  26. // @Summary 扫描设备
  27. // @Schemes
  28. // @Description 扫描设备
  29. // @Tags 设备管理
  30. // @Param device body string true "chip:芯片编号,1或1;filterName:0 脑电 1 心电;filterRssi:信号强度,小于0的整数,字符串格式传输;filterMac:过滤Mac地址,以","分割,如 61-Dg-89-22-39-3b,80-kD-0E-40-57-8A;filterType:1 表示已录入的设备"
  31. // @Accept json
  32. // @Produce json
  33. // @Success 200 {string} string "ok"
  34. // @Router /v1/device/scan [post]
  35. func ScanDevice(c *gin.Context) {
  36. var param gateway.DeviceScanParam
  37. err := c.ShouldBindJSON(&param)
  38. if err != nil {
  39. fmt.Printf("参数格式化异常:%s", err.Error())
  40. global.Log4J.Info("参数格式化异常:", err.Error())
  41. response.Failed(errors.ParamInvalid, c)
  42. return
  43. }
  44. paramMap := make(map[string]string)
  45. if param.Chip != "" {
  46. paramMap["chip"] = param.Chip
  47. }
  48. if param.FilterName != "" {
  49. //查询设备mac过滤信息
  50. filterMac := ""
  51. deviceInfos, count := GetDeviceService().DeviceService.FindDeviceByType(param.FilterName)
  52. if count > 0 {
  53. for i := range deviceInfos {
  54. filterMac += deviceInfos[i].Mac + ","
  55. }
  56. }
  57. if len(filterMac) > 0 {
  58. if strings.HasSuffix(filterMac, ",") {
  59. filterMac = filterMac[0 : len(filterMac)-1]
  60. }
  61. paramMap["filter_mac"] = filterMac
  62. }
  63. if param.FilterName == "0" {
  64. paramMap["filter_name"] = constant.FilterNameEEG
  65. } else if param.FilterName == "1" {
  66. paramMap["filter_name"] = constant.FilterNameECG
  67. } else {
  68. response.Failed(errors.ParamInvalid+":过滤类型-"+param.FilterName+"无效", c)
  69. return
  70. }
  71. } else {
  72. paramMap["filter_name"] = constant.FilterNameALL
  73. }
  74. if param.FilterRssi != "" {
  75. paramMap["filter_rssi"] = param.FilterRssi
  76. }
  77. if param.FilterMac != "" {
  78. paramMap["filter_mac"] = param.FilterMac
  79. }
  80. paramMap["active"] = "1"
  81. paramMap["event"] = "1"
  82. param.FilterType = "1"
  83. go SseScanDevice(paramMap, param.FilterType)
  84. response.Success("扫描完成", "", c)
  85. return
  86. }
  87. // ConnectDevice
  88. // PingExample confrontation-training
  89. // @Summary 连接设备
  90. // @Schemes
  91. // @Description 连接设备
  92. // @Tags 设备管理
  93. // @Param device body string true "chip:芯片编号,0或1;mac:Mac地址;addrType:地址类型 public/random "
  94. // @Accept json
  95. // @Produce json
  96. // @Success 200 {string} string "ok"
  97. // @Router /v1/device/connection [post]
  98. func ConnectDevice(c *gin.Context) {
  99. var param gateway.DeviceConnParam
  100. err := c.ShouldBindJSON(&param)
  101. if err != nil {
  102. fmt.Printf("参数格式化异常:%s", err.Error())
  103. log.Infof("参数格式化异常:%s", err.Error())
  104. response.Failed(errors.ParamInvalid, c)
  105. return
  106. }
  107. jsonParam, err := json.Marshal(param)
  108. if err != nil {
  109. fmt.Printf("参数转换异常:%s", err.Error())
  110. log.Infof("参数转换异常:%s", err.Error())
  111. response.Failed("参数转换异常:%s"+err.Error(), c)
  112. return
  113. }
  114. url := global.Config.Gateway.BaseUrl + global.Config.Gateway.ConnUrl
  115. url = strings.Replace(url, "MAC", param.Mac, -1)
  116. if param.FilterName == "0" {
  117. url = strings.Replace(url, "chip", "chip=0", -1)
  118. } else if param.FilterName == "1" {
  119. url = strings.Replace(url, "chip", "chip=1", -1)
  120. }
  121. httpResponse := http.PostReqJson(url, jsonParam)
  122. status := httpResponse.StatusCode
  123. body, _ := ioutil.ReadAll(httpResponse.Body)
  124. if status != 200 {
  125. response.Failed(errors.DeviceConnectError+string(body), c)
  126. return
  127. }
  128. if param.FilterName == "1" {
  129. openChannelUrl := global.Config.Gateway.BaseUrl + global.Config.Gateway.OpenChannel
  130. openChannelUrl = strings.Replace(openChannelUrl, "MAC", param.Mac, -1)
  131. httpResponse = http.GetReq(openChannelUrl)
  132. if httpResponse.StatusCode != 200 {
  133. fmt.Printf("%s:%s", errors.OpenChannelError, httpResponse.Body)
  134. log.Infof("%s:%s", errors.OpenChannelError, httpResponse.Body)
  135. response.Failed(errors.OpenChannelError, c)
  136. return
  137. }
  138. }
  139. go StopScan(c.Writer, c.Request)
  140. response.Success(errors.DeviceConnectSuccess, param.Mac, c)
  141. return
  142. }
  143. // WriteData
  144. // PingExample confrontation-training
  145. // @Summary 写入数据——发送指令
  146. // @Schemes
  147. // @Description 写入数据——发送指令 ,ECG设备开启测试功能
  148. // @Tags 设备管理
  149. // @Param mac body string true "mac:设备MAC地址 userName:用户姓名 gender:性别 age:年龄 height:身高 weight:体重"
  150. // @Accept json
  151. // @Produce json
  152. // @Success 200 {string} string "ok"
  153. // @Router /v1/device/write/data/ [post]
  154. func WriteData(c *gin.Context) {
  155. var param models.WriteData
  156. err := c.ShouldBindJSON(&param)
  157. if err != nil {
  158. fmt.Printf("参数格式化异常:%s", err.Error())
  159. log.Infof("参数格式化异常:%s", err.Error())
  160. response.Failed(errors.ParamInvalid, c)
  161. return
  162. }
  163. userNameHex := hex.EncodeToString([]byte(param.UserName))
  164. //1 绑定用户指令
  165. //指令头(E841) + user信息前缀(AA)+姓名(姓名字节长度+姓名+姓名不足12字节占位符)+性别+年龄+身高+体重
  166. var stringBuild strings.Builder
  167. stringBuild.WriteString(constant.BindUserInfoCmdPrefix)
  168. length := len(userNameHex) / 2
  169. bytes := common.Int2Bytes(length)
  170. result := common.Bytes2HexStr(bytes)
  171. result = common.Int2Byte(int64(length))
  172. if result == "" {
  173. response.Failed("用户名处理异常", c)
  174. return
  175. }
  176. result = result[len(result)-2:]
  177. stringBuild.WriteString(result)
  178. stringBuild.WriteString(userNameHex)
  179. placeHolder := common.GenerateHexStringCmdPlaceHolder(constant.MaxNameByteLength - length)
  180. stringBuild.WriteString(placeHolder)
  181. hexGender := common.Int2Byte(param.Gender)
  182. stringBuild.WriteString(hexGender[len(hexGender)-2:])
  183. if param.Age == 0 {
  184. param.Age = constant.EcgDefaultAge
  185. }
  186. hexAge := common.Int2Byte(param.Age)
  187. stringBuild.WriteString(hexAge[len(hexAge)-2:])
  188. if param.Height == 0 {
  189. param.Height = constant.EcgDefaultHeight
  190. }
  191. hexHeight := common.Int2Byte(param.Height)
  192. stringBuild.WriteString(hexHeight[len(hexHeight)-2:])
  193. if param.Weight == 0 {
  194. param.Weight = constant.EcgDefaultWeight
  195. }
  196. hexWeight := common.Int2Byte(param.Weight)
  197. stringBuild.WriteString(hexWeight[len(hexWeight)-2:])
  198. bindUserCmdByte := []byte(stringBuild.String())
  199. bindUserCmd := string(bindUserCmdByte)
  200. fmt.Println(bindUserCmd)
  201. log.Infoln(bindUserCmd)
  202. //2.授时指令
  203. //timeCmd := common.GetTimeCmd()
  204. timeCmd := common.GetHexTimeStr()
  205. //timeCmd = fmt.Sprintf("%s%s", "0x", timeCmd)
  206. setTimeCmd := fmt.Sprintf("%s%s", constant.SetTimeCmdPrefix, timeCmd)
  207. fmt.Println(setTimeCmd)
  208. log.Infoln(setTimeCmd)
  209. //3.开始收集指令
  210. startCollectCmd := fmt.Sprintf("%s%s", constant.StartCollectCmdPrefix, timeCmd)
  211. fmt.Println(startCollectCmd)
  212. log.Infoln(startCollectCmd)
  213. //发送指令
  214. //绑定用户
  215. bindUserUrl := fmt.Sprintf("%s%s", global.Config.Gateway.BaseUrl, global.Config.Gateway.WriteDataUrl)
  216. bindUserUrl = strings.Replace(bindUserUrl, "MAC", param.Mac, -1)
  217. bindUserUrl = strings.Replace(bindUserUrl, "DATA", bindUserCmd, -1)
  218. fmt.Println("bindUserUrl====" + bindUserUrl)
  219. log.Infoln("bindUserUrl====" + bindUserUrl)
  220. httpResponse := http.GetReq(bindUserUrl)
  221. if httpResponse.StatusCode != 200 {
  222. fmt.Printf("%s:%s", errors.BindUserFailed, httpResponse.Body)
  223. log.Infof("%s:%s", errors.BindUserFailed, httpResponse.Body)
  224. response.Failed(errors.BindUserFailed, c)
  225. return
  226. }
  227. //授时
  228. setTimeUrl := fmt.Sprintf("%s%s", global.Config.Gateway.BaseUrl, global.Config.Gateway.WriteDataUrl)
  229. setTimeUrl = strings.Replace(setTimeUrl, "MAC", param.Mac, -1)
  230. setTimeUrl = strings.Replace(setTimeUrl, "DATA", setTimeCmd, -1)
  231. httpResponse = http.GetReq(setTimeUrl)
  232. if httpResponse.StatusCode != 200 {
  233. fmt.Printf("%s:%s", errors.BindUserFailed, httpResponse.Body)
  234. log.Infof("%s:%s", errors.BindUserFailed, httpResponse.Body)
  235. response.Failed(errors.BindUserFailed, c)
  236. return
  237. }
  238. fmt.Println("setTimeUrl=====" + setTimeUrl)
  239. log.Infoln("setTimeUrl=====" + setTimeUrl)
  240. //开始收集
  241. startCollectUrl := fmt.Sprintf("%s%s", global.Config.Gateway.BaseUrl, global.Config.Gateway.WriteDataUrl)
  242. startCollectUrl = strings.Replace(startCollectUrl, "MAC", param.Mac, -1)
  243. startCollectUrl = strings.Replace(startCollectUrl, "DATA", startCollectCmd, -1)
  244. fmt.Println("startCollectUrl=====" + startCollectUrl)
  245. log.Infoln("startCollectUrl=====" + startCollectUrl)
  246. httpResponse = http.GetReq(startCollectUrl)
  247. if httpResponse.StatusCode != 200 {
  248. fmt.Printf("%s:%s", errors.StartCollocateFailed, httpResponse.Body)
  249. log.Infof("%s:%s", errors.StartCollocateFailed, httpResponse.Body)
  250. response.Failed(errors.StartCollocateFailed, c)
  251. return
  252. }
  253. //开始传输指令
  254. startTransUrl := fmt.Sprintf("%s%s", global.Config.Gateway.BaseUrl, global.Config.Gateway.WriteDataUrl)
  255. startTransUrl = strings.Replace(startTransUrl, "MAC", param.Mac, -1)
  256. startTransUrl = strings.Replace(startTransUrl, "DATA", constant.StartTransCmd, -1)
  257. fmt.Println("startTransUrl====" + startTransUrl)
  258. log.Infoln("startTransUrl====" + startTransUrl)
  259. httpResponse = http.GetReq(startTransUrl)
  260. if httpResponse.StatusCode != 200 {
  261. fmt.Printf("%s:%s", errors.StartTransFailed, httpResponse.Body)
  262. log.Infof("%s:%s", errors.StartTransFailed, httpResponse.Body)
  263. response.Failed(errors.StartTransFailed, c)
  264. return
  265. }
  266. response.Success(errors.WriteDataSuccess, nil, c)
  267. return
  268. }
  269. // OpenNotify
  270. // PingExample confrontation-training
  271. // @Summary 开启数据通知
  272. // @Schemes
  273. // @Description 开启数据通知
  274. // @Tags 设备管理
  275. // @Accept json
  276. // @Produce json
  277. // @Success 200 {string} string "ok"
  278. // @Router /v1/device/open/notify/ [get]
  279. func OpenNotify(c *gin.Context) {
  280. SseOpenNotify()
  281. response.Success("开启通知", "", c)
  282. return
  283. }
  284. // StopTrans
  285. // PingExample confrontation-training
  286. // @Summary 停止传输
  287. // @Schemes
  288. // @Description 停止传输
  289. // @Tags 设备管理
  290. // @Accept json
  291. // @Produce json
  292. // @Success 200 {string} string "ok"
  293. // @Router /v1/device/:mac/stop/trans [get]
  294. func StopTrans(c *gin.Context) {
  295. mac := c.Param("mac")
  296. stopTransUrl := global.Config.Gateway.BaseUrl + global.Config.Gateway.WriteDataUrl
  297. stopTransUrl = strings.Replace(stopTransUrl, "MAC", mac, -1)
  298. stopTransUrl = strings.Replace(stopTransUrl, "DATA", constant.StopTransCmd, -1)
  299. response.Success("停止传输", "", c)
  300. return
  301. }
  302. // StopCollect
  303. // PingExample confrontation-training
  304. // @Summary 停止采集
  305. // @Schemes
  306. // @Description 停止采集
  307. // @Tags 设备管理
  308. // @Accept json
  309. // @Produce json
  310. // @Success 200 {string} string "ok"
  311. // @Router /v1/device/:mac/stop/collect [get]
  312. func StopCollect(c *gin.Context) {
  313. mac := c.Param("mac")
  314. stopTransUrl := global.Config.Gateway.BaseUrl + global.Config.Gateway.WriteDataUrl
  315. stopTransUrl = strings.Replace(stopTransUrl, "MAC", mac, -1)
  316. stopTransUrl = strings.Replace(stopTransUrl, "DATA", constant.StopCollectCmd, -1)
  317. response.Success("停止采集", "", c)
  318. return
  319. }
  320. // ScanDeviceEmq
  321. // PingExample confrontation-training
  322. // @Summary 扫描设备
  323. // @Schemes
  324. // @Description 扫描设备
  325. // @Tags 设备管理
  326. // @Accept json
  327. // @Produce json
  328. // @Success 200 {string} string "ok"
  329. // @Router /v2/device/scan [get]
  330. func ScanDeviceEmq(c *gin.Context) {
  331. topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
  332. client := global.EmqClient
  333. //停止扫描
  334. fmt.Println("停止扫描")
  335. log.Infoln("停止扫描")
  336. global.Log4J.Info("停止扫描")
  337. fmt.Println(constant.CmdStopScan)
  338. Publish(client, topic, constant.CmdStopScan)
  339. //开启扫描
  340. //Publish(client, "/EE3870DA24C4/connect_packet/connect1_subscribe", "[{\"cmd\":\"AT+SCAN=\",\"s\":\"1\"}]")
  341. //停止扫描
  342. //Publish(client, "/EE3870DA24C4/connect_packet/connect1_subscribe", "[{\"cmd\":\"AT+SCAN=\",\"s\":\"0\"}]")
  343. //设置设备服务UUID
  344. //fmt.Println("设置设备服务UUID")
  345. if global.EmqConfig.FirstOpen == "0" {
  346. SendUUID(client, topic)
  347. }
  348. time.Sleep(time.Millisecond * 100)
  349. Publish(global.EmqClient, topic, constant.CmdStartScan)
  350. response.Success("开启扫描完成", "", c)
  351. return
  352. }
  353. // StopScanDeviceEmq
  354. // PingExample confrontation-training
  355. // @Summary 停止扫描设备
  356. // @Schemes
  357. // @Description 停止扫描设备
  358. // @Tags 设备管理
  359. // @Accept json
  360. // @Produce json
  361. // @Success 200 {string} string "ok"
  362. // @Router /v2/device/stop/scan [get]
  363. func StopScanDeviceEmq(c *gin.Context) {
  364. topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
  365. Publish(global.EmqClient, topic, constant.CmdStopScan)
  366. response.Success("关闭扫描完成", "", c)
  367. return
  368. }
  369. // ConnectDevice2
  370. // PingExample confrontation-training
  371. // @Summary 连接设备
  372. // @Schemes
  373. // @Description 连接设备
  374. // @Tags 设备管理
  375. // @Param device body string true "mac:设备MAC地址 ai:终端BLE设备的地址ID at:终端BLE设备的地址类型 "
  376. // @Accept json
  377. // @Produce json
  378. // @Success 200 {string} string "ok"
  379. // @Router /v2/device/conn [post]
  380. func ConnectDevice2(c *gin.Context) {
  381. var param gateway.ConnectDevice
  382. err := c.ShouldBindJSON(&param)
  383. if err != nil {
  384. fmt.Printf("参数格式化异常:%s", err.Error())
  385. global.Log4J.Info("参数格式化异常:", err.Error())
  386. response.Failed(errors.ParamInvalid, c)
  387. return
  388. }
  389. global.Log4J.Info("连接Mac:" + param.Mac)
  390. info := global.DeviceMap[param.Mac]
  391. for s, deviceInfo := range global.DeviceMap {
  392. global.Log4J.Info("mac"+s, "deviceInfo:", deviceInfo)
  393. }
  394. global.Log4J.Info("设备信息:", info)
  395. if info.Type == "" {
  396. response.Failed("设备未入库,请先添加设备", c)
  397. return
  398. }
  399. topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
  400. mac := strings.ReplaceAll(param.Mac, ":", "")
  401. ConnectDeviceEmq(global.EmqClient, topic, mac, "0", param.Ai, param.At)
  402. response.Success("连接设备完成", "", c)
  403. return
  404. }
  405. // DisConnect
  406. // PingExample confrontation-training
  407. // @Summary 断开连接设备
  408. // @Schemes
  409. // @Description 断开连接设备
  410. // @Tags 设备管理
  411. // @Param device body string true "mac:设备MAC地址 "
  412. // @Accept json
  413. // @Produce json
  414. // @Success 200 {string} string "ok"
  415. // @Router /v2/device/dis/conn [post]
  416. func DisConnect(c *gin.Context) {
  417. var param gateway.ConnectDevice
  418. err := c.ShouldBindJSON(&param)
  419. if err != nil {
  420. fmt.Printf("参数格式化异常:%s", err.Error())
  421. global.Log4J.Info("参数格式化异常:", err.Error())
  422. response.Failed(errors.ParamInvalid, c)
  423. return
  424. }
  425. topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
  426. mac := strings.ReplaceAll(param.Mac, ":", "")
  427. DisConnectDeviceEmq(global.EmqClient, topic, mac)
  428. response.Success("断开设备连接成功", "", c)
  429. return
  430. }
  431. // DisConnectAll
  432. // PingExample confrontation-training
  433. // @Summary 断开所有已连接设备
  434. // @Schemes
  435. // @Description 断开所有已连接设备
  436. // @Tags 设备管理
  437. // @Accept json
  438. // @Produce json
  439. // @Success 200 {string} string "ok"
  440. // @Router /v2/device/dis/connAll [get]
  441. func DisConnectAll(c *gin.Context) {
  442. topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
  443. //断开所有的连接
  444. for s := range global.DeviceMap {
  445. if len(s) == 17 {
  446. s = strings.ReplaceAll(s, ":", "")
  447. DisConnectDeviceEmq(global.EmqClient, topic, s)
  448. }
  449. }
  450. response.Success("断开所有已连接设备成功", "", c)
  451. return
  452. }
  453. // ConnectList
  454. // PingExample confrontation-training
  455. // @Summary 已连接列表 已连接列表中不再做任何处理,在连接或断开连接 成功或失败时系统自动调用
  456. // @Schemes
  457. // @Description 已连接列表
  458. // @Tags 设备管理
  459. // @Accept json
  460. // @Produce json
  461. // @Success 200 {string} string "ok"
  462. // @Router /v2/device/connected/list [get]
  463. func ConnectList(c *gin.Context) {
  464. topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
  465. //ConnectedListEmq(global.EmqClient, topic)
  466. //ConnectedNumber(global.EmqClient, topic)
  467. for i := 0; i < 6; i++ {
  468. ConnectedListEmq(global.EmqClient, topic, strconv.Itoa(i))
  469. time.Sleep(time.Millisecond * 500)
  470. }
  471. response.Success("查询连接列表完成", "", c)
  472. return
  473. }
  474. // WriteDataEmq
  475. // PingExample confrontation-training
  476. // @Summary 写入数据-脑电写入指令
  477. // @Schemes
  478. // @Description 写入数据-脑电写入指令
  479. // @Tags 设备管理
  480. // @Param mac body string true "mac:设备MAC地址 userName:用户姓名 gender:性别 age:年龄 height:身高 weight:体重"
  481. // @Accept json
  482. // @Produce json
  483. // @Success 200 {string} string "ok"
  484. // @Router /v2/device/write/data [post]
  485. func WriteDataEmq(c *gin.Context) {
  486. var param models.WriteData
  487. err := c.ShouldBindJSON(&param)
  488. if err != nil {
  489. fmt.Printf("参数格式化异常:%s", err.Error())
  490. global.Log4J.Info("参数格式化异常:", err.Error())
  491. response.Failed(errors.ParamInvalid, c)
  492. return
  493. }
  494. userNameHex := hex.EncodeToString([]byte(param.UserName))
  495. topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
  496. //写入
  497. //1 绑定用户指令
  498. //指令头(E841) + user信息前缀(AA)+姓名(姓名字节长度+姓名+姓名不足12字节占位符)+性别+年龄+身高+体重
  499. var stringBuild strings.Builder
  500. stringBuild.WriteString(constant.BindUserInfoCmdPrefix)
  501. length := len(userNameHex) / 2
  502. bytes := common.Int2Bytes(length)
  503. result := common.Bytes2HexStr(bytes)
  504. result = common.Int2Byte(int64(length))
  505. if result == "" {
  506. response.Failed("用户名处理异常", c)
  507. return
  508. }
  509. result = result[len(result)-2:]
  510. stringBuild.WriteString(result)
  511. stringBuild.WriteString(userNameHex)
  512. placeHolder := common.GenerateHexStringCmdPlaceHolder(constant.MaxNameByteLength - length)
  513. stringBuild.WriteString(placeHolder)
  514. hexGender := common.Int2Byte(param.Gender)
  515. stringBuild.WriteString(hexGender[len(hexGender)-2:])
  516. if param.Age == 0 {
  517. param.Age = constant.EcgDefaultAge
  518. }
  519. hexAge := common.Int2Byte(param.Age)
  520. stringBuild.WriteString(hexAge[len(hexAge)-2:])
  521. if param.Height == 0 {
  522. param.Height = constant.EcgDefaultHeight
  523. }
  524. hexHeight := common.Int2Byte(param.Height)
  525. stringBuild.WriteString(hexHeight[len(hexHeight)-2:])
  526. if param.Weight == 0 {
  527. param.Weight = constant.EcgDefaultWeight
  528. }
  529. hexWeight := common.Int2Byte(param.Weight)
  530. stringBuild.WriteString(hexWeight[len(hexWeight)-2:])
  531. bindUserCmdByte := []byte(stringBuild.String())
  532. bindUserCmd := string(bindUserCmdByte)
  533. fmt.Println(bindUserCmd)
  534. global.Log4J.Info(bindUserCmd)
  535. //2.授时指令
  536. //timeCmd := common.GetTimeCmd()
  537. timeCmd := common.GetHexTimeStr()
  538. //timeCmd = fmt.Sprintf("%s%s", "0x", timeCmd)
  539. setTimeCmd := fmt.Sprintf("%s%s", constant.SetTimeCmdPrefix, timeCmd)
  540. fmt.Println(setTimeCmd)
  541. global.Log4J.Info(setTimeCmd)
  542. //3.开始收集指令
  543. startCollectCmd := fmt.Sprintf("%s%s", constant.StartCollectCmdPrefix, timeCmd)
  544. fmt.Println(startCollectCmd)
  545. global.Log4J.Info(startCollectCmd)
  546. //发送指令
  547. //绑定用户
  548. WNP(global.EmqClient, topic, strings.ReplaceAll(param.Mac, ":", ""), "FFF1", bindUserCmd)
  549. //授时
  550. WNP(global.EmqClient, topic, strings.ReplaceAll(param.Mac, ":", ""), "FFF1", setTimeCmd)
  551. //开始收集
  552. WNP(global.EmqClient, topic, strings.ReplaceAll(param.Mac, ":", ""), "FFF1", startCollectCmd)
  553. //开始传输指令
  554. WNP(global.EmqClient, topic, strings.ReplaceAll(param.Mac, ":", ""), "FFF1", constant.StartTransCmd)
  555. response.Success(errors.WriteDataSuccess, nil, c)
  556. return
  557. }
  558. // FindGateway
  559. // PingExample confrontation-training
  560. // @Summary 查询可能是蓝牙网关的设备
  561. // @Schemes
  562. // @Description 查询可能是蓝牙网关的设备
  563. // @Tags 设备管理
  564. // @Accept json
  565. // @Produce json
  566. // @Success 200 {string} string "ok"
  567. // @Router /v2/gateway/find [get]
  568. func FindGateway(c *gin.Context) {
  569. var gateways []gateway.GatewayInfo
  570. if len(global.DeviceMap) > 0 {
  571. for _, deviceInfo := range global.GatewayList {
  572. gateways = append(gateways, deviceInfo)
  573. }
  574. }
  575. response.Success("查询网关设备完成", gateways, c)
  576. return
  577. }
  578. // SetGatewayMac
  579. // PingExample confrontation-training
  580. // @Summary 保存网关MAC
  581. // @Schemes
  582. // @Description 保存网关MAC-脑电写入指令
  583. // @Tags 设备管理
  584. // @Param mac body string true "mac:网关MAC地址 "
  585. // @Accept json
  586. // @Produce json
  587. // @Success 200 {string} string "ok"
  588. // @Router /v2/gateway/set [post]
  589. func SetGatewayMac(c *gin.Context) {
  590. var param gateway.GatewayInfo
  591. c.ShouldBindJSON(&param)
  592. file, err := os.OpenFile("./config/application.yaml", os.O_RDWR, 0666)
  593. defer file.Close()
  594. if err != nil {
  595. response.Failed("读取配置文件失败", c)
  596. return
  597. }
  598. pos := int64(0)
  599. reader := bufio.NewReader(file)
  600. for {
  601. line, err := reader.ReadString('\n')
  602. if err != nil {
  603. if err == io.EOF {
  604. if line == "" {
  605. break
  606. } else {
  607. global.Log4J.Info("File read ok!")
  608. }
  609. } else {
  610. global.Log4J.Info("Read File error", err.Error())
  611. return
  612. }
  613. }
  614. global.Log4J.Info(line)
  615. if strings.Contains(line, " gatewayMac:") {
  616. bytes := []byte(" gatewayMac: " + param.Mac)
  617. file.WriteAt(bytes, pos)
  618. }
  619. pos += int64(len(line))
  620. }
  621. global.EmqConfig.GatewayMac = param.Mac
  622. response.Success("网关信息保存成功,请重启软件!", "", c)
  623. return
  624. }