From 49669c6e5992d61deb016258039c9e6bcfcc4776 Mon Sep 17 00:00:00 2001 From: Guillaume ARM Date: Wed, 22 May 2024 21:05:55 +0200 Subject: [PATCH] feat(inferium-server): add setconfig --- inferium-server.lua | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/inferium-server.lua b/inferium-server.lua index 48ea124..a91c8f5 100644 --- a/inferium-server.lua +++ b/inferium-server.lua @@ -11,11 +11,13 @@ local UPGRADE_SCRIPT = '/upgrade.lua' local defaultConfig = inferium.defaultConfig or error('no default config provided in config', 0) +-- Persistance utils + local savePersistedConfigs = function(configs) local file = fs.open(PERSISTED_CONFIGS, 'w') if not file then - error('savePersistedConfigs: cannot open .minerstate file!') + error('savePersistedConfigs: cannot open ' .. PERSISTED_CONFIGS .. ' file!') end file.write(textutils.serialize(configs)) @@ -37,6 +39,7 @@ local readPersistedConfigs = function() return textutils.unserialize(serializedConfigs) end +-- State local LOCAL_CONFIGS = readPersistedConfigs() local function getConfigForComputer(computerId) @@ -48,6 +51,8 @@ local function saveConfigForComputer(computerId, config) savePersistedConfigs(LOCAL_CONFIGS) end +-- Utils + local function getConfigWithLength(config) local configWithLength = utils.shallowClone(config) configWithLength.length = utils.sizeof(config.plan) @@ -55,6 +60,21 @@ local function getConfigWithLength(config) return configWithLength end +local function isValidConfig(config) + if not config or type(config.plan) ~= 'table' then + return false + end + + if config.firstCropZ == nil or config.firstCropZ < 1 then + return false + end + + if config.fertilizedBoost == nil then + return false + end +end + +-- Routes local function getConfig(_, computerId) if not computerId == nil then @@ -76,6 +96,21 @@ local function getConfig(_, computerId) } end +local function setConfig(message) + local payload = message and message.payload + local harvesterId = payload and payload.id + local config = payload and payload.config + + if not isValidConfig(config) or not harvesterId then + return false + end + + LOCAL_CONFIGS[harvesterId] = config + saveConfigForComputer(harvesterId, config) + + return true +end + -- return a table of harvesters { id: string, name: string }[] local function listHarvesters() local result = {} @@ -99,7 +134,8 @@ end local ROUTES = { ['getconfig'] = getConfig, - ['listHarvesters'] = listHarvesters, + ['setconfig'] = setConfig, + ['list-harvesters'] = listHarvesters, ['exit-server'] = exitServer, ['upgrade-server'] = upgradeServer, }