handler.go 2.2 KB

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