No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

1477 líneas
42 KiB

  1. package main
  2. import (
  3. "bytes"
  4. "encoding/gob"
  5. "encoding/json"
  6. "flag"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "math"
  11. "net/http"
  12. "os"
  13. "os/signal"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. //"./utils"
  19. "os/exec"
  20. "github.com/boltdb/bolt"
  21. "gopkg.in/natefinch/lumberjack.v2"
  22. "github.com/yosssi/gmq/mqtt"
  23. "github.com/yosssi/gmq/mqtt/client"
  24. "github.com/gorilla/handlers"
  25. "github.com/gorilla/mux"
  26. "github.com/gorilla/websocket"
  27. )
  28. const (
  29. // Time allowed to write the file to the client.
  30. writeWait = 10 * time.Second
  31. // Time allowed to read the next pong message from the client.
  32. pongWait = 60 * time.Second
  33. // Send pings to client with this period. Must be less than pongWait.
  34. pingPeriod = (pongWait * 9) / 10
  35. beaconPeriod = 2 * time.Second
  36. )
  37. // data structures
  38. type Settings struct {
  39. Location_confidence int64 `json:"location_confidence"`
  40. Last_seen_threshold int64 `json:"last_seen_threshold"`
  41. Beacon_metrics_size int `json:"beacon_metrics_size"`
  42. HA_send_interval int64 `json:"ha_send_interval"`
  43. HA_send_changes_only bool `json:"ha_send_changes_only"`
  44. }
  45. type Incoming_json struct {
  46. Hostname string `json:"hostname"`
  47. MAC string `json:"mac"`
  48. RSSI int64 `json:"rssi"`
  49. Is_scan_response string `json:"is_scan_response"`
  50. Ttype string `json:"type"`
  51. Data string `json:"data"`
  52. Beacon_type string `json:"beacon_type"`
  53. UUID string `json:"uuid"`
  54. Major string `json:"major"`
  55. Minor string `json:"minor"`
  56. TX_power string `json:"tx_power"`
  57. Namespace string `json:"namespace"`
  58. Instance_id string `json:"instance_id"`
  59. // button stuff
  60. HB_ButtonCounter int64 `json:"hb_button_counter"`
  61. HB_ButtonCounter_Prev int64 `json:"hb_button_counter"`
  62. HB_Battery int64 `json:"hb_button_battery"`
  63. HB_RandomNonce string `json:"hb_button_random"`
  64. HB_ButtonMode string `json:"hb_button_mode"`
  65. }
  66. type Advertisement struct {
  67. ttype string
  68. content string
  69. seen int64
  70. }
  71. type beacon_metric struct {
  72. location string
  73. distance float64
  74. rssi int64
  75. timestamp int64
  76. }
  77. type Location struct {
  78. name string
  79. lock sync.RWMutex
  80. }
  81. type Best_location struct {
  82. distance float64
  83. name string
  84. last_seen int64
  85. }
  86. type HTTP_location struct {
  87. Previous_confident_location string `json:"previous_confident_location"`
  88. Distance float64 `json:"distance"`
  89. Name string `json:"name"`
  90. Beacon_name string `json:"beacon_name"`
  91. Beacon_id string `json:"beacon_id"`
  92. Beacon_type string `json:"beacon_type"`
  93. HB_Battery int64 `json:"hb_button_battery"`
  94. HB_ButtonMode string `json:"hb_button_mode"`
  95. HB_ButtonCounter int64 `json:"hb_button_counter"`
  96. Location string `json:"location"`
  97. Last_seen int64 `json:"last_seen"`
  98. }
  99. type Location_change struct {
  100. Beacon_ref Beacon `json:"beacon_info"`
  101. Name string `json:"name"`
  102. Beacon_name string `json:"beacon_name"`
  103. Previous_location string `json:"previous_location"`
  104. New_location string `json:"new_location"`
  105. Timestamp int64 `json:"timestamp"`
  106. }
  107. type HA_message struct {
  108. Beacon_id string `json:"id"`
  109. Beacon_name string `json:"name"`
  110. Distance float64 `json:"distance"`
  111. }
  112. type HTTP_locations_list struct {
  113. Beacons []HTTP_location `json:"beacons"`
  114. //Buttons []Button `json:"buttons"`
  115. }
  116. type Beacon struct {
  117. Name string `json:"name"`
  118. Beacon_id string `json:"beacon_id"`
  119. Beacon_type string `json:"beacon_type"`
  120. Beacon_location string `json:"beacon_location"`
  121. Last_seen int64 `json:"last_seen"`
  122. Incoming_JSON Incoming_json `json:"incoming_json"`
  123. Distance float64 `json:"distance"`
  124. Previous_location string
  125. Previous_confident_location string
  126. expired_location string
  127. Location_confidence int64
  128. Location_history []string
  129. beacon_metrics []beacon_metric
  130. HB_ButtonCounter int64 `json:"hb_button_counter"`
  131. HB_ButtonCounter_Prev int64 `json:"hb_button_counter"`
  132. HB_Battery int64 `json:"hb_button_battery"`
  133. HB_RandomNonce string `json:"hb_button_random"`
  134. HB_ButtonMode string `json:"hb_button_mode"`
  135. }
  136. type Button struct {
  137. Name string `json:"name"`
  138. Button_id string `json:"button_id"`
  139. Button_type string `json:"button_type"`
  140. Button_location string `json:"button_location"`
  141. Incoming_JSON Incoming_json `json:"incoming_json"`
  142. Distance float64 `json:"distance"`
  143. Last_seen int64 `json:"last_seen"`
  144. HB_ButtonCounter int64 `json:"hb_button_counter"`
  145. HB_Battery int64 `json:"hb_button_battery"`
  146. HB_RandomNonce string `json:"hb_button_random"`
  147. HB_ButtonMode string `json:"hb_button_mode"`
  148. }
  149. type Beacons_list struct {
  150. Beacons map[string]Beacon `json:"beacons"`
  151. lock sync.RWMutex
  152. }
  153. type Locations_list struct {
  154. locations map[string]Location
  155. lock sync.RWMutex
  156. }
  157. var clients = make(map[*websocket.Conn]bool) // connected clients
  158. var broadcast = make(chan Message) // broadcast channel
  159. // Define our message object
  160. type Message struct {
  161. Email string `json:"email"`
  162. Username string `json:"username"`
  163. Message string `json:"message"`
  164. }
  165. // Struttura per il parsing JSON multiplo
  166. type RawReading struct {
  167. Timestamp string `json:"timestamp"`
  168. Type string `json:"type"`
  169. MAC string `json:"mac"`
  170. RSSI int `json:"rssi"`
  171. RawData string `json:"rawData"`
  172. }
  173. // GLOBALS
  174. var BEACONS Beacons_list
  175. var Buttons_list map[string]Button
  176. var cli *client.Client
  177. var http_results HTTP_locations_list
  178. var http_results_lock sync.RWMutex
  179. var Latest_beacons_list map[string]Beacon
  180. var latest_list_lock sync.RWMutex
  181. var db *bolt.DB
  182. var err error
  183. var world = []byte("presence")
  184. var settings = Settings{
  185. Location_confidence: 4,
  186. Last_seen_threshold: 15,
  187. Beacon_metrics_size: 30,
  188. HA_send_interval: 5,
  189. HA_send_changes_only: false,
  190. }
  191. // utility function
  192. func parseButtonState(raw string) int64 {
  193. raw = strings.ToUpper(raw)
  194. // Minew B7 / C7 / D7 - frame tipo: 0201060303E1FF1216E1FFA103...
  195. if strings.HasPrefix(raw, "0201060303E1FF12") && len(raw) >= 38 {
  196. // La posizione 34-38 (indice 26:30) contiene il buttonCounter su 2 byte (hex)
  197. buttonField := raw[34:38] // NB: offset 34-38 zero-based
  198. if buttonValue, err := strconv.ParseInt(buttonField, 16, 64); err == nil {
  199. return buttonValue
  200. }
  201. }
  202. // Ingics (02010612FF590)
  203. if strings.HasPrefix(raw, "02010612FF590") && len(raw) >= 24 {
  204. counterField := raw[22:24]
  205. buttonState, err := strconv.ParseInt(counterField, 16, 64)
  206. if err == nil {
  207. return buttonState
  208. }
  209. }
  210. // Aggiungeremo qui facilmente nuovi beacon in futuro
  211. return 0
  212. }
  213. func twos_comp(inp string) int64 {
  214. i, _ := strconv.ParseInt("0x"+inp, 0, 64)
  215. return i - 256
  216. }
  217. func getBeaconID(incoming Incoming_json) string {
  218. unique_id := fmt.Sprintf("%s", incoming.MAC)
  219. /*if incoming.Beacon_type == "ibeacon" {
  220. unique_id = fmt.Sprintf("%s_%s_%s", incoming.UUID, incoming.Major, incoming.Minor)
  221. } else if incoming.Beacon_type == "eddystone" {
  222. unique_id = fmt.Sprintf("%s_%s", incoming.Namespace, incoming.Instance_id)
  223. } else if incoming.Beacon_type == "hb_button" {
  224. unique_id = fmt.Sprintf("%s_%s", incoming.Namespace, incoming.Instance_id)
  225. }*/
  226. return unique_id
  227. }
  228. func incomingBeaconFilter(incoming Incoming_json) Incoming_json {
  229. out_json := incoming
  230. if incoming.Beacon_type == "hb_button" {
  231. //do additional checks here to detect if a Habby Bubbles Button
  232. // looks like 020104020a0011ff045600012d3859db59e1000b9453
  233. raw_data := incoming.Data
  234. //company_id := []byte{0x04, 0x56}
  235. //product_id := []byte{0x00, 0x01}
  236. hb_button_prefix_str := fmt.Sprintf("02010612FF5900")
  237. if strings.HasPrefix(raw_data, hb_button_prefix_str) {
  238. out_json.Namespace = "ddddeeeeeeffff5544ff"
  239. //out_json.Instance_id = raw_data[24:36]
  240. counter_str := fmt.Sprintf("0x%s", raw_data[22:24])
  241. counter, _ := strconv.ParseInt(counter_str, 0, 64)
  242. out_json.HB_ButtonCounter = counter
  243. battery_str := fmt.Sprintf("0x%s%s", raw_data[20:22], raw_data[18:20])
  244. ////fmt.Println("battery has %s\n", battery_str)
  245. battery, _ := strconv.ParseInt(battery_str, 0, 64)
  246. out_json.HB_Battery = battery
  247. out_json.TX_power = fmt.Sprintf("0x%s", "4")
  248. out_json.Beacon_type = "hb_button"
  249. out_json.HB_ButtonMode = "presence_button"
  250. ///fmt.Println("Button adv has %#v\n", out_json)
  251. }
  252. }
  253. return out_json
  254. }
  255. func processButton(bbeacon Beacon, cl *client.Client) {
  256. btn := Button{Name: bbeacon.Name}
  257. btn.Button_id = bbeacon.Beacon_id
  258. btn.Button_type = bbeacon.Beacon_type
  259. btn.Button_location = bbeacon.Previous_location
  260. btn.Incoming_JSON = bbeacon.Incoming_JSON
  261. btn.Distance = bbeacon.Distance
  262. btn.Last_seen = bbeacon.Last_seen
  263. btn.HB_ButtonCounter = bbeacon.HB_ButtonCounter
  264. btn.HB_Battery = bbeacon.HB_Battery
  265. btn.HB_RandomNonce = bbeacon.HB_RandomNonce
  266. btn.HB_ButtonMode = bbeacon.HB_ButtonMode
  267. nonce, ok := Buttons_list[btn.Button_id]
  268. if !ok || nonce.HB_RandomNonce != btn.HB_RandomNonce {
  269. // send the button message to MQTT
  270. sendButtonMessage(btn, cl)
  271. }
  272. Buttons_list[btn.Button_id] = btn
  273. }
  274. func getiBeaconDistance(rssi int64, power string) float64 {
  275. ratio := float64(rssi) * (1.0 / float64(twos_comp(power)))
  276. //fmt.Printf("beaconpower: rssi %d ratio %e power %e \n",rssi, ratio, float64(twos_comp(power)))
  277. distance := 100.0
  278. if ratio < 1.0 {
  279. distance = math.Pow(ratio, 10)
  280. } else {
  281. distance = (0.89976)*math.Pow(ratio, 7.7095) + 0.111
  282. }
  283. return distance
  284. }
  285. func getBeaconDistance(incoming Incoming_json) float64 {
  286. distance := 1000.0
  287. distance = getiBeaconDistance(incoming.RSSI, incoming.TX_power)
  288. //distance = math.Abs(float64(incoming.RSSI))
  289. return distance
  290. }
  291. func getAverageDistance(beacon_metrics []beacon_metric) float64 {
  292. total := 0.0
  293. for _, v := range beacon_metrics {
  294. total += v.distance
  295. }
  296. return (total / float64(len(beacon_metrics)))
  297. }
  298. func sendHARoomMessage(beacon_id string, beacon_name string, distance float64, location string, cl *client.Client) {
  299. //first make the json
  300. ha_msg, err := json.Marshal(HA_message{Beacon_id: beacon_id, Beacon_name: beacon_name, Distance: distance})
  301. if err != nil {
  302. panic(err)
  303. }
  304. //send the message to HA
  305. err = cl.Publish(&client.PublishOptions{
  306. QoS: mqtt.QoS1,
  307. TopicName: []byte("afa-systems/presence/ha/" + location),
  308. Message: ha_msg,
  309. })
  310. if err != nil {
  311. panic(err)
  312. }
  313. }
  314. func sendButtonMessage(btn Button, cl *client.Client) {
  315. //first make the json
  316. btn_msg, err := json.Marshal(btn)
  317. if err != nil {
  318. panic(err)
  319. }
  320. //send the message to HA
  321. err = cl.Publish(&client.PublishOptions{
  322. QoS: mqtt.QoS1,
  323. TopicName: []byte("afa-systems/presence/button/" + btn.Button_id),
  324. Message: btn_msg,
  325. })
  326. if err != nil {
  327. panic(err)
  328. }
  329. }
  330. func sendButtonPressed(bcn Beacon, cl *client.Client) {
  331. //first make the json
  332. btn_msg, err := json.Marshal(bcn)
  333. if err != nil {
  334. panic(err)
  335. }
  336. //send the message to HA
  337. err = cl.Publish(&client.PublishOptions{
  338. QoS: mqtt.QoS1,
  339. TopicName: []byte("afa-systems/presence/button/" + bcn.Beacon_id),
  340. Message: btn_msg,
  341. })
  342. if err != nil {
  343. panic(err)
  344. }
  345. ///utils.Log.Printf("%s pressed ",bcn.Beacon_id)
  346. s := fmt.Sprintf("/usr/bin/php /usr/local/presence/alarm_handler.php --idt=%s --idr=%s --st=%d", bcn.Beacon_id, bcn.Incoming_JSON.Hostname, bcn.HB_ButtonCounter)
  347. ///utils.Log.Printf("%s",s)
  348. err, out, errout := Shellout(s)
  349. if err != nil {
  350. log.Printf("error: %v\n", err)
  351. }
  352. fmt.Println("--- stdout ---")
  353. fmt.Println(out)
  354. fmt.Println("--- stderr ---")
  355. fmt.Println(errout)
  356. // create the file if it doesn't exists with O_CREATE, Set the file up for read write, add the append flag and set the permission
  357. //f, err := os.OpenFile("/data/conf/presence/db.json", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
  358. //if err != nil {
  359. // log.Fatal(err)
  360. //}
  361. // write to file, f.Write()
  362. //f.Write(btn_msg)
  363. }
  364. func getLikelyLocations(settings Settings, locations_list Locations_list, cl *client.Client) {
  365. // create the http results structure
  366. http_results_lock.Lock()
  367. http_results = HTTP_locations_list{}
  368. http_results.Beacons = make([]HTTP_location, 0)
  369. ///http_results.Buttons = make([]Button, 0)
  370. http_results_lock.Unlock()
  371. should_persist := false
  372. // iterate through the beacons we want to search for
  373. for _, beacon := range BEACONS.Beacons {
  374. if len(beacon.beacon_metrics) == 0 {
  375. ////fmt.Printf("beacon_metrics = 0:\n")
  376. continue
  377. }
  378. if (int64(time.Now().Unix()) - (beacon.beacon_metrics[len(beacon.beacon_metrics)-1].timestamp)) > settings.Last_seen_threshold {
  379. ////fmt.Printf("beacon_metrics timestamp = %s %s \n",beacon.Name, beacon.beacon_metrics[len(beacon.beacon_metrics)-1].timestamp )
  380. if beacon.expired_location == "expired" {
  381. //beacon.Location_confidence = - 1
  382. continue
  383. } else {
  384. beacon.expired_location = "expired"
  385. msg := Message{
  386. Email: beacon.Previous_confident_location,
  387. Username: beacon.Name,
  388. Message: beacon.expired_location}
  389. res1B, _ := json.Marshal(msg)
  390. fmt.Println(string(res1B))
  391. if err != nil {
  392. log.Printf("error: %v", err)
  393. }
  394. // Send the newly received message to the broadcast channel
  395. broadcast <- msg
  396. }
  397. } else {
  398. beacon.expired_location = ""
  399. }
  400. best_location := Best_location{}
  401. // go through its beacon metrics and pick out the location that appears most often
  402. loc_list := make(map[string]float64)
  403. seen_weight := 1.5
  404. rssi_weight := 0.75
  405. for _, metric := range beacon.beacon_metrics {
  406. loc, ok := loc_list[metric.location]
  407. if !ok {
  408. loc = seen_weight + (rssi_weight * (1.0 - (float64(metric.rssi) / -100.0)))
  409. } else {
  410. loc = loc + seen_weight + (rssi_weight * (1.0 - (float64(metric.rssi) / -100.0)))
  411. }
  412. loc_list[metric.location] = loc
  413. }
  414. //fmt.Printf("beacon: %s list: %#v\n", beacon.Name, loc_list)
  415. // now go through the list and find the largest, that's the location
  416. best_name := ""
  417. ts := 0.0
  418. for name, times_seen := range loc_list {
  419. if times_seen > ts {
  420. best_name = name
  421. ts = times_seen
  422. }
  423. }
  424. /////fmt.Printf("BEST LOCATION FOR %s IS: %s with score: %f\n", beacon.Name, best_name, ts)
  425. best_location = Best_location{name: best_name, distance: beacon.beacon_metrics[len(beacon.beacon_metrics)-1].distance, last_seen: beacon.beacon_metrics[len(beacon.beacon_metrics)-1].timestamp}
  426. // //filter, only let this location become best if it was X times in a row
  427. // if best_location.name == beacon.Previous_location {
  428. // beacon.Location_confidence = beacon.Location_confidence + 1
  429. // } else {
  430. // beacon.Location_confidence = 0
  431. // /////fmt.Printf("beacon.Location_confidence %f\n", beacon.Location_confidence)
  432. // }
  433. // Aggiungiamo il nuovo best_location allo storico
  434. beacon.Location_history = append(beacon.Location_history, best_location.name)
  435. if len(beacon.Location_history) > 10 {
  436. beacon.Location_history = beacon.Location_history[1:] // manteniamo solo gli ultimi 10
  437. }
  438. // Calcoliamo la location più votata nello storico
  439. location_counts := make(map[string]int)
  440. for _, loc := range beacon.Location_history {
  441. location_counts[loc]++
  442. }
  443. max_count := 0
  444. most_common_location := ""
  445. for loc, count := range location_counts {
  446. if count > max_count {
  447. max_count = count
  448. most_common_location = loc
  449. }
  450. }
  451. // Applichiamo un filtro: consideriamo il cambio solo se almeno 7 su 10 votano per una location
  452. if max_count >= 7 {
  453. beacon.Previous_location = most_common_location
  454. if most_common_location == beacon.Previous_confident_location {
  455. beacon.Location_confidence++
  456. } else {
  457. beacon.Location_confidence = 1
  458. beacon.Previous_confident_location = most_common_location
  459. }
  460. }
  461. //create an http result from this
  462. r := HTTP_location{}
  463. r.Distance = best_location.distance
  464. r.Name = beacon.Name
  465. r.Beacon_name = beacon.Name
  466. r.Beacon_id = beacon.Beacon_id
  467. r.Beacon_type = beacon.Beacon_type
  468. r.HB_Battery = beacon.HB_Battery
  469. r.HB_ButtonMode = beacon.HB_ButtonMode
  470. r.HB_ButtonCounter = beacon.HB_ButtonCounter
  471. r.Location = best_location.name
  472. r.Last_seen = best_location.last_seen
  473. ////fmt.Printf("beacon.Location_confidence %s, settings.Location_confidence %s, beacon.Previous_confident_location %s: best_location.name %s\n",beacon.Location_confidence, settings.Location_confidence, beacon.Previous_confident_location, best_location.name)
  474. if (beacon.Location_confidence == settings.Location_confidence && beacon.Previous_confident_location != best_location.name) || beacon.expired_location == "expired" {
  475. // location has changed, send an mqtt message
  476. should_persist = true
  477. fmt.Printf("detected a change!!! %#v\n\n", beacon)
  478. if beacon.Previous_confident_location == "expired" && beacon.expired_location == "" {
  479. msg := Message{
  480. Email: beacon.Previous_confident_location,
  481. Username: beacon.Name,
  482. Message: "OK"}
  483. res1B, _ := json.Marshal(msg)
  484. fmt.Println(string(res1B))
  485. if err != nil {
  486. log.Printf("error: %v", err)
  487. }
  488. // Send the newly received message to the broadcast channel
  489. broadcast <- msg
  490. }
  491. beacon.Location_confidence = 0
  492. location := ""
  493. if beacon.expired_location == "expired" {
  494. location = "expired"
  495. } else {
  496. location = best_location.name
  497. }
  498. //first make the json
  499. js, err := json.Marshal(Location_change{Beacon_ref: beacon, Name: beacon.Name, Beacon_name: beacon.Name, Previous_location: beacon.Previous_confident_location, New_location: location, Timestamp: time.Now().Unix()})
  500. if err != nil {
  501. continue
  502. }
  503. //send the message
  504. err = cl.Publish(&client.PublishOptions{
  505. QoS: mqtt.QoS1,
  506. TopicName: []byte("afa-systems/presence/changes"),
  507. Message: js,
  508. })
  509. if err != nil {
  510. panic(err)
  511. }
  512. s := fmt.Sprintf("/usr/bin/php /usr/local/presence/alarm_handler.php --idt=%s --idr=%s --loct=%s", beacon.Beacon_id, beacon.Incoming_JSON.Hostname, location)
  513. ///utils.Log.Printf("%s",s)
  514. err, out, errout := Shellout(s)
  515. if err != nil {
  516. log.Printf("error: %v\n", err)
  517. }
  518. fmt.Println("--- stdout ---")
  519. fmt.Println(out)
  520. fmt.Println("--- stderr ---")
  521. fmt.Println(errout)
  522. //////beacon.logger.Printf("Log content: user id %v \n", best_location.name)
  523. if settings.HA_send_changes_only {
  524. sendHARoomMessage(beacon.Beacon_id, beacon.Name, best_location.distance, best_location.name, cl)
  525. }
  526. if beacon.expired_location == "expired" {
  527. beacon.Previous_confident_location = "expired"
  528. r.Location = "expired"
  529. } else {
  530. beacon.Previous_confident_location = best_location.name
  531. }
  532. ///beacon.Previous_confident_location = best_location.name
  533. }
  534. beacon.Previous_location = best_location.name
  535. r.Previous_confident_location = beacon.expired_location
  536. BEACONS.Beacons[beacon.Beacon_id] = beacon
  537. http_results_lock.Lock()
  538. http_results.Beacons = append(http_results.Beacons, r)
  539. http_results_lock.Unlock()
  540. if best_location.name != "" {
  541. if !settings.HA_send_changes_only {
  542. secs := int64(time.Now().Unix())
  543. if secs%settings.HA_send_interval == 0 {
  544. sendHARoomMessage(beacon.Beacon_id, beacon.Name, best_location.distance, best_location.name, cl)
  545. }
  546. }
  547. }
  548. /////fmt.Printf("\n\n%s is most likely in %s with average distance %f \n\n", beacon.Name, best_location.name, best_location.distance)
  549. ////beacon.logger.Printf("Log content: user id %v \n", beacon.Name)
  550. // publish this to a topic
  551. // Publish a message.
  552. err := cl.Publish(&client.PublishOptions{
  553. QoS: mqtt.QoS0,
  554. TopicName: []byte("afa-systems/presence"),
  555. Message: []byte(fmt.Sprintf("%s is most likely in %s with average distance %f", beacon.Name, best_location.name, best_location.distance)),
  556. })
  557. if err != nil {
  558. panic(err)
  559. }
  560. }
  561. /*for _, button := range Buttons_list {
  562. http_results.Buttons = append(http_results.Buttons, button)
  563. }*/
  564. if should_persist {
  565. persistBeacons()
  566. }
  567. }
  568. /*func doSomething(bcon Beacon, testo string ) {
  569. bcon.logger.Printf("Log content: user id %v \n", beacon.Name)
  570. }*/
  571. func IncomingMQTTProcessor(updateInterval time.Duration, cl *client.Client, db *bolt.DB, logger []*user) chan<- Incoming_json {
  572. incoming_msgs_chan := make(chan Incoming_json, 2000)
  573. // load initial BEACONS
  574. BEACONS.Beacons = make(map[string]Beacon)
  575. // retrieve the data
  576. // create bucket if not exist
  577. err = db.Update(func(tx *bolt.Tx) error {
  578. _, err := tx.CreateBucketIfNotExists(world)
  579. if err != nil {
  580. return err
  581. }
  582. return nil
  583. })
  584. err = db.View(func(tx *bolt.Tx) error {
  585. bucket := tx.Bucket(world)
  586. if bucket == nil {
  587. return err
  588. }
  589. key := []byte("beacons_list")
  590. val := bucket.Get(key)
  591. if val != nil {
  592. buf := bytes.NewBuffer(val)
  593. dec := gob.NewDecoder(buf)
  594. err = dec.Decode(&BEACONS)
  595. if err != nil {
  596. log.Fatal("decode error:", err)
  597. }
  598. }
  599. key = []byte("buttons_list")
  600. val = bucket.Get(key)
  601. if val != nil {
  602. buf := bytes.NewBuffer(val)
  603. dec := gob.NewDecoder(buf)
  604. err = dec.Decode(&Buttons_list)
  605. if err != nil {
  606. log.Fatal("decode error:", err)
  607. }
  608. }
  609. key = []byte("settings")
  610. val = bucket.Get(key)
  611. if val != nil {
  612. buf := bytes.NewBuffer(val)
  613. dec := gob.NewDecoder(buf)
  614. err = dec.Decode(&settings)
  615. if err != nil {
  616. log.Fatal("decode error:", err)
  617. }
  618. }
  619. return nil
  620. })
  621. if err != nil {
  622. log.Fatal(err)
  623. }
  624. //debug list them out
  625. /*fmt.Println("Database beacons:")
  626. for _, beacon := range BEACONS.Beacons {
  627. fmt.Println("Database has known beacon: " + beacon.Beacon_id + " " + beacon.Name)
  628. dog := new(user)
  629. //createUser( beacon.Name, true)
  630. //user1 := createUser( beacon.Name, true)
  631. //doSomething(beacon, "hello")
  632. //
  633. userFIle := &lumberjack.Logger{
  634. Filename: "/data/presence/presence/beacon_log_" + beacon.Name + ".log",
  635. MaxSize: 250, // mb
  636. MaxBackups: 5,
  637. MaxAge: 10, // in days
  638. }
  639. dog.id = beacon.Name
  640. dog.logger = log.New(userFIle, "User: ", log.Ldate|log.Ltime|log.Lshortfile)
  641. dog.logger.Printf("Log content: user id %v \n", beacon.Name)
  642. logger=append(logger,dog)
  643. }
  644. fmt.Println("leng has %d\n",len(logger))
  645. fmt.Printf("%v", logger)
  646. fmt.Println("Settings has %#v\n", settings)*/
  647. /**/
  648. Latest_beacons_list = make(map[string]Beacon)
  649. Buttons_list = make(map[string]Button)
  650. //create a map of locations, looked up by hostnames
  651. locations_list := Locations_list{}
  652. ls := make(map[string]Location)
  653. locations_list.locations = ls
  654. ticker := time.NewTicker(updateInterval)
  655. go func() {
  656. for {
  657. select {
  658. case <-ticker.C:
  659. getLikelyLocations(settings, locations_list, cl)
  660. case incoming := <-incoming_msgs_chan:
  661. func() {
  662. defer func() {
  663. if err := recover(); err != nil {
  664. log.Println("work failed:", err)
  665. }
  666. }()
  667. incoming = incomingBeaconFilter(incoming)
  668. this_beacon_id := getBeaconID(incoming)
  669. now := time.Now().Unix()
  670. ///fmt.Println("sawbeacon " + this_beacon_id + " at " + incoming.Hostname)
  671. //logger["FCB8351F5A21"].logger.Printf("Log content: user id \n")
  672. //if this beacon isn't in our search list, add it to the latest_beacons pile.
  673. beacon, ok := BEACONS.Beacons[this_beacon_id]
  674. if !ok {
  675. //should be unique
  676. //if it's already in list, forget it.
  677. latest_list_lock.Lock()
  678. x, ok := Latest_beacons_list[this_beacon_id]
  679. if ok {
  680. //update its timestamp
  681. x.Last_seen = now
  682. x.Incoming_JSON = incoming
  683. x.Distance = getBeaconDistance(incoming)
  684. Latest_beacons_list[this_beacon_id] = x
  685. } else {
  686. Latest_beacons_list[this_beacon_id] = Beacon{Beacon_id: this_beacon_id, Beacon_type: incoming.Beacon_type, Last_seen: now, Incoming_JSON: incoming, Beacon_location: incoming.Hostname, Distance: getBeaconDistance(incoming)}
  687. }
  688. for k, v := range Latest_beacons_list {
  689. if (now - v.Last_seen) > 10 { // 10 seconds
  690. delete(Latest_beacons_list, k)
  691. }
  692. }
  693. latest_list_lock.Unlock()
  694. //continue
  695. return
  696. }
  697. beacon.Incoming_JSON = incoming
  698. beacon.Last_seen = now
  699. beacon.Beacon_type = incoming.Beacon_type
  700. beacon.HB_ButtonCounter = incoming.HB_ButtonCounter
  701. beacon.HB_Battery = incoming.HB_Battery
  702. beacon.HB_RandomNonce = incoming.HB_RandomNonce
  703. beacon.HB_ButtonMode = incoming.HB_ButtonMode
  704. ////fmt.Println("button pressed " + this_beacon_id + " at " + strconv.Itoa(int(incoming.HB_ButtonCounter)) )
  705. if beacon.beacon_metrics == nil {
  706. beacon.beacon_metrics = make([]beacon_metric, settings.Beacon_metrics_size)
  707. }
  708. //create metric for this beacon
  709. this_metric := beacon_metric{}
  710. this_metric.distance = getBeaconDistance(incoming)
  711. this_metric.timestamp = now
  712. this_metric.rssi = int64(incoming.RSSI)
  713. this_metric.location = incoming.Hostname
  714. beacon.beacon_metrics = append(beacon.beacon_metrics, this_metric)
  715. ///fmt.Printf("APPENDING a metric from %s len %d\n", beacon.Name, len(beacon.beacon_metrics))
  716. if len(beacon.beacon_metrics) > settings.Beacon_metrics_size {
  717. //fmt.Printf("deleting a metric from %s len %d\n", beacon.Name, len(beacon.beacon_metrics))
  718. beacon.beacon_metrics = append(beacon.beacon_metrics[:0], beacon.beacon_metrics[0+1:]...)
  719. }
  720. //fmt.Printf("%#v\n", beacon.beacon_metrics)
  721. if beacon.HB_ButtonCounter_Prev != beacon.HB_ButtonCounter {
  722. beacon.HB_ButtonCounter_Prev = incoming.HB_ButtonCounter
  723. // send the button message to MQTT
  724. sendButtonPressed(beacon, cl)
  725. }
  726. BEACONS.Beacons[beacon.Beacon_id] = beacon
  727. /*if beacon.Beacon_type == "hb_button" {
  728. processButton(beacon, cl)
  729. }*/
  730. //lookup location by hostname in locations
  731. location, ok := locations_list.locations[incoming.Hostname]
  732. if !ok {
  733. //create the location
  734. locations_list.locations[incoming.Hostname] = Location{}
  735. location, ok = locations_list.locations[incoming.Hostname]
  736. location.name = incoming.Hostname
  737. }
  738. locations_list.locations[incoming.Hostname] = location
  739. }()
  740. }
  741. }
  742. }()
  743. return incoming_msgs_chan
  744. }
  745. func ParseTimeStamp(utime string) (string, error) {
  746. i, err := strconv.ParseInt(utime, 10, 64)
  747. if err != nil {
  748. return "", err
  749. }
  750. t := time.Unix(i, 0)
  751. return t.Format(time.UnixDate), nil
  752. }
  753. var http_host_path_ptr *string
  754. // var https_host_path_ptr *string
  755. var httpws_host_path_ptr *string
  756. //var httpwss_host_path_ptr *string
  757. type Todo struct {
  758. Id string `json:"id"`
  759. Value string `json:"value" binding:"required"`
  760. }
  761. type Job interface {
  762. ExitChan() chan error
  763. Run(todos map[string]Todo) (map[string]Todo, error)
  764. }
  765. func ProcessJobs(jobs chan Job, db string) {
  766. for {
  767. j := <-jobs
  768. todos := make(map[string]Todo, 0)
  769. content, err := ioutil.ReadFile(db)
  770. if err == nil {
  771. if err = json.Unmarshal(content, &todos); err == nil {
  772. todosMod, err := j.Run(todos)
  773. if err == nil && todosMod != nil {
  774. b, err := json.Marshal(todosMod)
  775. if err == nil {
  776. err = ioutil.WriteFile(db, b, 0644)
  777. }
  778. }
  779. }
  780. }
  781. j.ExitChan() <- err
  782. }
  783. }
  784. type user struct {
  785. id string
  786. logger *log.Logger
  787. }
  788. const ShellToUse = "bash"
  789. func Shellout(command string) (error, string, string) {
  790. var stdout bytes.Buffer
  791. var stderr bytes.Buffer
  792. ///utils.Log.Printf("command: %s",command)
  793. cmd := exec.Command(ShellToUse, "-c", command)
  794. cmd.Stdout = &stdout
  795. cmd.Stderr = &stderr
  796. err := cmd.Run()
  797. return err, stdout.String(), stderr.String()
  798. }
  799. func createUser(id string, logWanted bool) user {
  800. var l *log.Logger
  801. if logWanted {
  802. // Here the log content will be added in the user log file
  803. userFIle := &lumberjack.Logger{
  804. Filename: "/data/var/log/presence/presence/log_" + id + ".log",
  805. MaxSize: 250, // mb
  806. MaxBackups: 5,
  807. MaxAge: 10, // in days
  808. }
  809. l = log.New(userFIle, "User: ", log.Ldate|log.Ltime|log.Lshortfile)
  810. } else {
  811. // Here the log content will go nowhere
  812. l = log.New(ioutil.Discard, "User: ", log.Ldate|log.Ltime|log.Lshortfile)
  813. }
  814. return user{id, l}
  815. }
  816. func main() {
  817. loggers := []*user{}
  818. http_host_path_ptr = flag.String("http_host_path", "0.0.0.0:8080", "The host:port that the HTTP server should listen on")
  819. //https_host_path_ptr = flag.String("https_host_path", "0.0.0.0:5443", "The host:port that the HTTP server should listen on")
  820. httpws_host_path_ptr = flag.String("httpws_host_path", "0.0.0.0:8088", "The host:port websocket listen")
  821. //httpwss_host_path_ptr = flag.String("httpwss_host_path", "0.0.0.0:8443", "The host:port secure websocket listen")
  822. mqtt_host_ptr := flag.String("mqtt_host", "localhost:1883", "The host:port of the MQTT server to listen for beacons on")
  823. mqtt_username_ptr := flag.String("mqtt_username", "none", "The username needed to connect to the MQTT server, 'none' if it doesn't need one")
  824. mqtt_password_ptr := flag.String("mqtt_password", "none", "The password needed to connect to the MQTT server, 'none' if it doesn't need one")
  825. mqtt_client_id_ptr := flag.String("mqtt_client_id", "presence-detector", "The client ID for the MQTT server")
  826. flag.Parse()
  827. ///utils.NewLog(*logpath)
  828. ///utils.Log.Println("hello")
  829. // Set up channel on which to send signal notifications.
  830. sigc := make(chan os.Signal, 1)
  831. signal.Notify(sigc, os.Interrupt, os.Kill)
  832. // Create an MQTT Client.
  833. cli := client.New(&client.Options{
  834. // Define the processing of the error handler.
  835. ErrorHandler: func(err error) {
  836. fmt.Println(err)
  837. },
  838. })
  839. // Terminate the Client.
  840. defer cli.Terminate()
  841. //open the database
  842. db, err = bolt.Open("/data/conf/presence/presence.db", 0644, nil)
  843. if err != nil {
  844. log.Fatal(err)
  845. }
  846. defer db.Close()
  847. // Connect to the MQTT Server.
  848. err = cli.Connect(&client.ConnectOptions{
  849. Network: "tcp",
  850. Address: *mqtt_host_ptr,
  851. ClientID: []byte(*mqtt_client_id_ptr),
  852. UserName: []byte(*mqtt_username_ptr),
  853. Password: []byte(*mqtt_password_ptr),
  854. })
  855. if err != nil {
  856. panic(err)
  857. }
  858. incoming_updates_chan := IncomingMQTTProcessor(1*time.Second, cli, db, loggers)
  859. // Subscribe to topics.
  860. err = cli.Subscribe(&client.SubscribeOptions{
  861. SubReqs: []*client.SubReq{
  862. &client.SubReq{
  863. TopicFilter: []byte("publish_out/#"),
  864. QoS: mqtt.QoS0,
  865. Handler: func(topicName, message []byte) {
  866. msgStr := string(message)
  867. t := strings.Split(string(topicName), "/")
  868. hostname := t[1]
  869. //Formato JSON multiplo
  870. //publish_out/170361001234 [{"timestamp":"2025-06-11T11:27:28.492Z","type":"Gateway","mac":"E4B3230DB5CC","nums":10},{"timestamp":"2025-06-11T11:27:28.483Z","mac":"36CE2D7CA4E5","rssi":-27,"rawData":"1EFF0600010F20226F50BB5F834F6C9CE3D876B0C3F665882955B368D3B96C"},{"timestamp":"2025-06-11T11:27:28.586Z","mac":"36CE2D7CA4E5","rssi":-30,"rawData":"1EFF0600010F20226F50BB5F834F6C9CE3D876B0C3F665882955B368D3B96C"},{"timestamp":"2025-06-11T11:27:28.612Z","mac":"406260A302FC","rssi":-35,"rawData":"02011A020A0B0BFF4C001006371AAE2F6F5B"},{"timestamp":"2025-06-11T11:27:28.798Z","mac":"36CE2D7CA4E5","rssi":-28,"rawData":"1EFF0600010F20226F50BB5F834F6C9CE3D876B0C3F665882955B368D3B96C"},{"timestamp":"2025-06-11T11:27:28.905Z","mac":"36CE2D7CA4E5","rssi":-30,"rawData":"1EFF0600010F20226F50BB5F834F6C9CE3D876B0C3F665882955B368D3B96C"},{"timestamp":"2025-06-11T11:27:28.945Z","mac":"C300003947DF","rssi":-32,"rawData":"0201061AFF4C000215FDA50693A4E24FB1AFCFC6EB0764782500000000C5"},{"timestamp":"2025-06-11T11:27:29.013Z","mac":"36CE2D7CA4E5","rssi":-29,"rawData":"1EFF0600010F20226F50BB5F834F6C9CE3D876B0C3F665882955B368D3B96C"},{"timestamp":"2025-06-11T11:27:29.120Z","mac":"36CE2D7CA4E5","rssi":-27,"rawData":"1EFF0600010F20226F50BB5F834F6C9CE3D876B0C3F665882955B368D3B96C"},{"timestamp":"2025-06-11T11:27:29.166Z","mac":"406260A302FC","rssi":-34,"rawData":"02011A020A0B0BFF4C001006371AAE2F6F5B"},{"timestamp":"2025-06-11T11:27:29.337Z","mac":"36CE2D7CA4E5","rssi":-26,"rawData":"1EFF0600010F20226F50BB5F834F6C9CE3D876B0C3F665882955B368D3B96C"}]
  871. if strings.HasPrefix(msgStr, "[") {
  872. var readings []RawReading
  873. err := json.Unmarshal(message, &readings)
  874. if err != nil {
  875. log.Printf("Errore parsing JSON: %v", err)
  876. return
  877. }
  878. for _, reading := range readings {
  879. if reading.Type == "Gateway" {
  880. continue
  881. }
  882. incoming := Incoming_json{
  883. Hostname: hostname,
  884. MAC: reading.MAC,
  885. RSSI: int64(reading.RSSI),
  886. Data: reading.RawData,
  887. HB_ButtonCounter: parseButtonState(reading.RawData),
  888. }
  889. incoming_updates_chan <- incoming
  890. }
  891. } else {
  892. //Formato CSV
  893. //ingics solo annuncio
  894. //publish_out/171061001180 $GPRP,C83F8F17DB35,F5B0B0419FEF,-44,02010612FF590080BC280102FFFFFFFF000000000000,1749648798
  895. //ingics tasto premuto
  896. //publish_out/171061001180 $GPRP,C83F8F17DB35,F5B0B0419FEF,-44,02010612FF590080BC280103FFFFFFFF000000000000,1749648798
  897. s := strings.Split(string(message), ",")
  898. if len(s) < 6 {
  899. log.Printf("Messaggio CSV non valido: %s", msgStr)
  900. return
  901. }
  902. rawdata := s[4]
  903. buttonCounter := parseButtonState(rawdata)
  904. if buttonCounter > 0 {
  905. incoming := Incoming_json{}
  906. i, _ := strconv.ParseInt(s[3], 10, 64)
  907. incoming.Hostname = hostname
  908. incoming.Beacon_type = "hb_button"
  909. incoming.MAC = s[1]
  910. incoming.RSSI = i
  911. incoming.Data = rawdata
  912. incoming.HB_ButtonCounter = buttonCounter
  913. read_line := strings.TrimRight(string(s[5]), "\r\n")
  914. it, err33 := strconv.Atoi(read_line)
  915. if err33 != nil {
  916. fmt.Println(it)
  917. fmt.Println(err33)
  918. os.Exit(2)
  919. }
  920. incoming_updates_chan <- incoming
  921. }
  922. }
  923. },
  924. },
  925. },
  926. })
  927. if err != nil {
  928. panic(err)
  929. }
  930. fmt.Println("CONNECTED TO MQTT")
  931. fmt.Println("\n ")
  932. fmt.Println("Visit http://" + *http_host_path_ptr + " on your browser to see the web interface")
  933. fmt.Println("\n ")
  934. go startServer()
  935. // Wait for receiving a signal.
  936. <-sigc
  937. // Disconnect the Network Connection.
  938. if err := cli.Disconnect(); err != nil {
  939. panic(err)
  940. }
  941. }
  942. func startServer() {
  943. headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
  944. originsOk := handlers.AllowedOrigins([]string{"*"})
  945. methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"})
  946. // Set up HTTP server
  947. r := mux.NewRouter()
  948. r.HandleFunc("/api/results", resultsHandler)
  949. r.HandleFunc("/api/beacons/{beacon_id}", beaconsDeleteHandler).Methods("DELETE")
  950. r.HandleFunc("/api/beacons", beaconsListHandler).Methods("GET")
  951. r.HandleFunc("/api/beacons", beaconsAddHandler).Methods("POST") //since beacons are hashmap, just have put and post be same thing. it'll either add or modify that entry
  952. r.HandleFunc("/api/beacons", beaconsAddHandler).Methods("PUT")
  953. r.HandleFunc("/api/latest-beacons", latestBeaconsListHandler).Methods("GET")
  954. r.HandleFunc("/api/settings", settingsListHandler).Methods("GET")
  955. r.HandleFunc("/api/settings", settingsEditHandler).Methods("POST")
  956. r.PathPrefix("/js/").Handler(http.StripPrefix("/js/", http.FileServer(http.Dir("static_html/js/"))))
  957. r.PathPrefix("/css/").Handler(http.StripPrefix("/css/", http.FileServer(http.Dir("static_html/css/"))))
  958. r.PathPrefix("/img/").Handler(http.StripPrefix("/img/", http.FileServer(http.Dir("static_html/img/"))))
  959. r.PathPrefix("/").Handler(http.FileServer(http.Dir("static_html/")))
  960. http.Handle("/", r)
  961. mxWS := mux.NewRouter()
  962. mxWS.HandleFunc("/ws/api/beacons", serveWs)
  963. mxWS.HandleFunc("/ws/api/beacons/latest", serveLatestBeaconsWs)
  964. mxWS.HandleFunc("/ws/broadcast", handleConnections)
  965. http.Handle("/ws/", mxWS)
  966. go func() {
  967. log.Fatal(http.ListenAndServe(*httpws_host_path_ptr, nil))
  968. }()
  969. // Start listening for incoming chat messages
  970. go handleMessages()
  971. ///"/conf/etc/cert/certs/services/htdocs/majornet.crt", "/conf/etc/cert/private/services/htdocs/majornet.key"
  972. http.ListenAndServe(*http_host_path_ptr, handlers.CORS(originsOk, headersOk, methodsOk)(r))
  973. }
  974. func handleConnections(w http.ResponseWriter, r *http.Request) {
  975. // Upgrade initial GET request to a websocket
  976. ws, err := upgrader.Upgrade(w, r, nil)
  977. if err != nil {
  978. log.Fatal(err)
  979. }
  980. // Make sure we close the connection when the function returns
  981. defer ws.Close()
  982. // Register our new client
  983. clients[ws] = true
  984. for {
  985. var msg Message
  986. // Read in a new message as JSON and map it to a Message object
  987. err := ws.ReadJSON(&msg)
  988. if err != nil {
  989. log.Printf("error: %v", err)
  990. delete(clients, ws)
  991. break
  992. }
  993. // Send the newly received message to the broadcast channel
  994. broadcast <- msg
  995. }
  996. }
  997. func handleMessages() {
  998. for {
  999. // Grab the next message from the broadcast channel
  1000. msg := <-broadcast
  1001. // Send it out to every client that is currently connected
  1002. for client := range clients {
  1003. err := client.WriteJSON(msg)
  1004. if err != nil {
  1005. log.Printf("error: %v", err)
  1006. client.Close()
  1007. delete(clients, client)
  1008. }
  1009. }
  1010. }
  1011. }
  1012. func resultsHandler(w http.ResponseWriter, r *http.Request) {
  1013. http_results_lock.RLock()
  1014. js, err := json.Marshal(http_results)
  1015. http_results_lock.RUnlock()
  1016. if err != nil {
  1017. http.Error(w, err.Error(), http.StatusInternalServerError)
  1018. return
  1019. }
  1020. w.Write(js)
  1021. }
  1022. func beaconsListHandler(w http.ResponseWriter, r *http.Request) {
  1023. latest_list_lock.RLock()
  1024. js, err := json.Marshal(BEACONS)
  1025. latest_list_lock.RUnlock()
  1026. if err != nil {
  1027. http.Error(w, err.Error(), http.StatusInternalServerError)
  1028. return
  1029. }
  1030. w.Write(js)
  1031. }
  1032. func persistBeacons() error {
  1033. // gob it first
  1034. buf := &bytes.Buffer{}
  1035. enc := gob.NewEncoder(buf)
  1036. if err := enc.Encode(BEACONS); err != nil {
  1037. return err
  1038. }
  1039. key := []byte("beacons_list")
  1040. // store some data
  1041. err = db.Update(func(tx *bolt.Tx) error {
  1042. bucket, err := tx.CreateBucketIfNotExists(world)
  1043. if err != nil {
  1044. return err
  1045. }
  1046. err = bucket.Put(key, []byte(buf.String()))
  1047. if err != nil {
  1048. return err
  1049. }
  1050. return nil
  1051. })
  1052. return nil
  1053. }
  1054. func persistSettings() error {
  1055. // gob it first
  1056. buf := &bytes.Buffer{}
  1057. enc := gob.NewEncoder(buf)
  1058. if err := enc.Encode(settings); err != nil {
  1059. return err
  1060. }
  1061. key := []byte("settings")
  1062. // store some data
  1063. err = db.Update(func(tx *bolt.Tx) error {
  1064. bucket, err := tx.CreateBucketIfNotExists(world)
  1065. if err != nil {
  1066. return err
  1067. }
  1068. err = bucket.Put(key, []byte(buf.String()))
  1069. if err != nil {
  1070. return err
  1071. }
  1072. return nil
  1073. })
  1074. return nil
  1075. }
  1076. func beaconsAddHandler(w http.ResponseWriter, r *http.Request) {
  1077. decoder := json.NewDecoder(r.Body)
  1078. var in_beacon Beacon
  1079. err = decoder.Decode(&in_beacon)
  1080. if err != nil {
  1081. http.Error(w, err.Error(), 400)
  1082. return
  1083. }
  1084. //make sure name and beacon_id are present
  1085. if (len(strings.TrimSpace(in_beacon.Name)) == 0) || (len(strings.TrimSpace(in_beacon.Beacon_id)) == 0) {
  1086. http.Error(w, "name and beacon_id cannot be blank", 400)
  1087. return
  1088. }
  1089. BEACONS.Beacons[in_beacon.Beacon_id] = in_beacon
  1090. err := persistBeacons()
  1091. if err != nil {
  1092. http.Error(w, "trouble persisting beacons list, create bucket", 500)
  1093. return
  1094. }
  1095. w.Write([]byte("ok"))
  1096. }
  1097. func beaconsDeleteHandler(w http.ResponseWriter, r *http.Request) {
  1098. vars := mux.Vars(r)
  1099. beacon_id := vars["beacon_id"]
  1100. delete(BEACONS.Beacons, beacon_id)
  1101. _, ok := Buttons_list[beacon_id]
  1102. if ok {
  1103. delete(Buttons_list, beacon_id)
  1104. }
  1105. err := persistBeacons()
  1106. if err != nil {
  1107. http.Error(w, "trouble persisting beacons list, create bucket", 500)
  1108. return
  1109. }
  1110. w.Write([]byte("ok"))
  1111. }
  1112. func latestBeaconsListHandler(w http.ResponseWriter, r *http.Request) {
  1113. latest_list_lock.RLock()
  1114. var la = make([]Beacon, 0)
  1115. for _, b := range Latest_beacons_list {
  1116. la = append(la, b)
  1117. }
  1118. latest_list_lock.RUnlock()
  1119. js, err := json.Marshal(la)
  1120. if err != nil {
  1121. http.Error(w, err.Error(), http.StatusInternalServerError)
  1122. return
  1123. }
  1124. w.Write(js)
  1125. }
  1126. func settingsListHandler(w http.ResponseWriter, r *http.Request) {
  1127. js, err := json.Marshal(settings)
  1128. if err != nil {
  1129. http.Error(w, err.Error(), http.StatusInternalServerError)
  1130. return
  1131. }
  1132. w.Write(js)
  1133. }
  1134. func settingsEditHandler(w http.ResponseWriter, r *http.Request) {
  1135. decoder := json.NewDecoder(r.Body)
  1136. var in_settings Settings
  1137. err = decoder.Decode(&in_settings)
  1138. if err != nil {
  1139. http.Error(w, err.Error(), 400)
  1140. return
  1141. }
  1142. //make sure values are > 0
  1143. if (in_settings.Location_confidence <= 0) ||
  1144. (in_settings.Last_seen_threshold <= 0) ||
  1145. (in_settings.HA_send_interval <= 0) {
  1146. http.Error(w, "values must be greater than 0", 400)
  1147. return
  1148. }
  1149. settings = in_settings
  1150. err := persistSettings()
  1151. if err != nil {
  1152. http.Error(w, "trouble persisting settings, create bucket", 500)
  1153. return
  1154. }
  1155. w.Write([]byte("ok"))
  1156. }
  1157. func reader(ws *websocket.Conn) {
  1158. defer ws.Close()
  1159. ws.SetReadLimit(512)
  1160. ws.SetReadDeadline(time.Now().Add(pongWait))
  1161. ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
  1162. for {
  1163. _, _, err := ws.ReadMessage()
  1164. if err != nil {
  1165. break
  1166. }
  1167. }
  1168. }
  1169. func writer(ws *websocket.Conn) {
  1170. pingTicker := time.NewTicker(pingPeriod)
  1171. beaconTicker := time.NewTicker(beaconPeriod)
  1172. defer func() {
  1173. pingTicker.Stop()
  1174. beaconTicker.Stop()
  1175. ws.Close()
  1176. }()
  1177. for {
  1178. select {
  1179. case <-beaconTicker.C:
  1180. http_results_lock.RLock()
  1181. js, err := json.Marshal(http_results)
  1182. http_results_lock.RUnlock()
  1183. if err != nil {
  1184. js = []byte("error")
  1185. }
  1186. ws.SetWriteDeadline(time.Now().Add(writeWait))
  1187. if err := ws.WriteMessage(websocket.TextMessage, js); err != nil {
  1188. return
  1189. }
  1190. case <-pingTicker.C:
  1191. ws.SetWriteDeadline(time.Now().Add(writeWait))
  1192. if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  1193. return
  1194. }
  1195. }
  1196. }
  1197. }
  1198. func serveWs(w http.ResponseWriter, r *http.Request) {
  1199. ws, err := upgrader.Upgrade(w, r, nil)
  1200. if err != nil {
  1201. if _, ok := err.(websocket.HandshakeError); !ok {
  1202. log.Println(err)
  1203. }
  1204. return
  1205. }
  1206. go writer(ws)
  1207. reader(ws)
  1208. }
  1209. func latestBeaconWriter(ws *websocket.Conn) {
  1210. pingTicker := time.NewTicker(pingPeriod)
  1211. beaconTicker := time.NewTicker(beaconPeriod)
  1212. defer func() {
  1213. pingTicker.Stop()
  1214. beaconTicker.Stop()
  1215. ws.Close()
  1216. }()
  1217. for {
  1218. select {
  1219. case <-beaconTicker.C:
  1220. latest_list_lock.RLock()
  1221. var la = make([]Beacon, 0)
  1222. for _, b := range Latest_beacons_list {
  1223. la = append(la, b)
  1224. }
  1225. latest_list_lock.RUnlock()
  1226. js, err := json.Marshal(la)
  1227. if err != nil {
  1228. js = []byte("error")
  1229. }
  1230. ws.SetWriteDeadline(time.Now().Add(writeWait))
  1231. if err := ws.WriteMessage(websocket.TextMessage, js); err != nil {
  1232. return
  1233. }
  1234. case <-pingTicker.C:
  1235. ws.SetWriteDeadline(time.Now().Add(writeWait))
  1236. if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  1237. return
  1238. }
  1239. }
  1240. }
  1241. }
  1242. func serveLatestBeaconsWs(w http.ResponseWriter, r *http.Request) {
  1243. ws, err := upgrader.Upgrade(w, r, nil)
  1244. if err != nil {
  1245. if _, ok := err.(websocket.HandshakeError); !ok {
  1246. log.Println(err)
  1247. }
  1248. return
  1249. }
  1250. go latestBeaconWriter(ws)
  1251. reader(ws)
  1252. }