assits.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package iot
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "imuslab.com/arozos/mod/utils"
  6. )
  7. /*
  8. assits.go
  9. Author: tobychui
  10. This script handle assistant functions for iot devices.
  11. The function implement here should have no effect to the core operation of the iot hub nor the iot pipeline.
  12. */
  13. //Handle the set and get nickname of a particular IoT device
  14. func (m *Manager) HandleNickName(w http.ResponseWriter, r *http.Request) {
  15. opr, err := utils.Mv(r, "opr", true)
  16. if err != nil {
  17. utils.SendErrorResponse(w, "Invalid operation mode")
  18. return
  19. }
  20. uuid, err := utils.Mv(r, "uuid", true)
  21. if err != nil {
  22. utils.SendErrorResponse(w, "Invalid uuid given")
  23. return
  24. }
  25. //Check if the device with the given uuid exists
  26. deviceExist := false
  27. for _, dev := range m.cachedDeviceList {
  28. if dev.DeviceUUID == uuid {
  29. //Device found. Create a new object and make the pointer point to it
  30. deviceExist = true
  31. }
  32. }
  33. //Reject operation if device not exists
  34. if deviceExist == false {
  35. utils.SendErrorResponse(w, "Target device UUID not exists")
  36. return
  37. }
  38. //Process the required operation
  39. if opr == "get" {
  40. if m.db.KeyExists("iot", uuid) {
  41. deviceNickname := ""
  42. err := m.db.Read("iot", uuid, &deviceNickname)
  43. if err != nil {
  44. utils.SendErrorResponse(w, "Unable to read nickname from database")
  45. return
  46. }
  47. js, _ := json.Marshal(deviceNickname)
  48. utils.SendJSONResponse(w, string(js))
  49. } else {
  50. utils.SendErrorResponse(w, "Nickname not exists")
  51. }
  52. } else if opr == "set" {
  53. //Get name from paramter
  54. name, err := utils.Mv(r, "name", true)
  55. if err != nil {
  56. utils.SendErrorResponse(w, "No nickname was given to the device")
  57. return
  58. }
  59. //Set the name in database
  60. err = m.db.Write("iot", uuid, name)
  61. if err != nil {
  62. utils.SendErrorResponse(w, err.Error())
  63. return
  64. }
  65. utils.SendOK(w)
  66. } else {
  67. utils.SendErrorResponse(w, "Unknown operation mode")
  68. return
  69. }
  70. }