Advertisement
4epB9Ik

rControl.lua

May 12th, 2016
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 19.25 KB | None | 0 0
  1. --#Библиотеки
  2.  
  3. local fs = require("filesystem")
  4. local term = require("term")
  5. local serialization = require("serialization")
  6. local component = require("component")
  7. local event = require("event")
  8. local colors = require("colors")
  9.  
  10. --#глобальные перменные
  11. local gpu = component.gpu
  12. local config = {}
  13. local reactor = nil
  14. local running = true
  15. local screen = "main"
  16. local max_speed = "N.A"
  17. local reason = "неопознаная ошибка"
  18. local reactor_error = "Реактор не найден!"
  19.  
  20. --#переменне системы
  21. local version = "[1.2]"
  22.  
  23. --#Процедура установки
  24. function install()
  25.   screen = "install"
  26.   term.clear()
  27.   print("Вас привествует мастер установки rControl "..version)
  28.   print("")
  29.   print("Требывания:")
  30.   print("Дисплей - не менее 2уровня")
  31.   print("Видеокарта - не менее 2 уровня")
  32.   print("Ваш реактор должен быть подключен к компьютеру через специальный порт")
  33.   print("Клавиатура [Опционально]")
  34.   print("")
  35.   print("Начать установку rControl? [да - y, нет - n]")
  36.   --21,49
  37.   local result = false
  38.   while not result do
  39.     local name, adress, char, code, player = event.pull("key_down")
  40.     if code == 21 then
  41.       result = true
  42.     elseif code == 49 then
  43.       os.exit()
  44.     else
  45.       print("Некорректный ввод. Возможно включен CapsLock")
  46.     end
  47.   end
  48.  
  49.   --set resolution and continue
  50.   gpu.setResolution(80,25)
  51.   gpu.setForeground(0x000000)
  52.   term.clear()
  53.   gpu.setBackground(0xF8F8FF) -- белый слегка серый цвет фона (общий)
  54.   term.clear()
  55.   gpu.setBackground(0x808080) -- серый цвет
  56.   gpu.fill(20,9,40,6," ")
  57.   term.setCursor(25,9)
  58.   print("Спасибо что выбрали")
  59.   term.setCursor(25,10)
  60.   print("rControl")
  61.   term.setCursor(25,11)
  62.   print("Нажми ok чтоб продолжить")
  63.   term.setCursor(25,12)
  64.   print("Нажми отмена чтоб выйти")
  65.   gpu.setBackground(0x008000)
  66.   gpu.fill(20,14,20,1," ")
  67.   term.setCursor(29,14)
  68.   print("ok")
  69.   gpu.setBackground(0x800000)
  70.   gpu.fill(40,14,20,1," ")
  71.   term.setCursor(48,14)
  72.   print("отмена")
  73.   local event_running = true
  74.   while event_running do
  75.     local name, address, x, y, button, player = event.pull("touch")
  76.     if x >= 20 and x <= 39 and y == 14 then
  77.       print("ok")
  78.       event_running = false
  79.     elseif x>=40 and x <= 59 and y == 14 then
  80.       os.exit()
  81.     end
  82.   end
  83.   install_pick_reactor()
  84.   set_color_scheme()
  85.   save_config()
  86.   main()
  87. end
  88.  
  89. --#главная функция
  90. function main()
  91.   screen = "main"
  92.   running = true
  93.   gpu.setResolution(82,26)
  94.   read_config()
  95.   reactor_error = "Реактор ["..config.reactor.."] не найден!"
  96.   reactor = component.proxy(config.reactor)
  97.  
  98.   event.listen("touch",listen)
  99.   while running do
  100.     gpu.setBackground(0xB0C4DE) -- главная прорисовка фона (общего)
  101.     -- попытка прорисовать футер.. ловим ошибки
  102.     status_futter, err = pcall(draw_futter)
  103.     if not status_futter then
  104.     --draw_error(reactor_error)
  105.   running = false
  106.   reactor_search()
  107.   break    
  108. end
  109.     ---------------------------------------------
  110.     -- попытка нарисовать меню-бар.. ловим ошибки
  111.     status_menu_bar, err = pcall(draw_menubar)
  112.     if not status_menu_bar then
  113.     --draw_error(reactor_error)
  114.   running = false
  115.   reactor_search()
  116.   break
  117.     end
  118.    
  119.     if screen == "main" then
  120.       status_main, err = pcall(draw_main)
  121.       if not status_main then
  122.         draw_error(reactor_error)
  123.         running = false
  124.         reactor_search()
  125.         break
  126.       end
  127.     elseif screen == "config" then
  128.       draw_config()
  129.     elseif screen == "error" then
  130.       draw_error(reason)
  131.     end
  132.     os.sleep(.05)
  133.   end
  134.  
  135. end
  136. function reactor_search()
  137.   gpu.setBackground(0xB0C4DE)
  138.   term.clear()
  139.     search_timer = true
  140.   while search_timer do
  141.   reactor = component.proxy(config.reactor)
  142.   if reactor == nil then
  143.     draw_error(reactor_error)
  144. else
  145.     gpu.setBackground(0xB0C4DE)
  146.     term.clear()
  147.     screen = "main"  
  148.     main()
  149.     search_timer = false
  150.   end
  151.   end
  152. end
  153. function draw_error(str)
  154.   head = 0x8A0808 -- темно красный (шапка)
  155.   body = 0xF6CECE -- светло красный (тело)
  156.   head_text = 0xFFFFFF -- белый (цвет текста)
  157.   body_text = 0x000000 -- черный (цвет причины)
  158.   gpu.setBackground(head)
  159.   gpu.fill(12,8,60,3," ")
  160.   gpu.setForeground(head_text)
  161.   term.setCursor(36,9)
  162.   term.write("Внимание!")
  163.   gpu.setBackground(body)
  164.   gpu.fill(12,11,60,6," ")
  165.   gpu.setForeground(body_text)
  166.   term.setCursor(13,14)
  167.   term.write(str)
  168.   os.sleep(0,2)
  169.  
  170. end
  171.  
  172. --#прорисовка верхнего меню
  173. function draw_menubar()
  174.   gpu.setResolution(82,26)
  175.   term.setCursor(1,1)
  176.   gpu.setBackground(config.color_scheme.menubar.background)
  177.   gpu.setForeground(config.color_scheme.menubar.foreground)
  178.   term.clearLine()
  179.   term.setCursor(1,1)
  180.   term.write("Напряжение: ")
  181.   gpu.setForeground(config.color_scheme.info)
  182.   if config.max_speed == nil then
  183.     config.max_speed = 0
  184.     max_speed = 0
  185.     save_config()
  186.   end
  187.   if round(reactor.getEnergyProducedLastTick()) > config.max_speed then
  188.     config.max_speed = round(reactor.getEnergyProducedLastTick())
  189.     save_config()
  190.   end
  191.   max_speed = config.max_speed
  192.   term.write(round(reactor.getEnergyProducedLastTick()) .. "/" .. max_speed .. "RF/t")
  193.   gpu.setForeground(config.color_scheme.menubar.foreground)
  194.   term.write(" Темп. стержней: ")
  195.   gpu.setForeground(config.color_scheme.info)
  196.   term.write(round(reactor.getFuelTemperature()).."C ")
  197.   gpu.setForeground(config.color_scheme.menubar.foreground)
  198.   term.write(" Темп. корпуса: ")
  199.   gpu.setForeground(config.color_scheme.info)
  200.   term.write(round(reactor.getCasingTemperature()).."C ")
  201.   term.setCursor(76,1)
  202.   gpu.setForeground(config.color_scheme.menubar.foreground)
  203.   term.write("[")
  204.   gpu.setForeground(config.color_scheme.error)
  205.   term.write("Выход")
  206.   gpu.setForeground(config.color_scheme.menubar.foreground)
  207.   term.write("]")
  208. end
  209.  
  210. --#прорисовка футера
  211. function draw_futter()
  212.   gpu.setBackground(config.color_scheme.menubar.background)
  213.   gpu.setForeground(config.color_scheme.menubar.foreground)
  214.   term.setCursor(1,26)
  215.   term.clearLine()
  216.   term.write("Статус: ")
  217.   if reactor.getActive() then
  218.     gpu.setForeground(config.color_scheme.success)
  219.     term.write("В работе ")
  220.   else
  221.     gpu.setForeground(config.color_scheme.error)
  222.     term.write("Отключен ")
  223.   end
  224.   if config.auto_power.enabled then
  225.     gpu.setForeground(config.color_scheme.menubar.foreground)
  226.     term.write("(")
  227.     gpu.setForeground(config.color_scheme.info)
  228.     term.write("Автомат")
  229.     gpu.setForeground(config.color_scheme.menubar.foreground)
  230.     term.write(") ")
  231.   end
  232.   term.setCursor(58,26)
  233.   gpu.setForeground(config.color_scheme.info)
  234.   term.write("rControl" .. version)
  235.   gpu.setForeground(config.color_scheme.error)
  236.   term.write(" (с)4epB9Ik")
  237. end
  238.  
  239. --#сохранение конфига
  240. function save_config()
  241.   local file = io.open("/home/rControl.cfg","w")
  242.   file:write(serialization.serialize(config,false))
  243.   file:close()
  244. end
  245.  
  246. --#считывание конфига
  247. function read_config()
  248.   local file = io.open("/home/rControl.cfg","r")
  249.   local c = serialization.unserialize(file:read(fs.size("/home/rControl.cfg")))
  250.   file:close()
  251.   for k,v in pairs(c) do
  252.     config[k] = v
  253.   end
  254. end
  255.  
  256. --#установка цветовой схемы
  257.  function set_color_scheme()
  258.   config.color_scheme = {}
  259.   config.color_scheme.background = 0xF8F8FF
  260.   config.color_scheme.button = 0x606060
  261.   config.color_scheme.button_disabled = 0xC0C0C0
  262.   config.color_scheme.foreground = 0x000000
  263.   config.color_scheme.progressBar = {}
  264.   config.color_scheme.progressBar.background = 0x008080
  265.   config.color_scheme.progressBar.foreground = 0xB22222
  266.   config.color_scheme.menubar={}
  267.   config.color_scheme.menubar.background = 0x000000
  268.   config.color_scheme.menubar.foreground = 0xFFFFFF
  269.   config.color_scheme.success = 0x008000
  270.   config.color_scheme.error = 0x800000
  271.   config.color_scheme.info = 0x808000
  272.   config.auto_power = {}
  273.   config.auto_power.enabled = false
  274.   config.auto_power.start_percent = 15
  275.   config.auto_power.stop_percent = 80
  276. end
  277.  
  278. --#выбор реактора при установке
  279. function install_pick_reactor()
  280.   gpu.setBackground(0xF8F8FF)-- общий фон
  281.   term.clear()
  282.   gpu.setBackground(0x808080)
  283.   local reactors = component.list("br_reactor")
  284.   local len = 3
  285.   for k,v in pairs(reactors) do
  286.     if len<#k then
  287.       len = #k
  288.     end
  289.   end
  290.   local s_x = 40-len/2
  291.   local s_y = 13-round(countTable(reactors)/2)
  292.   gpu.fill(s_x-1,s_y-2,len+2,countTable(reactors)+3," ")
  293.   term.setCursor(s_x+7,s_y-2)
  294.   print("Выбери нужный реактор")
  295.   local i = s_y
  296.   for k,v in pairs(reactors) do
  297.     term.setCursor(s_x,i)
  298.     print(k)
  299.     i=i+1
  300.   end
  301.   local event_running = true
  302.   while event_running do
  303.     local name, address, x, y, button, player = event.pull("touch")
  304.     print(y-s_y)
  305.     if x>=s_x and x <= s_x+len and y>=s_y and y<= s_y+countTable(reactors) then
  306.       event_running = false
  307.       local i = y-s_y
  308.       for k,v in pairs(reactors) do
  309.         if i == 0 then
  310.           config.reactor = k
  311.         end
  312.         i=i-1
  313.       end
  314.     end
  315.   end
  316. end
  317.  
  318. --#прорисовка главного экрана
  319. function draw_main()
  320.   if config.auto_power.enabled == true then
  321.       if reactor.getEnergyStored()/10^5<config.auto_power.start_percent then
  322.         reactor.setActive(true)
  323.       elseif reactor.getEnergyStored()/10^5>config.auto_power.stop_percent then
  324.         reactor.setActive(false)
  325.       end
  326.   end
  327.   if config.auto_power.enabled then
  328.     gpu.setBackground(config.color_scheme.button)
  329.     gpu.setForeground(0xFFFFFF)
  330.     gpu.fill(1,2,71,3," ")
  331.     term.setCursor(25,3)
  332.     term.write("Выкл. автоматический  режим")
  333.     gpu.setBackground(0x153F3F)
  334.     gpu.fill(72,2,11,3," ")
  335.     term.setCursor(73,3)
  336.     term.write("Настроить")
  337.   else
  338.     gpu.setBackground(config.color_scheme.button)
  339.     gpu.setForeground(0xFFFFFF)
  340.     gpu.fill(1,2,71,3," ")
  341.     term.setCursor(25,3)
  342.     term.write("Вкл. автоматический режим")
  343.     gpu.setBackground(0x153F3F)
  344.     gpu.fill(72,2,11,3," ")
  345.     term.setCursor(74,3)
  346.     term.write("Питание")
  347.   end
  348.   gpu.setForeground(0xFFFFFF)
  349.   gpu.setBackground(config.color_scheme.button)
  350.   gpu.fill(1,6,13,3," ")
  351.   gpu.fill(1,10,13,3," ")
  352.   gpu.fill(1,14,13,3," ")
  353.   gpu.fill(1,18,13,3," ")
  354.  
  355.   -- отрисовка пункта "энергоблок"
  356.   term.setCursor(2,6)
  357.   term.write("Энерго-блок")
  358.   term.setCursor(4,7)
  359.   term.write("[ mRF ]")
  360.   term.setCursor(2,8)
  361.   reactor_storage = calculate(reactor.getEnergyStored()/1000000,2)
  362.   rsalt_1, rsalt_2 = math.modf(reactor_storage)
  363.   if rsalt_2 == 0 then
  364.     term.write(reactor_storage ..",00/10,00")
  365.   else
  366.     term.write(calculate(reactor_storage,2) .. "/10,00")
  367.   end
  368.  
  369.   -- отрисовка пункта "топливо"
  370.   term.setCursor(2,10)
  371.   term.write("Топлив-блок")
  372.   term.setCursor(3,11)
  373.   term.write("[ buck ]")
  374.   reactor_fuel_max = reactor.getFuelAmountMax() / 1000
  375.   reactor_fuel_curent = calculate(reactor.getFuelAmount() / 1000, 2)
  376.   term.setCursor(2,12)
  377.   term.write(reactor_fuel_curent.."/"..reactor_fuel_max..".00")
  378.  
  379.   -- отрисовка пункта "радиоктивность топлива"
  380.   term.setCursor(2,15)
  381.   term.write("Рад.топлива")
  382.  
  383.   -- отрисовка пункта "мощность"
  384.   term.setCursor(3,19)
  385.   term.write("Мощность")
  386.   drawProgressBar(14,6,67,3,reactor.getEnergyStored()/10^7)
  387.   drawProgressBar(14,10,67,3,reactor.getFuelAmount()/reactor.getFuelAmountMax())
  388.   react = 50
  389.   if reactor.getFuelReactivity() > 100 then
  390.     react = 100
  391.   else
  392.     react = reactor.getFuelReactivity()
  393.   end
  394.   drawProgressBar(14,14,67,3,react/10^2)
  395.   if config.auto_power.enabled then
  396.     gpu.setBackground(config.color_scheme.success)
  397.     gpu.fill(14+67*config.auto_power.start_percent/10^2,6,1,3," ")
  398.     gpu.setBackground(config.color_scheme.error)
  399.     gpu.fill(14+67*config.auto_power.stop_percent/10^2,6,1,3," ")
  400.   end
  401.  -- power_percent = 100-reactor.getControlRodLevel()
  402.   power_percent = 0
  403.   for i = 0, reactor.getNumberOfControlRods()-1 do  
  404.       power_percent = power_percent+(100/reactor.getNumberOfControlRods()/100*(100-reactor.getControlRodLevel(i)))
  405.   end
  406.   drawProgressBar(14,18,67,3,power_percent/10^2)
  407.   draw_buttons()
  408. end
  409.  
  410. --#Функция округления чисел
  411. function calculate(num,rows)
  412.   local mul = math.pow(10,rows)
  413.   return (math.floor((num*mul)+0.5)/mul)
  414. end
  415.  
  416. --#Прорисовка кнопок с низу
  417. function draw_buttons()
  418.   gpu.setForeground(0xB22222)
  419.   gpu.setBackground(0xB0C4De)
  420.   term.setCursor(24,21)
  421.   term.write("(..функции в процессе разработки..)")
  422.   term.setCursor(4,23)
  423.   gpu.setForeground(0xFFFFFF)
  424.   gpu.setBackground(config.color_scheme.button)
  425.   term.write("[Регулировка мощности]")
  426.   term.setCursor(56,23)
  427.   term.write("[Прием/выгрузка топлива]")
  428. end
  429.  
  430. --#прорисовка экрана конфигурации
  431. function draw_config()
  432.   gpu.setBackground(config.color_scheme.button)
  433.   gpu.fill(5,9,71,9," ")
  434.   gpu.setForeground(0xFFFFFF)
  435.   term.setCursor(36,9)
  436.   term.write("Конфигурация")
  437.   term.setCursor(33,10)
  438.   term.write("Старт: "..config.auto_power.start_percent.."%")
  439.   term.setCursor(34,11)
  440.   term.write("Стоп: "..config.auto_power.stop_percent.."%")
  441.   drawProgressBar(8,12,65,3,reactor.getEnergyStored()/10^7)
  442.   gpu.setBackground(config.color_scheme.success)
  443.   gpu.fill(8+65*config.auto_power.start_percent/100,12,1,3," ")
  444.   gpu.setBackground(config.color_scheme.error)
  445.   gpu.fill(8+65*config.auto_power.stop_percent/100,12,1,3," ")
  446.   gpu.setBackground(config.color_scheme.button)
  447.   gpu.setForeground(0xFFFFFF)
  448.   term.setCursor(32+#("Старт: "..config.auto_power.start_percent.."%"),10)
  449.   term.write("[")
  450.   gpu.setForeground(config.color_scheme.error)
  451.   term.write("-")
  452.   gpu.setForeground(0xFFFFFF)
  453.   term.write("]  [")
  454.   gpu.setForeground(config.color_scheme.success)
  455.   term.write("+")
  456.   gpu.setForeground(0xFFFFFF)
  457.   term.write("]")
  458.   term.setCursor(38+#("Stop: "..config.auto_power.stop_percent.."#"),11)
  459.   term.write("[")
  460.   gpu.setForeground(config.color_scheme.error)
  461.   term.write("-")
  462.   gpu.setForeground(0xFFFFFF)
  463.   term.write("]  [")
  464.   gpu.setForeground(config.color_scheme.success)
  465.   term.write("+")
  466.   gpu.setForeground(0xFFFFFF)
  467.   term.write("]")
  468.   term.setCursor(5,9)
  469.   term.write("[")
  470.   gpu.setForeground(config.color_scheme.info)
  471.   term.write("Назад")
  472.   gpu.setForeground(0xFFFFFF)
  473.   term.write("]")
  474. end
  475.  
  476. --#прорисовка прогресс баров
  477.  function drawProgressBar(x,y,w,h,percent)
  478.   red_back = 0xFA8072
  479.   blue_back = 0x1E90FF
  480.   percent_new = calculate(percent*w,0)
  481.   gpu.setBackground(red_back) -- (красный - нижний слой прогрес бара)
  482.   gpu.fill(x,y,w,h," ")
  483.   gpu.setBackground(blue_back) -- (зеленый - верхний слой прогрес бара)
  484.   gpu.fill(x,y,percent_new,h," ")
  485.   percent_new = calculate(percent*100,0)
  486.   salt = string.len(percent_new .. "%")
  487.   per_pos_x = (w-x)/2+x+6
  488.   -- term.setCursor(per_pos_x,y+1)
  489.   if percent_new <=9 then
  490.     per_pos_x = per_pos_x - 1
  491.   elseif percent_new <= 99 then
  492.     per_pos_x = per_pos_x - 1
  493.   elseif percent_new == 100 then
  494.     per_pos_x = per_pos_x - 2
  495.   end
  496.   term.setCursor(per_pos_x + 1, y+1)    
  497.   if percent_new < 49 then
  498.     gpu.setBackground(red_back)
  499.     term.write(percent_new .. "%")
  500.   elseif percent_new == 49 then
  501.     gpu.setBackground(blue_back)
  502.     term.write("4")
  503.     gpu.setBackground(red_back)
  504.     term.write("9%")  
  505.   elseif percent_new == 50 then
  506.     gpu.setBackground(blue_back)
  507.     term.write("50")
  508.     gpu.setBackground(red_back)
  509.     term.write("%")
  510.   elseif percent_new == 51 then
  511.     gpu.setBackground(blue_back)
  512.     term.write("51%")
  513.   elseif percent_new <= 100 then
  514.     gpu.setBackground(blue_back)
  515.     term.write(percent_new .. "%")
  516.   end
  517. end
  518.  
  519. --#слушатель кликов
  520. function listen(name,address,x,y,button,player)
  521.   if x >= 76 and x <= 80 and y == 1 then
  522.     running = false
  523.   end
  524.   if screen == "main" then
  525.     if x >= 72 and y >=2 and x <= 80 and y <= 4 and config.auto_power.enabled ~= true then
  526.       reactor.setActive(not reactor.getActive())
  527.     elseif x >= 1 and y >=2 and x <= 71 and y <= 4 then
  528.       config.auto_power.enabled = not config.auto_power.enabled
  529.       save_config()
  530.     elseif x >= 72 and y >= 2 and x <= 80 and y <= 4 and config.auto_power.enabled then
  531.       gpu.setBackground(0xB0C4DE)
  532.       term.clear()
  533.       screen = "config"
  534.     end
  535.   elseif screen=="config" then
  536.     if x>= 5 and x <= 10 and y == 9 then
  537.       gpu.setBackground(0xB0C4DE)
  538.       term.clear()
  539.       screen="main"
  540.     elseif x >= 34 + #("Пуск: "..config.auto_power.start_percent.."%") and x <= 35+#("Пуск: "..config.auto_power.start_percent.."%") and y == 10 and config.auto_power.start_percent ~= 0 then
  541.       config.auto_power.start_percent = config.auto_power.start_percent-1
  542.       save_config()
  543.     elseif x >= 39 + #("Пуск: "..config.auto_power.start_percent.."%") and x <= 40+#("Пуск: "..config.auto_power.start_percent.."%") and y == 10 and config.auto_power.start_percent+1 ~= config.auto_power.stop_percent then
  544.       config.auto_power.start_percent = config.auto_power.start_percent+1
  545.       save_config()
  546.     elseif x >= 34 + #("Стоп: "..config.auto_power.stop_percent.."%") and x <= 35 + #("Стоп: "..config.auto_power.stop_percent.."%") and y == 11 and config.auto_power.stop_percent - 1 ~= config.auto_power.start_percent then
  547.       config.auto_power.stop_percent = config.auto_power.stop_percent - 1
  548.       save_config()
  549.     elseif x >= 39 + #("Стоп: "..config.auto_power.stop_percent.."%") and x <= 40 + #("Стоп: "..config.auto_power.stop_percent.."%") and y == 11 and config.auto_power.stop_percent ~= 100 then
  550.       config.auto_power.stop_percent = config.auto_power.stop_percent + 1
  551.       save_config()
  552.     end
  553.   end
  554. end
  555.  
  556. --#просчет таблиц
  557. function countTable(table)
  558. local result = 0
  559.   for k,v in pairs(table) do
  560.     result = result+1
  561.   end
  562. return result
  563. end
  564.  
  565. --#round
  566. function round(num,idp)
  567.   local mult = 10^(idp or 0)
  568.   return math.floor(num*mult+0.5)/mult
  569. end
  570.  
  571. --#Начало работы софта
  572. gpu.setBackground(0xB0C4DE)
  573. term.clear()
  574. if not fs.exists("/home/rControl.cfg") then
  575.   install()
  576. else
  577.   main()
  578. end
  579.  
  580. function event.shouldInterrupt()
  581.     return false
  582. end
  583.  
  584. function soft_exit()
  585.     gpu.setBackground(0x000000)
  586.     gpu.setForeground(0xFFFFFF)
  587.     gpu.setResolution(160,50)
  588.     term.clear()
  589. end
  590. event.ignore("touch",listen)
  591. soft_exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement