comm.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package comm
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "time"
  8. "unsafe"
  9. "github.com/gin-gonic/gin"
  10. "github.com/jacobsa/go-serial/serial"
  11. "kpt.xdmy/apiserver/routers/restful"
  12. "kpt.xdmy/pkg/app"
  13. "kpt.xdmy/pkg/e"
  14. "kpt.xdmy/pkg/setting"
  15. )
  16. //一个已经被关闭的channel不会阻塞,已经被关闭的channel会实时返回
  17. //goroutine退出,关闭done来进行广播
  18. var done = make(chan struct{})
  19. var Id = make(chan int)
  20. var timeout = make(chan int)
  21. var ReturnString = make(chan string)
  22. //判断done是否关闭,即是否执行goroutine退出
  23. func cancelled() bool {
  24. select {
  25. case <-done:
  26. return true
  27. default:
  28. return false
  29. }
  30. }
  31. func Int2Byte(data int) (ret []byte) {
  32. var len uintptr = unsafe.Sizeof(data)
  33. ret = make([]byte, len)
  34. var tmp int = 0xff
  35. var index uint = 0
  36. for index = 0; index < uint(len); index++ {
  37. ret[index] = byte((tmp << (index * 8) & data) >> (index * 8))
  38. }
  39. return ret
  40. }
  41. func OpenComm() {
  42. var sum byte
  43. var recLength, dataLength, state int
  44. comtimeout := 0
  45. buf := make([]byte, 32)
  46. recbuf := make([]byte, 1)
  47. //s_params := make([]interface{}, 1)
  48. openSerial:
  49. f, err := serial.Open(*setting.CommSetting)
  50. if err != nil {
  51. fmt.Println("Error opening serial port: ", err)
  52. time.Sleep(1 * time.Second)
  53. goto openSerial
  54. } else {
  55. log.Printf("[info] Serial %s is Started", setting.CommSetting.PortName)
  56. if comtimeout == 0 {
  57. defer f.Close()
  58. }
  59. for {
  60. sum = (0x55 + 0xAA + 0x06 + 0x01 + 0x03 + 0x01) & 0xFF
  61. v := 0
  62. if comtimeout == 0 {
  63. v, _ = <-Id
  64. }
  65. comtimeout = 0
  66. cowidByte := Int2Byte(v)[:3]
  67. sum = (sum + cowidByte[0] + cowidByte[1] + cowidByte[2]) & 0xFF
  68. cowidByte = append(cowidByte, sum)
  69. requestCowid := "55AA06010301" + hex.EncodeToString(cowidByte)
  70. txData_, err := hex.DecodeString(requestCowid)
  71. recLength = 0
  72. state = 0
  73. _, err = f.Write(txData_)
  74. fmt.Println(hex.EncodeToString(txData_))
  75. if err != nil {
  76. fmt.Println("Error writing to serial port: ", err)
  77. time.Sleep(1 * time.Second)
  78. comtimeout = 1
  79. goto openSerial
  80. }
  81. loop:
  82. for {
  83. select {
  84. case <-timeout:
  85. break loop
  86. default:
  87. n, err := f.Read(buf)
  88. if err != nil {
  89. //if err != io.EOF {
  90. fmt.Println("Error reading from serial port: ", err)
  91. time.Sleep(1 * time.Second)
  92. comtimeout = 1
  93. goto openSerial
  94. //}
  95. //break loop
  96. } else if n > 0 {
  97. buf = buf[:n]
  98. for _, value := range buf {
  99. switch state {
  100. case 0: //头判断
  101. if value == 0x55 {
  102. state = 1
  103. recLength = 1
  104. recbuf = recbuf[:0]
  105. recbuf = append(recbuf, (byte)(value&0xFF))
  106. }
  107. case 1: //头判断中
  108. if value == 0xAA {
  109. state = 2
  110. recLength = 2
  111. recbuf = append(recbuf, (byte)(value&0xFF))
  112. } else {
  113. state = 0
  114. recLength = 0
  115. }
  116. case 2: //接收数据长度
  117. state = 3
  118. recLength = 3
  119. dataLength = (int)(value + 4)
  120. recbuf = append(recbuf, (byte)(value&0xFF))
  121. case 3: //接收数据中
  122. recbuf = append(recbuf, (byte)(value&0xFF))
  123. recLength++
  124. if recLength == dataLength {
  125. fmt.Println(hex.EncodeToString(recbuf))
  126. ReturnString <- hex.EncodeToString(recbuf)
  127. state = 0
  128. recLength = 0
  129. break loop
  130. }
  131. }
  132. }
  133. } else {
  134. time.Sleep(10 * time.Millisecond)
  135. }
  136. }
  137. }
  138. }
  139. }
  140. }
  141. func saveData(ReceStr string, x int, y int) (string, error) {
  142. s_params := make([]interface{}, 0)
  143. //bytelist, err := hex.DecodeString(ReturnS)
  144. s_params = append(s_params, 1)
  145. s_params = append(s_params, x)
  146. s_params = append(s_params, y)
  147. s_params = append(s_params, 1)
  148. _, err := restful.ExecQuery("INSERT INTO `cps_m` (`barid`, `x`, `y`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE barid = ?", s_params)
  149. if err != nil {
  150. return "", err
  151. } else {
  152. bytelist, err := hex.DecodeString(ReceStr)
  153. rodecount := (int)((bytelist[2] - 5) >> 1)
  154. s_params = s_params[1:3]
  155. if rodecount > 0 {
  156. for i := 0; i < rodecount; i++ {
  157. beaconname := (int)(bytelist[8+2*i])
  158. rssi := (int)(bytelist[9+2*i])
  159. s_params = s_params[:2]
  160. s_params = append(s_params, beaconname)
  161. s_params = append(s_params, rssi)
  162. s_params = append(s_params, rssi)
  163. _, err = restful.ExecQuery("INSERT INTO `cps_d`(`pid`,`beaconid`,`rssi`) "+
  164. "SELECT (SELECT `id` FROM `cps_m` WHERE `x`=? AND `y`=?),?,? ON DUPLICATE KEY UPDATE rssi = ?", s_params)
  165. if err != nil {
  166. return "", err
  167. }
  168. }
  169. if err == nil {
  170. return "成功保存", nil
  171. }
  172. } else {
  173. return "没有收到数据", nil
  174. }
  175. }
  176. return "没有收到数据", nil
  177. }
  178. func savePointData(ReceStr string, limit int) (interface{}, error) {
  179. s_params := make([]interface{}, 1)
  180. //bytelist, err := hex.DecodeString(ReturnS)
  181. bytelist, err := hex.DecodeString(ReceStr)
  182. rodecount := (int)((bytelist[2] - 5) >> 1)
  183. low := (int)(bytelist[5])
  184. mid := (int)(bytelist[6])
  185. mid = mid << 8
  186. high := (int)(bytelist[7])
  187. high = high << 16
  188. tagid := (int)(low | mid | high)
  189. s_params[0] = tagid
  190. if rodecount > 0 {
  191. for i := 0; i < rodecount; i++ {
  192. beaconname := (int)(bytelist[8+2*i])
  193. rssi := (int)(bytelist[9+2*i])
  194. s_params = s_params[:1]
  195. s_params = append(s_params, beaconname)
  196. s_params = append(s_params, rssi)
  197. s_params = append(s_params, rssi)
  198. _, err = restful.ExecQuery(" INSERT INTO `cps_point`(`tagid`,`beaconid`,`rssi`) "+
  199. " Values( ?, ?, ?) ON DUPLICATE KEY UPDATE rssi = ?", s_params)
  200. if err != nil {
  201. return "", err
  202. }
  203. }
  204. if err == nil {
  205. s_params = s_params[:2]
  206. s_params[0] = tagid
  207. s_params[1] = limit
  208. resultdata, err := restful.QueryByMap(" SELECT AVG(X) X,AVG(Y) Y FROM ( "+
  209. "SELECT `cps_m`.x,`cps_m`.y, SUM(ABS(`cps_d`.`rssi`-`cps_point`.`rssi`)) absrssi "+
  210. "FROM `cps_d` JOIN `cps_point` ON `cps_d`.`beaconid`=`cps_point`.`beaconid` "+
  211. "JOIN `cps_m` ON `cps_m`.`id`=`cps_d`.`pid` WHERE `cps_point`.`tagid`= ? "+
  212. "GROUP BY `cps_m`.x,`cps_m`.y "+
  213. "ORDER BY SUM(ABS(`cps_d`.`rssi`-`cps_point`.`rssi`)) "+
  214. "LIMIT ?) AS d ", 0, 0, s_params)
  215. if err != nil {
  216. return "", err
  217. } else {
  218. return resultdata, nil
  219. }
  220. }
  221. } else {
  222. return "没有收到数据", nil
  223. }
  224. return "没有收到数据", nil
  225. }
  226. func ProcessHttp(c *gin.Context) {
  227. var (
  228. appG = app.Gin{C: c}
  229. )
  230. id := 0 //com.StrTo(c.Param("id")).MustInt()
  231. x := 0 //com.StrTo(c.Param("x")).MustInt()
  232. y := 0 //com.StrTo(c.Param("y")).MustInt()
  233. Id <- id
  234. select {
  235. case ReturnS := <-ReturnString: //拿到锁
  236. if x >= 0 && y >= 0 {
  237. returnData, err := saveData(ReturnS, x, y)
  238. if err != nil {
  239. appG.Response(http.StatusOK, e.ERROR, err.Error())
  240. } else {
  241. appG.Response(http.StatusOK, e.SUCCESS, returnData)
  242. }
  243. } else {
  244. returnData, err := savePointData(ReturnS, 1)
  245. if err != nil {
  246. appG.Response(http.StatusOK, e.ERROR, err.Error())
  247. } else {
  248. appG.Response(http.StatusOK, e.SUCCESS, returnData)
  249. }
  250. }
  251. case <-time.After(10 * time.Second): //超时5s
  252. timeout <- 1
  253. appG.Response(http.StatusOK, e.ERROR, "超时")
  254. }
  255. }
  256. func ProcessHttpCPS(c *gin.Context) {
  257. var (
  258. appG = app.Gin{C: c}
  259. )
  260. id := 0 //com.StrTo(c.Param("id")).MustInt()
  261. limit := 0 //com.StrTo(c.Param("limit")).MustInt()
  262. Id <- id
  263. select {
  264. case ReturnS := <-ReturnString: //拿到锁
  265. {
  266. returnData, err := savePointData(ReturnS, limit)
  267. if err != nil {
  268. appG.Response(http.StatusOK, e.ERROR, err.Error())
  269. } else {
  270. appG.Response(http.StatusOK, e.SUCCESS, returnData)
  271. }
  272. }
  273. case <-time.After(10 * time.Second): //超时5s
  274. timeout <- 1
  275. appG.Response(http.StatusOK, e.ERROR, "超时")
  276. }
  277. }
  278. // 用于判断每年月份的天数
  279. func MonthDay(date string) (month string, sumday string) {
  280. //date :=
  281. return month, sumday
  282. }