handler.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package remdeshid
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "github.com/gorilla/websocket"
  8. )
  9. type HIDCommand struct {
  10. EventType string `json:"t"`
  11. EventSubType string `json:"s"`
  12. Data string `json:"d"`
  13. }
  14. // HIDWebSocketHandler is a handler for the HID WebSocket connection
  15. var upgrader = websocket.Upgrader{
  16. ReadBufferSize: 1024,
  17. WriteBufferSize: 1024,
  18. CheckOrigin: func(r *http.Request) bool {
  19. return true
  20. },
  21. }
  22. func (c *Controller) HIDWebSocketHandler(w http.ResponseWriter, r *http.Request) {
  23. conn, err := upgrader.Upgrade(w, r, nil)
  24. if err != nil {
  25. log.Println("Failed to upgrade to websocket:", err)
  26. return
  27. }
  28. defer conn.Close()
  29. for {
  30. _, message, err := conn.ReadMessage()
  31. if err != nil {
  32. log.Println("Error reading message:", err)
  33. break
  34. }
  35. log.Printf("Received: %s", message)
  36. //Try parsing the message as a HIDCommand
  37. var hidCmd HIDCommand
  38. if err := json.Unmarshal(message, &hidCmd); err != nil {
  39. log.Println("Error parsing message:", err)
  40. continue
  41. }
  42. //Send the command to the HID controller
  43. bytes, err := ConvHIDCommandToBytes(hidCmd)
  44. if err != nil {
  45. errmsg := map[string]string{"error": err.Error()}
  46. if err := conn.WriteJSON(errmsg); err != nil {
  47. log.Println("Error writing message:", err)
  48. }
  49. continue
  50. }
  51. fmt.Println("Sending bytes:", bytes)
  52. //Write the bytes to the serial port
  53. if err := c.Send(bytes); err != nil {
  54. errmsg := map[string]string{"error": err.Error()}
  55. if err := conn.WriteJSON(errmsg); err != nil {
  56. log.Println("Error writing message:", err)
  57. }
  58. continue
  59. }
  60. if err := conn.WriteMessage(websocket.TextMessage, []byte("ok")); err != nil {
  61. log.Println("Error writing message:", err)
  62. continue
  63. }
  64. }
  65. }