mrnosuch

invmon

Nov 25th, 2014
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 15.44 KB | None | 0 0
  1. -- stockman
  2. -- Inventory Monitor for ComputerCraft/AE ME System in TPPI
  3. -- version 0.9
  4. -- (c) Alex Shaffer / mrnosuch 2014
  5. -- [email protected] / nosuch.org
  6.  
  7. -- Assumptions:
  8.  
  9. --  Computer has two attached monitors, the primary monitor (2x3) and the energy monitor (1x2)
  10. --  Computer is connected to ME Controller and ME Fluid Terminal
  11. --  Device connections are set up in the installation part near the end (sides/device names)
  12.  
  13.  
  14. -- Known issues:
  15.  
  16. --  Cannot seem to monitor fluid levels, so removed this
  17. --  Nuclear fuel levels are hardcoded (yellorium/blutonium)
  18.  
  19.  
  20. -- Future plans:
  21.  
  22. --  Monitor assembler for being stuck.
  23. --  Use separate file for inventory config
  24. --  Prevent errors in communication with the ME system from halting program
  25.  
  26. ver = "0.9"
  27.  
  28.  
  29.  
  30. function inventoryConfig()
  31.  
  32.     invConfig = {}
  33.    
  34.     -- set up the items you want to monitor below
  35.     -- stock is minimum to keep on hand
  36.     -- order is the quantity used to request crafting, set to 0 if ME Assembler cannot craft.
  37.     -- priority determines what should be crafted/listed first, lower is more urgent (1-9)
  38.     -- It is recommended that items which are slow to craft (chipsets, for instance) are
  39.     -- given lower priority, so quick items can be made first
  40.     -- item names should be 16 characters or less
  41.  
  42.     -- NameMax"1234567890123456"
  43.  
  44.     invConfig["Certus Quartz"] = { id = 4362, meta = 6, stock = 320, order = 0, priority = 1 }
  45.     invConfig["Nether Quartz"] = { id = 406, meta = 0, stock = 320, order = 0, priority = 1 }
  46.     invConfig["N. Quartz Dust"] = { id = 4362, meta = 22, stock = 320, order = 32, priority = 5 }
  47.     invConfig["C. Quartz Dust"] = { id = 4362, meta = 7, stock = 320, order = 32, priority = 5 }
  48.     invConfig["Silicon"] = { id = 4362, meta = 13, stock = 128, order = 32, priority = 5 }
  49.     invConfig["Fluix Dust"] = { id = 4362, meta = 14, stock = 256, order = 64, priority = 5 }
  50.     invConfig["Glass"] = { id = 20, meta = 0, stock = 640, order = 64, priority = 5 }
  51.     invConfig["Glass Pane"] = { id = 102, meta = 0, stock = 320, order = 64, priority = 5 }
  52.     invConfig["Fused Quartz"] = { id = 704, meta = 0, stock = 320, order = 64, priority = 5 }
  53.     invConfig["Snowball"] = { id = 332, meta = 0, stock = 128, order = 0, priority = 1 }
  54.     invConfig["Sand"] = { id = 12, meta = 0, stock = 1024, order = 0 , priority = 1 }
  55.     invConfig["ME Blank Patt."] = { id = 4362, meta = 16, stock = 16, order = 1, priority = 5 }
  56.     invConfig["Turbine Rotor"] = { id = 7810, meta = 0, stock = 2, order = 1, priority = 4 }
  57.     invConfig["Bucket"] = { id = 325, meta = 0, stock = 8, order = 1, priority = 5 }
  58.     invConfig["ME Basic Proc."] = { id = 4362, meta = 18, stock = 16, order = 1 , priority = 6 }
  59.     invConfig["ME Adv. Proc."] = { id = 4362, meta = 19, stock = 16, order = 1 , priority = 6 }
  60.     invConfig["RS Gold Chip."] = { id = 19373, meta = 2, stock = 128, order = 1, priority = 9 }
  61.     invConfig["ME Cable"] = { id = 852, meta = 14, stock = 64, order = 1, priority = 5 }
  62.     invConfig["Bronze Ingot"] = { id = 30067, meta = 2, stock = 128, order = 1, priority = 6 }
  63.     invConfig["Bronze Gear"] = { id = 31968, meta = 0, stock = 16, order = 1, priority = 5 }
  64.  
  65.     invConfig["ME Prc Exprt Bus"] = { id = 852, meta = 0, stock = 8, order = 1, priority = 6 }
  66.     invConfig["ME Import Bus"] = { id = 853, meta = 3, stock = 8, order = 1, priority = 6 }
  67.  
  68.     -- procedurally add the item name to the item info
  69.    
  70.     -- it makes sense to use the item name as the key for the master list
  71.     -- but when we reference the item details in secondary arrays and tables
  72.     -- we may use other indexes/keys
  73.     invCount = 0
  74.  
  75.     for itemName,itemDetails in pairs(invConfig) do
  76.         itemDetails["name"]=itemName
  77.         invCount = invCount + 1
  78.     end
  79.  
  80.     return invConfig
  81.  
  82. end
  83.  
  84.  
  85. function mainLoop()
  86.  
  87.     local invFullPollTime = 30 -- time to wait in seconds between full update cycles, to reduce lag/load
  88.  
  89.     local invLastCheck = os.clock()-invFullPollTime -- set to force a run on the first loop
  90.    
  91.     activityList = {} -- contains items with activity (low or being crafted)
  92.     activityListLength = 0
  93.    
  94.     print("Starting main loop.")
  95.    
  96.     while true do
  97.    
  98.         sleepTime=5 -- Default time to pause between polling
  99.  
  100.         showHeader()
  101.  
  102.         clockUpdate()
  103.        
  104.         -- Do we need to do a full update?
  105.         if(os.clock()-invLastCheck>=invFullPollTime) then
  106.  
  107.             print("Starting full inventory update...")
  108.             resetMonitorPages()
  109.             didCraft=updateInventory()
  110.             print("Inventory update completed.")
  111.            
  112.             invLastCheck = os.clock() -- Set the time we did a full update
  113.            
  114.             -- if we are crafting, we want to refresh quicker and force a full update
  115.             if(didCraft) then
  116.                 invLastCheck = invLastCheck - invFullPollTime - 1
  117.                 sleepTime = 1
  118.             end
  119.  
  120.         end
  121.  
  122.         showMonitorPage()
  123.  
  124.         showFooter()
  125.        
  126.         showEnergyStatus()
  127.  
  128.         showSpinner()
  129.        
  130.         -- Nap for a bit to reduce load/lag
  131.  
  132.         os.sleep(sleepTime)
  133.    
  134.     end
  135.    
  136. end
  137.  
  138.  
  139.  
  140. function updateInventory()
  141.  
  142.     activityList = {} -- reset list
  143.     didCraft = false
  144.  
  145.     local actItems = itemsInTable(activityList)
  146.  
  147.     for itemName,itemDetails in pairs(inv) do
  148.  
  149.         checkItem(itemName,itemDetails)
  150.        
  151.         -- is there an issue?
  152.        
  153.         if ( itemDetails.status~="OK" ) then
  154.        
  155.             -- can we craft more?
  156.            
  157.             if ( itemDetails.order > 0 ) then
  158.            
  159.                 -- we can!
  160.                 if(not itemDetails.isCrafting) then
  161.                     itemDetails.status="QUE"
  162.                 end
  163.                
  164.                 itemDetails.sortKey = "B"..itemDetails.priority..":"..itemName
  165.            
  166.             else
  167.            
  168.                 itemDetails.sortKey = "A"..itemDetails.priority..":"..itemName         
  169.            
  170.             end
  171.  
  172.             activityList[itemName]=itemDetails
  173.            
  174.         end
  175.  
  176.     end
  177.  
  178.     -- count up how big the activityList table is  
  179.     activityListLength = itemsInTable(activityList)
  180.  
  181.  
  182.     -- Sort the list if there's anything in it
  183.  
  184.     if(activityListLength>0) then
  185.        
  186.         -- Check if assembler is idle
  187.         local jobs = invSys.getJobList()
  188.    
  189.         local jobsPending = itemsInTable(jobs)
  190.    
  191.         print("Jobs pending = "..jobsPending)
  192.  
  193.         -- If assember is idle, request crafting of first QUE item in activity list
  194.         -- change from QUE to FAB on that item, and update craft request time
  195.    
  196.         if(jobsPending==0) then
  197.    
  198.             -- find QUE item with highest sort key
  199.            
  200.             local bestSortKey="Z9:Z" -- Worst possible key
  201.             local bestSortKeyRow = nil
  202.            
  203.             for i, item in pairs(activityList) do
  204.  
  205.                 if(item.status=="QUE" or item.status=="FAB") then
  206.  
  207.                     if (bestSortKey>item.sortKey) then
  208.                         bestSortKey=item.sortKey
  209.                         bestSortKeyRow = i
  210.                     end
  211.  
  212.                     item.status="QUE"
  213.                     item.isCrafting=false
  214.                
  215.                 end
  216.            
  217.             end
  218.  
  219.             -- bestSortKeyRow now contains the row of the item to craft
  220.  
  221.             if (bestSortKeyRow) then
  222.            
  223.                 item = activityList[bestSortKeyRow]
  224.                 item.status="FAB"
  225.                 item.isCrafting=true
  226.                
  227.                 stack = { qty = item.order, id = item.id, dmg = item.meta }
  228.                 print("Craft request for "..item.name)
  229.                 invSys.requestCrafting(stack)
  230.                 didCraft = true
  231.  
  232.             end
  233.  
  234.         else
  235.  
  236.             -- We have jobs queued on the assembler
  237.             -- a job is defined as
  238.             -- job.id, job.name, job.maxdmg, job.rawName, job.dmg, job.maxSize, job.ench (table), job.qty
  239.  
  240.             -- This is a debug stub
  241.  
  242.             print("Job details:")
  243.             for k,v in ipairs(jobs) do
  244.                 print("Job "..k)
  245.                 print("id:"..v.id)
  246.                 print("name:"..v.name)
  247.                 print("maxdmg:"..v.maxdmg)
  248.                 print("rawname:"..v.rawName)
  249.                 print("dmg:"..v.dmg)
  250.                 print("maxSize:"..v.maxSize)
  251.                 -- print("ench:"..v.ench)
  252.                 print("qty:"..v.qty)
  253.             end
  254.  
  255.         end
  256.    
  257.     end
  258.    
  259.     pagingLoadData(activityList)
  260.    
  261.     return didCraft
  262.  
  263. end
  264.  
  265.  
  266. function checkItem(name, itemInfo)
  267.  
  268.     itemInfo.count=invSys.countOfItemType(itemInfo.id,itemInfo.meta)
  269.     itemInfo.lastCheck=os.clock()
  270.    
  271.     if(itemInfo.count==0) then
  272.         itemInfo.status="OUT"
  273.     elseif(itemInfo.count<itemInfo.stock) then
  274.         itemInfo.status="LOW"
  275.     else
  276.         itemInfo.status="OK"
  277.         itemInfo.isCrafting=false
  278.     end
  279.  
  280.     if(itemInfo.isCrafting) then
  281.         itemInfo.status="FAB"
  282.     end
  283.    
  284.     itemInfo.listOrder = itemInfo.priority
  285.  
  286. end
  287.  
  288.  
  289. function pagingLoadData(data)
  290.  
  291.     -- Load into paging array
  292.    
  293.     local rowNumber = 0
  294.     paging.rowData = {}
  295.     paging.rowCount = 0
  296.    
  297.     for k,v in pairs(data) do
  298.        
  299.         rowNumber = rowNumber + 1
  300.        
  301.         paging.rowData[rowNumber] = v
  302.    
  303.     end
  304.    
  305.     paging.rowCount = rowNumber
  306.  
  307.     -- Sort the table by sortKey...
  308.     table.sort( paging.rowData, function( a, b ) return a.sortKey < b.sortKey end )
  309.  
  310. end
  311.  
  312.  
  313. function showMonitorPage()
  314.  
  315.     local data = paging.rowData
  316.     local dataRowCount = paging.rowCount
  317.  
  318.     if (dataRowCount > 0) then
  319.  
  320.         for rowNumber = 1, paging.itemsPerPage, 1 do
  321.  
  322.             dataRowNumber = rowNumber + ((paging.currentPage - 1) * paging.itemsPerPage)
  323.        
  324.             mon.setCursorPos(1,2+rowNumber)
  325.        
  326.             if(dataRowNumber<=dataRowCount) then
  327.            
  328.                 local rowNumString = string.format("%2d ",dataRowNumber)
  329.                 local rowItemStatus = fixedString(data[dataRowNumber].status,3)..": "
  330.                 local rowItemName = fixedString(data[dataRowNumber].name,16)
  331.                 local rowItemQty = string.format(" %4d",data[dataRowNumber].count)
  332.                 local statusColor = format.craft_text
  333.                
  334.                 if(dataStatus=="OUT") then
  335.                    
  336.                     statusColor = format.out_text
  337.                    
  338.                 elseif (dataStatus=="LOW") then
  339.                
  340.                     statusColor = format.low_text
  341.                
  342.                 end
  343.            
  344.                 mon.setTextColor(format.number)
  345.                 mon.write(rowNumString)
  346.                
  347.                 mon.setTextColor(statusColor)
  348.                 mon.write(rowItemStatus)
  349.                
  350.                 mon.setTextColor(format.name)
  351.                 mon.write(rowItemName)
  352.                
  353.                 mon.setTextColor(format.quantity)
  354.                 mon.write(rowItemQty)
  355.            
  356.            
  357.             else
  358.            
  359.                 -- blank row!
  360.                
  361.                 mon.clearLine()
  362.            
  363.             end
  364.            
  365.         end
  366.  
  367.     else
  368.  
  369.         -- clear data area
  370.         for rowNumber = 1, paging.itemsPerPage, 1 do
  371.             mon.setCursorPos(1,2+rowNumber)
  372.             mon.clearLine()
  373.         end
  374.  
  375.         -- show ALL OK message
  376.         mon.setTextColor(format.craft_text)
  377.  
  378.         mon.setCursorPos(1,4)
  379.         -----------12345678901234567890123456789
  380.         mon.write("    Monitoring "..invCount.." items.")
  381.         mon.setCursorPos(1,5)
  382.         mon.write("  All stock levels are good.")
  383.  
  384.     end
  385.  
  386. end
  387.  
  388.  
  389. function setMonitorPage(pageNum)
  390.  
  391.     paging.currentPage = pageNum
  392.  
  393. end
  394.  
  395.  
  396. function nextMonitorPage()
  397.  
  398.     if (paging.currentPage == paging.pageCount) then
  399.         paging.currentPage = 1
  400.     else
  401.         paging.currentPage = paging.currentPage + 1
  402.     end
  403.  
  404. end
  405.  
  406.  
  407. function resetMonitorPages()
  408.  
  409.     paging = {}
  410.    
  411.     paging.itemsPerPage = 7 -- Probably not right
  412.     paging.currentPage = 1
  413.     paging.pageCount = ((activityListLength-1) / paging.itemsPerPage ) + 1
  414.     paging.rowData = {}
  415.     paging.rowCount = 0
  416.  
  417. end
  418.  
  419.  
  420. function clockUpdate()
  421.  
  422.     -- This will return the time like this "12:30 PM"
  423.     local timeString = textutils.formatTime(os.time(), false)
  424.    
  425.     if(string.len(timeString)==7) then
  426.         timeString = " "..timeString
  427.     end
  428.    
  429.     local startX = monWidth - 7
  430.    
  431.     mon.setCursorPos(startX, 1)
  432.    
  433.     mon.setTextColor(format.clock)
  434.     mon.write(timeString)
  435.  
  436. end
  437.  
  438.  
  439. function showHeader()
  440.  
  441.     local header = "StockMan "..ver
  442.    
  443.     -- local headerLen = string.len(header)
  444.    
  445.     -- local startX = ( monWidth / 2 ) - (headerLen / 2 )
  446.     local startX = 3
  447.  
  448.     mon.setCursorPos(startX, 1)
  449.    
  450.     mon.setTextColor(format.header)
  451.     mon.write(header)
  452.  
  453. end
  454.  
  455.  
  456. function showFooter()
  457.  
  458.     local jobs = invSys.getJobList()
  459.    
  460.     local jobsPending = itemsInTable(jobs)
  461.  
  462.     mon.setCursorPos(1,monHeight)
  463.     mon.clearLine()
  464.    
  465.     local footerMsg = "Fabricator is idle."
  466.  
  467.  
  468.     if jobsPending == 0 then
  469.  
  470.         mon.setTextColor(format.footer_idle)
  471.         print("No crafting jobs running.")
  472.  
  473.     else
  474.  
  475.         mon.setTextColor(format.footer_busy)
  476.  
  477.         local job = jobs[1]
  478.  
  479.         local itemname = job.name
  480.  
  481.         itemname = fixItemName(itemname)
  482.  
  483.         if (string.len(itemname)>19) then
  484.             itemname=string.sub(itemname,1,19)
  485.         end
  486.  
  487.         footerMsg = "FAB: "..itemname.." ("..job.qty..")"
  488.  
  489.         print("Crafting: "..job.id.."/"..job.name.."/"..job.qty)
  490.  
  491.     end
  492.  
  493.     local footerLen = string.len(footerMsg)
  494.    
  495.     local startX = ( monWidth / 2 ) - (footerLen / 2 ) + 1
  496.  
  497.     mon.setCursorPos(startX,monHeight)
  498.     mon.write(footerMsg)
  499.  
  500. end
  501.  
  502.  
  503. function showEnergyStatus()
  504.  
  505.     local maxW, maxH = energyMon.getSize()
  506.  
  507.     local yellorium = invSys.countOfItemType(18006,0)
  508.     local blutonium = invSys.countOfItemType(18006,3)
  509.  
  510.     energyMon.setCursorPos(1,4)
  511.     energyMon.write("Yellorium: "..yellorium)
  512.  
  513.     energyMon.setCursorPos(1,5)
  514.     energyMon.write("Blutonium: "..blutonium)
  515.  
  516. end
  517.  
  518.  
  519. function showSpinner()
  520.  
  521.     local spinIndicator = "|/-\\"
  522.  
  523.     mon.setCursorPos(1,1)
  524.     mon.setTextColor(format.craft_text)
  525.     mon.write(string.sub(spinIndicator,spinner,spinner))
  526.  
  527.     spinner=spinner+1
  528.     if(spinner>string.len(spinIndicator)) then
  529.         spinner=1
  530.     end
  531.  
  532. end
  533.  
  534. -- Some item names are "broken" and instead of being human readable nice names ("bucket")
  535. -- they are horrible object paths ("modname.blahblah.thethingname.name")
  536. -- If we see a name that ends in .name, we chop that part off, and use the string
  537. -- after the last remaining period
  538. -- This is used to clean up names we get from the job queue
  539.  
  540. function fixItemName(name)
  541.  
  542.     local cleanName=name
  543.  
  544.     local endpart = string.sub(cleanName,-5)
  545.  
  546.     if (endpart==".name") then
  547.  
  548.         cleanName = string.sub(cleanName,1,-6)
  549.  
  550.         cleanName = string.gsub(cleanName,"%."," ")
  551.  
  552.         local lastPart = ""
  553.  
  554.         for part in string.gmatch(cleanName,"%a+") do lastPart=part end
  555.  
  556.         cleanName = lastPart
  557.  
  558.     end
  559.  
  560.     return cleanName
  561.  
  562. end
  563.  
  564.  
  565. function fixedString(s,len)
  566.  
  567.     local r = s..string.rep(" ",len)
  568.     r = string.sub(r,1,len)
  569.    
  570.     return r
  571.  
  572. end
  573.  
  574.  
  575. function itemsInTable(t)
  576.  
  577.     numItems = 0
  578.     for k,v in pairs(t) do
  579.         numItems = numItems + 1
  580.     end
  581.  
  582.     return numItems
  583.  
  584. end
  585.  
  586.  
  587. function screenReset(display, backgroundColor, textColor)
  588.    
  589.     display.setBackgroundColor(backgroundColor)
  590.     display.setTextColor(textColor)
  591.    
  592.     display.clear()
  593.     display.setCursorPos(1,1)
  594.     display.setTextScale(1)
  595.  
  596. end
  597.  
  598.  
  599. function colorsInit()
  600.  
  601.     format = {}
  602.    
  603.     format.log_background = colors.green
  604.     format.log_text = colors.black
  605.    
  606.     format.monitor_background = colors.white
  607.     format.clock = colors.blue
  608.     format.header = colors.gray
  609.     format.number = colors.gray
  610.     format.quantity = colors.gray
  611.     format.footer_idle = colors.cyan
  612.     format.footer_busy = colors.green
  613.     format.footer_overdue = colors.red
  614.     format.name = colors.black
  615.     format.monitor_text = colors.black
  616.     format.low_text = colors.magenta
  617.     format.out_text = colors.red
  618.     format.craft_text = colors.green
  619.  
  620.     format.energyMon_background = colors.green
  621.     format.energyMon_text = colors.black
  622.  
  623. end
  624.  
  625.  
  626.  
  627. -- installation variables (also need to update the InventoryConfig data for items)
  628.  
  629. local meControllerSide = "bottom" -- set to the side/device name that has the ME Controller
  630.  
  631. local monitorSide = "right" -- set to side/device name that a 2h 3w advanced monitor is setup
  632.  
  633. local fluidTerminal = "tile_block_fluid_terminal_0" -- set to the side/device name of a fluid terminal
  634.  
  635. local energyMonitor = "monitor_0" -- set to the side/device name of a 1 x 2 monitor to show fuel levels
  636.  
  637. -- end config
  638.  
  639.  
  640.  
  641. invSys = peripheral.wrap(meControllerSide)
  642. fluidInvSys = peripheral.wrap(fluidTerminal)
  643. mon = peripheral.wrap(monitorSide)
  644. energyMon = peripheral.wrap(energyMonitor)
  645. monWidth, monHeight = mon.getSize()
  646. log = term.native()
  647. spinner = 1
  648. invCount = 0
  649.  
  650. colorsInit() -- sets up format array with colors
  651.  
  652. -- screenReset(log, format.log_background, format.log_text)
  653. screenReset(mon, format.monitor_background,format.monitor_text)
  654. screenReset(energyMon, format.energyMon_background, format.energyMon_text)
  655.  
  656. print("Inventory Monitor starting up.")
  657.  
  658. print("Loading inventory config...")
  659. inv = inventoryConfig()
  660. print("Inventory config loaded.")
  661.  
  662. mainLoop()
  663.  
  664. -- end of program
Advertisement
Add Comment
Please, Sign In to add comment