Advertisement
Alex1979

Remoute Control Robot [OpenComputers]

May 17th, 2015
3,687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 13.46 KB | None | 0 0
  1. ----------------------------------------------------
  2. --       Универсальная многоцелевая программа     --  
  3. --    для ручного управления роботом с планшета!  --  
  4. --          проект http://computercraft.ru        --  
  5. --                 2015, © AlexCC                 --  
  6. ----------------------------------------------------
  7. --------------------ROBOT---------------------------
  8.  
  9.  
  10. local robot = require('robot')
  11. local computer = require('computer')
  12. local event = require('event')
  13. local fs = require("filesystem")
  14. local term = require('term')
  15. local serial = require('serialization')
  16. local com = require('component')
  17. local sides = require('sides')
  18. local rssignal
  19.  
  20. -- Безопасная подгрузка компонентов
  21. local function safeLoadComponents(name)
  22.   if com.isAvailable(name) then
  23.     return com.getPrimary(name), true
  24.   else
  25.     return 'ERROR! Компонент '..name..' не найден!', false
  26.   end
  27. end
  28.  
  29. -- ===== Всякие принтилки, писалки на экран разной кучи инфы и всякие проверки =====
  30.  
  31. -- проверка компонентов
  32. local tun, state_tun = safeLoadComponents('tunnel')
  33. local rs, state_redstone = safeLoadComponents('redstone')
  34. local icontroller, state_icontroller = safeLoadComponents('inventory_controller')  
  35. local magnet, state_magnet = safeLoadComponents('tractor_beam')
  36. local sign, state_sign = safeLoadComponents('sign')
  37.  
  38. term.clear()
  39. print('-------------------------------------------------')
  40. print('       Универсальная многоцелевая программа      ')
  41. print('    для ручного управления роботом с планшета!   ')
  42. print('          проект http://computercraft.ru         ')
  43. print('                 2015, © AlexCC                  ')
  44. print('-------------------------------------------------')
  45. print('Рекомендуемые аппаратные требования:')
  46. print('ЦП / ОЗУ:    - 3 ур. / 1 Мб')
  47. print('Сеть:        - связанная карта (обязательно)')
  48. print('Размер инв.: - 16+ слотов')
  49. print('Апгрейды:    - контроллер инвентаря (обязательно)')
  50. print('магнит, редстоун-карта, апгрейд Табличка I/O')
  51. print('Опционально: ЧЛ и др. (пока не реализовано)')
  52. print('-------------------------------------------------')
  53. term.write('Нажмите ENTER для продолжения...')
  54. io.read()
  55. term.clear()
  56.         print('=============  Проверка компонентов  ===========')
  57.         if not state_tun then
  58.                     print (tun)
  59.                     print('ВНИМАНИЕ! Аппаратные возможности Вашего робота')
  60.                     print('не удовлетворяют миним. требованиям программы!')
  61.                     print('Установите в робота тоннельную (связанную) карту для максимально комфортной работы.')
  62.                     print('=================================================')
  63.                     print ('Программа завершена.')
  64.                     os.exit()
  65.                 else
  66.                     print('Тоннельная карта:      ОК ')
  67.         end
  68.         if not state_icontroller then
  69.                     print (icontroller)
  70.                     print('ВНИМАНИЕ! Аппаратные возможности Вашего робота')
  71.                     print('не удовлетворяют миним. требованиям программы!')
  72.                     print('Установите в робота контроллер инвентаря!')
  73.                     print('=================================================')
  74.                     print ('Программа завершена.')
  75.                     os.exit()
  76.                 else
  77.                     print('Контроллер инвентаря:  ОК ')
  78.         end
  79.         if not state_redstone then
  80.                     print (rs)
  81.                     print('Аппаратные возможности робота ограничены!')
  82.                     print('Вы не сможете управлять редстоун сигналами!')
  83.                     rssignal = 'редстоун НЕ УСТ.'
  84.                 else
  85.                     print('Красная карта:         ОК ')
  86.                     rssignal = 'редстоун выкл.'
  87.                     rs.setOutput(sides.front, 0)
  88.                     rs.setOutput(sides.bottom, 0)
  89.                     rs.setOutput(sides.top, 0)
  90.         end
  91.         if not state_magnet then
  92.                     print(magnet)
  93.                     print('Аппаратные возможности робота ограничены!')
  94.                     print('Вы не сможете подбирать лут с земли!')
  95.                 else
  96.                     print('Магнит апгрейд:        ОК ')
  97.         end
  98.         if not state_sign then
  99.                     print (sign)
  100.                     print('Аппаратные возможности робота ограничены!')
  101.                     print('Вы не сможете писать на табличках!')
  102.                 else
  103.                     print('Апгрейд Табличка I/O:  ОК ')
  104.         end
  105.         print('=================================================')
  106.         term.write('Нажмите ENTER для продолжения...')
  107.         io.read()
  108.  
  109.  
  110. -- Константы
  111. local MAXPACKET = tun.maxPacketSize()
  112. local INVSIZE = robot.inventorySize()
  113. local MAX_EU  = computer.maxEnergy()
  114. local TOTAL_MEM = computer.totalMemory()/1024
  115. local neon = {0x0000ff,0x00ff00,0xffff00,0x00ffff,0xff00c0,0xff0000, 0x000000}
  116.  
  117. -- Переменные
  118. local DYNAMIC_VIEW = true
  119. local current_neon = 1
  120. local robot_status = 'Ожидаю команд...'
  121.  
  122. local  function sendData(array)
  123.   local data = serial.serialize(array)
  124.   tun.send(data)
  125. end
  126.  
  127. local function getEU()
  128.     return math.floor(computer.energy())
  129. end
  130.  
  131. local function freeMEM()
  132.     return math.floor(computer.freeMemory()/1024)
  133. end
  134.  
  135. local  function  printStatus()
  136.     term.clear()
  137.     print('==================== Статус =====================')
  138.     print('Имя робота:            '..robot.name())
  139.     print('Уровень прокачки:      '..robot.level())
  140.     print('Всего/свободно слотов: '..INVSIZE..'/'..'нет данных')
  141.     print('Ёмкость батареи:       '..MAX_EU..' EU')
  142.     print('Текущий заряд:         '..getEU()..' EU')
  143.     print('Всего RAM:             '..TOTAL_MEM..' KБ')
  144.     print('Свободно RAM:          '..freeMEM()..' KБ')
  145.     print('Время работы/RS:       '..math.floor(computer.uptime()/60)..' мин./'..rssignal)
  146.     print('=================================================')
  147.     print('Данные Wi-Fi:  ', robot_status)
  148. end
  149. -- формирование и отправка данных о роботе (параметры, инвентарь и прочее)
  150. local  function infoStatSend()
  151.     local full_info = {
  152.     'infoRobot',
  153.     'Имя робота/уровень прокачки:     '..robot.name()..'/'..robot.level(),
  154.     'Всего/свободно слотов:           '..INVSIZE..'/нет данных',
  155.     'Ёмкость батареи/текущий заряд:   '..MAX_EU..'/'..getEU()..' EU',
  156.     'Всего/cвободно RAM:              '..TOTAL_MEM..'/'..freeMEM()..' KБ',
  157.     'Время работы/редстоун:           '..math.floor(computer.uptime()/60)..' мин./'..rssignal,
  158.     '  --- Перечень предметов в слотах (слот, имя, кол-во) ---'
  159.     }
  160.     for i=1, INVSIZE do
  161.         local amount = robot.count(i)
  162.         if amount > 0 then
  163.             robot.select(i)
  164.             stack = icontroller.getStackInInternalSlot(i)
  165.             local data_item = i..': '..stack.label..' - '..amount..' шт.'
  166.             table.insert(full_info, data_item) 
  167.         end
  168.     end
  169.     sendData(full_info)
  170. end
  171.  
  172. local  function infoStatSendDynamicView()
  173.     if DYNAMIC_VIEW == true then infoStatSend() end
  174. end
  175.  
  176. -- =====  таблица действий робота на сетевые команды  ======
  177. local list = {
  178.  
  179.         --движение робота
  180.         ['w'] = function() robot.forward() end,
  181.         ['s']= function() robot.back() end,
  182.         ['d']= function() robot.turnRight() end,
  183.         ['a']= function() robot.turnLeft() end,
  184.         ['lshift']= function() robot.up() end,
  185.         ['lcontrol']= function() robot.down() end,
  186.  
  187.         --дейстия сверху ЛКМ, ПКМ, Shift-ПКМ
  188.         ['i']= function() robot.swingUp() end,
  189.         ['o']= function() robot.useUp() end,
  190.         ['p']= function() robot.useUp(sides.top, true) end,
  191.  
  192.         --дейстия спереди ЛКМ, ПКМ, Shift-ПКМ
  193.         ['q']= function() robot.swing() end,
  194.         ['e']= function() robot.use() end,
  195.         ['r']= function() robot.use(sides.front, true) end,
  196.  
  197.         --дейстия снизу ЛКМ, ПКМ, Shift-ПКМ
  198.         ['j']= function() robot.swingDown() end,
  199.         ['k']= function() robot.useDown() end,
  200.         ['l']= function() robot.useDown(sides.bottom, true) end,
  201.  
  202.         --======команды 0-9=================
  203.         --ВЫБРОСИТЬ ВСЕ и выбрать 1-й слот
  204.         ['1']= function()
  205.                 for i=1, INVSIZE do
  206.                     if robot.count(i) > 0 then
  207.                         robot.select(i)
  208.                         robot.drop()
  209.                         infoStatSendDynamicView()
  210.                     end
  211.                 end
  212.                 robot.select(1)
  213.         end,
  214.  
  215.         --собрать весь дроп с земли, пока могу это делать!
  216.         ['2']= function()
  217.                 if not state_magnet then return end
  218.                 robot.select(1)
  219.                 while magnet.suck()  do
  220.                     infoStatSendDynamicView()
  221.                 end
  222.         end,
  223.  
  224.         -- ВЗЯТЬ из сундука СВЕРХУ
  225.         ['3']= function()
  226.                 robot.select(1)
  227.                 robot.suckUp()
  228.                 infoStatSendDynamicView()
  229.         end,
  230.  
  231.         -- ВЗЯТЬ из сундука СПЕРЕДИ
  232.         ['4']= function()
  233.                 robot.select(1)
  234.                 robot.suck()
  235.                 infoStatSendDynamicView()
  236.         end,
  237.  
  238.         -- ВЗЯТЬ из сундука СНИЗУ
  239.         ['5']= function()
  240.                 robot.select(1)
  241.                 robot.suckDown()
  242.                 infoStatSendDynamicView()
  243.         end,
  244.  
  245.         -- Что вокруг меня?
  246.         ['6']= function()
  247.         local scan = {'scan'}
  248.                 if robot.detect() then
  249.                     table.insert(scan,'     Cпереди - БЛОК')
  250.                 else
  251.                     table.insert(scan,'     Cпереди - 0')
  252.                 end
  253.                 if robot.detectUp() then
  254.                     table.insert(scan,'     Cверху  - БЛОК')
  255.                 else
  256.                     table.insert(scan,'     Cверху  - 0')
  257.                 end
  258.                 if robot.detectDown() then
  259.                     table.insert(scan,'     Cнизу   - БЛОК')
  260.                 else
  261.                     table.insert(scan,'     Cнизу   - 0')
  262.                 end
  263.                 robot.turnRight()
  264.                 if robot.detect() then
  265.                     table.insert(scan,'     Cправа  - БЛОК')
  266.                 else
  267.                     table.insert(scan,'     Cправа  - 0')
  268.                 end
  269.                 robot.turnRight()
  270.                 if robot.detect() then
  271.                     table.insert(scan,'     Сзади   - БЛОК')
  272.                 else
  273.                     table.insert(scan,'     Сзади   - 0')
  274.                 end
  275.                 robot.turnRight()
  276.                 if robot.detect() then
  277.                     table.insert(scan,'     Слева   - БЛОК')
  278.                 else
  279.                     table.insert(scan,'     Слева   - 0')
  280.                 end
  281.                 robot.turnRight()
  282.                 sendData(scan)
  283.         end,
  284.  
  285.         -- Выбрать слот N
  286.         ['7']= function(data) pcall(robot.select, tonumber(data[2])) end,
  287.  
  288.         --Дроп текущего слота
  289.         ['8']= function() robot.drop() end,
  290.  
  291.         --показать статистику
  292.         ['9']= function() infoStatSend() end,
  293.  
  294.         --поставить блок Сверху
  295.         ['z']= function() robot.placeUp() end,
  296.  
  297.         --поставить блок Спереди
  298.         ['x']= function() robot.place() end,
  299.  
  300.         --поставить блок Снизу
  301.         ['c']= function() robot.placeDown() end,
  302.  
  303.         --включить/выключить редстоун излучение
  304.         ['f']= function()
  305.                 if not state_redstone then return end
  306.                 if rssignal == 'редстоун выкл.' then
  307.                     rs.setOutput(sides.front, 15)
  308.                     rs.setOutput(sides.bottom, 15)
  309.                     rs.setOutput(sides.top, 15)
  310.                     rssignal = 'редстоун вкл.'
  311.                 else
  312.                     rs.setOutput(sides.front, 0)
  313.                     rs.setOutput(sides.bottom, 0)
  314.                     rs.setOutput(sides.top, 0)
  315.                     rssignal = 'редстоун выкл.'
  316.                 end
  317.         end,
  318.         --цикличная смена цвета неоновой подсветки робота
  319.         ['n']= function()
  320.                 if current_neon > #neon then
  321.                     current_neon = 1
  322.                 end
  323.                 robot.setLightColor(neon[current_neon])
  324.                 current_neon =  current_neon + 1
  325.         end,
  326.  
  327.         -- вкл./выкл. показа динамического изменения инвентаря робота
  328.         ['v']= function() DYNAMIC_VIEW = not DYNAMIC_VIEW end,
  329.  
  330.         --меняем инструмент на инструмент в активном слоте инвентаря
  331.         ['y']= function() if not state_icontroller then return end icontroller.equip() end,
  332.  
  333.         --пишем текст на табличках
  334.         ['t']= function(data)
  335.                 if not state_sign then return end
  336.                 sign.setValue(tostring(data[2]))
  337.     end
  338.  
  339. }
  340.  
  341.  
  342. local  function  main()
  343.     robot.select(1)
  344.     printStatus()
  345.     while true do
  346.         --ожидаем команд (события) по wi-fi, каждые 30 сек - срыв ожидания и принт статуса
  347.         e, _, _, _, _, msg  = event.pull(30,'modem_message')
  348.         if e then
  349.             robot_status = msg
  350.             printStatus()
  351.             data = serial.unserialize(msg)
  352.             --если существует ключ, вызываем действие из массива и передаем все данные из сообщения
  353.             if list[data[1]] then
  354.                 list[data[1]](data)
  355.             end
  356.         else
  357.             -- ничего не делаем, курим, принтим на экран инфу о разряжающейся батарейке:)
  358.             printStatus()
  359.         end
  360.     end
  361. end
  362.  
  363. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement