comm.go 8.3 KB

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