blob: a3f8d77782af7c0b694cd5bb1d3f4d3f7ebcb184 (
plain) (
tree)
|
|
---@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
|