Advertisement
civilwargeeky

Quarry Receiver 3.6.1

Jan 2nd, 2015
658
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 61.77 KB | None | 0 0
  1. --Quarry Receiver Version 3.6.1
  2. --Made by Civilwargeeky
  3. --[[
  4. Recent Changes:
  5.   Completely Remade!
  6. ]]
  7.  
  8.  
  9. --Config
  10. local doDebug = false --For testing purposes
  11. local ySizes = 3 --There are 3 different Y Screen Sizes right now
  12. local quadEnabled = false --This is for the quadrotors mod by Lyqyd
  13.  
  14. --Initializing Program-Wide Variables
  15. local expectedMessage = "Civil's Quarry" --Expected initial message
  16. local expectedFingerprint = "quarry"
  17. local replyMessage = "Turtle Quarry Receiver" --Message to respond to  handshake with
  18. local replyFingerprint = "quarryReceiver"
  19. local stopMessage = "stop"
  20. local expectedFingerprint = "quarry"
  21. local themeFolder = "quarryResources/receiverThemes/"
  22. local modemSide --User can specify a modem side, but it is not necessary
  23. local modem --This will be the table for the modem
  24. local computer --The main screen is special. It gets defined first :3
  25. local continue = true --This keeps the main while loop going
  26. local quadDirection = "north"
  27. local quadDirections = {n = "north", s = "south", e = "east", w = "west"}
  28. local quadBase, computerLocation
  29. local tArgs = {...}
  30. --These two are used by controller in main loop
  31. local commandString = "" --This will be a command string sent to turtle. This var is stored for display
  32. local lastCommand --If a command needs to be sent, this gets set
  33. local defaultSide
  34. local defaultCommand
  35.  
  36. for i=1, #tArgs do --Parameters that must be set before rest of program for proper debugging
  37.   local val = tArgs[i]:lower()
  38.   if val == "-v" or val == "-verbose" then
  39.     doDebug = true
  40.   end
  41.   if val == "-q" or val == "-quiet" then
  42.     doDebug = false
  43.   end
  44. end
  45.  
  46. local keyMap = {[57] = " ", [11] = "0", [12] = "_", [52] = ".", [82] = "0", [83] = "."} --This is for command string
  47. for i=2,10 do keyMap[i] = tostring(i-1) end --Add top numbers
  48. for a=0,2 do --All the numpad numbers
  49.   for b=0,2 do
  50.     keyMap[79-(4*a)+b] = tostring(b + 1 + a*3) --Trust me, this just works
  51.   end
  52. end
  53. for a,b in pairs(keys) do --Add all letters from keys api
  54.   if #a == 1 then
  55.     keyMap[b] = a:upper()
  56.   end
  57. end
  58. keyMap[keys.enter] = "enter"
  59. keyMap[156] = "enter" --Numpad enter
  60. keyMap[keys.backspace] = "backspace"
  61. keyMap[200] = "up"
  62. keyMap[208] = "down"
  63. keyMap[203] = "left"
  64. keyMap[205] = "right"
  65.  
  66. local helpResources = { --$$ is a new page
  67. main = [[$$Hello and welcome to
  68. Quarry Receiver Help!
  69.  
  70. This goes over everything there is to know about the receiver
  71.  
  72. Use the arrow keys to navigate!
  73. Press '0' to come back here!
  74. Press 'q' to quit!
  75.  
  76. Press a section number at any time to go the beginning of that section
  77.  1. Basic Use
  78.  2. Parameters
  79.  3. Commands
  80.  4. Turtle Commands
  81.  
  82. $$A secret page!
  83. You found it! Good job :)
  84. ]],
  85. [[$$Your turtle and you!
  86.  
  87. To use this program, you need a wireless modem on both this computer and the turtle
  88.  
  89. Make sure they are attached to both the turtle and this computer
  90. $$Using your new program!
  91.  
  92. Once you have done that, start the turtle and when it says "Rednet?", say "Yes"
  93.   Optionally, you can use the parameter "-rednet true"
  94. Then remember the channel it tells you to open.
  95.  
  96. Come back to this computer, and run the program. Follow onscreen directions.
  97.   Optionally, you can use the parameter "-receiveChannel"
  98.  
  99. Check out the other help sections for more parameters
  100. $$Adding Screens!
  101. You can add screens with the "-screen" parameter or the "SCREEN" command
  102. An example would be "SCREEN LEFT" for a screen on the left side.
  103.  
  104. You can connect screens over wired modems. Attach a modem to the computer and screen, then right click the modem on the screen.
  105. Then you can say "SCREEN MONITOR_0" or whatever it says
  106.  
  107. ]],
  108. [[$$Parameters!
  109.   note: {} means required, [] means optional
  110.  
  111. -help/help/-?/?/-usage/usage: That's this!
  112.  
  113. -receiveChannel {channel}: Sets the main screen's receive channel
  114.  
  115. -theme {name}: sets the "default" theme that screens use when they don't have a set theme
  116.  
  117. -screen {side} [channel] [theme]: makes a new screen on the given side with channel and theme
  118. $$Parameters!
  119.  note: {} means required, [] means optional
  120.  
  121. -station: makes the main computer a "station" that monitors all screens
  122.  
  123. -auto [channel list]: This finds all attached monitors and initializes them. The channel list assigns channels to screens sequentially
  124.  example: -auto 1 2 5 9   This looks for screens and automatically gives them channels 1, 2, 5, and 9
  125.  
  126. -colorEditor: makes the main screen a color editor that just prints the current colors. Good for theme making
  127. current typeColors: title, subtitle, pos, dim, extra, error, info, inverse, command, help, background
  128. $$Parameters!
  129. -modem {side}: Sets the modem side to side
  130.  
  131. -v/-verbose: turns on debug
  132.  
  133. -q/-quiet: turns off debug
  134. ]],
  135. [[$$Commands!
  136.  These commands can use the "side" command
  137.  
  138. COMMAND [screen] [text]: Sends text to the connected turtle. See turtle commands for valid commands
  139.  
  140. REMOVE [screen]: Removes the selected screen (cannot remove the main screen)
  141.  
  142. THEME [screen] [name]: Sets the theme of the given screen. THEME [screen] resets the screen to default theme
  143. $$Commands!
  144.  These commands can use the "side" command
  145.  
  146. COLOR [screen] [typeName] [textColor] [backColor]: Changes the local theme of the screen. If the screen has no theme, it changes the global default theme. See notes on "colorEditor" parameter for more info
  147.  
  148. RECEIVE [screen] [channel]: Changes the receive channel of the given screen
  149.  
  150. SEND [screen] [channel]: Changes the send channel of the given screen (for whatever reason)
  151. $$Commands!
  152.  These are regular commands
  153.  
  154. SET [text]: Sets a default command that can be backspaced. Useful for color editing or command sending
  155.  
  156. SIDE [screen]: Sets a default screen for "sided" commands
  157.  
  158. EXIT/QUIT: Quits the program gracefully
  159.  
  160. THEME [name]: Sets the default theme.
  161. $$Commands!
  162.  These are regular commands
  163.  
  164. COLOR [themeName] [typeColor] [textColor] [backColor]: Sets the the text and background colors of the given typeColor of the given theme. See notes on "colorEditor" parameter for more info
  165.  
  166. SAVETHEME [themeName] [fileName]: Saves the given theme as fileName for later use
  167.  
  168. AUTO [channelList]: Automatically searches for nearby screens, providing them sequentially with channels if a channel list is given
  169.  Example Use: AUTO 1 2 5 9
  170. $$Commands!
  171.  These are regular commands
  172.  
  173. HELP: Displays this again!
  174.  
  175. VERBOSE: Turns debug on
  176.  
  177. QUIET: Turns debug off
  178.  
  179. ]],
  180. [[$$Turtle Commands!
  181.  
  182. Stop: Stops the turtle where it is
  183.  
  184. Return: The turtle will return to its starting point, drop off its load, and stop
  185.  
  186. Drop: Turtle will immediately go and drop its inventory
  187.  
  188. Pause: Pauses the turtle
  189.  
  190. Resume: Resumes paused turtles
  191. ]]
  192. }
  193.  
  194. --Generic Functions--
  195. local function debug(...)
  196.  --if doDebug then return print(...) end --Basic
  197.  if doDebug then
  198.    print("\nDEBUG: ",...)
  199.    os.pullEvent("char")
  200.  end
  201. end
  202. local function clearScreen(x,y, periph)
  203.  periph, x, y = periph or term, x or 1, y or 1
  204.  periph.clear()
  205.  periph.setCursorPos(x,y)
  206. end
  207.  
  208. local function swapKeyValue(tab)
  209.  for a,b in pairs(tab) do
  210.    tab[b] = a
  211.  end
  212.  return tab
  213. end
  214. local function copyTable(tab)
  215.  local toRet = {}
  216.  for a,b in pairs(tab) do
  217.    toRet[a] = b
  218.  end
  219.  return toRet
  220. end
  221. local function checkChannel(num)
  222.  num = tonumber(num)
  223.  if not num then return false end
  224.  if 1 <= num and num <= 65535 then
  225.    return num
  226.  end
  227.  return false
  228. end
  229. local function align(text, xDim, direction)
  230.  text = tostring(text or "None")
  231.  if #text >= xDim then return text end
  232.  for i=1, xDim-#text do
  233.    if direction == "right" then
  234.      text = " "..text
  235.    elseif direction == "left" then
  236.      text = text.." "
  237.    end
  238.  end
  239.  return text
  240. end
  241. local function alignR(text, xDim)
  242.  return align(text, xDim, "right")
  243. end
  244. local function alignL(text, xDim)
  245.  return align(text, xDim, "left")
  246. end
  247. local function center(text, xDim)
  248.  xDim = xDim or dim[1] --Temp fix
  249.  local a = (xDim-#text)/2
  250.  for i=1, a do
  251.    text = " "..text.." "
  252.  end
  253.  return text  
  254. end
  255. local function roundNegative(num) --Rounds numbers up to 0
  256.  if num >= 0 then return num else return 0 end
  257. end
  258. local function displayHelp()
  259.  local tab = {}
  260.  local indexOuter = "main"
  261.  local indexInner = 1
  262.  for key, value in pairs(helpResources) do
  263.    tab[key] = {}
  264.    for a in value:gmatch("$$([^$]+)") do
  265.      table.insert(tab[key], a) --Just inserting pages
  266.    end
  267.  end
  268.  while true do
  269.    clearScreen()
  270.    print(tab[indexOuter][indexInner])
  271.    local text = tostring(indexInner).."/"..tostring(#tab[indexOuter])
  272.    term.setCursorPos(({term.getSize()})[1]-#text,1)
  273.    term.write(text) --Print the current page number
  274.    local event, key = os.pullEvent("key")
  275.    key = keyMap[key]
  276.    if tonumber(key) and tab[tonumber(key)] then
  277.      indexOuter = tonumber(key)
  278.      indexInner = 1
  279.    elseif key == "Q" then
  280.      os.pullEvent("char") --Capture extra event (note: this always works because only q triggers this)
  281.      return true
  282.    elseif key == "0" then --Go back to beginning
  283.      indexOuter, indexInner = "main",1
  284.    elseif key == "up" and indexInner > 1 then
  285.      indexInner = indexInner-1
  286.    elseif key == "down" and indexInner < #tab[indexOuter] then
  287.      indexInner = indexInner + 1
  288.    end
  289.  end
  290.    
  291. end
  292.  
  293.  
  294. local function testPeripheral(periph, periphFunc)
  295.  if type(periph) ~= "table" then return false end
  296.  if type(periph[periphFunc]) ~= "function" then return false end
  297.  if periph[periphFunc]() == nil then --Expects string because the function could access nil
  298.    return false
  299.  end
  300.  return true
  301. end
  302.  
  303. local function initModem() --Sets up modem, returns true if modem exists
  304.  if not testPeripheral(modem, "isWireless") then
  305.    if peripheral.getType(modemSide or "") == "modem" then
  306.      modem = peripheral.wrap(modemSide)    
  307.      if not modem.isWireless() then --Apparently this is a thing
  308.        modem = nil
  309.        return false
  310.      end
  311.      return true
  312.    end
  313.    if peripheral.find then
  314.      modem = peripheral.find("modem", function(side, obj) return obj.isWireless() end)
  315.    end
  316.    return modem and true or false
  317.  end
  318.  return true
  319. end
  320.  
  321. --COLOR/THEME RELATED
  322. for a, b in pairs(colors) do --This is so commands color commands can be entered in one case
  323.  colors[a:lower()] = b
  324. end
  325.  
  326. local requiredColors = {"title", "subtitle", "pos", "dim", "extra", "error", "info", "inverse", "command", "help", "background"}
  327.  
  328. local function checkColor(name, text, back) --Checks if a given color works
  329.  local flag = false
  330.  for a, b in ipairs(requiredColors) do
  331.    if b == name then
  332.      flag = true
  333.      break
  334.    end
  335.  end
  336.  if not flag or not (tonumber(text) or colors[text]) or not (tonumber(back) or colors[back]) then return false end
  337.  return true
  338. end
  339.  
  340.  
  341. local themes = {} --Loaded themes, gives each one a names
  342. local function newTheme(name)
  343.  name = name:lower() or "none"
  344.  local self = {name = name}
  345.  self.addColor = function(self, colorName, text, back) --Background is optional. Will not change if nil
  346.    if not checkColor(colorName, text, back or "black") then debug("Color check failed: ",name," ",text," ",back); return self end --Back or black because optional
  347.    colorName = colorName or "none"
  348.    self[colorName] = {text = text, background = back}
  349.    return self --Allows for chaining :)
  350.  end
  351.  themes[name] = self
  352.  return self
  353. end
  354.  
  355. local function parseTheme(file)
  356.  local addedTheme = newTheme(file:match("^.-\n") or "newTheme") --Initializes the new theme to the first line
  357.  file:sub(file:find("\n") or 1) --If there is a newLine, this cuts everything before it. I don't care that the newLine is kept
  358.   for line in file:gmatch("[^\n]+\n") do --Go through all the color lines (besides first one)
  359.     local args = {}
  360.     for word in line:gmatch("%S+") do
  361.       table.insert(args,word)
  362.     end
  363.     addedTheme:addColor(args[1]:match("%a+") or "nothing", tonumber(args[2]) or colors[args[2]], tonumber(args[3]) or colors[args[3]]) --"nothing" will never get used, so its just lazy error prevention
  364.   end
  365.   local flag = true --Make sure a theme has all required elements
  366.   for a,b in ipairs(requiredColors) do
  367.     if not addedTheme[b] then
  368.       flag = false
  369.       debug("Theme is missing color '",b,"'")
  370.     end
  371.   end
  372.   if not flag then
  373.     themes[addedTheme.name] = nil
  374.     debug("Failed to load theme")
  375.     return false
  376.   end
  377.   return addedTheme
  378. end
  379. --This is how adding colors will work
  380. newTheme("default")
  381.   :addColor("title", colors.green, colors.gray)
  382.   :addColor("subtitle", colors.white, colors.black)
  383.   :addColor("pos", colors.green, colors.black)
  384.   :addColor("dim", colors.lightBlue, colors.black)
  385.   :addColor("extra", colors.lightGray, colors.black)
  386.   :addColor("error", colors.red, colors.white)
  387.   :addColor("info", colors.blue, colors.lightGray)
  388.   :addColor("inverse", colors.yellow, colors.lightGray)
  389.   :addColor("command", colors.lightBlue, colors.black)
  390.   :addColor("help", colors.red, colors.white)
  391.   :addColor("background", colors.white, colors.black)
  392.  
  393. newTheme("blue")
  394.   :addColor("title", 2048, 8192)
  395.   :addColor("subtitle", 1, 2048)
  396.   :addColor("pos", 16, 2048)
  397.   :addColor("dim", 4096, 2048)
  398.   :addColor("extra", 8, 2048)
  399.   :addColor("error",  8, 16384)
  400.   :addColor("info", 2048, 256)
  401.   :addColor("inverse", 2048, 1)
  402.   :addColor("command", 2048, 8)
  403.   :addColor("help", 16384, 1)
  404.   :addColor("background", 1, 2048)
  405.  
  406. newTheme("seagle")
  407.   :addColor("title", colors.white, colors.black)
  408.   :addColor("subtitle", colors.red, colors.black)
  409.   :addColor("pos", colors.gray, colors.black)
  410.   :addColor("dim", colors.lightBlue, colors.black)
  411.   :addColor("extra", colors.lightGray, colors.black)
  412.   :addColor("error", colors.red, colors.white)
  413.   :addColor("info", colors.blue, colors.lightGray)
  414.   :addColor("inverse", colors.yellow, colors.lightGray)
  415.   :addColor("command", colors.lightBlue, colors.black)
  416.   :addColor("help", colors.red, colors.white)
  417.   :addColor("background", colors.white, colors.black)
  418.  
  419. newTheme("random")
  420.   :addColor("title", colors.pink, colors.blue)
  421.   :addColor("subtitle", colors.black, colors.white)
  422.   :addColor("pos", colors.green, colors.black)
  423.   :addColor("dim", colors.lightBlue, colors.black)
  424.   :addColor("extra", colors.lightGray, colors.lightBlue)
  425.   :addColor("error", colors.white, colors.yellow)
  426.   :addColor("info", colors.blue, colors.lightGray)
  427.   :addColor("inverse", colors.yellow, colors.lightGray)
  428.   :addColor("command", colors.green, colors.lightGray)
  429.   :addColor("help", colors.white, colors.yellow)
  430.   :addColor("background", colors.white, colors.red)
  431.  
  432. --If you modify a theme a bunch and want to save it
  433. local function saveTheme(theme, fileName)
  434.   if not theme or not type(fileName) == "string" then return false end
  435.   local file = fs.open(fileName,"w")
  436.   if not file then return false end
  437.   file.writeLine(fileName)
  438.   for a,b in pairs(theme) do
  439.     if type(b) == "table" then --If it contains color objects
  440.       file.writeLine(a.." "..tostring(b.text).." "..tostring(b.background))
  441.     end
  442.   end
  443.   file.close()
  444.   return true
  445. end
  446.  
  447.  
  448. --==SCREEN CLASS FUNCTIONS==
  449. local screenClass = {} --This is the class for all monitor/screen objects
  450. screenClass.screens = {} --A simply numbered list of screens
  451. screenClass.sides = {} --A mapping of screens by their side attached
  452. screenClass.channels = {} --A mapping of receiving channels that have screens attached. Used for the receiver part
  453. screenClass.sizes = {{7,18,29,39,50}, {5,12,19} , computer = {51, 19}, turtle = {39,13}, pocket = {26,20}}
  454.  
  455. screenClass.setTextColor = function(self, color) --Accepts raw color
  456.   if color and self.term.isColor() then
  457.     self.textColor = color
  458.     self.term.setTextColor(color)
  459.     return true
  460.   end
  461.   return false
  462. end
  463. screenClass.setBackgroundColor = function(self, color) --Accepts raw color
  464.   if color and self.term.isColor() then
  465.     self.backgroundColor = color
  466.     self.term.setBackgroundColor(color)
  467.     return true
  468.   end
  469.   return false
  470. end
  471. screenClass.setColor = function(self, color) --Wrapper, accepts themecolor objects
  472.   if type(color) ~= "table" then error("Set color received a non-table",2) end
  473.   return self:setTextColor(color.text) and self:setBackgroundColor(color.background)
  474. end
  475.  
  476. screenClass.themeName = "default" --Setting super for fallback
  477. screenClass.theme = themes.default
  478.  
  479.  
  480. screenClass.new = function(side, receive, themeFile)
  481.   local self = {}
  482.   setmetatable(self, {__index = screenClass}) --Establish Hierarchy
  483.   self.side = side
  484.   if side == "computer" then
  485.     self.term = term
  486.   else
  487.     self.term = peripheral.wrap(side)
  488.     if not (self.term and peripheral.getType(side) == "monitor") then --Don't create an object if it doesn't exist
  489.       if doDebug then
  490.         error("No monitor on side "..tostring(side))
  491.       end
  492.       self = nil --Save memory?
  493.       return false
  494.     end
  495.   end
  496.  
  497.   --Channels and ids
  498.   self.receive = tonumber(receive) --Receive Channel
  499.   self.send = nil --Reply Channel, obtained in handshake
  500.   self.id = #screenClass.screens+1
  501.   --Colors
  502.   self.themeName = nil --Will be set by setTheme
  503.   self.theme = nil
  504.   self.isColor = self.term.isColor() --Just for convenience
  505.   --Other Screen Properties
  506.   self.dim = {self.term.getSize()} --Raw dimensions
  507.   --Initializations
  508.   self.isDone = false --Flag for when the turtle is done transmitting
  509.   self.size = {} --Screen Size, assigned in setSize
  510.   self.textColor = colors.white --Just placeholders until theme is loaded and run
  511.   self.backColor = colors.black
  512.   self.toPrint = {}
  513.   self.isComputer = false
  514.   self.isTurtle = false
  515.   self.isPocket = false
  516.   self.acceptsInput = false
  517.   self.legacy = false --Whether it expects tables or strings
  518.   self.rec = { --Initial values for all displayed numbers
  519.     label = "Quarry Bot",
  520.     id = 1,
  521.     percent = 0,
  522.     xPos = 0,
  523.     zPos = 0,
  524.     layersDone = 0,
  525.     x = 0,
  526.     z = 0,
  527.     layers = 0,
  528.     openSlots = 0,
  529.     mined = 0,
  530.     moved = 0,
  531.     chestFull = false,
  532.     isAtChest = false,
  533.     isGoingToNextLayer = false,
  534.     foundBedrock = false,
  535.     fuel = 0,
  536.     volume = 0,
  537.     distance = 0,
  538.     yPos = 0
  539.     --Maybe add in some things like if going to then add a field
  540.   }
  541.  
  542.   screenClass.screens[self.id] = self
  543.   screenClass.sides[self.side] = self
  544.   if self.receive then
  545.     modem.open(self.receive) --Modem should be defined by the time anything is open
  546.     screenClass.channels[self.receive] = self --If anyone ever asked, you could have multiple screens per channel, but its silly if no one ever needs it
  547.   end
  548.   self:setSize() --Finish Initialization
  549.   self:setTheme(themeFile)
  550.   return self
  551. end
  552.  
  553. screenClass.remove = function(tab) --Cleanup function
  554.   if type(tab) == "number" then --Expects table, can take id (for no apparent reason)
  555.     tab = screenClass.screens[tab]
  556.   end
  557.   if tab.side == "REMOVED" then return end
  558.   if tab.side == "computer" then error("Tried removing computer screen",2) end --This should never happen
  559.   tab:reset() --Clear screen
  560.   tab:say("Removed", tab.theme.info, 1) --Let everyone know whats up
  561.   screenClass.screens[tab.id] = {side = "REMOVED"} --Not nil because screw up len()
  562.   screenClass.sides[tab.side] = nil
  563.   if tab.receive then --may not have a channel
  564.     screenClass.channels[tab.receive] = nil
  565.     if modem and modem.isOpen(tab.receive) then
  566.       modem.close(tab.receive)
  567.     end
  568.   end
  569. end
  570.  
  571. --Init Functions
  572. screenClass.setChannel = function(self, channel)
  573.   self.send = nil --No matter what, send channel should be reset
  574.   if self.receive then
  575.     screenClass.channels[self.receive] = nil
  576.     if modem and modem.isOpen(tab.receive) then
  577.       modem.close(tab.receive)
  578.     end
  579.   end
  580.   if type(channel) == "number" then
  581.     self.receive = channel
  582.     screenClass.channels[self.receive] = self
  583.     if modem and not modem.isOpen(channel) then modem.open(channel) end
  584.   end
  585. end
  586.  
  587. screenClass.setSize = function(self) --Sets screen size
  588.   if self.side ~= "computer" and not self.term then self.term = peripheral.wrap(self.side) end
  589.   if not self.term.getSize() then --If peripheral is having problems/not there. Don't go further than term, otherwise index nil (maybe?)
  590.     debug("There is no term...")
  591.     self.updateDisplay = function() end --Do nothing on screen update, overrides class
  592.     return true
  593.   elseif not self.receive then
  594.     self:setBrokenDisplay() --This will prompt user to set channel
  595.   elseif self.send then --This allows for class inheritance
  596.     self:init() --In case objects have special updateDisplay methods --Remove function in case it exists, defaults to super
  597.   else --If the screen needs to have a handshake display
  598.     self:setHandshakeDisplay()
  599.   end
  600.   self.dim = { self.term.getSize()}
  601.   local tab = screenClass.sizes
  602.   for a=1, 2 do --Want x and y dim
  603.     for b=1, #tab[a] do --Go through all normal sizes, x and y individually
  604.       if tab[a][b] <= self.dim[a] then --This will set size higher until false
  605.         self.size[a] = b
  606.       end
  607.     end
  608.   end
  609.   local function isThing(toCheck, thing) --E.G. isThing(self.dim,"computer")
  610.     return toCheck[1] == tab[thing][1] and toCheck[2] == tab[thing][2]
  611.   end
  612.   self.isComputer = isThing(self.dim, "computer")
  613.   self.isTurtle = isThing(self.dim, "turtle")
  614.   self.isPocket = isThing(self.dim, "pocket")
  615.   self.acceptsInput = self.isComputer or self.isTurtle or self.isPocket
  616.   return self
  617. end
  618.  
  619. screenClass.setTheme = function(self, themeName, stopReset)
  620.   if not themes[themeName] then --If we don't have it already, try to load it
  621.     local fileName = themeName or ".." --.. returns false and I don't think you can name a file this
  622.     if fs.exists(themeFolder) then fileName = themeFolder..fileName end
  623.     if fs.exists(fileName) then
  624.       debug("Loading theme: ",fileName)
  625.       local file = fs.open(fileName, "r")
  626.       if not file then debug("Could not load theme '",themeName,"' file not found") end
  627.       parseTheme(file.readAll()) --Parses the text to make a theme, returns theme
  628.       file.close()
  629.       self.themeName = themeName:lower() --We can now set our themeName to the fileName
  630.     else
  631.       --Resets theme to super
  632.       if not stopReset then --This exists so its possible to set default theme without breaking world
  633.         self.themeName = nil
  634.         self.theme = nil
  635.       end
  636.       return false
  637.     end
  638.    else
  639.     self.themeName = themeName:lower()
  640.    end
  641.    self.theme = themes[self.themeName] --Now the theme is loaded or the function doesn't get here
  642.    return true
  643. end
  644.  
  645. --Adds text to the screen buffer
  646. screenClass.tryAddRaw = function(self, line, text, color, ...) --This will try to add text if Y dimension is a certain size
  647.   local doAdd = {...} --booleans for small, medium, and large
  648.   if type(text) ~= "string" then error("tryAddRaw got "..type(text)..", expected string",2) end
  649.   if not text then
  650.     debug("tryAddRaw got no string on line ",line)
  651.     return false
  652.   end
  653.   if type(color) ~= "table" then error("tryAddRaw did not get a color",2) end
  654.   --color = color or {text = colors.white}
  655.   for i=1, ySizes do --As of now there are 3 Y sizes
  656.     local test = doAdd[i]
  657.     if test == nil then test = doAdd[#doAdd] end --Set it to the last known setting if doesn't exist
  658.     if test and self.size[2] == i then --If should add this text for this screen size and the monitor is this size
  659.       if #text <= self.dim[1] then
  660.         self.toPrint[line] = {text = text, color = color}
  661.         return true
  662.       else
  663.         debug("Tried adding ",text," on line ",line," but was too long")
  664.       end
  665.     end
  666.   end
  667.   return false
  668. end
  669. screenClass.tryAdd = function(self, text, color,...) --Just a wrapper
  670.   return self:tryAddRaw(#self.toPrint+1, text, color, ...)
  671. end
  672. screenClass.tryAddC = function(self, text, color, ...) --Centered text
  673.   return self:tryAdd(center(text, self.dim[1]), color, ...)
  674. end
  675.  
  676. screenClass.reset = function(self,color)
  677.   color = color or self.theme.background
  678.   self:setColor(color)
  679.   self.term.clear()
  680.   self.term.setCursorPos(1,1)
  681. end
  682. screenClass.say = function(self, text, color, line)
  683.   local currColor = self.backgroundColor
  684.   color = color or debug("Printing ",text," but had no themeColor: ",self.theme.name) or {} --Set default for nice error, alert that errors occur
  685.   self:setColor(color)
  686.   local line = line or ({self.term.getCursorPos()})[2] or self:setSize() or 1 --If current yPos not found, sets screen size and moves cursor to 1
  687.   if doDebug and #text > self.dim[1] then error("Tried printing: '"..text.."', but was too big") end
  688.   self.term.setCursorPos(1,line)
  689.   for i=1, self.dim[1]-#text do --This is so the whole line's background gets filled.
  690.     text = text.." "
  691.   end
  692.   self.term.write(text)
  693.   self.term.setCursorPos(1, line+1)
  694. end
  695. screenClass.pushScreenUpdates = function(self)
  696.   for i=1, self.dim[2] do
  697.     local tab = self.toPrint[i]
  698.     if tab then
  699.       self:say(tab.text, tab.color, i)
  700.     end
  701.   end
  702.   self.term.setCursorPos(1,self.dim[2]) --So we can see errors
  703. end
  704.  
  705. screenClass.updateNormal = function(self) --This is the normal updateDisplay function
  706.   local str = tostring
  707.   self.toPrint = {} --Reset table
  708.   local message, theme = self.rec, self.theme
  709.  
  710.   if not self.isDone then --Normally
  711.    
  712.      
  713.     if self.size[1] == 1 then --Small Width Monitor
  714.       if not self:tryAdd(message.label, theme.title, false, false, true) then --This will be a title, basically
  715.         self:tryAdd("Quarry!", theme.title, false, false, true)
  716.       end
  717.      
  718.       self:tryAdd("-Fuel-", theme.subtitle , false, true, true)
  719.       if not self:tryAdd(str(message.fuel), theme.extra, false, true, true) then --The fuel number may be bigger than the screen
  720.         self:tryAdd("A lot", theme.extra, false, true, true)
  721.       end
  722.      
  723.       self:tryAdd("--%%%--", theme.subtitle, false, true, true)
  724.       self:tryAdd(alignR(str(message.percent).."%", 7), theme.pos , false, true, true) --This can be an example. Print (receivedMessage).percent in blue on all different screen sizes
  725.       self:tryAdd(center(str(message.percent).."%", self.dim[1]), theme.pos, true, false) --I want it to be centered on 1x1
  726.      
  727.       self:tryAdd("--Pos--", theme.subtitle, false, true, true)
  728.       self:tryAdd("X:"..alignR(str(message.xPos), 5), theme.pos, true)
  729.       self:tryAdd("Z:"..alignR(str(message.zPos), 5), theme.pos , true)
  730.       self:tryAdd("Y:"..alignR(str(message.layersDone), 5), theme.pos , true)
  731.      
  732.       if not self:tryAdd(str(message.x).."x"..str(message.z).."x"..str(message.layers), theme.dim , true, false) then --If you can't display the y, then don't
  733.         self:tryAdd(str(message.x).."x"..str(message.z), theme.dim , true, false)
  734.       end
  735.       self:tryAdd("--Dim--", theme.subtitle, false, true, true)
  736.       self:tryAdd("X:"..alignR(str(message.x), 5), theme.dim, false, true, true)
  737.       self:tryAdd("Z:"..alignR(str(message.z), 5), theme.dim, false, true, true)
  738.       self:tryAdd("Y:"..alignR(str(message.layers), 5), theme.dim, false, true, true)
  739.      
  740.       self:tryAdd("-Extra-", theme.subtitle, false, false, true)
  741.       self:tryAdd(alignR(textutils.formatTime(os.time()):gsub(" ","").."", 7), theme.extra, false, false, true) --Adds the current time, formatted, without spaces.
  742.       self:tryAdd("Open:"..alignR(str(message.openSlots),2), theme.extra, false, false, true)
  743.       self:tryAdd("Dug"..alignR(str(message.mined), 4), theme.extra, false, false, true)
  744.       self:tryAdd("Mvd"..alignR(str(message.moved), 4), theme.extra, false, false, true)
  745.       if message.chestFull then
  746.         self:tryAdd("ChstFll", theme.error, false, false, true)
  747.       end
  748.      
  749.     end
  750.     if self.size[1] == 2 then --Medium Monitor
  751.       if not self:tryAdd(message.label, theme.title, false, false, true) then --This will be a title, basically
  752.         self:tryAdd("Quarry!", theme.title, false, false, true)
  753.       end
  754.      
  755.       self:tryAdd("-------Fuel-------", theme.subtitle , false, true, true)
  756.       if not self:tryAdd(str(message.fuel), theme.extra, false, true, true) then --The fuel number may be bigger than the screen
  757.         self.toPrint[#self.toPrint] = nil
  758.         self:tryAdd("A lot", theme.extra, false, true, true)
  759.       end
  760.      
  761.       self:tryAdd(str(message.percent).."% Complete", theme.pos , true) --This can be an example. Print (receivedMessage).percent in blue on all different screen sizes
  762.      
  763.       self:tryAdd("-------Pos--------", theme.subtitle, false, true, true)
  764.       self:tryAdd("X Coordinate:"..alignR(str(message.xPos), 5), theme.pos, true)
  765.       self:tryAdd("Z Coordinate:"..alignR(str(message.zPos), 5), theme.pos , true)
  766.       self:tryAdd("On Layer:"..alignR(str(message.layersDone), 9), theme.pos , true)
  767.      
  768.       if not self:tryAdd("Size: "..str(message.x).."x"..str(message.z).."x"..str(message.layers), theme.dim , true, false) then --This is already here... I may as well give an alternative for those people with 1000^3quarries
  769.         self:tryAdd(str(message.x).."x"..str(message.z).."x"..str(message.layers), theme.dim , true, false)
  770.       end
  771.       self:tryAdd("-------Dim--------", theme.subtitle, false, true, true)
  772.       self:tryAdd("Total X:"..alignR(str(message.x), 10), theme.dim, false, true, true)
  773.       self:tryAdd("Total Z:"..alignR(str(message.z), 10), theme.dim, false, true, true)
  774.       self:tryAdd("Total Layers:"..alignR(str(message.layers), 5), theme.dim, false, true, true)
  775.       self:tryAdd("Volume"..alignR(str(message.volume),12), theme.dim, false, false, true)
  776.      
  777.       self:tryAdd("------Extras------", theme.subtitle, false, false, true)
  778.       self:tryAdd("Time: "..alignR(textutils.formatTime(os.time()):gsub(" ","").."", 12), theme.extra, false, false, true) --Adds the current time, formatted, without spaces.
  779.       self:tryAdd("Used Slots:"..alignR(str(16-message.openSlots),7), theme.extra, false, false, true)
  780.       self:tryAdd("Blocks Mined:"..alignR(str(message.mined), 5), theme.extra, false, false, true)
  781.       self:tryAdd("Spaces Moved:"..alignR(str(message.moved), 5), theme.extra, false, false, true)
  782.       if message.status then
  783.         self:tryAdd(message.status, theme.info, false, false, true)
  784.       end
  785.       if message.chestFull then
  786.         self:tryAdd("Chest Full, Fix It", theme.error, false, true, true)
  787.       end
  788.     end
  789.     if self.size[1] >= 3 then --Large or larger screens
  790.       if not self:tryAdd(message.label..alignR(" Turtle #"..str(message.id),self.dim[1]-#message.label), theme.title, true) then
  791.         self:tryAdd("Your turtle's name is long...", theme.title, true)
  792.       end
  793.       self:tryAdd("Fuel: "..alignR(str(message.fuel),self.dim[1]-6), theme.extra, true)
  794.      
  795.       self:tryAdd("Percentage Done: "..alignR(str(message.percent).."%",self.dim[1]-17), theme.pos, true)
  796.      
  797.       local var1 = math.max(#str(message.x), #str(message.z), #str(message.layers))
  798.       local var2 = (self.dim[1]-6-var1+3)/3
  799.       self:tryAdd("Pos: "..alignR(" X:"..alignR(str(message.xPos),var1),var2)..alignR(" Z:"..alignR(str(message.zPos),var1),var2)..alignR(" Y:"..alignR(str(message.layersDone),var1),var2), theme.pos, true)
  800.       self:tryAdd("Size:"..alignR(" X:"..alignR(str(message.x),var1),var2)..alignR(" Z:"..alignR(str(message.z),var1),var2)..alignR(" Y:"..alignR(str(message.layers),var1),var2), theme.dim, true)
  801.       self:tryAdd("Volume: "..str(message.volume), theme.dim, false, true, true)
  802.       self:tryAdd("",{}, false, false, true)
  803.       self:tryAdd(center("____---- EXTRAS ----____",self.dim[1]), theme.subtitle, false, false, true)
  804.       self:tryAdd(center("Time:"..alignR(textutils.formatTime(os.time()),8), self.dim[1]), theme.extra, false, true, true)
  805.       self:tryAdd(center("Current Day: "..str(os.day()), self.dim[1]), theme.extra, false, false, true)
  806.       self:tryAdd("Used Inventory Slots: "..alignR(str(16-message.openSlots),self.dim[1]-22), theme.extra, false, true, true)
  807.       self:tryAdd("Blocks Mined: "..alignR(str(message.mined),self.dim[1]-14), theme.extra, false, true, true)
  808.       self:tryAdd("Blocks Moved: "..alignR(str(message.moved),self.dim[1]-14), theme.extra, false, true, true)
  809.       self:tryAdd("Distance to Turtle: "..alignR(str(message.distance), self.dim[1]-20), theme.extra, false, false, true)
  810.       self:tryAdd("Actual Y Pos (Not Layer): "..alignR(str(message.yPos), self.dim[1]-26), theme.extra, false, false, true)
  811.      
  812.       if message.chestFull then
  813.         self:tryAdd("Dropoff is Full, Please Fix", theme.error, false, true, true)
  814.       end
  815.       if message.foundBedrock then
  816.         self:tryAdd("Found Bedrock! Please Check!!", theme.error, false, true, true)
  817.       end
  818.       if message.status then
  819.         self:tryAdd("Turtle Status: "..message.status, theme.info, false, true, true)
  820.       end
  821.       if message.isAtChest then
  822.         self:tryAdd("Turtle is at home chest", theme.info, false, true, true)
  823.       end
  824.       if message.isGoingToNextLayer then
  825.         self:tryAdd("Turtle is going to next layer", theme.info, false, true, true)
  826.       end
  827.     end
  828.   else --If is done
  829.     if self.size[1] == 1 then --Special case for small monitors
  830.       self:tryAdd("Done", theme.title, true)
  831.       self:tryAdd("Dug"..alignR(str(message.mined),4), theme.pos, true)
  832.       self:tryAdd("Fuel"..alignR(str(message.fuel),3), theme.pos, true)
  833.       self:tryAdd("-------", theme.subtitle, false,true,true)
  834.       self:tryAdd("Turtle", theme.subtitle, false, true, true)
  835.       self:tryAdd(center("is", self.dim[1]), theme.subtitle, false, true, true)
  836.       self:tryAdd(center("Done!", self.dim[1]), theme.subtitle, false, true, true)
  837.     else
  838.       self:tryAdd("Done!", theme.title, true)
  839.       self:tryAdd("Blocks Dug: "..str(message.mined), theme.inverse, true)
  840.       self:tryAdd("Cobble Dug: "..str(message.cobble), theme.pos, false, true, true)
  841.       self:tryAdd("Fuel Dug: "..str(message.fuelblocks), theme.pos, false, true, true)
  842.       self:tryAdd("Others Dug: "..str(message.other), theme.pos, false, true, true)
  843.       self:tryAdd("Curr Fuel: "..str(message.fuel), theme.inverse, true)
  844.     end
  845.   end
  846. end
  847. screenClass.updateHandshake = function(self)
  848.   self.toPrint = {}
  849.   local half = math.ceil(self.dim[2]/2)
  850.   if self.size[1] == 1 then --Not relying on the parameter system because less calls
  851.     self:tryAddRaw(half-2, "Waiting", self.theme.error, true)
  852.     self:tryAddRaw(half-1, "For Msg", self.theme.error, true)
  853.     self:tryAddRaw(half, "On Chnl", self.theme.error, true)
  854.     self:tryAddRaw(half+1, tostring(self.receive), self.theme.error, true)
  855.   else
  856.     local str = "for"
  857.     if self.size[1] == 2 then str = "4" end--Just a small grammar change
  858.     self:tryAddRaw(half-2, "", self.theme.error, true) --Filler
  859.     self:tryAddRaw(half-1, center("Waiting "..str.." Message", self.dim[1]), self.theme.error, true)
  860.     self:tryAddRaw(half, center("On Channel "..tostring(self.receive), self.dim[1]), self.theme.error, true)
  861.     self:tryAddRaw(half+1, "",self.theme.error, true)
  862.   end
  863. end
  864. screenClass.updateBroken = function(self) --If screen needs channel
  865.   self.toPrint = {}
  866.   if self.size[1] == 1 then
  867.     self:tryAddC("No Rec", self.theme.pos, false, true, true)
  868.     self:tryAddC("Channel", self.theme.pos, false, true, true)
  869.     self:tryAddC("-------", self.theme.title, false, true, true)
  870.     self:tryAddC("On Comp", self.theme.info, true)
  871.     self:tryAddC("Type:", self.theme.info, true)
  872.     self:tryAddC("RECEIVE", self.theme.command, true)
  873.     if not self:tryAddC(self.side:upper(), self.theme.command, true) then --If we can't print the full side
  874.       self:tryAddC("[side]",self.theme.command, true)
  875.     end
  876.     self:tryAddC("[Chnl]", self.theme.command, true)
  877.   else
  878.     self:tryAddC("No receiving", self.theme.pos, false, true, true)
  879.     self:tryAddC("channel for", self.theme.pos, false, true, true)
  880.     self:tryAddC("this screen", self.theme.pos, false, true, true)
  881.     self:tryAddC("-----------------", self.theme.title, false, true, true)
  882.     self:tryAddC("On main computer,", self.theme.info, true)
  883.     self:tryAddC("Type:", self.theme.info, true)
  884.     self:tryAdd("", self.theme.command, false, true, true)
  885.     self:tryAddC('"""', self.theme.command, false, true, true)
  886.     self:tryAddC("RECEIVE", self.theme.command, true)
  887.     if not self:tryAddC(self.side:upper(), self.theme.command, true) then --If we can't print the full side
  888.       self:tryAddC("[side]",self.theme.command, true)
  889.     end
  890.     self:tryAddC("[desired channel]", self.theme.command, true)
  891.     self:tryAddC('"""', self.theme.command, false, true, true)
  892.   end
  893. end
  894.  
  895. screenClass.updateDisplay = screenClass.updateNormal --Update screen method is normally this one
  896.  
  897. --Misc
  898. screenClass.init = function(self) --Currently used by computer screen to replace its original method
  899.   self.updateDisplay = self.updateNormal --This defaults to super if doesn't exist
  900. end
  901. screenClass.setHandshakeDisplay = function(self)
  902.   self.updateDisplay = self.updateHandshake --Sets update to handshake version, defaults to super if doesn't exist
  903. end
  904. screenClass.setBrokenDisplay = function(self)
  905.   self.updateDisplay = self.updateBroken
  906. end
  907.  
  908.  
  909. local function wrapPrompt(prefix, str, dim) --Used to wrap the commandString
  910.   return prefix..str:sub(roundNegative(#str+#prefix-computer.dim[1]+2), -1).."_" --it is str + 2 because we add in the "_"
  911. end
  912.  
  913. local function updateAllScreens()
  914.   for a, b in pairs(screenClass.sides) do
  915.     b:updateDisplay()
  916.     b:reset()
  917.     b:pushScreenUpdates()
  918.   end
  919. end
  920. --Rednet
  921. local function newMessageID()
  922.   return math.random(1,2000000000) --1 through 2 billion. Good enough solution
  923. end
  924. local function transmit(send, receive, message, legacy, fingerprint)
  925.   fingerprint = fingerprint or replyFingerprint
  926.   if legacy then
  927.     modem.transmit(send, receive, message)
  928.   else
  929.     modem.transmit(send, receive, {message = message, id = newMessageID(), fingerprint = fingerprint})
  930.   end
  931. end
  932.  
  933. --QuadRotor
  934. local function launchQuad(message)
  935.   if quadEnabled and message.emergencyLocation then --This means the turtle is out of fuel. Also that it sent its two initial positions
  936.     local movement = {}
  937.     local function add(what) table.insert(movement,what) end
  938.     add(quadDirection) --Get to the fuel chest
  939.     add("suck")
  940.     add(quadDirection) --So it can properly go down/up first
  941.     local function go(dest, orig, firstMove) --Goes to a place. firstMove because I'm lazy. Its for getting away from computer. If false, its the second move so go one above turtle. If nothing then nothing
  942.       local distX, distY, distZ = dest[1]-orig[1], dest[2]-orig[2], dest[3]-orig[3]
  943.       if firstMove then
  944.         distX = distX - 3 * (quadDirection == "east" and 1 or (quadDirection == "west" and -1 or 0))
  945.         distZ = distZ - 3 * (quadDirection == "south" and 1 or (quadDirection == "north" and -1 or 0))
  946.         distY = distY - 1 --Because the quad is a block above the first thing
  947.       elseif firstMove == false then
  948.         local num = 2
  949.         if message.layersDone  <= 1 then
  950.           num = 1
  951.         end
  952.         distY = distY + num * (distY < 0 and 1 or -1) --This is to be above the turtle and accounts for invert
  953.       end
  954.       add((distY > 0 and "up" or "down").." "..tostring(math.abs(distY)))
  955.       add((distX > 0 and "east" or "west").." "..tostring(math.abs(distX)))
  956.       add((distZ > 0 and "south" or "north").." "..tostring(math.abs(distZ)))
  957.       if firstMove == false and message.layersDone > 1 then
  958.         add(distY < 0 and "down" or "up") --This is so it goes into the turtle's proper layer (invert may or may not work, actually)
  959.       end
  960.     end
  961.     debug("Location Types")
  962.     debug(computerLocation)
  963.     debug(message.firstPos)
  964.     debug(message.secondPos)
  965.     debug(message.emergencyLocation)
  966.     go(message.firstPos, computerLocation, true) --Get to original position of turtle
  967.     go(message.secondPos,message.firstPos) --Get into quarry
  968.     go(message.emergencyLocation, message.secondPos, false)
  969.    
  970.     add("drop")
  971.     add("return")
  972.     for a,b in pairs(movement) do
  973.       debug(a,"   ",b)
  974.     end
  975.     quadBase.flyQuad(movement) --Note, if there are no quadrotors, nothing will happen and the turtle will sit forever
  976.    
  977.   end
  978. end
  979.  
  980. --==SET UP==
  981. clearScreen()
  982. print("Welcome to Quarry Receiver!")
  983. sleep(1)
  984.  
  985. --==ARGUMENTS==
  986.  
  987. --[[
  988. Parameters:
  989.   -help/-?/help/?
  990.   -receiveChannel [channel] --For only the main screen
  991.   -theme --Sets a default theme
  992.   -screen [side] [channel] [theme]
  993.   -station
  994.   -auto --Prompts for all sides, or you can supply a list of receive channels for random assignment!
  995.   -colorEditor
  996.   -quad [cardinal direction] --This looks for a quadrotor from the quadrotors mod. The direction is of the fuel chest.
  997. ]]
  998.  
  999. --tArgs init
  1000. local parameters = {} --Each command is stored with arguments
  1001. local parameterIndex = 0 --So we can add new commands to the right table
  1002. for a,b in ipairs(tArgs) do
  1003.   val = b:lower()
  1004.   if val == "help" or val == "-help" or val == "?" or val == "-?" or val == "usage" or val == "-usage" then
  1005.     displayHelp() --To make
  1006.     error("The End of Help",0)
  1007.   end
  1008.   if val:match("^%-") then
  1009.     parameterIndex = parameterIndex + 1
  1010.     parameters[parameterIndex] = {val:sub(2)} --Starts a chain with the command. Can be unpacked later
  1011.     parameters[val:sub(2)] = {} --Needed for force/before/after parameters
  1012.   elseif parameterIndex ~= 0 then
  1013.     table.insert(parameters[parameterIndex], b) --b because arguments should be case sensitive for filenames
  1014.     table.insert(parameters[parameters[parameterIndex][1]], b) --Needed for force/after parameters
  1015.   end
  1016. end
  1017.  
  1018. if parameters.v or parameters.verbose then --Why not
  1019.   doDebug = true
  1020. end
  1021.  
  1022. for i=1,#parameters do
  1023.   debug("Parameter: ",parameters[i][1])
  1024. end
  1025.  
  1026. --Options before screen loads
  1027. if parameters.theme then
  1028.   screenClass:setTheme(parameters.theme[1])
  1029. end
  1030.  
  1031. if parameters.modem then
  1032.   modemSide = parameters.modem[1]
  1033. end
  1034.  
  1035. if parameters.quad then
  1036.   if not parameters.quad[1] then parameters.quad[1] = "direction doesn't exist" end
  1037.   local dir = parameters.quad[1]:lower():sub(1,1)
  1038.   if quadDirections[dir] then
  1039.     quadEnabled = true
  1040.     quadDirection = quadDirections[dir]
  1041.   else
  1042.     clearScreen()
  1043.     print("Please specify the cardinal direction your quad station is in")
  1044.     print("Make sure you have a quad station on one side with a chest behind it, forming a line")
  1045.     print("Like this: [computer] [station] [fuel chest]")
  1046.     print("The program will now terminate")
  1047.     error("",0)
  1048.   end
  1049. end
  1050.  
  1051. --Init Modem
  1052. while not initModem() do
  1053.   clearScreen()
  1054.   print("No modem is connected, please attach one")
  1055.   if not peripheral.find then
  1056.     print("What side was that on?")
  1057.     modemSide = read()
  1058.   else
  1059.     os.pullEvent("peripheral")
  1060.   end
  1061. end
  1062. debug("Modem successfully connected!")
  1063.  
  1064. local function autoDetect(channels)
  1065.   if type(channels) ~= "table" then channels = {} end
  1066.   local tab = peripheral.getNames()
  1067.   local index = 1
  1068.   for i=1, #tab do
  1069.     if peripheral.getType(tab[i]) == "monitor" and not screenClass.sides[tab[i]] then
  1070.       screenClass.new(tab[i], channels[index]) --You can specify a list of channels in "auto" parameter
  1071.       index = index+1
  1072.     end
  1073.   end
  1074. end
  1075.  
  1076. --Init QuadRotor Station
  1077. if quadEnabled then
  1078.   local flag
  1079.   while not flag do
  1080.     for a,b in ipairs({"front","back","left","right","top"}) do
  1081.       if peripheral.isPresent(b) and peripheral.getType(b) == "quadbase" then
  1082.         quadBase = peripheral.wrap(b)
  1083.       end
  1084.     end
  1085.     clearScreen()
  1086.     if not quadBase then
  1087.       print("No QuadRotor Base Attached, please attach one")
  1088.     elseif quadBase.getQuadCount() == 0 then
  1089.       print("Please install at least one QuadRotor in the base")
  1090.     else
  1091.       flag = true
  1092.       debug("QuadBase successfully connected!")
  1093.     end
  1094.     if not gps.locate(5) then
  1095.       flag = false
  1096.       error("No GPS lock. Please make a GPS network to use quadrotors")
  1097.     else
  1098.       computerLocation = {gps.locate(5)}
  1099.       debug("GPS Location Acquired")
  1100.     end
  1101.   end
  1102. end
  1103.  
  1104. --Init Computer Screen Object (was defined at top)
  1105. computer = screenClass.new("computer", parameters.receivechannel and parameters.receivechannel[1])--This sets channel, checking if parameter exists
  1106.  
  1107. if parameters.auto then --This must go after computer declaration so computer ID is 1
  1108.   autoDetect(parameters.auto)
  1109.   parameters.station = true
  1110. end
  1111.  
  1112. computer.displayCommand = function(self)
  1113.   local sideString = ((defaultSide and " (") or "")..(defaultSide or "")..((defaultSide and ")") or "")
  1114.   if self.size == 1 then
  1115.     self:tryAddRaw(self.dim[2], wrapPrompt("Cmd"..sideString:sub(2,-2)..": ", commandString, self.dim[1]), self.theme.command, true)
  1116.   else
  1117.     self:tryAddRaw(self.dim[2], wrapPrompt("Command"..sideString..": ",commandString, self.dim[1]), self.theme.command, true) --This displays the last part of a string.
  1118.   end
  1119. end
  1120. --Technically, you could have any screen be the station, but oh well.
  1121. --Initializing the computer screen
  1122. if parameters.station then --This will set the screen update to display stats on all other monitors. For now it does little
  1123.   computer:setChannel() --So it doesn't receive messages
  1124.   computer.isStation = true --For updating
  1125.    
  1126.   computer.updateNormal = function(self)--This gets set in setSize
  1127.     self.toPrint = {}
  1128.     local part = math.floor(self.dim[1]/4)-1
  1129.     self:tryAdd(alignL(" ID",part).."| "..alignL("Side",part).."| "..alignL("Channel",part).."| "..alignL("Theme",part), self.theme.title, false, true, true) --Headings
  1130.     local line = ""
  1131.     for i=1, self.dim[1] do line = line.."-" end
  1132.     self:tryAdd(line, self.theme.title, false, true, true)
  1133.     for a,b in ipairs(screenClass.screens) do
  1134.       if b.side ~= "REMOVED" then
  1135.         self:tryAdd(" "..alignL(b.id,part-1).."| "..alignL(b.side,part).."| "..alignL(b.receive, part).."| "..alignL(b.theme.name,part), self.theme.info, false, true, true) --Prints info about all screens
  1136.       end
  1137.     end
  1138.     self:displayCommand()
  1139.   end
  1140.   computer.setHandshakeDisplay = computer.init --Handshake is same as regular
  1141.   computer.setBrokenDisplay = computer.init
  1142. elseif parameters.coloreditor then
  1143.  
  1144.   computer:setChannel() --So it doesn't receive messages
  1145.   computer.isStation = true --So we can't assign a channel
  1146.  
  1147.   computer.updateNormal = function(self) --This is only for editing colors
  1148.     self.toPrint = {}
  1149.     for a,b in pairs(self.theme) do
  1150.       if type(b) == "table" then
  1151.         self:tryAdd(a, b, true)
  1152.       end
  1153.     end
  1154.     self:displayCommand()
  1155.   end
  1156.   computer.updateHandshake = computer.updateNormal
  1157.   computer.updateBroken = computer.updateNormal
  1158. else --If computer is a regular screen
  1159.   computer.updateNormal = function(self)
  1160.     screenClass.updateDisplay(self)
  1161.     computer:displayCommand()
  1162.   end
  1163.   computer.updateHandshake = function(self) --Not in setHandshake because that func checks object updateHandshake
  1164.     screenClass.updateHandshake(self)
  1165.     computer:displayCommand()
  1166.   end
  1167.   computer.updateBroken = function(self)
  1168.     screenClass.updateBroken(self)
  1169.     computer:displayCommand()
  1170.   end
  1171. end
  1172. computer:setSize() --Update changes made to display functions
  1173.  
  1174.  
  1175. for i=1, #parameters do --Do actions for parameters that can be used multiple times
  1176.   local command, args = parameters[i][1], parameters[i] --For ease
  1177.   if command == "screen" then
  1178.     if not screenClass.sides[args[2]] then --Because this screwed up the computer
  1179.       local a = screenClass.new(args[2], args[3], args[4])
  1180.       debug(type(a))
  1181.     else
  1182.       debug("Overwriting existing screen settings for '",args[2],"'")
  1183.       local a = screenClass.sides[args[2]]
  1184.       a:setChannel(tonumber(args[3]))
  1185.       a:setTheme(args[4])
  1186.     end
  1187.   end
  1188.  
  1189. end
  1190.  
  1191. for a,b in pairs(screenClass.sides) do debug(a) end
  1192.  
  1193. --==FINAL CHECKS==
  1194.  
  1195. --Updating all screen for first time and making sure channels are open
  1196. for a, b in pairs(screenClass.sides) do
  1197.   if b.receive then --Because may not have channel
  1198.     if not modem.isOpen(b.receive) then modem.open(b.receive); debug("Opening channel ",b.receive) end
  1199.   end
  1200.   b:setSize()
  1201.   b:updateDisplay()--Finish initialization process
  1202.   b:reset()
  1203.   b:pushScreenUpdates()
  1204. end
  1205.  
  1206. --Handshake will be handled in main loop
  1207.  
  1208. --[[Workflow
  1209.   Wait for events
  1210.   modem_message
  1211.     if valid channel and valid message, update appropriate screen
  1212.   key
  1213.     if any letter, add to command string if room.
  1214.     if enter key
  1215.       if valid self command, execute command. Commands:
  1216.         command [side] [command] --If only one screen, then don't need channel. Send a command to a turtle
  1217.         screen [side] [channel] [theme] --Links a new screen to use.
  1218.         remove [side] --Removes a screen
  1219.         theme [themeName] --Sets the default theme
  1220.         theme [side] [themeName] --Changes this screen's theme
  1221.         savetheme [new name] [themeName]
  1222.         color [side/theme] [colorName] [textColor] [backgroundColor]
  1223.         side [side] --Sets a default side, added to prompts
  1224.         set [string] --Sets a default command, added to display immediately
  1225.         receive [side] [newChannel] --Changes the channel of the selected screen
  1226.         send [side] [newChannel]
  1227.         auto --Automatically adds screens not connected
  1228.         exit/quit/end
  1229.   peripheral_detach
  1230.     check what was lost, if modem, set to nil. If screen side, do screen:setSize()
  1231.   peripheral
  1232.     check if screen side already added
  1233.       reset screen size
  1234.   monitor_resize
  1235.     resize proper screen
  1236.   monitor_touch
  1237.     if screen already added
  1238.       select screen on main computer
  1239.     else
  1240.       add screen
  1241.  
  1242. ]]
  1243.  
  1244. --Modes: 1 - Sided, 2 - Not Sided, 3 - Both sided and not
  1245. local validCommands = {command = 1, screen = 2, remove = 1, theme = 3, exit = 2, quit = 2, ["end"] = 2, color = 3, side = 2, set = 2, receive = 1, send = 1, savetheme = 2,
  1246.                        auto = 2, verbose = 2, quiet = 2}
  1247. while continue do
  1248.   local event, par1, par2, par3, par4, par5 = os.pullEvent()
  1249.   ----MESSAGE HANDLING----
  1250.   if event == "modem_message" and screenClass.channels[par2] then --If we got a message for a screen that exists
  1251.     local screen = screenClass.channels[par2] --For convenience
  1252.     if not screen.send then --This is the handshake
  1253.       debug("\nChecking handshake. Received: ",par4)
  1254.       local flag = false
  1255.       if par4 == expectedMessage then --Legacy quarries don't accept receiver dropping in mid-run
  1256.         screen.legacy = true --Accepts serialized tables
  1257.         flag = true
  1258.       elseif type(par4) == "table" and par4.fingerprint == expectedFingerprint then --Don't care about expected message, allows us to start receiver mid-run, fingerprint should be pretty specific
  1259.         screen.legacy = false
  1260.         flag = true
  1261.       end
  1262.      
  1263.       if flag then
  1264.         debug("Screen ",screen.side," received a handshake")
  1265.         screen.send = par3
  1266.         screen:setSize() --Resets update method to proper since channel is set
  1267.         debug("Sending back on ",screen.send)
  1268.         transmit(screen.send,screen.receive, replyMessage, screen.legacy)
  1269.       end
  1270.    
  1271.     else --Everything else is for regular messages
  1272.      
  1273.       local rec
  1274.       if screen.legacy then --We expect strings here
  1275.         if type(par4) == "string" then --Otherwise its not ours
  1276.           if par4 == "stop" then --This is the stop message. All other messages will be ending ones
  1277.             screen.isDone = true
  1278.           elseif par4 == expectedMessage then --We support dropping in mid-run
  1279.             debug("Screen ",screen.side," received mid-run handshake")
  1280.             transmit(screen.send,screen.receive, replyMessage, screen.legacy)
  1281.           elseif textutils.unserialize(par4) then
  1282.             rec = textutils.unserialize(par4)
  1283.             rec.distance = par5
  1284.           end
  1285.         end
  1286.       elseif type(par4) == "table" and par4.fingerprint == expectedFingerprint then --Otherwise, we check if it is valid message
  1287.        
  1288.         if type(par4.message) == "table" then
  1289.           rec = par4.message
  1290.           if not par4.distance then --This is cool because it can add distances from the repeaters
  1291.             rec.distance = par5
  1292.           else
  1293.             rec.distance = par4.distance + par5
  1294.           end
  1295.           if rec.isDone then
  1296.             screen.isDone = true
  1297.           end
  1298.         elseif par4.message == expectedMessage then
  1299.           debug("Screen ",screen.side," received mid-run handshake")
  1300.           transmit(screen.send,screen.receive, replyMessage, screen.legacy)
  1301.         else
  1302.           debug("Message received did not contain table")
  1303.         end
  1304.       end
  1305.        
  1306.       if rec then
  1307.         rec.distance = math.floor(rec.distance)
  1308.         rec.label = rec.label or "Quarry!"
  1309.         screen.rec = rec --Set the table
  1310.         --Updating screen occurs outside of the if
  1311.         local toSend
  1312.         if screen.queuedMessage then
  1313.           toSend = screen.queuedMessage
  1314.           screen.queuedMessage = nil
  1315.         else
  1316.           toSend = replyMessage
  1317.         end
  1318.         transmit(screen.send,screen.receive, toSend, screen.legacy) --Send reply message for turtle
  1319.       end
  1320.      
  1321.     end
  1322.    
  1323.     launchQuad(screen.rec) --Launch the Quad!
  1324.    
  1325.     screen:updateDisplay() --isDone is queried inside this
  1326.     screen:reset(screen.theme.background)
  1327.     screen:pushScreenUpdates() --Actually write things to screen
  1328.    
  1329.  
  1330.   ----KEY HANDLING----
  1331.   elseif event == "key" and keyMap[par1] then
  1332.     local key = keyMap[par1]
  1333.     if key ~= "enter" then --If we aren't submitting a command
  1334.       if key == "backspace" then
  1335.         if #commandString > 0 then
  1336.           commandString = commandString:sub(1,-2)
  1337.         end
  1338.       elseif key == "up" then
  1339.         commandString = lastCommand or commandString --Set to last command, or do nothing if it doesn't exist
  1340.       elseif key == "down" then
  1341.         commandString = "" --If key down, clear
  1342.       elseif #key == 1 then
  1343.         commandString = commandString..key
  1344.       end
  1345.     --ALL THE COMMANDS
  1346.     else --If we are submitting a command
  1347.       lastCommand = commandString --For using up arrow
  1348.       local args = {}
  1349.       for a in commandString:gmatch("%S+") do --This captures all individual words in the command string
  1350.         args[#args+1] = a:lower()
  1351.       end
  1352.       local command = args[1]
  1353.       if validCommands[command] then --If it is a valid command...
  1354.         local commandType = validCommands[command]
  1355.         if commandType == 1 or commandType == 3 then --If the command requires a "side" like transmitting commands, versus setting a default
  1356.           if defaultSide then table.insert(args, 2, defaultSide) end
  1357.           local screen
  1358.           local test = screenClass.screens[tonumber(args[2])]
  1359.           if test and test.side ~= "REMOVED" then --This way we can specify IDs as well
  1360.             screen = test
  1361.           else
  1362.             screen = screenClass.sides[args[2]]
  1363.           end
  1364.           if screen then --If the side exists
  1365.             if command == "command" and screen.send then --If sending command to the turtle
  1366.               screen.queuedMessage = table.concat(args," ", 3) --Tells message handler to send appropriate message
  1367.               --transmit(screen.send, screen.receive, table.concat(args," ", 3), screen.legacy) --This transmits all text in the command with spaces. Duh this is handled when we get message
  1368.             end
  1369.  
  1370.             if command == "color" then
  1371.               screen.theme:addColor(args[3],colors[args[4]],colors[args[5]] )
  1372.               updateAllScreens() --Because we are changing a theme color which others may have
  1373.             end
  1374.             if command == "theme" then
  1375.               screen:setTheme(args[3])
  1376.             end
  1377.             if command == "send" then --This changes a send channel, and can also revert to handshake
  1378.               local chan = checkChannel(tonumber(args[3]) or -1)
  1379.               if chan then screen.send = chan else screen.send = nil end
  1380.               screen:setSize() --If on handshake, resets screen
  1381.             end
  1382.             if command == "receive" and not screen.isStation then
  1383.               local chan = checkChannel(tonumber(args[3]) or -1)
  1384.               if chan and not screenClass.channels[chan] then
  1385.                 if screen.receive then --Computer may not have a channel yet
  1386.                   modem.close(screen.receive)
  1387.                   screenClass.channels[screen.receive] = nil
  1388.                 end
  1389.                 modem.open(chan)
  1390.                 screen.receive = chan
  1391.                 screenClass.channels[chan] = screen
  1392.                 screen:setSize() --Update broken status
  1393.               end
  1394.             end
  1395.            
  1396.             if command == "remove" and screen.side ~= "computer" then --We don't want to remove the main display!
  1397.               print()
  1398.               screen:remove()
  1399.             else --Because if removed it does stupid things
  1400.               screen:reset()
  1401.               screen:updateDisplay()
  1402.               screen:pushScreenUpdates()
  1403.             end
  1404.           end
  1405.         end
  1406.         if commandType == 2 or commandType == 3 then--Does not require a screen side
  1407.           if command == "screen" and peripheral.getType(args[2]) == "monitor" then  --Makes sure there is a monitor on the screen side
  1408.             if not args[3] or not screenClass.channels[tonumber(args[3])] then --Make sure the channel doesn't already exist
  1409.               local mon = screenClass.new(args[2], args[3], args[4])
  1410.                 --args[3] is the channel  and will set broken display if it doesn't exist
  1411.                 --args[4] is the theme, and will default if doesn't exists.
  1412.               mon:updateDisplay()
  1413.               mon:reset()
  1414.               mon:pushScreenUpdates()
  1415.             end
  1416.           end
  1417.           if command == "theme" then
  1418.             screenClass:setTheme(args[2], true) --Otherwise this would set base theme to nil, erroring
  1419.             updateAllScreens()
  1420.           end
  1421.           if command == "color" and themes[args[2]] then
  1422.             themes[args[2]]:addColor(args[3],colors[args[4]],colors[args[5]])
  1423.             updateAllScreens() --Because any screen could have this theme
  1424.           end
  1425.           if command == "side" then
  1426.             if screenClass.sides[args[2]] then
  1427.               defaultSide = args[2]
  1428.             else
  1429.               defaultSide = nil
  1430.             end
  1431.           end
  1432.           if command == "set" then
  1433.             if args[2] then
  1434.               defaultCommand = table.concat(args," ",2)
  1435.               defaultCommand = defaultCommand:upper()
  1436.             else
  1437.               defaultCommand = nil
  1438.             end
  1439.           end
  1440.           if command == "savetheme" then
  1441.             if saveTheme(themes[args[2]], args[3]) then
  1442.               computer:tryAddRaw(computer.dim[2]-1, "Save Theme Succeeded!", computer.theme.inverse, true)
  1443.             else
  1444.               computer:tryAddRaw(computer.dim[2]-1, "Save Theme Failed!", computer.theme.inverse, true)
  1445.             end
  1446.             computer:reset()
  1447.             computer:pushScreenUpdates()
  1448.             sleep(1)
  1449.           end
  1450.           if command == "auto" then
  1451.             local newTab = copyTable(args) --This is so we can pass all additional words as channel numbers
  1452.             table.remove(newTab, 1)
  1453.             autoDetect(newTab)
  1454.             updateAllScreens()
  1455.           end
  1456.           if command == "verbose" then doDebug = true end
  1457.           if command == "quiet" then doDebug = false end
  1458.           if command == "quit" or command == "exit" or command == "end" then
  1459.             continue = false
  1460.           end
  1461.         end
  1462.       else
  1463.         debug("\nInvalid Command")
  1464.       end
  1465.       if defaultCommand then commandString = defaultCommand.." " else commandString = "" end --Reset command string because it was sent
  1466.     end
  1467.    
  1468.    
  1469.     --Update computer display (computer is only one that displays command string
  1470.     computer:updateDisplay() --Note: Computer's method automatically adds commandString to last line
  1471.     if not continue then computer:tryAddRaw(computer.dim[2]-1,"Program Exiting", computer.theme.inverse, false, true, true) end
  1472.     computer:reset()
  1473.     computer:pushScreenUpdates()
  1474.    
  1475.   elseif event == "monitor_resize" then
  1476.     local screen = screenClass.sides[par1]
  1477.     if screen then
  1478.       screen:setSize()
  1479.       screen:updateDisplay()
  1480.       screen:reset()
  1481.       screen:pushScreenUpdates()
  1482.     end
  1483.   elseif event == "monitor_touch" then
  1484.     local screen = screenClass.sides[par1]
  1485.     debug("Side: ",par1," touched")
  1486.     if screen then --This part is copied from the "side" command
  1487.       if defaultSide ~= par1 then
  1488.         defaultSide = par1
  1489.       else
  1490.         defaultSide = nil
  1491.       end
  1492.     else
  1493.       debug("Adding Screen")
  1494.       local mon = screenClass.new(par1)
  1495.       mon:reset()
  1496.       mon:updateDisplay()
  1497.       mon:pushScreenUpdates()
  1498.      
  1499.     end
  1500.  
  1501.   elseif event == "peripheral_detach" then
  1502.     local screen = screenClass.sides[par1]
  1503.     if screen then
  1504.       screen:setSize()
  1505.     end
  1506.     --if screen then
  1507.     --  screen:remove()
  1508.     --end
  1509.    
  1510.   elseif event == "peripheral" then
  1511.     local screen = screenClass.sides[par1]
  1512.     if screen then
  1513.       screen:setSize()
  1514.     end
  1515.     --Maybe prompt to add a new screen? I don't know
  1516.  
  1517.   end
  1518.  
  1519.   local flag = false --Saying all screens are done, must disprove
  1520.   local count = 0 --We want it to wait if no screens have channels
  1521.   for a,b in pairs(screenClass.channels) do
  1522.     count = count + 1
  1523.     if not b.isDone then
  1524.       flag = true
  1525.     end
  1526.   end
  1527.   if continue and count > 0 then --If its not already false from something else
  1528.     continue = flag
  1529.   end
  1530.  
  1531.   if computer.isStation and event ~= "key" then --So screen is properly updated
  1532.     computer:reset()
  1533.     computer:updateDisplay()
  1534.     computer:pushScreenUpdates()
  1535.   end
  1536.  
  1537.  
  1538. end
  1539.  
  1540. sleep(1.5)
  1541. for a in pairs(screenClass.channels) do
  1542.   modem.close(a)
  1543. end
  1544. for a, b in pairs(screenClass.sides) do
  1545.   if not b.isDone then --Otherwise we want it display the ending stats
  1546.     b:setTextColor(colors.white)
  1547.     b:setBackgroundColor(colors.black)
  1548.     b.term.clear()
  1549.     b.term.setCursorPos(1,1)
  1550.   end
  1551. end
  1552.  
  1553. local text --Fun :D
  1554. if computer.isComputer then text = "SUPER COMPUTER OS 9000"
  1555. elseif computer.isTurtle then text = "SUPER DIAMOND-MINING OS XXX"
  1556. elseif computer.isPocket then text = "PoCkEt OOS AMAYZE 65"
  1557. end
  1558. if text and not computer.isDone then
  1559.   computer:say(text, computer.theme.title,1)
  1560. else
  1561.   computer.term.setCursorPos(1,computer.dim[2])
  1562.   computer.term.clearLine()
  1563. end
  1564. --Down here shut down all the channels, remove the saved file, other cleanup stuff
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement