diff --git a/consumer/main.lua b/consumer/main.lua index e5be2fe..083791d 100644 --- a/consumer/main.lua +++ b/consumer/main.lua @@ -1,10 +1,16 @@ local kernel = require("kernel") local monitor = kernel.addDriver("monitor-driver") +local data = kernel.addDriver("disk-driver") local function run() monitor.initialize() + disk.initialize() + monitor.writeLine("Starting system...") monitor.writeLine("System started successfully!") + data.writeValue("computer-name", "Papercut87") + computerName = data.getValue("computer-name") + monitor.writeLine("Computer name: " .. computerName) end return { run = run } \ No newline at end of file diff --git a/disk-driver.lua b/disk-driver.lua new file mode 100644 index 0000000..18aa398 --- /dev/null +++ b/disk-driver.lua @@ -0,0 +1,90 @@ +local diskDrive = peripheral.find("drive") +local monitor = require("monitor-driver") +local function getFilePath() + if diskDrive and diskDrive.isDiskPresent() then + local path = diskDrive.getMountPath() + if path then + return fs.combine(path, "data.tbl") + end + end + return nil +end + +local function loadData() + local path = getFilePath() + if path and fs.exists(path) then + local file = fs.open(path, "r") + local content = file.readAll() + file.close() + local parsed + if content then + parsed = textutils.unserialize(content) + end + return parsed or {} + end + return {} +end + +local function saveData(data) + local path = getFilePath() + if path then + local file = fs.open(path, "w") + file.write(textutils.serialize(data)) + file.close() + return true + end + return false +end + +local function generateGuid() + local template ='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' + return string.gsub(template, '[xy]', function (c) + local v = (c == 'x') and math.random(0, 0xf) or math.random(8, 0xb) + return string.format('%x', v) + end) +end + +local function getValue(key) + local data = loadData() + for _, item in ipairs(data) do + if item.Key == key then + return item.Value + end + end + return nil +end + +local function updateValue(key, value) + local data = loadData() + for _, item in ipairs(data) do + if item.Key == key then + item.Value = value + saveData(data) + return true + end + end + return false +end + +local function writeValue(key, value) + local data = loadData() + local guid = generateGuid() + table.insert(data, { GeneratedGuid = guid, Key = key, Value = value }) + saveData(data) + return guid +end + +local function initialize() + monitor.writeLine("Initializing Data Storage...") + if diskDrive and diskDrive.isDiskPresent() then + monitor.writeLine("Disk detected. Initializing data storage.") + local path = getFilePath() + if path and not fs.exists(path) then + saveData({}) + end + return true + end + return false +end + +return { getValue = getValue, updateValue = updateValue, writeValue = writeValue, initialize = initialize } \ No newline at end of file