summaryrefslogtreecommitdiff
path: root/messages.lua
blob: a3f8d77782af7c0b694cd5bb1d3f4d3f7ebcb184 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
---@diagnostic disable: duplicate-set-field

local json = require("json")

WsClient = require("websocket").new("127.0.0.1", 12345, "/")

CONNECTED = false

function WsClient:onmessage(message)
  HandleResponse(ResponseContent(message))
  if CONNECTED == true then
    print("StartScanning")
    StartScanning()
    CONNECTED = false
  end
end

function WsClient:onopen()
  RequestServerInfo()
end

Messages = {
  -- Handshake
  RequestServerInfo = {
    RequestServerInfo = {
      Id = 1,
      ClientName = "Funsaac v0.0.3",
      MessageVersion = 3
    }
  },

  -- Enumeration

  StartScanning = {
    StartScanning = {
      Id = 1
    }
  },

  -- Generic Device
  ScalarCmd = {
    ScalarCmd = {
      Id = 1,
      DeviceIndex = 0,
      Scalars = {
        {
          Index = 0,
          Scalar = 1,
          ActuatorType = "Vibrate"
        }
      }
    }
  }
}

local cnt = 1;

local function getEncodedJson(msg)
  return "[" .. json.encode(msg) .. "]"
end

---Get message with correct id
---@param msg table Message from Messages table
function GetMessage(msg)
  local message = msg
  message[next(msg)]["Id"] = cnt
  cnt = cnt + 1
  return message
end

-- REQUESTS

---Request Info from the server
function RequestServerInfo()
  WsClient:send(getEncodedJson(GetMessage(Messages.RequestServerInfo)))
end

function StartScanning()
  WsClient:send(getEncodedJson(GetMessage(Messages.StartScanning)))
end

function ScalarCmd(strength)
  local message = GetMessage(Messages.ScalarCmd)
  -- message[next(Messages.ScalarCmd)]["Scalars"][0]["Scalar"] = strength
  WsClient:send(getEncodedJson(message))
end


--RESPONSES

function ResponseContent(message)
  local msg = json.decode(message)[1]
  local type = next(msg)
  return type, msg[type]
end

function HandleResponse(type, content)
  if type == "ServerInfo" then
    print("Connected to Server: " .. content["ServerName"])
    CONNECTED = true
  elseif type == "Ok" then
    print("Id: " .. content["Id"])
  elseif type == "DeviceAdded" then
    print("DeviceAdded: " .. content["DeviceName"])
  end
end