handler.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. PosX int `json:"x"` //Only used for mouse events
  14. PosY int `json:"y"` //Only used for mouse events
  15. }
  16. // HIDWebSocketHandler is a handler for the HID WebSocket connection
  17. var upgrader = websocket.Upgrader{
  18. ReadBufferSize: 1024,
  19. WriteBufferSize: 1024,
  20. CheckOrigin: func(r *http.Request) bool {
  21. return true
  22. },
  23. }
  24. func (c *Controller) HIDWebSocketHandler(w http.ResponseWriter, r *http.Request) {
  25. conn, err := upgrader.Upgrade(w, r, nil)
  26. if err != nil {
  27. log.Println("Failed to upgrade to websocket:", err)
  28. return
  29. }
  30. defer conn.Close()
  31. for {
  32. _, message, err := conn.ReadMessage()
  33. if err != nil {
  34. log.Println("Error reading message:", err)
  35. break
  36. }
  37. log.Printf("Received: %s", message)
  38. //Try parsing the message as a HIDCommand
  39. var hidCmd HIDCommand
  40. if err := json.Unmarshal(message, &hidCmd); err != nil {
  41. log.Println("Error parsing message:", err)
  42. continue
  43. }
  44. //Send the command to the HID controller
  45. bytes, err := ConvHIDCommandToBytes(hidCmd)
  46. if err != nil {
  47. errmsg := map[string]string{"error": err.Error()}
  48. if err := conn.WriteJSON(errmsg); err != nil {
  49. log.Println("Error writing message:", err)
  50. }
  51. continue
  52. }
  53. fmt.Println("Sending bytes:", bytes)
  54. //Write the bytes to the serial port
  55. if err := c.Send(bytes); err != nil {
  56. errmsg := map[string]string{"error": err.Error()}
  57. if err := conn.WriteJSON(errmsg); err != nil {
  58. log.Println("Error writing message:", err)
  59. }
  60. continue
  61. }
  62. if err := conn.WriteMessage(websocket.TextMessage, []byte("ok")); err != nil {
  63. log.Println("Error writing message:", err)
  64. continue
  65. }
  66. }
  67. }