Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

1517 rindas
43 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. // Read in a new message as JSON and map it to a Message object
  513. //err := ws.ReadJSON(&msg)
  514. /*msg := Message{
  515. Email: "apple",
  516. Username: "peach",
  517. Message: "change",}
  518. res1B, _ := json.Marshal(msg)
  519. fmt.Println(string(res1B))
  520. if err != nil {
  521. log.Printf("error: %v", err)
  522. }
  523. // Send the newly received message to the broadcast channel
  524. broadcast <- msg*/
  525. ///utils.Log.Printf("%s changes ",beacon.Beacon_id)
  526. 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)
  527. ///utils.Log.Printf("%s",s)
  528. err, out, errout := Shellout(s)
  529. if err != nil {
  530. log.Printf("error: %v\n", err)
  531. }
  532. fmt.Println("--- stdout ---")
  533. fmt.Println(out)
  534. fmt.Println("--- stderr ---")
  535. fmt.Println(errout)
  536. //////beacon.logger.Printf("Log content: user id %v \n", best_location.name)
  537. if settings.HA_send_changes_only {
  538. sendHARoomMessage(beacon.Beacon_id, beacon.Name, best_location.distance, best_location.name, cl)
  539. }
  540. if beacon.expired_location == "expired" {
  541. beacon.Previous_confident_location = "expired"
  542. r.Location = "expired"
  543. } else {
  544. beacon.Previous_confident_location = best_location.name
  545. }
  546. ///beacon.Previous_confident_location = best_location.name
  547. }
  548. beacon.Previous_location = best_location.name
  549. r.Previous_confident_location = beacon.expired_location
  550. BEACONS.Beacons[beacon.Beacon_id] = beacon
  551. http_results_lock.Lock()
  552. http_results.Beacons = append(http_results.Beacons, r)
  553. http_results_lock.Unlock()
  554. if best_location.name != "" {
  555. if !settings.HA_send_changes_only {
  556. secs := int64(time.Now().Unix())
  557. if secs%settings.HA_send_interval == 0 {
  558. sendHARoomMessage(beacon.Beacon_id, beacon.Name, best_location.distance, best_location.name, cl)
  559. }
  560. }
  561. }
  562. /////fmt.Printf("\n\n%s is most likely in %s with average distance %f \n\n", beacon.Name, best_location.name, best_location.distance)
  563. ////beacon.logger.Printf("Log content: user id %v \n", beacon.Name)
  564. // publish this to a topic
  565. // Publish a message.
  566. err := cl.Publish(&client.PublishOptions{
  567. QoS: mqtt.QoS0,
  568. TopicName: []byte("afa-systems/presence"),
  569. Message: []byte(fmt.Sprintf("%s is most likely in %s with average distance %f", beacon.Name, best_location.name, best_location.distance)),
  570. })
  571. if err != nil {
  572. panic(err)
  573. }
  574. }
  575. /*for _, button := range Buttons_list {
  576. http_results.Buttons = append(http_results.Buttons, button)
  577. }*/
  578. if should_persist {
  579. persistBeacons()
  580. }
  581. }
  582. /*func doSomething(bcon Beacon, testo string ) {
  583. bcon.logger.Printf("Log content: user id %v \n", beacon.Name)
  584. }*/
  585. func IncomingMQTTProcessor(updateInterval time.Duration, cl *client.Client, db *bolt.DB, logger []*user) chan<- Incoming_json {
  586. incoming_msgs_chan := make(chan Incoming_json, 2000)
  587. // load initial BEACONS
  588. BEACONS.Beacons = make(map[string]Beacon)
  589. // retrieve the data
  590. // create bucket if not exist
  591. err = db.Update(func(tx *bolt.Tx) error {
  592. _, err := tx.CreateBucketIfNotExists(world)
  593. if err != nil {
  594. return err
  595. }
  596. return nil
  597. })
  598. err = db.View(func(tx *bolt.Tx) error {
  599. bucket := tx.Bucket(world)
  600. if bucket == nil {
  601. return err
  602. }
  603. key := []byte("beacons_list")
  604. val := bucket.Get(key)
  605. if val != nil {
  606. buf := bytes.NewBuffer(val)
  607. dec := gob.NewDecoder(buf)
  608. err = dec.Decode(&BEACONS)
  609. if err != nil {
  610. log.Fatal("decode error:", err)
  611. }
  612. }
  613. key = []byte("buttons_list")
  614. val = bucket.Get(key)
  615. if val != nil {
  616. buf := bytes.NewBuffer(val)
  617. dec := gob.NewDecoder(buf)
  618. err = dec.Decode(&Buttons_list)
  619. if err != nil {
  620. log.Fatal("decode error:", err)
  621. }
  622. }
  623. key = []byte("settings")
  624. val = bucket.Get(key)
  625. if val != nil {
  626. buf := bytes.NewBuffer(val)
  627. dec := gob.NewDecoder(buf)
  628. err = dec.Decode(&settings)
  629. if err != nil {
  630. log.Fatal("decode error:", err)
  631. }
  632. }
  633. return nil
  634. })
  635. if err != nil {
  636. log.Fatal(err)
  637. }
  638. //debug list them out
  639. /*fmt.Println("Database beacons:")
  640. for _, beacon := range BEACONS.Beacons {
  641. fmt.Println("Database has known beacon: " + beacon.Beacon_id + " " + beacon.Name)
  642. dog := new(user)
  643. //createUser( beacon.Name, true)
  644. //user1 := createUser( beacon.Name, true)
  645. //doSomething(beacon, "hello")
  646. //
  647. userFIle := &lumberjack.Logger{
  648. Filename: "/data/presence/presence/beacon_log_" + beacon.Name + ".log",
  649. MaxSize: 250, // mb
  650. MaxBackups: 5,
  651. MaxAge: 10, // in days
  652. }
  653. dog.id = beacon.Name
  654. dog.logger = log.New(userFIle, "User: ", log.Ldate|log.Ltime|log.Lshortfile)
  655. dog.logger.Printf("Log content: user id %v \n", beacon.Name)
  656. logger=append(logger,dog)
  657. }
  658. fmt.Println("leng has %d\n",len(logger))
  659. fmt.Printf("%v", logger)
  660. fmt.Println("Settings has %#v\n", settings)*/
  661. /**/
  662. Latest_beacons_list = make(map[string]Beacon)
  663. Buttons_list = make(map[string]Button)
  664. //create a map of locations, looked up by hostnames
  665. locations_list := Locations_list{}
  666. ls := make(map[string]Location)
  667. locations_list.locations = ls
  668. ticker := time.NewTicker(updateInterval)
  669. go func() {
  670. for {
  671. select {
  672. case <-ticker.C:
  673. getLikelyLocations(settings, locations_list, cl)
  674. case incoming := <-incoming_msgs_chan:
  675. func() {
  676. defer func() {
  677. if err := recover(); err != nil {
  678. log.Println("work failed:", err)
  679. }
  680. }()
  681. incoming = incomingBeaconFilter(incoming)
  682. this_beacon_id := getBeaconID(incoming)
  683. now := time.Now().Unix()
  684. ///fmt.Println("sawbeacon " + this_beacon_id + " at " + incoming.Hostname)
  685. //logger["FCB8351F5A21"].logger.Printf("Log content: user id \n")
  686. //if this beacon isn't in our search list, add it to the latest_beacons pile.
  687. beacon, ok := BEACONS.Beacons[this_beacon_id]
  688. if !ok {
  689. //should be unique
  690. //if it's already in list, forget it.
  691. latest_list_lock.Lock()
  692. x, ok := Latest_beacons_list[this_beacon_id]
  693. if ok {
  694. //update its timestamp
  695. x.Last_seen = now
  696. x.Incoming_JSON = incoming
  697. x.Distance = getBeaconDistance(incoming)
  698. Latest_beacons_list[this_beacon_id] = x
  699. } else {
  700. 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)}
  701. }
  702. for k, v := range Latest_beacons_list {
  703. if (now - v.Last_seen) > 10 { // 10 seconds
  704. delete(Latest_beacons_list, k)
  705. }
  706. }
  707. latest_list_lock.Unlock()
  708. //continue
  709. return
  710. }
  711. beacon.Incoming_JSON = incoming
  712. beacon.Last_seen = now
  713. beacon.Beacon_type = incoming.Beacon_type
  714. beacon.HB_ButtonCounter = incoming.HB_ButtonCounter
  715. beacon.HB_Battery = incoming.HB_Battery
  716. beacon.HB_RandomNonce = incoming.HB_RandomNonce
  717. beacon.HB_ButtonMode = incoming.HB_ButtonMode
  718. ////fmt.Println("button pressed " + this_beacon_id + " at " + strconv.Itoa(int(incoming.HB_ButtonCounter)) )
  719. if beacon.beacon_metrics == nil {
  720. beacon.beacon_metrics = make([]beacon_metric, settings.Beacon_metrics_size)
  721. }
  722. //create metric for this beacon
  723. this_metric := beacon_metric{}
  724. this_metric.distance = getBeaconDistance(incoming)
  725. this_metric.timestamp = now
  726. this_metric.rssi = int64(incoming.RSSI)
  727. this_metric.location = incoming.Hostname
  728. beacon.beacon_metrics = append(beacon.beacon_metrics, this_metric)
  729. ///fmt.Printf("APPENDING a metric from %s len %d\n", beacon.Name, len(beacon.beacon_metrics))
  730. if len(beacon.beacon_metrics) > settings.Beacon_metrics_size {
  731. //fmt.Printf("deleting a metric from %s len %d\n", beacon.Name, len(beacon.beacon_metrics))
  732. beacon.beacon_metrics = append(beacon.beacon_metrics[:0], beacon.beacon_metrics[0+1:]...)
  733. }
  734. //fmt.Printf("%#v\n", beacon.beacon_metrics)
  735. if beacon.HB_ButtonCounter_Prev != beacon.HB_ButtonCounter {
  736. beacon.HB_ButtonCounter_Prev = incoming.HB_ButtonCounter
  737. // send the button message to MQTT
  738. sendButtonPressed(beacon, cl)
  739. }
  740. BEACONS.Beacons[beacon.Beacon_id] = beacon
  741. /*if beacon.Beacon_type == "hb_button" {
  742. processButton(beacon, cl)
  743. }*/
  744. //lookup location by hostname in locations
  745. location, ok := locations_list.locations[incoming.Hostname]
  746. if !ok {
  747. //create the location
  748. locations_list.locations[incoming.Hostname] = Location{}
  749. location, ok = locations_list.locations[incoming.Hostname]
  750. location.name = incoming.Hostname
  751. }
  752. locations_list.locations[incoming.Hostname] = location
  753. }()
  754. }
  755. }
  756. }()
  757. return incoming_msgs_chan
  758. }
  759. func ParseTimeStamp(utime string) (string, error) {
  760. i, err := strconv.ParseInt(utime, 10, 64)
  761. if err != nil {
  762. return "", err
  763. }
  764. t := time.Unix(i, 0)
  765. return t.Format(time.UnixDate), nil
  766. }
  767. var http_host_path_ptr *string
  768. // var https_host_path_ptr *string
  769. var httpws_host_path_ptr *string
  770. //var httpwss_host_path_ptr *string
  771. type Todo struct {
  772. Id string `json:"id"`
  773. Value string `json:"value" binding:"required"`
  774. }
  775. type Job interface {
  776. ExitChan() chan error
  777. Run(todos map[string]Todo) (map[string]Todo, error)
  778. }
  779. func ProcessJobs(jobs chan Job, db string) {
  780. for {
  781. j := <-jobs
  782. todos := make(map[string]Todo, 0)
  783. content, err := ioutil.ReadFile(db)
  784. if err == nil {
  785. if err = json.Unmarshal(content, &todos); err == nil {
  786. todosMod, err := j.Run(todos)
  787. if err == nil && todosMod != nil {
  788. b, err := json.Marshal(todosMod)
  789. if err == nil {
  790. err = ioutil.WriteFile(db, b, 0644)
  791. }
  792. }
  793. }
  794. }
  795. j.ExitChan() <- err
  796. }
  797. }
  798. type user struct {
  799. id string
  800. logger *log.Logger
  801. }
  802. const ShellToUse = "bash"
  803. func Shellout(command string) (error, string, string) {
  804. var stdout bytes.Buffer
  805. var stderr bytes.Buffer
  806. ///utils.Log.Printf("command: %s",command)
  807. cmd := exec.Command(ShellToUse, "-c", command)
  808. cmd.Stdout = &stdout
  809. cmd.Stderr = &stderr
  810. err := cmd.Run()
  811. return err, stdout.String(), stderr.String()
  812. }
  813. func createUser(id string, logWanted bool) user {
  814. var l *log.Logger
  815. if logWanted {
  816. // Here the log content will be added in the user log file
  817. userFIle := &lumberjack.Logger{
  818. Filename: "/data/var/log/presence/presence/log_" + id + ".log",
  819. MaxSize: 250, // mb
  820. MaxBackups: 5,
  821. MaxAge: 10, // in days
  822. }
  823. l = log.New(userFIle, "User: ", log.Ldate|log.Ltime|log.Lshortfile)
  824. } else {
  825. // Here the log content will go nowhere
  826. l = log.New(ioutil.Discard, "User: ", log.Ldate|log.Ltime|log.Lshortfile)
  827. }
  828. return user{id, l}
  829. }
  830. func main() {
  831. loggers := []*user{}
  832. // initialize empty-object json file if not found
  833. //if _, err := ioutil.ReadFile(Db); err != nil {
  834. // str := "{}"
  835. // if err = ioutil.WriteFile(Db, []byte(str), 0644); err != nil {
  836. // log.Fatal(err)
  837. // }
  838. //}
  839. // create channel to communicate over
  840. //jobs := make(chan Job)
  841. // start watching jobs channel for work
  842. //go ProcessJobs(jobs, Db)
  843. // create dependencies
  844. //client := &TodoClient{Jobs: jobs}
  845. //handlers := &TodoHandlers{Client: client}
  846. //work := WorkRequest{Name: name, Delay: delay}
  847. //jobs <- work
  848. http_host_path_ptr = flag.String("http_host_path", "0.0.0.0:8080", "The host:port that the HTTP server should listen on")
  849. //https_host_path_ptr = flag.String("https_host_path", "0.0.0.0:5443", "The host:port that the HTTP server should listen on")
  850. httpws_host_path_ptr = flag.String("httpws_host_path", "0.0.0.0:8088", "The host:port websocket listen")
  851. //httpwss_host_path_ptr = flag.String("httpwss_host_path", "0.0.0.0:8443", "The host:port secure websocket listen")
  852. mqtt_host_ptr := flag.String("mqtt_host", "localhost:1883", "The host:port of the MQTT server to listen for beacons on")
  853. mqtt_username_ptr := flag.String("mqtt_username", "none", "The username needed to connect to the MQTT server, 'none' if it doesn't need one")
  854. mqtt_password_ptr := flag.String("mqtt_password", "none", "The password needed to connect to the MQTT server, 'none' if it doesn't need one")
  855. mqtt_client_id_ptr := flag.String("mqtt_client_id", "presence-detector", "The client ID for the MQTT server")
  856. flag.Parse()
  857. ///utils.NewLog(*logpath)
  858. ///utils.Log.Println("hello")
  859. // Set up channel on which to send signal notifications.
  860. sigc := make(chan os.Signal, 1)
  861. signal.Notify(sigc, os.Interrupt, os.Kill)
  862. // Create an MQTT Client.
  863. cli := client.New(&client.Options{
  864. // Define the processing of the error handler.
  865. ErrorHandler: func(err error) {
  866. fmt.Println(err)
  867. },
  868. })
  869. // Terminate the Client.
  870. defer cli.Terminate()
  871. //open the database
  872. db, err = bolt.Open("/data/conf/presence/presence.db", 0644, nil)
  873. if err != nil {
  874. log.Fatal(err)
  875. }
  876. defer db.Close()
  877. // Connect to the MQTT Server.
  878. err = cli.Connect(&client.ConnectOptions{
  879. Network: "tcp",
  880. Address: *mqtt_host_ptr,
  881. ClientID: []byte(*mqtt_client_id_ptr),
  882. UserName: []byte(*mqtt_username_ptr),
  883. Password: []byte(*mqtt_password_ptr),
  884. })
  885. if err != nil {
  886. panic(err)
  887. }
  888. incoming_updates_chan := IncomingMQTTProcessor(1*time.Second, cli, db, loggers)
  889. // Subscribe to topics.
  890. err = cli.Subscribe(&client.SubscribeOptions{
  891. SubReqs: []*client.SubReq{
  892. &client.SubReq{
  893. TopicFilter: []byte("publish_out/#"),
  894. QoS: mqtt.QoS0,
  895. Handler: func(topicName, message []byte) {
  896. msgStr := string(message)
  897. t := strings.Split(string(topicName), "/")
  898. hostname := t[1]
  899. //Formato JSON multiplo
  900. //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"}]
  901. if strings.HasPrefix(msgStr, "[") {
  902. var readings []RawReading
  903. err := json.Unmarshal(message, &readings)
  904. if err != nil {
  905. log.Printf("Errore parsing JSON: %v", err)
  906. return
  907. }
  908. for _, reading := range readings {
  909. if reading.Type == "Gateway" {
  910. continue
  911. }
  912. incoming := Incoming_json{
  913. Hostname: hostname,
  914. MAC: reading.MAC,
  915. RSSI: int64(reading.RSSI),
  916. Data: reading.RawData,
  917. HB_ButtonCounter: parseButtonState(reading.RawData),
  918. }
  919. incoming_updates_chan <- incoming
  920. }
  921. } else {
  922. //Formato CSV
  923. //ingics solo annuncio
  924. //publish_out/171061001180 $GPRP,C83F8F17DB35,F5B0B0419FEF,-44,02010612FF590080BC280102FFFFFFFF000000000000,1749648798
  925. //ingics tasto premuto
  926. //publish_out/171061001180 $GPRP,C83F8F17DB35,F5B0B0419FEF,-44,02010612FF590080BC280103FFFFFFFF000000000000,1749648798
  927. s := strings.Split(string(message), ",")
  928. if len(s) < 6 {
  929. log.Printf("Messaggio CSV non valido: %s", msgStr)
  930. return
  931. }
  932. rawdata := s[4]
  933. buttonCounter := parseButtonState(rawdata)
  934. if buttonCounter > 0 {
  935. incoming := Incoming_json{}
  936. i, _ := strconv.ParseInt(s[3], 10, 64)
  937. incoming.Hostname = hostname
  938. incoming.Beacon_type = "hb_button"
  939. incoming.MAC = s[1]
  940. incoming.RSSI = i
  941. incoming.Data = rawdata
  942. incoming.HB_ButtonCounter = buttonCounter
  943. read_line := strings.TrimRight(string(s[5]), "\r\n")
  944. it, err33 := strconv.Atoi(read_line)
  945. if err33 != nil {
  946. fmt.Println(it)
  947. fmt.Println(err33)
  948. os.Exit(2)
  949. }
  950. incoming_updates_chan <- incoming
  951. }
  952. }
  953. },
  954. },
  955. },
  956. })
  957. if err != nil {
  958. panic(err)
  959. }
  960. fmt.Println("CONNECTED TO MQTT")
  961. fmt.Println("\n ")
  962. fmt.Println("Visit http://" + *http_host_path_ptr + " on your browser to see the web interface")
  963. fmt.Println("\n ")
  964. go startServer()
  965. // Wait for receiving a signal.
  966. <-sigc
  967. // Disconnect the Network Connection.
  968. if err := cli.Disconnect(); err != nil {
  969. panic(err)
  970. }
  971. }
  972. func startServer() {
  973. headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
  974. originsOk := handlers.AllowedOrigins([]string{"*"})
  975. methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"})
  976. // Set up HTTP server
  977. r := mux.NewRouter()
  978. r.HandleFunc("/api/results", resultsHandler)
  979. r.HandleFunc("/api/beacons/{beacon_id}", beaconsDeleteHandler).Methods("DELETE")
  980. r.HandleFunc("/api/beacons", beaconsListHandler).Methods("GET")
  981. 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
  982. r.HandleFunc("/api/beacons", beaconsAddHandler).Methods("PUT")
  983. r.HandleFunc("/api/latest-beacons", latestBeaconsListHandler).Methods("GET")
  984. r.HandleFunc("/api/settings", settingsListHandler).Methods("GET")
  985. r.HandleFunc("/api/settings", settingsEditHandler).Methods("POST")
  986. r.PathPrefix("/js/").Handler(http.StripPrefix("/js/", http.FileServer(http.Dir("static_html/js/"))))
  987. r.PathPrefix("/css/").Handler(http.StripPrefix("/css/", http.FileServer(http.Dir("static_html/css/"))))
  988. r.PathPrefix("/img/").Handler(http.StripPrefix("/img/", http.FileServer(http.Dir("static_html/img/"))))
  989. r.PathPrefix("/").Handler(http.FileServer(http.Dir("static_html/")))
  990. http.Handle("/", r)
  991. mxWS := mux.NewRouter()
  992. mxWS.HandleFunc("/ws/api/beacons", serveWs)
  993. mxWS.HandleFunc("/ws/api/beacons/latest", serveLatestBeaconsWs)
  994. mxWS.HandleFunc("/ws/broadcast", handleConnections)
  995. http.Handle("/ws/", mxWS)
  996. go func() {
  997. log.Fatal(http.ListenAndServe(*httpws_host_path_ptr, nil))
  998. }()
  999. // Start listening for incoming chat messages
  1000. go handleMessages()
  1001. ///"/conf/etc/cert/certs/services/htdocs/majornet.crt", "/conf/etc/cert/private/services/htdocs/majornet.key"
  1002. http.ListenAndServe(*http_host_path_ptr, handlers.CORS(originsOk, headersOk, methodsOk)(r))
  1003. }
  1004. func handleConnections(w http.ResponseWriter, r *http.Request) {
  1005. // Upgrade initial GET request to a websocket
  1006. ws, err := upgrader.Upgrade(w, r, nil)
  1007. if err != nil {
  1008. log.Fatal(err)
  1009. }
  1010. // Make sure we close the connection when the function returns
  1011. defer ws.Close()
  1012. // Register our new client
  1013. clients[ws] = true
  1014. for {
  1015. var msg Message
  1016. // Read in a new message as JSON and map it to a Message object
  1017. err := ws.ReadJSON(&msg)
  1018. if err != nil {
  1019. log.Printf("error: %v", err)
  1020. delete(clients, ws)
  1021. break
  1022. }
  1023. // Send the newly received message to the broadcast channel
  1024. broadcast <- msg
  1025. }
  1026. }
  1027. func handleMessages() {
  1028. for {
  1029. // Grab the next message from the broadcast channel
  1030. msg := <-broadcast
  1031. // Send it out to every client that is currently connected
  1032. for client := range clients {
  1033. err := client.WriteJSON(msg)
  1034. if err != nil {
  1035. log.Printf("error: %v", err)
  1036. client.Close()
  1037. delete(clients, client)
  1038. }
  1039. }
  1040. }
  1041. }
  1042. func resultsHandler(w http.ResponseWriter, r *http.Request) {
  1043. http_results_lock.RLock()
  1044. js, err := json.Marshal(http_results)
  1045. http_results_lock.RUnlock()
  1046. if err != nil {
  1047. http.Error(w, err.Error(), http.StatusInternalServerError)
  1048. return
  1049. }
  1050. w.Write(js)
  1051. }
  1052. func beaconsListHandler(w http.ResponseWriter, r *http.Request) {
  1053. latest_list_lock.RLock()
  1054. js, err := json.Marshal(BEACONS)
  1055. latest_list_lock.RUnlock()
  1056. if err != nil {
  1057. http.Error(w, err.Error(), http.StatusInternalServerError)
  1058. return
  1059. }
  1060. w.Write(js)
  1061. }
  1062. func persistBeacons() error {
  1063. // gob it first
  1064. buf := &bytes.Buffer{}
  1065. enc := gob.NewEncoder(buf)
  1066. if err := enc.Encode(BEACONS); err != nil {
  1067. return err
  1068. }
  1069. key := []byte("beacons_list")
  1070. // store some data
  1071. err = db.Update(func(tx *bolt.Tx) error {
  1072. bucket, err := tx.CreateBucketIfNotExists(world)
  1073. if err != nil {
  1074. return err
  1075. }
  1076. err = bucket.Put(key, []byte(buf.String()))
  1077. if err != nil {
  1078. return err
  1079. }
  1080. return nil
  1081. })
  1082. return nil
  1083. }
  1084. func persistSettings() error {
  1085. // gob it first
  1086. buf := &bytes.Buffer{}
  1087. enc := gob.NewEncoder(buf)
  1088. if err := enc.Encode(settings); err != nil {
  1089. return err
  1090. }
  1091. key := []byte("settings")
  1092. // store some data
  1093. err = db.Update(func(tx *bolt.Tx) error {
  1094. bucket, err := tx.CreateBucketIfNotExists(world)
  1095. if err != nil {
  1096. return err
  1097. }
  1098. err = bucket.Put(key, []byte(buf.String()))
  1099. if err != nil {
  1100. return err
  1101. }
  1102. return nil
  1103. })
  1104. return nil
  1105. }
  1106. func beaconsAddHandler(w http.ResponseWriter, r *http.Request) {
  1107. decoder := json.NewDecoder(r.Body)
  1108. var in_beacon Beacon
  1109. err = decoder.Decode(&in_beacon)
  1110. if err != nil {
  1111. http.Error(w, err.Error(), 400)
  1112. return
  1113. }
  1114. //make sure name and beacon_id are present
  1115. if (len(strings.TrimSpace(in_beacon.Name)) == 0) || (len(strings.TrimSpace(in_beacon.Beacon_id)) == 0) {
  1116. http.Error(w, "name and beacon_id cannot be blank", 400)
  1117. return
  1118. }
  1119. BEACONS.Beacons[in_beacon.Beacon_id] = in_beacon
  1120. err := persistBeacons()
  1121. if err != nil {
  1122. http.Error(w, "trouble persisting beacons list, create bucket", 500)
  1123. return
  1124. }
  1125. w.Write([]byte("ok"))
  1126. }
  1127. func beaconsDeleteHandler(w http.ResponseWriter, r *http.Request) {
  1128. vars := mux.Vars(r)
  1129. beacon_id := vars["beacon_id"]
  1130. delete(BEACONS.Beacons, beacon_id)
  1131. _, ok := Buttons_list[beacon_id]
  1132. if ok {
  1133. delete(Buttons_list, beacon_id)
  1134. }
  1135. err := persistBeacons()
  1136. if err != nil {
  1137. http.Error(w, "trouble persisting beacons list, create bucket", 500)
  1138. return
  1139. }
  1140. w.Write([]byte("ok"))
  1141. }
  1142. func latestBeaconsListHandler(w http.ResponseWriter, r *http.Request) {
  1143. latest_list_lock.RLock()
  1144. var la = make([]Beacon, 0)
  1145. for _, b := range Latest_beacons_list {
  1146. la = append(la, b)
  1147. }
  1148. latest_list_lock.RUnlock()
  1149. js, err := json.Marshal(la)
  1150. if err != nil {
  1151. http.Error(w, err.Error(), http.StatusInternalServerError)
  1152. return
  1153. }
  1154. w.Write(js)
  1155. }
  1156. func settingsListHandler(w http.ResponseWriter, r *http.Request) {
  1157. js, err := json.Marshal(settings)
  1158. if err != nil {
  1159. http.Error(w, err.Error(), http.StatusInternalServerError)
  1160. return
  1161. }
  1162. w.Write(js)
  1163. }
  1164. func settingsEditHandler(w http.ResponseWriter, r *http.Request) {
  1165. decoder := json.NewDecoder(r.Body)
  1166. var in_settings Settings
  1167. err = decoder.Decode(&in_settings)
  1168. if err != nil {
  1169. http.Error(w, err.Error(), 400)
  1170. return
  1171. }
  1172. //make sure values are > 0
  1173. if (in_settings.Location_confidence <= 0) ||
  1174. (in_settings.Last_seen_threshold <= 0) ||
  1175. (in_settings.HA_send_interval <= 0) {
  1176. http.Error(w, "values must be greater than 0", 400)
  1177. return
  1178. }
  1179. settings = in_settings
  1180. err := persistSettings()
  1181. if err != nil {
  1182. http.Error(w, "trouble persisting settings, create bucket", 500)
  1183. return
  1184. }
  1185. w.Write([]byte("ok"))
  1186. }
  1187. func reader(ws *websocket.Conn) {
  1188. defer ws.Close()
  1189. ws.SetReadLimit(512)
  1190. ws.SetReadDeadline(time.Now().Add(pongWait))
  1191. ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
  1192. for {
  1193. _, _, err := ws.ReadMessage()
  1194. if err != nil {
  1195. break
  1196. }
  1197. }
  1198. }
  1199. func writer(ws *websocket.Conn) {
  1200. pingTicker := time.NewTicker(pingPeriod)
  1201. beaconTicker := time.NewTicker(beaconPeriod)
  1202. defer func() {
  1203. pingTicker.Stop()
  1204. beaconTicker.Stop()
  1205. ws.Close()
  1206. }()
  1207. for {
  1208. select {
  1209. case <-beaconTicker.C:
  1210. http_results_lock.RLock()
  1211. js, err := json.Marshal(http_results)
  1212. http_results_lock.RUnlock()
  1213. if err != nil {
  1214. js = []byte("error")
  1215. }
  1216. ws.SetWriteDeadline(time.Now().Add(writeWait))
  1217. if err := ws.WriteMessage(websocket.TextMessage, js); err != nil {
  1218. return
  1219. }
  1220. case <-pingTicker.C:
  1221. ws.SetWriteDeadline(time.Now().Add(writeWait))
  1222. if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  1223. return
  1224. }
  1225. }
  1226. }
  1227. }
  1228. func serveWs(w http.ResponseWriter, r *http.Request) {
  1229. ws, err := upgrader.Upgrade(w, r, nil)
  1230. if err != nil {
  1231. if _, ok := err.(websocket.HandshakeError); !ok {
  1232. log.Println(err)
  1233. }
  1234. return
  1235. }
  1236. go writer(ws)
  1237. reader(ws)
  1238. }
  1239. func latestBeaconWriter(ws *websocket.Conn) {
  1240. pingTicker := time.NewTicker(pingPeriod)
  1241. beaconTicker := time.NewTicker(beaconPeriod)
  1242. defer func() {
  1243. pingTicker.Stop()
  1244. beaconTicker.Stop()
  1245. ws.Close()
  1246. }()
  1247. for {
  1248. select {
  1249. case <-beaconTicker.C:
  1250. latest_list_lock.RLock()
  1251. var la = make([]Beacon, 0)
  1252. for _, b := range Latest_beacons_list {
  1253. la = append(la, b)
  1254. }
  1255. latest_list_lock.RUnlock()
  1256. js, err := json.Marshal(la)
  1257. if err != nil {
  1258. js = []byte("error")
  1259. }
  1260. ws.SetWriteDeadline(time.Now().Add(writeWait))
  1261. if err := ws.WriteMessage(websocket.TextMessage, js); err != nil {
  1262. return
  1263. }
  1264. case <-pingTicker.C:
  1265. ws.SetWriteDeadline(time.Now().Add(writeWait))
  1266. if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  1267. return
  1268. }
  1269. }
  1270. }
  1271. }
  1272. func serveLatestBeaconsWs(w http.ResponseWriter, r *http.Request) {
  1273. ws, err := upgrader.Upgrade(w, r, nil)
  1274. if err != nil {
  1275. if _, ok := err.(websocket.HandshakeError); !ok {
  1276. log.Println(err)
  1277. }
  1278. return
  1279. }
  1280. go latestBeaconWriter(ws)
  1281. reader(ws)
  1282. }