From ab76e442ab4fb4d41ccbc211f9ac05e19aaefd4b Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Mon, 29 Apr 2024 19:36:48 +0200 Subject: connection, counter, messages and device scan --- main.lua | 37 ++++++++++++++++++++++++------------- messages.lua | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 13 deletions(-) create mode 100644 messages.lua diff --git a/main.lua b/main.lua index 40acc5b..31555ee 100644 --- a/main.lua +++ b/main.lua @@ -1,24 +1,35 @@ +---@diagnostic disable: duplicate-set-field + local funsaac = RegisterMod("funsaac", 1) -local json = require("json") +require("messages") + +local client = require("websocket").new("127.0.0.1", 12345, "/") -local requestServerInfo = { - Id = 1, - ClientName = "Funsaac v.0.0.1", - MessageVersion = 3 -} +CONNECTED = false -local client = require("websocket").new("127.0.0.1", 12345) function client:onmessage(message) - print(message) + HandleResponse(ResponseContent(message)) + if CONNECTED == true then + self:send(GetMessage(Messages.StartScanning)) + CONNECTED = false + end end + function client:onopen() - local msg = '[{"RequestServerInfo": ' .. json.encode(requestServerInfo) .. "}]" - print(msg) - self:send(msg) + self:send(GetMessage(Messages.RequestServerInfo)) end -local function onUpdate() + +local render_tick = 0 +local s = 0; +local function onRender() client:update() + + render_tick = render_tick + 1 + if render_tick >= 60 then + render_tick = 0 + s = s + 1 + end end -funsaac:AddCallback(ModCallbacks.MC_POST_UPDATE, onUpdate) \ No newline at end of file +funsaac:AddCallback(ModCallbacks.MC_POST_RENDER, onRender) \ No newline at end of file diff --git a/messages.lua b/messages.lua new file mode 100644 index 0000000..69576e1 --- /dev/null +++ b/messages.lua @@ -0,0 +1,46 @@ +local json = require("json") + +Messages = { + -- Handshake + RequestServerInfo = { + RequestServerInfo = { + Id = 1, + ClientName = "Funsaac v0.0.2", + MessageVersion = 3 + } + }, + + -- Enumeration + + StartScanning = { + StartScanning = { + Id = 1 + } + } +} + +local cnt = 1; + +function GetMessage(msg) + local message = msg + message[next(msg)]["Id"] = cnt + cnt = cnt + 1 + return "[" .. json.encode(message) .. "]" +end + +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 \ No newline at end of file -- cgit v1.2.3