SHARE
TWEET

Интерпретатор для EEPROM (OpenComputers)

rollton Sep 28th, 2017 174 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local enableSaveHistory = true -- Сохранение истории консоли
  2.  
  3. local comp = require("component")
  4. local event = require("event")
  5. local term = require("term")
  6. local shell = require("shell")
  7. local fs = require("filesystem")
  8. local serialization = require("serialization")
  9.  
  10. function chekModul(mod) if pcall(load(mod.." = ".."require('component')."..mod)) then return true else return false end end
  11. modem = {}
  12. if not chekModul("modem") then if not chekModul("tunnel") then print(' Error: No Modem Card or Linked Card  |  Отсутствует модем или связная карта\a') os.exit() else tunnelOn = true end else broadcast = modem.broadcast end
  13. function send(a,b,c) if broadcast ~= nil then if c == nil then broadcast(a,b) else broadcast(a,b,c) end else tunnel.send(b,c) end end
  14.  
  15. gpu = comp.gpu
  16.  
  17. local args = shell.parse(...)
  18. local port
  19. local nameFileHist = "//historyDcp.txt"
  20.  
  21. function write(gg) gpu.setForeground(0x00ffff) io.write(gg..'\n') gpu.setForeground(0xffffff) end
  22.  
  23. function noError(kode) pcall(load(kode)) end
  24.  
  25. function download(kod)
  26.     if not chekModul("internet") then print(' Error: No Internet Card') os.exit()  end
  27.     local txt = ''
  28.     if not pcall(function() for chunk in require("internet").request('https://pastebin.com/raw/'..kod) do txt = txt..chunk end end) then print('file not found, use for example: "m364BGpZ"') end
  29.     return txt:gsub("\n","\n "):gsub("\13",""):gsub("\9","")
  30. end
  31.  
  32. function online()
  33.     local onli = 0
  34.     local distanceUuid = {}
  35.     send(port,'modem.broadcast('..port..'+1,"test online...")')
  36.     repeat
  37.         local e = {event.pull(0.5,"modem_message")}
  38.         if e[6] == "test online..." then onli = onli + 1 distanceUuid[onli] = {e[3],e[5]} end
  39.     until e[6] == nil
  40.     return {onli,distanceUuid}
  41. end
  42.  
  43. function runHelp()
  44.     print([[
  45. Usages:
  46.   dcp help
  47.   dcp <port> -  run console  |  Запуск консоли
  48.   dcp new <port> - record EEPROM  |  Запись EEPROM
  49.   dcp run <name programm> <port> - Running the program  |  Запуск программы
  50.   dcp pastebin <kode pastebin> <port> - Start the program  |  Запуск программы c pastebin]])
  51. end
  52.  
  53. local consoleCommand = {
  54.         online = function() local nn = online() print("Online device: "..nn[1]) for i,v in pairs(nn[2]) do print(i..')','Modem Card: '..v[1],' distance: '..v[2]) end end,
  55.         help = function()
  56.         print([[
  57. Usages:
  58.     components - List of components  |  Список компонентов
  59.     components [<device>] - List of methods  |  Список методов компонента
  60.     online - List of online device  |  Список онлайн устройств
  61.     start - Start the whole device  |  Запуск всех устройств
  62.     = date - return the date of recording EEPROM  |  Вернуть дату записи EEPROM]])    
  63.             end,
  64.         start = function() if broadcast ~= nil then broadcast(1,'_start') os.sleep(0.5) print("Online device: "..online()[1]) end end
  65. }
  66.  
  67. local function runProgramma(prog)
  68.     if prog == nil then
  69.         local put = args[2]
  70.         if put == nil then print('dcp run <name program> <port>') print() io.write('Введите название файла: ') put = io.read() end -- можно сделать табом
  71.         if not fs.exists("/home/"..put) then print(' Error: Файл не найден.') os.exit() end
  72.         local file = io.open("/home/"..put)
  73.         prog = file:read("*a")
  74.         file:close()
  75.     end
  76.  
  77.     port = tonumber(args[3])
  78.     if port == nil then io.write('Введите порт: ') port = tonumber(io.read()) end
  79.     if type(port) ~= 'number' then print('Error type.') os.exit() end
  80.  
  81.     -- print(prog)
  82.     noError("modem.open("..port.."+1)")
  83.  
  84.     print("Press 'q' to exit error handler | Нажмите 'q' для выхода из обработчика ошибок")
  85.     print("Press 'w' stop program ( using os.sleep () in the program ) ")
  86.  
  87.     local limit = 8000 -- Величина одного пакета. Максимум 8192
  88.     if #prog > limit then
  89.         for i = 0, math.floor(#prog/limit) do
  90.             send(port,prog:sub(i*limit,(i+1)*limit-1),'_echo')
  91.             os.sleep(0.5)
  92.         end
  93.     else send(port,prog) end
  94.  
  95.     local e
  96.     repeat
  97.         e = {event.pull(1)}
  98.         if e[1] == "modem_message" and e[6] ~= nil then print(e[6]) end
  99.         if (e[1] == "key_down" and e[4] == 17) then send(port,"exit") end
  100.     until e[1] == "modem_message" or (e[1] == "key_down" and (e[4] == 16 or e[4] == 17))
  101. end
  102.  
  103. local function runConsole()
  104.  
  105.     if args[1] ~= nil and port == nil then port = tonumber(args[1]) end
  106.     noError("modem.close()")
  107.     io.write('Dcp 2.5 Copyright (C) 2017 Porn.hub :D ')
  108.     if port == nil then
  109.         write(' -> help')
  110.     end
  111.     gpu.setForeground(0xffff00)
  112.     print('Enter a statement and hit enter to evaluate it.')
  113.     print("Prefix an expression with '=' to show its value.")
  114.     print('Press Ctrl+D to exit the interpreter.')
  115.     gpu.setForeground(0xffffff)
  116.     print()
  117.     if (port == nil) and not tunnelOn then
  118.         io.write(' >> Port to connect: ')
  119.         port = tonumber(term.read(_,_,_,"*"))
  120.     else if tunnelOn then print(' >> Connect to tunnel') port=0 else print(' >> Connect to port: '..port:gsub("%d","*")) end end
  121.     if type(port) ~= 'number' then print() print('Error type') os.exit() end
  122.     noError("modem.open("..port.."+1)")
  123.     print('    Online: '..online()[1]..'\n')
  124.     local history = {}
  125.  
  126.     if fs.exists(nameFileHist) and enableSaveHistory then
  127.         local file = io.open(nameFileHist):read()
  128.         if file ~= nil then history = serialization.unserialize(file) end
  129.     end
  130.  
  131.     if #history > 40 then
  132.         local buffer = {}
  133.         for i = 1,30 do
  134.             buffer[i] = history[i]
  135.         end
  136.         history = buffer
  137.     end
  138.  
  139.     while term.isAvailable() do
  140.         gpu.setForeground(0x00ff00) term.write('dcp> ') gpu.setForeground(0xffffff)
  141.         history[11] = history[10]
  142.         command = term.read(history):gsub('\n','')
  143.  
  144.         if enableSaveHistory then
  145.             local file = io.open(nameFileHist,"w")
  146.             file:write(serialization.serialize(history))
  147.             file:close()
  148.         end
  149.  
  150.         if command:sub(1,1) == '=' then command = 'pcall(load("txt = tostring('..command:sub(2)..')")) modem.broadcast('..port..'+1,tostring(txt)) txt = nil' end
  151.  
  152.         local flag,info
  153.         local aa,bb = command:find("components")
  154.  
  155.         if aa ~= nil and aa < 4 and command:sub(bb+2):gsub(" ","") == "" then
  156.             info = online()
  157.             if info[1] > 1 then
  158.                 for i,v in pairs(info[2]) do print(i..')','Modem Card: '..v[1]..' distance: '..v[2]) end
  159.                 io.write(" Select a device | Выберите устройство: ")
  160.                 flag = tonumber(term.read())
  161.             end
  162.         end
  163.  
  164.         local chekCommand = consoleCommand[command]
  165.         if chekCommand ~= nil then chekCommand() else
  166.             if flag == nil then send(port,command) else modem.send(info[2][flag][1],port,command) end
  167.             local e = {event.pull(10,"modem_message")}
  168.             if e[1] == false then print('No connect to modem') end
  169.             for i=6,10 do if e[i] ~= nil then io.write(e[i]..'   ') else print() break end end
  170.         end
  171.     end
  172. end
  173.  
  174. local function runNew()
  175.     if not chekModul("internet") then print(' Error: No Internet Card') os.exit() end
  176.     if not comp.isAvailable('eeprom') then print('Отсутствует EEPROM. Вставьте EEPRON.') event.pull("component_added") end
  177.     if comp.eeprom.getLabel() == 'EEPROM (Lua BIOS)' then print('Вставьте чистый EEPROM за место EEPROM (Lua BIOS)') event.pull("component_added") end
  178.  
  179.     local bios = download('m364BGpZ')
  180.    
  181.     port = tonumber(args[2])
  182.     if args[2] == nil then io.write('Укажите новый порт: ') port = tonumber(term.read(_,_,_,"*")) end
  183.     if port == nil then print('Ошибка! Не верно указан порт') os.exit() end
  184.     print('Идет запись EEPROMa, пожалуйста подождите...')
  185.     comp.eeprom.set(' date = \"'..os.date()..'\" local port = '..port..' '..bios:gsub("\13",""):gsub("\9",""))
  186.     comp.eeprom.setLabel('EEPROM Port: '..port)
  187.     print('EEPROM Успешно записан! Поместите в окно крафта EEPROM + drone / microcontroller')
  188.     -- runConsole()
  189. end
  190.  
  191. local function runPastebin()
  192.     if not chekModul("internet") then print(' Error: No Internet Card') os.exit() end
  193.     local put = args[2]
  194.     if put == nil then print('dcp pastebin <program code on pastebin> <port>') print() io.write('Введите код файла (например: m364BGpZ ): ') put = io.read() end
  195.     runProgramma(download(put))
  196. end
  197.  
  198. local h = {
  199.     new = function() runNew() end,
  200.     run = function() runProgramma() end,
  201.     pastebin = function() runPastebin() end,
  202.     help =  function() runHelp() end,
  203. }
  204.  
  205. if fs.exists(nameFileHist) then
  206.     if h[args[1]] ~= nil then
  207.         h[args[1]]()
  208.     else
  209.         pcall(runConsole)
  210.     end
  211. else
  212.     io.open(nameFileHist,"w"):write(''):close()
  213.     runHelp()
  214.     io.write('\nFor the first run, type: ') write('dcp new')
  215.     io.write('Для первого запуска введите: ') write('dcp new')
  216.     gpu.setForeground(0xffffff)
  217. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top