main.go 2.2 KB

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