You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

417 lines
9.0 KiB

  1. package nanoleaf
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "git.aiterp.net/lucifer/new-server/models"
  8. "github.com/lucasb-eyer/go-colorful"
  9. "io"
  10. "io/ioutil"
  11. "log"
  12. "math"
  13. "net"
  14. "net/http"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. )
  20. type bridge struct {
  21. mu sync.Mutex
  22. externalID int
  23. host string
  24. apiKey string
  25. panels []*panel
  26. panelIDMap map[uint16]int
  27. }
  28. func (b *bridge) Devices() []models.Device {
  29. results := make([]models.Device, 0, len(b.panels))
  30. for i, panel := range b.panels {
  31. red := float64(panel.ColorRGBA[0]) / 255.0
  32. green := float64(panel.ColorRGBA[1]) / 255.0
  33. blue := float64(panel.ColorRGBA[2]) / 255.0
  34. hue, sat, value := colorful.LinearRgb(red, green, blue).Hsv()
  35. results = append(results, models.Device{
  36. ID: -1,
  37. BridgeID: b.externalID,
  38. InternalID: strconv.Itoa(int(panel.ID)),
  39. Icon: "hexagon",
  40. Name: fmt.Sprintf("Hexagon %d", i),
  41. Capabilities: []models.DeviceCapability{
  42. models.DCPower,
  43. models.DCColorHS,
  44. models.DCIntensity,
  45. models.DCButtons,
  46. },
  47. ButtonNames: []string{"Touch"},
  48. DriverProperties: map[string]string{
  49. "x": strconv.Itoa(panel.X),
  50. "y": strconv.Itoa(panel.Y),
  51. "o": strconv.Itoa(panel.O),
  52. "shapeType": shapeTypeMap[panel.ShapeType],
  53. "shapeWidth": strconv.Itoa(shapeWidthMap[panel.ShapeType]),
  54. },
  55. UserProperties: nil,
  56. State: models.DeviceState{
  57. Power: panel.ColorRGBA[3] == 0,
  58. Color: models.ColorValue{
  59. Hue: math.Mod(hue, 360),
  60. Saturation: sat,
  61. },
  62. Intensity: value,
  63. Temperature: 0,
  64. },
  65. Tags: nil,
  66. })
  67. }
  68. return results
  69. }
  70. func (b *bridge) Refresh(ctx context.Context) error {
  71. overview, err := b.Overview(ctx)
  72. if err != nil {
  73. return err
  74. }
  75. b.mu.Lock()
  76. PanelLoop:
  77. for _, panelInfo := range overview.PanelLayout.Data.PositionData {
  78. if panelInfo.PanelID == 0 {
  79. continue
  80. }
  81. for _, existingPanel := range b.panels {
  82. if existingPanel.ID == panelInfo.PanelID {
  83. existingPanel.O = panelInfo.O
  84. existingPanel.X = panelInfo.X
  85. existingPanel.Y = panelInfo.Y
  86. existingPanel.ShapeType = panelInfo.ShapeType
  87. continue PanelLoop
  88. }
  89. }
  90. b.panels = append(b.panels, &panel{
  91. ID: panelInfo.PanelID,
  92. ColorRGBA: [4]byte{0, 0, 0, 0},
  93. TransitionAt: time.Time{},
  94. O: panelInfo.O,
  95. X: panelInfo.X,
  96. Y: panelInfo.Y,
  97. ShapeType: panelInfo.ShapeType,
  98. Stale: true,
  99. SlowUpdates: 5,
  100. })
  101. }
  102. b.mu.Unlock()
  103. return nil
  104. }
  105. func (b *bridge) Overview(ctx context.Context) (*Overview, error) {
  106. req, err := http.NewRequest("GET", b.URL(), nil)
  107. if err != nil {
  108. return nil, err
  109. }
  110. res, err := http.DefaultClient.Do(req.WithContext(ctx))
  111. if err != nil {
  112. return nil, err
  113. }
  114. defer res.Body.Close()
  115. switch res.StatusCode {
  116. case 400, 403, 500, 503:
  117. return nil, models.ErrUnexpectedResponse
  118. case 401:
  119. return nil, models.ErrIncorrectToken
  120. }
  121. overview := Overview{}
  122. err = json.NewDecoder(res.Body).Decode(&overview)
  123. if err != nil {
  124. return nil, err
  125. }
  126. return &overview, nil
  127. }
  128. func (b *bridge) URL(resource ...string) string {
  129. return fmt.Sprintf("http://%s:16021/api/v1/%s/%s", b.host, b.apiKey, strings.Join(resource, "/"))
  130. }
  131. func (b *bridge) Update(devices []models.Device) {
  132. b.mu.Lock()
  133. defer b.mu.Unlock()
  134. for _, device := range devices {
  135. id, err := strconv.Atoi(device.InternalID)
  136. if err != nil {
  137. continue
  138. }
  139. b.panelIDMap[uint16(id)] = device.ID
  140. for _, panel := range b.panels {
  141. if panel.ID == uint16(id) {
  142. if device.State.Power {
  143. color := colorful.Hsv(device.State.Color.Hue, device.State.Color.Saturation, device.State.Intensity)
  144. red, green, blue := color.RGB255()
  145. newColor := [4]byte{red, green, blue, 255}
  146. if newColor != panel.ColorRGBA {
  147. panel.update(newColor, time.Now().Add(time.Millisecond*120))
  148. }
  149. } else {
  150. panel.update([4]byte{0, 0, 0, 0}, time.Now())
  151. }
  152. break
  153. }
  154. }
  155. }
  156. }
  157. func (b *bridge) Run(ctx context.Context, info models.Bridge, ch chan<- models.Event) error {
  158. err := b.updateEffect(ctx)
  159. if err != nil {
  160. return err
  161. }
  162. conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
  163. IP: net.ParseIP(info.Address),
  164. Port: 60222,
  165. })
  166. if err != nil {
  167. return err
  168. }
  169. defer conn.Close()
  170. // Notify connections and disconnections
  171. ch <- models.Event{Name: "BridgeConnected", Payload: map[string]string{"bridgeId": strconv.Itoa(info.ID)}}
  172. defer func() {
  173. ch <- models.Event{Name: "BridgeDisconnected", Payload: map[string]string{"bridgeId": strconv.Itoa(info.ID)}}
  174. }()
  175. // Start touch listener. This one should go down together with this one, though, so it needs a new context.
  176. ctx2, cancel := context.WithCancel(ctx)
  177. defer cancel()
  178. go b.runTouchListener(ctx2, info.Address, info.Token, ch)
  179. go func() {
  180. ticker := time.NewTicker(time.Second * 5)
  181. for {
  182. select {
  183. case <-ticker.C:
  184. case <-ctx2.Done():
  185. }
  186. err := b.updateEffect(ctx)
  187. if err != nil {
  188. log.Println("Failed to update effects:", err, "This error is non-fatal, and it will be retried shortly.")
  189. }
  190. }
  191. }()
  192. ticker := time.NewTicker(time.Millisecond * 100)
  193. defer ticker.Stop()
  194. strikes := 0
  195. for range ticker.C {
  196. if ctx.Err() != nil {
  197. break
  198. }
  199. panelUpdate := make(PanelUpdate, 2)
  200. b.mu.Lock()
  201. for _, panel := range b.panels {
  202. if !panel.Stale {
  203. if panel.SlowUpdates > 0 {
  204. panel.TicksUntilSlowUpdate -= 1
  205. if panel.TicksUntilSlowUpdate > 0 {
  206. continue
  207. }
  208. panel.TicksUntilSlowUpdate = 10
  209. panel.SlowUpdates -= 1
  210. } else {
  211. continue
  212. }
  213. } else {
  214. panel.Stale = false
  215. }
  216. panelUpdate.Add(panel.message())
  217. if panelUpdate.Len() > 150 {
  218. break
  219. }
  220. }
  221. b.mu.Unlock()
  222. if panelUpdate.Len() == 0 {
  223. continue
  224. }
  225. _, err := conn.Write(panelUpdate)
  226. if err != nil {
  227. strikes++
  228. if strikes >= 3 {
  229. return err
  230. }
  231. } else {
  232. strikes = 0
  233. }
  234. }
  235. return nil
  236. }
  237. func (b *bridge) updateEffect(ctx context.Context) error {
  238. overview, err := b.Overview(ctx)
  239. if err != nil {
  240. return err
  241. }
  242. if overview.Effects.Select == "*Dynamic*" && overview.State.ColorMode == "effect" {
  243. return nil
  244. }
  245. req, err := http.NewRequest("PUT", b.URL("effects"), bytes.NewReader(httpMessage))
  246. if err != nil {
  247. return err
  248. }
  249. res, err := http.DefaultClient.Do(req.WithContext(ctx))
  250. if err != nil {
  251. return err
  252. }
  253. defer res.Body.Close()
  254. if res.StatusCode != 204 {
  255. return models.ErrUnexpectedResponse
  256. }
  257. b.mu.Lock()
  258. for _, panel := range b.panels {
  259. panel.Stale = true
  260. }
  261. b.mu.Unlock()
  262. return nil
  263. }
  264. func (b *bridge) runTouchListener(ctx context.Context, host, apiKey string, ch chan<- models.Event) {
  265. cooldownID := 0
  266. cooldownUntil := time.Now()
  267. message := make(PanelEventMessage, 65536)
  268. reqCloser := io.Closer(nil)
  269. for {
  270. // Set up touch event receiver
  271. touchListener, err := net.ListenUDP("udp4", &net.UDPAddr{
  272. Port: 0,
  273. IP: net.IPv4(0, 0, 0, 0),
  274. })
  275. if err != nil {
  276. log.Println("Socket error:", err)
  277. goto teardownAndRetry
  278. }
  279. {
  280. // Create touch event sender on the remote end.
  281. req, err := http.NewRequest("GET", fmt.Sprintf("http://%s:16021/api/v1/%s/events?id=4", host, apiKey), nil)
  282. if err != nil {
  283. log.Println("HTTP error:", err)
  284. goto teardownAndRetry
  285. }
  286. req.Header["TouchEventsPort"] = []string{strconv.Itoa(touchListener.LocalAddr().(*net.UDPAddr).Port)}
  287. res, err := http.DefaultClient.Do(req.WithContext(ctx))
  288. if err != nil {
  289. log.Println("HTTP error:", err)
  290. goto teardownAndRetry
  291. }
  292. // Discard all data coming over http.
  293. reqCloser = res.Body
  294. go io.Copy(ioutil.Discard, res.Body)
  295. for {
  296. if ctx.Err() != nil {
  297. goto teardownAndRetry
  298. }
  299. // Check in with the context every so often
  300. _ = touchListener.SetReadDeadline(time.Now().Add(time.Second))
  301. n, _, err := touchListener.ReadFromUDP(message)
  302. if err != nil {
  303. if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
  304. continue
  305. } else if ctx.Err() == nil {
  306. log.Println("UDP error:", err)
  307. }
  308. goto teardownAndRetry
  309. }
  310. if !message[:n].ValidateLength() {
  311. log.Println("Bad message length field")
  312. continue
  313. }
  314. for i := 0; i < message.Count(); i += 1 {
  315. b.mu.Lock()
  316. externalID, hasExternalID := b.panelIDMap[message.PanelID(i)]
  317. swipedFromID, hasSwipedFromID := b.panelIDMap[message.SwipedFromPanelID(i)]
  318. b.mu.Unlock()
  319. if !hasExternalID || (externalID == cooldownID && time.Now().Before(cooldownUntil)) {
  320. continue
  321. }
  322. event := models.Event{
  323. Name: "ButtonPressed",
  324. Payload: map[string]string{
  325. "buttonIndex": "0",
  326. "buttonName": "Touch",
  327. "deviceId": strconv.Itoa(externalID),
  328. },
  329. }
  330. if hasSwipedFromID {
  331. event.Payload["swipedFromDeviceId"] = strconv.Itoa(swipedFromID)
  332. }
  333. ch <- event
  334. cooldownID = externalID
  335. cooldownUntil = time.Now().Add(time.Second)
  336. }
  337. }
  338. }
  339. teardownAndRetry:
  340. if touchListener != nil {
  341. _ = touchListener.Close()
  342. }
  343. if reqCloser != nil {
  344. _ = reqCloser.Close()
  345. reqCloser = nil
  346. }
  347. if ctx.Err() != nil {
  348. break
  349. }
  350. time.Sleep(time.Second * 3)
  351. }
  352. }