April_The_Sergal

induc

Sep 28th, 2025 (edited)
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 30.22 KB | None | 0 0
  1. -- === Config ===
  2. local borderColour = 128
  3. local chartBGColour = 128
  4. local inputChartColour = 32
  5. local outputChartColour = 16384
  6. local batteryChargeColour = 8
  7. local idleColour = 16
  8. local sectionTitleColour = 1
  9. local baseTextColour = 1
  10.  
  11. local screenRefreshRate = 0.1
  12. local unitFormatCaps = true
  13. local dataCorrection = 2.5
  14.  
  15. -- === Discover monitor + Induction (handles local + wired modem) ===
  16. local function findMonitorAndInduction()
  17.   local foundMonitor, foundInduction, legacy
  18.   local function consider(name, getType)
  19.     local pType = (getType and getType(name)) or peripheral.getType(name)
  20.     local lname = tostring(name):lower()
  21.  
  22.     if (not foundMonitor) and (pType == "monitor" or lname:find("monitor", 1, true)) then
  23.       local ok, p = pcall(peripheral.wrap, name); if ok and p then foundMonitor = p end
  24.     end
  25.  
  26.     if not foundInduction then
  27.       -- “Port” indicates modern; plain “matrix/induction” indicates legacy block name
  28.       local isPort = (pType == "inductionPort")
  29.         or (pType and pType:lower():find("induction", 1, true) and pType:lower():find("port", 1, true))
  30.         or (lname:find("inductionport", 1, true) ~= nil)
  31.  
  32.       local looksLikeIM = isPort
  33.         or (pType and pType:lower():find("induction", 1, true))
  34.         or lname:find("induction", 1, true)
  35.         or lname:find("matrix", 1, true)
  36.  
  37.       if looksLikeIM then
  38.         local ok, p = pcall(peripheral.wrap, name)
  39.         if ok and p then
  40.           foundInduction = p
  41.           legacy = (not isPort) and (lname:find("matrix", 1, true) or (pType and pType:lower():find("matrix", 1, true))) or false
  42.         end
  43.       end
  44.     end
  45.   end
  46.  
  47.   for _, name in ipairs(peripheral.getNames()) do
  48.     local pType = peripheral.getType(name)
  49.     consider(name, peripheral.getType)
  50.  
  51.     if pType == "modem" then
  52.       local mdm = peripheral.wrap(name)
  53.       if mdm and mdm.isWireless and mdm.getNamesRemote then
  54.         local isWireless = false; pcall(function() isWireless = mdm.isWireless() end)
  55.         if not isWireless then
  56.           local ok, remotes = pcall(mdm.getNamesRemote)
  57.           if ok and type(remotes) == "table" then
  58.             for _, rname in ipairs(remotes) do
  59.               local function getTypeRemote(n) if mdm.getTypeRemote then return mdm.getTypeRemote(n) end return nil end
  60.               consider(rname, getTypeRemote)
  61.               if foundMonitor and foundInduction then return foundMonitor, foundInduction, legacy end
  62.             end
  63.           end
  64.         end
  65.       end
  66.     end
  67.  
  68.     if foundMonitor and foundInduction then break end
  69.   end
  70.  
  71.   return foundMonitor, foundInduction, legacy
  72. end
  73.  
  74. local m, im, imLegacy = findMonitorAndInduction()
  75. local w, h
  76.  
  77. -- === Peripheral helpers & legacy shims ===
  78. local function hasMethod(p, name) return p and type(p[name]) == "function" end
  79.  
  80. local function getLastInput()
  81.   if hasMethod(im, "getLastInput") then return im.getLastInput() end
  82.   if hasMethod(im, "getInput") then return im.getInput() end
  83.   return 0
  84. end
  85.  
  86. local function getLastOutput()
  87.   if hasMethod(im, "getLastOutput") then return im.getLastOutput() end
  88.   if hasMethod(im, "getOutput") then return im.getOutput() end
  89.   return 0
  90. end
  91.  
  92. local function getFilledPct()
  93.   if hasMethod(im, "getEnergyFilledPercentage") then return im.getEnergyFilledPercentage() end
  94.   local e = im.getEnergy and im.getEnergy() or 0
  95.   local mE = im.getMaxEnergy and im.getMaxEnergy() or 0
  96.   if mE > 0 then return e / mE end
  97.   return 0
  98. end
  99.  
  100. -- === UI helpers ===
  101. local colorText = {"White","Orange","Magenta","Light blue","Yellow","Lime","Pink","Gray","Light gray","Cyan","Purple","Blue","Brown","Green","Red","Black"}
  102. local colorDec  = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768}
  103. local refreshRates = { values = {0.1,0.3,0.5,1.0,1.0,2.0}, display = {"Fastest","Fast","Normal","Slow","Very Slow","Slowest"} }
  104. local unitStyle    = { values = {true,false}, display = {"X.X KRF","X.XkRF"} }
  105.  
  106. local function fromBlit(hex)
  107.   if #hex ~= 1 then return nil end
  108.   local value = tonumber(hex, 16); if not value then return nil end
  109.   return 2 ^ value
  110. end
  111.  
  112. local function draw(xStart, xLen, yStart, yLen, c, target)
  113.   target = target or m
  114.   local ob = target.getBackgroundColour()
  115.   target.setBackgroundColor(c)
  116.   target.setCursorPos(xStart, yStart)
  117.  
  118.   if xLen > 1 then
  119.     for i = 1, xLen do
  120.       target.write(" "); target.setCursorPos(xStart+i, yStart)
  121.     end
  122.   elseif xLen ~= 0 and yLen ~= 0 then
  123.     target.write(" ")
  124.   end
  125.  
  126.   if yLen > 1 then
  127.     for k = 1, yLen-1 do
  128.       target.setCursorPos(xStart, yStart+k); target.write(" ")
  129.     end
  130.   end
  131.  
  132.   target.setBackgroundColor(ob)
  133. end
  134.  
  135. local function drawBar(xmin, xmax, y, r, c)
  136.   for i=1, r do draw(xmin, xmax, y+i-1, 1, c) end
  137. end
  138.  
  139. local function writeAt(x, y, t, c, b, target)
  140.   target = target or m
  141.   local oc = target.getTextColour and target.getTextColour() or colors.white
  142.   local ob = target.getBackgroundColour and target.getBackgroundColour() or colors.black
  143.   if target.setTextColour       then target.setTextColour(c or oc) end
  144.   if target.setBackgroundColour then target.setBackgroundColour(b or ob) end
  145.   target.setCursorPos(x, y); target.write(t)
  146.   if target.setTextColour       then target.setTextColour(oc) end
  147.   if target.setBackgroundColour then target.setBackgroundColour(ob) end
  148. end
  149.  
  150. local function newWindow(target, x, y, w_, h_, bg)
  151.   local win = window.create(target, x, y, w_, h_)
  152.   win.setBackgroundColor(bg or 32768); win.clear()
  153.   return win
  154. end
  155.  
  156. local function displayError(index)
  157.   local x, y = m.getSize()
  158.   local errorText = "ERROR"
  159.   local errors = {
  160.     "The Induction Matrix has been tampered with.",
  161.     "Induction Port not connected.",
  162.     "The Induction Matrix is incomplete."
  163.   }
  164.   m.clear()
  165.   m.setTextColour(16384)
  166.   m.setCursorPos((x/2) - (string.len(errorText)/2), (y/2)-1)
  167.   m.write(errorText)
  168.   writeAt((x/2) - (string.len(errors[index])/2), y/2, errors[index], baseTextColour)
  169.   printError("ERROR: " .. errors[index])
  170.  
  171.   local timer = 10
  172.   while timer > -1 do
  173.     local countdownStr = "Next attempt in " .. timer
  174.     draw((x/2) - (string.len(countdownStr)/2), string.len(countdownStr) + 1, (y/2)+2, 1, 32768)
  175.     writeAt((x/2) - (string.len(countdownStr)/2), (y/2)+2, countdownStr, baseTextColour)
  176.     print(countdownStr)
  177.     timer = timer -1
  178.     os.sleep(1)
  179.   end
  180.   os.reboot()
  181. end
  182.  
  183. -- === Init monitor ===
  184. if m ~= nil then
  185.   pcall(function() m.setTextScale(0.5) end)
  186.   local x, y = m.getSize()
  187.   if x ~= 100 or y ~= 38 then print("WARNING: Monitor size is "..x.."x"..y..". Designed for 100x38.") end
  188.   w, h = m.getSize()
  189.   m.setBackgroundColor(32768); m.clear(); m.setTextColour(1)
  190. else
  191.   print("No monitor found (local or via wired modem)."); return
  192. end
  193.  
  194. -- === Validate matrix/port ===
  195. if not im then
  196.   displayError(2)
  197. else
  198.   if (not imLegacy) and hasMethod(im, "isFormed") then
  199.     while not im.isFormed() do displayError(3) end
  200.   end
  201. end
  202.  
  203. -- === Misc helpers ===
  204. local function removeOverflow(tab, maxDataCount)
  205.   while #tab >= maxDataCount do table.remove(tab, 1) end
  206.   return tab
  207. end
  208.  
  209. local function getRange(input)
  210.   local max, min = 0, 0
  211.   for i = 1, #input do
  212.     if i == 1 then max = input[i]; min = input[i] end
  213.     if input[i] > max then max = input[i] end
  214.     if input[i] < min then min = input[i] end
  215.   end
  216.   return min, max
  217. end
  218.  
  219. local function round(x, decimal)
  220.   local m_ = 10^(decimal or 0)
  221.   local result = math.floor(x * m_ + 0.5) / m_
  222.   return string.format("%." .. (decimal or 0) .. "f", result)
  223. end
  224.  
  225. local function roundD(exact, quantum)
  226.   local quant,frac = math.modf(exact/quantum)
  227.   return quantum * (quant + (frac > 0.5 and 1 or 0))
  228. end
  229.  
  230. local timeUnits = {
  231.   {threshold = 8553600, unit = "99+ days"},
  232.   {threshold = 86400, unit = "days",  divisor = 86400},
  233.   {threshold = 3600,   unit = "hours", divisor = 3600},
  234.   {threshold = 60,     unit = "min",   divisor = 60},
  235.   {threshold = 1,      unit = "sec",   divisor = 1}
  236. }
  237. local function adjustTime(time)
  238.   for _, unitData in ipairs(timeUnits) do
  239.     if time >= unitData.threshold then
  240.       local adjustedTime
  241.       if unitData.divisor and unitData.divisor ~= 1 then
  242.         adjustedTime = string.format("%.1f", time / unitData.divisor)
  243.       elseif unitData.divisor then
  244.         adjustedTime = math.floor(time / unitData.divisor)
  245.       else
  246.         adjustedTime = ""
  247.       end
  248.       return string.format("%s %s", adjustedTime, unitData.unit)
  249.     end
  250.   end
  251.   return "0 sec."
  252. end
  253.  
  254. local function conversion(exact, text, addPlus, afterDecimalPoint)
  255.   afterDecimalPoint = afterDecimalPoint or 0.1
  256.   addPlus = addPlus or false
  257.   local units = unitFormatCaps and {"", "K", "M", "G", "T", "P", "E", "Z", "Y"} or {"", "k", "m", "g", "t", "p", "e", "z", "y"}
  258.   local pot = 1
  259.   local absExact = math.abs(exact)
  260.   while absExact >= (1000^pot) do pot = pot + 1 end
  261.   local value = roundD(exact / (1000^(pot - 1)), afterDecimalPoint)
  262.   local out = tostring(value)
  263.   if addPlus and value > 0 then out = "+" .. out end
  264.   if text then out = out .. (unitFormatCaps and " " .. units[pot] or units[pot]) end
  265.   return out
  266. end
  267.  
  268. local function protCall(func, errIndex)
  269.   local success, result = pcall(func)
  270.   if success and result ~= nil then return result else displayError(errIndex) end
  271. end
  272.  
  273. local function indexOf(array, value)
  274.   for i, v in ipairs(array) do if v == value then return i end end
  275.   return nil
  276. end
  277.  
  278. -- === Globals ===
  279. local energy, maxEnergy, installedCells, installedProviders, lastInput, lastOutput, filledPercentage, maxTransfer
  280. local inputHistory, outputHistory, flowHistory = {}, {}, {}
  281. local imWidth, imLength, imHeight
  282.  
  283. -- ---------- Stable predictor (linear regression on energy vs time) ----------
  284. local PRED_WINDOW = 200       -- ~20s at 0.1s refresh
  285. local ENERGY_TREND_CHECK = 20 -- require recent direction agreement
  286. local FLOW_EPS = 1            -- ignore tiny changes (<1 RF/s)
  287.  
  288. local energyHist = {}         -- { {t=seconds, e=RF}, ... }
  289. local t_elapsed = 0           -- seconds since start
  290. local dEdt_sec = 0            -- slope RF/s (used by drawBattery)
  291.  
  292. local function pushEnergySample(t, e)
  293.   table.insert(energyHist, { t = t, e = e })
  294.   removeOverflow(energyHist, PRED_WINDOW)
  295. end
  296.  
  297. local function energySlope()
  298.   local n = #energyHist
  299.   if n < 2 then return 0 end
  300.   local sumt, sume, sumtt, sumte = 0, 0, 0, 0
  301.   for i = 1, n do
  302.     local t = energyHist[i].t
  303.     local e = energyHist[i].e
  304.     sumt  = sumt  + t
  305.     sume  = sume  + e
  306.     sumtt = sumtt + t*t
  307.     sumte = sumte + t*e
  308.   end
  309.   local denom = n * sumtt - sumt * sumt
  310.   if denom == 0 then return 0 end
  311.   return (n * sumte - sumt * sume) / denom
  312. end
  313.  
  314. local function stableSlope()
  315.   local s = energySlope() -- RF/s
  316.   local n = #energyHist
  317.   if n < 2 then return 0 end
  318.   local checks = math.min(ENERGY_TREND_CHECK, n - 1)
  319.   local agree = 0
  320.   for i = n - checks + 1, n do
  321.     if i > 1 then
  322.       local d = energyHist[i].e - energyHist[i-1].e
  323.       if d * s > 0 then agree = agree + 1 end
  324.     end
  325.   end
  326.   local ok = (checks == 0) or (agree / checks >= 0.7)
  327.   if not ok then return 0 end
  328.   if math.abs(s) < FLOW_EPS then return 0 end
  329.   return s
  330. end
  331. -- ---------------------------------------------------------------------------
  332.  
  333. -- === Drawing ===
  334. local function drawStaticElements()
  335.   local p = 2
  336.   draw(p, w-3, p, 1, borderColour)
  337.   draw(p, w-3, h-1, 1, borderColour)
  338.   draw(p, 1, p, h-p, borderColour)
  339.   draw(w-1, 1, p, h-p, borderColour)
  340.   draw(27, 1, p, h-p, borderColour)
  341.   draw(28, 71, h/2+2, 1, borderColour)
  342.   draw(63, 1, h/2+3, 15, borderColour)
  343.   draw(2, 25, 28, 1, borderColour)
  344.  
  345.   writeAt(5, 2, "  BATTERY  ", sectionTitleColour)
  346.   writeAt(30, 2, "  ENERGY FLOW:  ", sectionTitleColour)
  347.   writeAt(5, 28, "  STATS:  ", sectionTitleColour)
  348.  
  349.   local configButtonText = "SETTINGS " .. string.char(26)
  350.   local configButtonSpaceMaker = "  "
  351.   local buttonX = w - #configButtonText - 3
  352.   local buttonY = 2
  353.   for i = 1, #configButtonText do configButtonSpaceMaker = configButtonSpaceMaker .. " " end
  354.   writeAt(buttonX - 1, buttonY, configButtonSpaceMaker)
  355.   writeAt(buttonX, buttonY, configButtonText, colors.white, colors.gray)
  356.  
  357.   writeAt(30, 21, "  INPUT:  ", sectionTitleColour)
  358.   writeAt(66, 21, "  OUTPUT:  ", sectionTitleColour)
  359. end
  360.  
  361. local function drawInputGraph()
  362.   table.insert(inputHistory, lastInput); removeOverflow(inputHistory, 34)
  363.  
  364.   local inGraph = newWindow(m, 29, 23, 33, 13, chartBGColour)
  365.   local ox, oy = inGraph.getSize()
  366.   local _, rf_max = getRange(inputHistory)
  367.  
  368.   for i = 0, #inputHistory do
  369.     local value = inputHistory[#inputHistory-i]; if not value then break end
  370.     local denom = (rf_max == 0 and 1 or rf_max)
  371.     local result = math.floor(math.min(math.max((value * (13 / denom)), 0), 13) + 0.5)
  372.     if result ~= result then result = 0 end
  373.     draw(ox-i, 1, oy-result+1, result, inputChartColour, inGraph)
  374.   end
  375.  
  376.   local maxRf = conversion(rf_max, true, true) .. "RF/t"
  377.   local _, _, bgtop = inGraph.getLine(1)
  378.   for i = 0, #maxRf do
  379.     local char = maxRf:sub(1+i, 1+i)
  380.     local b = fromBlit(bgtop:sub(1+i, 1+i)) or chartBGColour
  381.     writeAt(1+i, 1, char, baseTextColour, b, inGraph)
  382.   end
  383.  
  384.   local maxPercent = tostring(round((rf_max/(maxTransfer==0 and 1 or maxTransfer))*100) .. "%")
  385.   for i = 0, #maxPercent do
  386.     local c = ox-#maxPercent+i+1
  387.     local char = maxPercent:sub(1+i, 1+i)
  388.     local b = fromBlit(bgtop:sub(c, c)) or chartBGColour
  389.     writeAt(c, 1, char, baseTextColour, b, inGraph)
  390.   end
  391.  
  392.   local minRf = "0RF/t"
  393.   local _, _, bglow = inGraph.getLine(oy)
  394.   for i = 0, #minRf do
  395.     local char = minRf:sub(1+i, 1+i)
  396.     local b = fromBlit(bglow:sub(1+i, 1+i)) or chartBGColour
  397.     writeAt(1+i, oy, char, baseTextColour, b, inGraph)
  398.   end
  399.  
  400.   local minPercent = "0%"
  401.   for i = 0, #minPercent do
  402.     local c = ox-#minPercent+i+1
  403.     local char = minPercent:sub(1+i, 1+i)
  404.     local b = fromBlit(bglow:sub(c, c)) or chartBGColour
  405.     writeAt(c, oy, char, baseTextColour, b, inGraph)
  406.   end
  407.  
  408.   draw(39, 22, 21, 1, borderColour)
  409.   local rf_tick = conversion(lastInput, true, true) .. "RF/t "
  410.   writeAt(39, 21, rf_tick, (lastInput > 0 and inputChartColour or idleColour))
  411.   writeAt(39+#rf_tick, 21, "(" .. tostring(round((lastInput/(maxTransfer==0 and 1 or maxTransfer))*100) .. "%)  "))
  412.  
  413.   if lastInput == maxTransfer and maxTransfer > 0 then
  414.     local maxStrings = {"MAX INPUT!","Add / Upgrade","Providers."}
  415.     drawBar(46-(math.max(#maxStrings[1], #maxStrings[2], #maxStrings[3])/2)-1, #maxStrings[2]+2, 27, #maxStrings+2, 1)
  416.     writeAt(46-(#maxStrings[1]/2), 28, maxStrings[1], outputChartColour, 1)
  417.     writeAt(46-(#maxStrings[2]/2), 29, maxStrings[2], outputChartColour, 1)
  418.     writeAt(46-(#maxStrings[3]/2), 30, maxStrings[3], outputChartColour, 1)
  419.   end
  420. end
  421.  
  422. local function drawOutputGraph()
  423.   table.insert(outputHistory, lastOutput); removeOverflow(outputHistory, 34)
  424.  
  425.   local outGraph = newWindow(m, 65, 23, 33, 13, chartBGColour)
  426.   local ox, oy = outGraph.getSize()
  427.   local _, rf_max = getRange(outputHistory)
  428.  
  429.   for i = 0, #outputHistory do
  430.     local value = outputHistory[#outputHistory-i]; if not value then break end
  431.     local denom = (rf_max == 0 and 1 or rf_max)
  432.     local result = math.floor(math.min(math.max((value * (13 / denom)), 0), 13) + 0.5)
  433.     if result ~= result then result = 0 end
  434.     draw(ox-i, 1, oy-result+1, result, outputChartColour, outGraph)
  435.   end
  436.  
  437.   local maxRf = conversion(rf_max*-1, true, true) .. "RF/t"
  438.   local _, _, bgtop = outGraph.getLine(1)
  439.   for i = 0, #maxRf do
  440.     local char = maxRf:sub(1+i, 1+i)
  441.     local b = fromBlit(bgtop:sub(1+i, 1+i)) or chartBGColour
  442.     writeAt(1+i, 1, char, baseTextColour, b, outGraph)
  443.   end
  444.  
  445.   local maxPercent = tostring(round((rf_max/(maxTransfer==0 and 1 or maxTransfer))*100) .. "%")
  446.   for i = 0, #maxPercent do
  447.     local c = ox-#maxPercent+i+1
  448.     local char = maxPercent:sub(1+i, 1+i)
  449.     local b = fromBlit(bgtop:sub(c, c)) or chartBGColour
  450.     writeAt(c, 1, char, baseTextColour, b, outGraph)
  451.   end
  452.  
  453.   local minRf = "0RF/t"
  454.   local _, _, bglow = outGraph.getLine(oy)
  455.   for i = 0, #minRf do
  456.     local char = minRf:sub(1+i, 1+i)
  457.     local b = fromBlit(bglow:sub(1+i, 1+i)) or chartBGColour
  458.     writeAt(1+i, oy, char, baseTextColour, b, outGraph)
  459.   end
  460.  
  461.   local minPercent = "0%"
  462.   for i = 0, #minPercent do
  463.     local c = ox-#minPercent+i+1
  464.     local char = minPercent:sub(1+i, 1+i)
  465.     local b = fromBlit(bglow:sub(c, c)) or chartBGColour
  466.     writeAt(c, oy, char, baseTextColour, b, outGraph)
  467.   end
  468.  
  469.   draw(76, 22, 21, 1, borderColour)
  470.   local rf_tick = conversion(lastOutput*-1, true) .. "RF/t "
  471.   writeAt(76, 21, rf_tick, (lastOutput > 0 and outputChartColour or idleColour))
  472.   writeAt(76+#rf_tick, 21, "(" .. tostring(round((lastOutput/(maxTransfer==0 and 1 or maxTransfer))*100) .. "%)  "))
  473.  
  474.   if lastOutput == maxTransfer and maxTransfer > 0 then
  475.     local maxStrings = {"MAX OUTPUT!","Add / Upgrade","Providers."}
  476.     drawBar(82-(math.max(#maxStrings[1], #maxStrings[2], #maxStrings[3])/2)-1, #maxStrings[2]+2, 27, #maxStrings+2, 1)
  477.     writeAt(82-(#maxStrings[1]/2), 28, maxStrings[1], outputChartColour, 1)
  478.     writeAt(82-(#maxStrings[2]/2), 29, maxStrings[2], outputChartColour, 1)
  479.     writeAt(82-(#maxStrings[3]/2), 30, maxStrings[3], outputChartColour, 1)
  480.   end
  481. end
  482.  
  483. local function drawFlowGraph()
  484.   table.insert(flowHistory, lastInput-lastOutput); removeOverflow(flowHistory, 70)
  485.  
  486.   local flowGraph = newWindow(m, 29, 4, 69, 16, chartBGColour)
  487.   local fx, fy = flowGraph.getSize()
  488.   local rf_min, rf_max = getRange(flowHistory)
  489.   local scale = math.max(math.abs(rf_min), rf_max); if scale == 0 then scale = 1 end
  490.  
  491.   for i = 0, #flowHistory do
  492.     local value = flowHistory[#flowHistory-i]; if not value then break end
  493.     value = math.abs(value)
  494.     local result = math.floor(math.min(math.max((value * (8 / scale)), 0), 8) + 0.5)
  495.     if result ~= result then result = 0 end
  496.  
  497.     if result == 0 then
  498.       writeAt(fx-i, 8, "_", 32768, chartBGColour, flowGraph)
  499.     elseif flowHistory[#flowHistory-i] < 0 then
  500.       draw(fx-i, 1, 9, result, outputChartColour, flowGraph)
  501.     else
  502.       draw(fx-i, 1, 9-result, result, inputChartColour, flowGraph)
  503.     end
  504.   end
  505.  
  506.   local lastFlow = flowHistory[#flowHistory]
  507.   draw(45, 15, 2, 1, borderColour)
  508.   writeAt(45, 2, conversion(lastFlow, true, true) .. "RF/t  ", (lastFlow == 0 and idleColour or (lastFlow > 0 and inputChartColour or outputChartColour)))
  509.  
  510.   local positiveRf = conversion(scale, true, true) .. "RF/t"
  511.   local _, _, bgtop = flowGraph.getLine(1)
  512.   for i = 0, #positiveRf do
  513.     local char = positiveRf:sub(1+i, 1+i)
  514.     local b = fromBlit(bgtop:sub(1+i, 1+i)) or chartBGColour
  515.     writeAt(1+i, 1, char, baseTextColour, b, flowGraph)
  516.   end
  517.  
  518.   local noRF = "0 RF/t"
  519.   local _, _, bgn = flowGraph.getLine(8)
  520.   for i = 0, #noRF do
  521.     local char = noRF:sub(1+i, 1+i)
  522.     local b = fromBlit(bgn:sub(1+i, 1+i)) or chartBGColour
  523.     writeAt(1+i, 8, char, baseTextColour, b, flowGraph)
  524.   end
  525.  
  526.   local negativeRf = conversion(scale*-1, true, true) .. "RF/t"
  527.   local _, _, bgbot = flowGraph.getLine(16)
  528.   for i = 0, #negativeRf do
  529.     local char = negativeRf:sub(1+i, 1+i)
  530.     local b = fromBlit(bgbot:sub(1+i, 1+i)) or chartBGColour
  531.     writeAt(1+i, 16, char, baseTextColour, b, flowGraph)
  532.   end
  533. end
  534.  
  535. local function drawBattery()
  536.   drawBar(4, 22, 4, 23, chartBGColour)
  537.   local chargeHeight = round(filledPercentage*23)
  538.   drawBar(4, 22, 27-chargeHeight, chargeHeight, batteryChargeColour)
  539.  
  540.   local percent = tostring(round((energy/maxEnergy)*100, 2)) .. "%"
  541.   local percentPos = (22/2) - (string.len(percent)/2) + 4
  542.   writeAt(percentPos, 15, percent, baseTextColour, chartBGColour)
  543.  
  544.   local stored = "STORED: " .. conversion(energy, true, false, 0.01) .. "RF"
  545.   local storedPos = (22/2) - (string.len(stored)/2) + 4
  546.   writeAt(storedPos, 5, stored, baseTextColour, chartBGColour)
  547.  
  548.   -- Use regression slope (dE/dt in RF/s) for steady ETA
  549.   local chargeStatus, timeStatus = "Idle", ""
  550.   local timeStr = "Inf."
  551.   if dEdt_sec < -FLOW_EPS then
  552.     chargeStatus = "Depleting"
  553.     timeStatus   = "Empty In:"
  554.     timeStr = adjustTime(energy / (-dEdt_sec))
  555.   elseif dEdt_sec > FLOW_EPS then
  556.     chargeStatus = "Charging"
  557.     timeStatus   = "Full In:"
  558.     timeStr = adjustTime((maxEnergy - energy) / dEdt_sec)
  559.   end
  560.  
  561.   local timeString = (timeStatus ~= "" and (timeStatus .. " " .. timeStr) or timeStr)
  562.   local timePos = (22/2) - (string.len(timeString)/2) + 4
  563.   writeAt((22/2) - (string.len(chargeStatus)/2) + 4, 24, chargeStatus, baseTextColour, chartBGColour)
  564.   writeAt(timePos, 25, timeString, baseTextColour, chartBGColour)
  565. end
  566.  
  567. local function drawStatistics()
  568.   local row = 30
  569.   if imWidth and imHeight and imLength then
  570.     writeAt(4, row, "Size: " .. imWidth .. " x " .. imHeight .. " x " .. imLength, baseTextColour); row = row + 1
  571.   end
  572.   if installedCells     ~= nil then writeAt(4, row, "Cells: "      .. installedCells,     baseTextColour); row = row + 1 end
  573.   if installedProviders ~= nil then writeAt(4, row, "Providers: "  .. installedProviders, baseTextColour); row = row + 1 end
  574.   if imWidth and imHeight and imLength and installedCells and installedProviders then
  575.     local empty = ((imWidth - 2) * (imLength - 2) * (imHeight - 2)) - installedCells - installedProviders
  576.     writeAt(4, row, "Empty Slots: " .. tostring(empty), baseTextColour); row = row + 1
  577.   end
  578.   writeAt(4, row, "MaxTransfer: " .. conversion(maxTransfer, true) .. "/t", baseTextColour); row = row + 1
  579.   writeAt(4, row, "MaxCapacity: " .. conversion(maxEnergy,  true), baseTextColour)
  580. end
  581.  
  582. -- === Read static capabilities (with legacy tolerance) ===
  583. installedCells     = hasMethod(im, "getInstalledCells")     and protCall(im.getInstalledCells, 1)     or nil
  584. installedProviders = hasMethod(im, "getInstalledProviders") and protCall(im.getInstalledProviders, 1) or nil
  585. maxEnergy          = (protCall(im.getMaxEnergy, 1) or 0) / dataCorrection
  586. maxTransfer        = (protCall(im.getTransferCap, 1) or 0) / dataCorrection
  587. imWidth            = hasMethod(im, "getWidth")  and protCall(im.getWidth, 1)  or nil
  588. imLength           = hasMethod(im, "getLength") and protCall(im.getLength, 1) or nil
  589. imHeight           = hasMethod(im, "getHeight") and protCall(im.getHeight, 1) or nil
  590.  
  591. drawStaticElements()
  592. drawStatistics()
  593.  
  594. -- === Input handling ===
  595. local monitor_touched, x_touch, y_touch
  596. local function touch()
  597.   while true do
  598.     local event_data = table.pack(os.pullEvent())
  599.     if event_data[1] == "monitor_touch" then
  600.       monitor_touched, x_touch, y_touch = table.unpack(event_data, 2, event_data.n)
  601.       break
  602.     end
  603.   end
  604. end
  605.  
  606. -- === Main display loop ===
  607. local function display()
  608.   while true do
  609.     energy          = protCall(im.getEnergy, 1) / dataCorrection
  610.     lastInput       = (getLastInput()  or 0) / dataCorrection
  611.     lastOutput      = (getLastOutput() or 0) / dataCorrection
  612.     filledPercentage = getFilledPct()
  613.  
  614.     -- feed predictor with energy vs time (seconds)
  615.     t_elapsed = t_elapsed + screenRefreshRate
  616.     pushEnergySample(t_elapsed, energy)
  617.     dEdt_sec = stableSlope()  -- RF / second (smoothed)
  618.  
  619.     -- draw
  620.     drawInputGraph()
  621.     drawOutputGraph()
  622.     drawFlowGraph()
  623.     drawBattery()
  624.  
  625.     os.sleep(screenRefreshRate)
  626.   end
  627. end
  628.  
  629. -- === Settings persistence ===
  630. function saveConfig(name, value)
  631.   local filename = shell.getRunningProgram()
  632.   local lines = {}
  633.   for line in io.lines(filename) do table.insert(lines, line) end
  634.   local settingsMap = {
  635.     borderColour       = { var = "borderColour",       line = 2 },
  636.     chartBGColour      = { var = "chartBGColour",      line = 3 },
  637.     inputChartColour   = { var = "inputChartColour",   line = 4 },
  638.     outputChartColour  = { var = "outputChartColour",  line = 5 },
  639.     batteryChargeColour= { var = "batteryChargeColour",line = 6 },
  640.     idleColour         = { var = "idleColour",         line = 7 },
  641.     sectionTitleColour = { var = "sectionTitleColour", line = 8 },
  642.     baseTextColour     = { var = "baseTextColour",     line = 9 },
  643.     screenRefreshRate  = { var = "screenRefreshRate",  line = 11 },
  644.     unitFormatCaps     = { var = "unitFormatCaps",     line = 12 },
  645.   }
  646.   if settingsMap[name] then
  647.     if name == "borderColour" then borderColour = value
  648.     elseif name == "chartBGColour" then chartBGColour = value
  649.     elseif name == "inputChartColour" then inputChartColour = value
  650.     elseif name == "outputChartColour" then outputChartColour = value
  651.     elseif name == "batteryChargeColour" then batteryChargeColour = value
  652.     elseif name == "idleColour" then idleColour = value
  653.     elseif name == "sectionTitleColour" then sectionTitleColour = value
  654.     elseif name == "baseTextColour" then baseTextColour = value
  655.     elseif name == "screenRefreshRate" then screenRefreshRate = value
  656.     elseif name == "unitFormatCaps" then unitFormatCaps = value
  657.     end
  658.     lines[settingsMap[name].line] = "local " .. settingsMap[name].var .. " = " .. tostring(value)
  659.   end
  660.   local h_ = io.open(filename, 'w'); for _, line in ipairs(lines) do h_:write(line .. "\n") end; h_:close()
  661. end
  662.  
  663. local function dropdownMenu(x, y, options)
  664.   local width, optionText = 0, ""
  665.   for i = 1, #options do options[i] = tostring(options[i]); if #options[i] > width then width = #options[i] end end
  666.   for i = 1, #options do
  667.     optionText = " " .. options[i] .. "  "
  668.     for j = 1, width - #options[i] do optionText = optionText .. " " end
  669.     writeAt(x - 2 - width, y + i, optionText, 1, 256)
  670.   end
  671.   while true do
  672.     local event, side, ox, oy = os.pullEvent("monitor_touch")
  673.     if (ox >= x - 2 - width and ox <= x and oy >= y + 1 and oy <= y + #options) then
  674.       return oy-y
  675.     else
  676.       return nil
  677.     end
  678.   end
  679. end
  680.  
  681. local function drawSettings(settingsX, settingsY, sWidth, sHeight)
  682.   local sTextColour, sBGColour = 1, 128
  683.   drawBar(settingsX - 2, sWidth, settingsY - 2, 1, sBGColour)
  684.   drawBar(settingsX - 2, sWidth, settingsY + sHeight - 3, 1, sBGColour)
  685.   drawBar(settingsX - 2, 1, settingsY - 2, sHeight, sBGColour)
  686.   drawBar(settingsX - 2 + sWidth, 1, settingsY - 2, sHeight, sBGColour)
  687.  
  688.   local labels = {"Borders: ","Chart Background: ","Input Chart: ","Output Chart: ","Battery: ","Idle: ","Section Titles: ","Base Text: "}
  689.   for i, label in ipairs(labels) do writeAt(settingsX, i + settingsY - 1, label) end
  690.  
  691.   writeAt(settingsX, settingsY + 9,  "Refresh Rate: ")
  692.   writeAt(settingsX, settingsY + 10, "Unit Style: ")
  693.  
  694.   local configs = {
  695.     {row = 0,  config = borderColour},
  696.     {row = 1,  config = chartBGColour},
  697.     {row = 2,  config = inputChartColour},
  698.     {row = 3,  config = outputChartColour},
  699.     {row = 4,  config = batteryChargeColour},
  700.     {row = 5,  config = idleColour},
  701.     {row = 6,  config = sectionTitleColour},
  702.     {row = 7,  config = baseTextColour},
  703.     {row = 9,  config = screenRefreshRate},
  704.     {row = 10, config = unitFormatCaps},
  705.   }
  706.  
  707.   for i, data in ipairs(configs) do
  708.     local row, config, configText = data.row, data.config
  709.     if row <= 7 then
  710.       configText = tostring(colorText[indexOf(colorDec, config)]) .. " "
  711.       writeAt(settingsX + 18, settingsY + row, "  ", 1, config)
  712.       writeAt(settingsX + 20, settingsY + row, "            ", 1, sBGColour)
  713.     elseif row == 9 then
  714.       configText = tostring(refreshRates.display[indexOf(refreshRates.values, config)]) .. " "
  715.       writeAt(settingsX + 18, settingsY + row, "              ", 1, sBGColour)
  716.     elseif row == 10 then
  717.       configText = tostring(unitStyle.display[indexOf(unitStyle.values, config)]) .. " "
  718.       writeAt(settingsX + 18, settingsY + row, "              ", 1, sBGColour)
  719.     end
  720.     writeAt(settingsX + 21, settingsY + row, configText, sTextColour, sBGColour)
  721.     writeAt(settingsX + 32, settingsY + row, string.char(31), sTextColour, sBGColour)
  722.   end
  723.  
  724.   writeAt(settingsX, settingsY - 2, "  SETTINGS  ", sTextColour, 32768)
  725.   writeAt(settingsX, settingsY + sHeight - 5, " " .. string.char(27) .. " BACK ", sTextColour, 16384)
  726.   writeAt(settingsX + 10, settingsY + sHeight - 5, " RESET ", sTextColour, 512)
  727. end
  728.  
  729. local function settings()
  730.   local sWidth, sHeight = 37, 17
  731.   local settingsX = (w / 2) - math.floor(sWidth / 2) + 2
  732.   local settingsY = (h / 2) - math.floor(sHeight / 2) + 2
  733.  
  734.   local colourConfigs = {
  735.     [settingsY + 0] = "borderColour",
  736.     [settingsY + 1] = "chartBGColour",
  737.     [settingsY + 2] = "inputChartColour",
  738.     [settingsY + 3] = "outputChartColour",
  739.     [settingsY + 4] = "batteryChargeColour",
  740.     [settingsY + 5] = "idleColour",
  741.     [settingsY + 6] = "sectionTitleColour",
  742.     [settingsY + 7] = "baseTextColour",
  743.   }
  744.   local numberConfigs = {
  745.     [settingsY + 9]  = "screenRefreshRate",
  746.     [settingsY + 10] = "unitFormatCaps",
  747.   }
  748.  
  749.   while true do
  750.     m.clear()
  751.     drawSettings(settingsX, settingsY, sWidth, sHeight)
  752.     local event, side, x_, y_ = os.pullEvent("monitor_touch")
  753.  
  754.     if x_ >= settingsX + 18 and x_ <= settingsX + 32 then
  755.       if colourConfigs[y_] then
  756.         local optionIndex = dropdownMenu(settingsX + 32, y_, colorText)
  757.         if optionIndex ~= nil then saveConfig(colourConfigs[y_], colorDec[optionIndex]) end
  758.       elseif y_ == settingsY + 9 then
  759.         local optionIndex = dropdownMenu(settingsX + 32, y_, refreshRates.display)
  760.         if optionIndex ~= nil then saveConfig("screenRefreshRate", refreshRates.values[optionIndex]) end
  761.       elseif y_ == settingsY + 10 then
  762.         local optionIndex = dropdownMenu(settingsX + 32, y_, unitStyle.display)
  763.         if optionIndex ~= nil then saveConfig("unitFormatCaps", unitStyle.values[optionIndex]) end
  764.       end
  765.     elseif x_ >= settingsX and x_ <= settingsX + 7 and y_ == settingsY + sHeight - 5 then
  766.       return
  767.     elseif x_ >= settingsX + 10 and x_ <= settingsX + 16 and y_ == settingsY + sHeight - 5 then
  768.       local defaults = {
  769.         borderColour = 128, chartBGColour = 128, inputChartColour = 32,
  770.         outputChartColour = 16384, batteryChargeColour = 8, idleColour = 16,
  771.         sectionTitleColour = 1, baseTextColour = 1, screenRefreshRate = 0.1,
  772.         unitFormatCaps = true
  773.       }
  774.       for configName, value in pairs(defaults) do saveConfig(tostring(configName), value) end
  775.     end
  776.   end
  777. end
  778.  
  779. -- === Main loop ===
  780. local redrawRequired = false
  781. while true do
  782.   if redrawRequired then
  783.     m.clear(); drawStaticElements(); drawStatistics(); redrawRequired = false
  784.   end
  785.  
  786.   parallel.waitForAny(touch, display)
  787.  
  788.   if y_touch == 2 and x_touch >= 87 and x_touch <= 96 then
  789.     redrawRequired = true; m.clear(); settings()
  790.   end
  791. end
  792.  
Add Comment
Please, Sign In to add comment