split into library

This commit is contained in:
Baipyrus 2023-10-29 13:37:30 +01:00
parent 5128965d09
commit 5c7076199b
2 changed files with 221 additions and 218 deletions

View File

@ -13,237 +13,45 @@ math.randomseed(os.time())
-- system options/components
local system = {}
-- mekanismEnergyHelper conversion function
-- this gets a pre-made function to convert joules (input values) to provided options.unit
local convert_joules = mekanismEnergyHelper[
string.format('joulesTo%s', options.unit)
]
local inputLib = dofile('inputClient.lua')
-- initialize components
wait_for_components(system)
-- convert number to compact form (1000 => 1k)
function compact_number(number)
local units = {'K', 'M', 'G', 'T'}
local index = 0
-- scale number, increment unit index
while number >= 1000 do
number = number / 1000
index = index + 1
end
-- keep 2 decimals, add units
return string.format('%.2f %s', number, units[index] or '')
end
-- format number with energy (/transfer) units
function format_energy(number, transfer)
local energy = tostring(number)
-- compact number
if options.compact then
energy = compact_number(number)
end
-- append transfer unit
local t_unit = ' '
if transfer or false then
t_unit = '/t'
end
-- build string
return energy .. options.unit .. t_unit
end
-- format percentages as number with two decimals and padded unit
function format_percent(number)
return string.format('%.2f', number * 100) .. ' % ' .. string.rep(' ', #options.unit)
end
-- scan for system components
function scan_components()
-- try finding with peripherals
local matrix = peripheral.find('inductionPort')
local modem = peripheral.find('modem')
-- check if components were found
local found_matrix = not matrix
local found_modem = not modem
-- output corresponding error messages
if found_matrix or found_modem then
print('Invalid configuration detected!')
if found_matrix then print('Induction Matrix not found!') end
if found_modem then print('Modem not found!') end
end
-- return component data
local success = not (found_matrix or found_modem)
return {
success = success,
matrix = matrix,
modem = modem,
}
end
-- split string by delimiter
function split_string(text, delimiter)
local result = {}
for match in (text .. delimiter):gmatch('(.-)' .. delimiter) do
table.insert(result, match)
end
return result
end
-- initialize ender modem
function init_modem()
system.channel = nil
-- open initializer port
system.modem.open(1)
-- try initializing communication
local count = 1
while true do
local channel = math.random(2, 1 + options.channels)
-- open reply channel
system.modem.open(channel)
system.modem.transmit(1, channel, 'matrix')
term.setCursorPos(1, 6)
print('\nTry #' .. count)
print('Trying channel ' .. channel .. string.rep(' ', #tostring(1+options.channels)))
-- increment try-counter
count = count + 1
-- wait for response
local timer_id = os.startTimer(options.timeout)
while true do
local event, _, senderChannel, _, message, _ = os.pullEvent()
if event == 'modem_message' and senderChannel == channel then
local result = split_string(message, ' ')
-- save channel for communication
if result[1] == 'ready' then
system.width = tonumber(result[2])
system.channel = channel
-- cancel timer on success
os.cancelTimer(timer_id)
-- already in use; reset channel
elseif message == 'used' then
system.modem.close(channel)
end
break
-- retry on timeout
elseif event == 'timer' then break end
end
-- success condition
if system.channel then break end
end
-- close initializer port
system.modem.close(1)
end
-- scan for components and retry on fail
function wait_for_components()
system.timeout = false
local count = 1
-- fixed print out
term.clear()
term.setCursorPos(1, 1)
print('Scanning for valid configuration:')
while true do
-- reset terminal
term.setCursorPos(1, 2)
-- output retry count
print('Try #' .. count .. '\n')
count = count + 1
-- scan for components
local components = scan_components()
if components.success then
-- output success message
print('Success!')
print('Trying to connect to receiver . . .')
-- set system components
system.matrix = components.matrix
system.modem = components.modem
init_modem()
print('\nSuccess!')
return
end
-- components not found, wait to retry
print('Failed!')
end
end
wait_for_components()
-- queue message for transfer
function message(buffer, text)
table.insert(buffer, text)
end
-- output aligned string by padding whitespaces in the middle of it to reach width
function message_aligned(buffer, text, value, width)
local str = tostring(value)
local length = width - #str
message(buffer, string.format("%-" .. length .. "s%s", text, value))
end
-- generate induction matrix values
function generate_message(buffer)
-- read induction matrix values
local p_raw = system.matrix.getEnergyFilledPercentage()
local c_raw = system.matrix.getEnergy()
local m_raw = system.matrix.getMaxEnergy()
local i_raw = system.matrix.getLastInput()
local o_raw = system.matrix.getLastOutput()
local t_raw = system.matrix.getTransferCap()
local p_raw = system.main.getEnergyFilledPercentage()
local c_raw = system.main.getEnergy()
local m_raw = system.main.getMaxEnergy()
local i_raw = system.main.getLastInput()
local o_raw = system.main.getLastOutput()
local t_raw = system.main.getTransferCap()
-- convert raw values from joules to specified options.unit
local c_conv = convert_joules(c_raw)
local m_conv = convert_joules(m_raw)
local i_conv = convert_joules(i_raw)
local o_conv = convert_joules(o_raw)
local t_conv = convert_joules(t_raw)
local c_conv = inputLib.convert_joules(c_raw)
local m_conv = inputLib.convert_joules(m_raw)
local i_conv = inputLib.convert_joules(i_raw)
local o_conv = inputLib.convert_joules(o_raw)
local t_conv = inputLib.convert_joules(t_raw)
-- format and align fill values
message_aligned(buffer, 'Fill....:', format_percent(p_raw), system.width)
message_aligned(buffer, 'Fill....:', format_energy(c_conv), system.width)
inputLib.message_aligned(buffer, 'Fill....:', inputLib.format_percent(p_raw), system.width)
inputLib.message_aligned(buffer, 'Fill....:', inputLib.format_energy(c_conv), system.width)
-- format and align capacity
message(buffer, '\n')
message_aligned(buffer, 'Capacity:', format_energy(m_conv), system.width)
inputLib.message(buffer, '\n')
inputLib.message_aligned(buffer, 'Capacity:', inputLib.format_energy(m_conv), system.width)
-- format and align i/o values
message(buffer, '\n') message(buffer, '\n')
message_aligned(buffer, 'Input...:', format_energy(i_conv, true), system.width)
message_aligned(buffer, 'Output..:', format_energy(o_conv, true), system.width)
inputLib.message(buffer, '\n') inputLib.message(buffer, '\n')
inputLib.message_aligned(buffer, 'Input...:', inputLib.format_energy(i_conv, true), system.width)
inputLib.message_aligned(buffer, 'Output..:', inputLib.format_energy(o_conv, true), system.width)
-- format and align transfer
message(buffer, '\n')
message_aligned(buffer, 'Transfer:', format_energy(t_conv, true), system.width)
end
-- transmit buffered messages over ender modem
function transmit_messages(buffer)
system.modem.transmit(system.channel, system.channel, table.concat(buffer, '\n'))
local timer_id = os.startTimer(options.timeout)
while true do
local event, _, senderChannel, _, message, _ = os.pullEvent()
-- respond to corresponding message only
if event == 'modem_message' and senderChannel == system.channel and message == 'ok' then
-- cancel timer on success
os.cancelTimer(timer_id)
return
-- cancel on timeout
elseif event == 'timer' then
system.timeout = true
return
end
end
inputLib.message(buffer, '\n')
inputLib.message_aligned(buffer, 'Transfer:', inputLib.format_energy(t_conv, true), system.width)
end
function send_info()
@ -252,7 +60,7 @@ function send_info()
-- generate messages in buffer
generate_message(buffer)
-- transmit messages in form of buffer
transmit_messages(buffer)
inputLib.transmit_messages(options, system, buffer)
end
function event_listener()
@ -274,11 +82,11 @@ function main()
-- reset terminal
term.clear()
-- run while all components are detected
while scan_components().success and (not system.timeout) do
while inputLib.scan_components('inductionPort').success and (not system.timeout) do
event_listener()
end
-- rescan components
wait_for_components()
wait_for_components(system)
end
end
main()

195
inputClient.lua Normal file
View File

@ -0,0 +1,195 @@
-- mekanismEnergyHelper conversion function
-- this gets a pre-made function to convert joules (input values) to provided options.unit
local convert_joules = mekanismEnergyHelper[
string.format('joulesTo%s', options.unit)
]
-- convert number to compact form (1000 => 1k)
function compact_number(number)
local units = {'K', 'M', 'G', 'T'}
local index = 0
-- scale number, increment unit index
while number >= 1000 do
number = number / 1000
index = index + 1
end
-- keep 2 decimals, add units
return string.format('%.2f %s', number, units[index] or '')
end
-- format number with energy (/transfer) units
function format_energy(number, transfer)
local energy = tostring(number)
-- compact number
if options.compact then
energy = compact_number(number)
end
-- append transfer unit
local t_unit = ' '
if transfer or false then
t_unit = '/t'
end
-- build string
return energy .. options.unit .. t_unit
end
-- format percentages as number with two decimals and padded unit
function format_percent(number)
return string.format('%.2f', number * 100) .. ' % ' .. string.rep(' ', #options.unit)
end
-- scan for system components
function scan_components(name)
-- try finding with peripherals
local component = peripheral.find(name)
local modem = peripheral.find('modem')
-- check if components were found
local found_component = not matrix
local found_modem = not modem
-- output corresponding error messages
if found_component or found_modem then
print('Invalid configuration detected!')
if found_component then print('Main component not found!') end
if found_modem then print('Modem not found!') end
end
-- return component data
local success = not (found_component or found_modem)
return {
success = success,
main = component,
modem = modem,
}
end
-- split string by delimiter
function split_string(text, delimiter)
local result = {}
for match in (text .. delimiter):gmatch('(.-)' .. delimiter) do
table.insert(result, match)
end
return result
end
-- initialize ender modem
function init_modem(options, system)
system.channel = nil
-- open initializer port
system.modem.open(1)
-- try initializing communication
local count = 1
while true do
local channel = math.random(2, 1 + options.channels)
-- open reply channel
system.modem.open(channel)
system.modem.transmit(1, channel, 'matrix')
term.setCursorPos(1, 6)
print('\nTry #' .. count)
print('Trying channel ' .. channel .. string.rep(' ', #tostring(1+options.channels)))
-- increment try-counter
count = count + 1
-- wait for response
local timer_id = os.startTimer(options.timeout)
while true do
local event, _, senderChannel, _, message, _ = os.pullEvent()
if event == 'modem_message' and senderChannel == channel then
local result = split_string(message, ' ')
-- save channel for communication
if result[1] == 'ready' then
system.width = tonumber(result[2])
system.channel = channel
-- cancel timer on success
os.cancelTimer(timer_id)
-- already in use; reset channel
elseif message == 'used' then
system.modem.close(channel)
end
break
-- retry on timeout
elseif event == 'timer' then break end
end
-- success condition
if system.channel then break end
end
-- close initializer port
system.modem.close(1)
end
-- scan for components and retry on fail
function wait_for_components(system)
system.timeout = false
local count = 1
-- fixed print out
term.clear()
term.setCursorPos(1, 1)
print('Scanning for valid configuration:')
while true do
-- reset terminal
term.setCursorPos(1, 2)
-- output retry count
print('Try #' .. count .. '\n')
count = count + 1
-- scan for components
local components = scan_components('inductionPort')
if components.success then
-- output success message
print('Success!')
print('Trying to connect to receiver . . .')
-- set system components
system.main = components.main
system.modem = components.modem
init_modem()
print('\nSuccess!')
return
end
-- components not found, wait to retry
print('Failed!')
end
end
-- queue message for transfer
function message(buffer, text)
table.insert(buffer, text)
end
-- output aligned string by padding whitespaces in the middle of it to reach width
function message_aligned(buffer, text, value, width)
local str = tostring(value)
local length = width - #str
message(buffer, string.format("%-" .. length .. "s%s", text, value))
end
-- transmit buffered messages over ender modem
function transmit_messages(options, system, buffer)
system.modem.transmit(system.channel, system.channel, table.concat(buffer, '\n'))
local timer_id = os.startTimer(options.timeout)
while true do
local event, _, senderChannel, _, message, _ = os.pullEvent()
-- respond to corresponding message only
if event == 'modem_message' and senderChannel == system.channel and message == 'ok' then
-- cancel timer on success
os.cancelTimer(timer_id)
return
-- cancel on timeout
elseif event == 'timer' then
system.timeout = true
return
end
end
end