main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package main
  2. /*
  3. HDS-Audio
  4. Author: tobychui
  5. Experimental HDS based iot device for Audio playback in local area network
  6. */
  7. import (
  8. "flag"
  9. "log"
  10. "net/http"
  11. "os"
  12. "os/signal"
  13. "strconv"
  14. "strings"
  15. "syscall"
  16. "time"
  17. "imuslab.com/hds/audio/mod/mdns"
  18. )
  19. var (
  20. port = flag.Int("port", 12110, "The port for the HDS device API")
  21. MDNS *mdns.MDNSHost
  22. deviceStatus *Status
  23. deviceUUID = ""
  24. )
  25. func SetupCloseHandler() {
  26. c := make(chan os.Signal, 2)
  27. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  28. go func() {
  29. <-c
  30. //Clear up the tmp folder
  31. os.RemoveAll("./tmp")
  32. //Exit
  33. os.Exit(0)
  34. }()
  35. }
  36. func main() {
  37. //Parse flag
  38. flag.Parse()
  39. //Get system UUID by MAC addr
  40. macAddr, _ := getMacAddr()
  41. if len(macAddr) > 0 {
  42. deviceUUID = strings.ReplaceAll(macAddr[0], ":", "-")
  43. } else {
  44. //Just generate one randomly
  45. deviceUUID = strconv.Itoa(int(time.Now().Unix()))
  46. }
  47. SetupCloseHandler()
  48. //Start MDNS broadcast
  49. hostController, err := mdns.NewMDNS(mdns.NetworkHost{
  50. HostName: "hdsAudio_" + deviceUUID,
  51. Port: *port,
  52. Domain: "hds.arozos.com",
  53. Model: "Audio Device",
  54. UUID: deviceUUID,
  55. Vendor: "Home Dynamic Project",
  56. BuildVersion: "1.0",
  57. MinorVersion: "0.00",
  58. })
  59. if err != nil {
  60. panic(err)
  61. }
  62. MDNS = hostController
  63. //Create a new status objecty
  64. currentStatus := Status{
  65. Playing: false,
  66. Status: "ready",
  67. Gain: 0,
  68. }
  69. deviceStatus = &currentStatus
  70. //Register all required APIs for HDSv2
  71. http.HandleFunc("/", handleIndex)
  72. http.HandleFunc("/status", handleStatus)
  73. http.HandleFunc("/eps", handleEndpoints)
  74. //handlers for playback endpoints
  75. http.HandleFunc("/play", handlePlayToggle)
  76. http.HandleFunc("/stop", handleStop)
  77. http.HandleFunc("/load", handleLoad)
  78. http.HandleFunc("/loop", handleLoop)
  79. http.HandleFunc("/gain", handleVol)
  80. http.HandleFunc("/mute", handleMute)
  81. http.HandleFunc("/name", handleSetName)
  82. //Start web server
  83. log.Println("Web API Started on port ", *port)
  84. err = http.ListenAndServe(":"+strconv.Itoa(*port), nil)
  85. if err != nil {
  86. panic(err)
  87. }
  88. }