This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
turtle5204's profile picture

Open All Modems At The Same Time?

Started by turtle5204, 10 September 2013 - 02:12 PM
turtle5204 #1
Posted 10 September 2013 - 04:12 PM
How to have a program check for modems, then open the ones that exist. This could be useful for rednet programs, or a email program.
Lyqyd #2
Posted 10 September 2013 - 09:26 PM
This is pretty common and fairly well-documented. You simply iterate the available sides returned in a table by redstone.getSides() and use the peripheral.getType method on each side to see if it's a "modem", then act accordingly.
GravityScore #3
Posted 11 September 2013 - 03:22 AM
What Lyqyd said above in code form:

local present = false
for _, side in pairs(rs.getSides()) do
  if peripheral.getType(side) == "modem" then
    present = true
    rednet.open(side) -- this or wrap to a modem object if you're planning to use the modem API instead of rednet
  end
end

if not present then
  print("A modem was not found, please attach one and re-run this program")
end
theoriginalbit #4
Posted 11 September 2013 - 04:59 AM
A tutorial that could have helped you.
Hydra #5
Posted 11 September 2013 - 05:53 AM
I use a somewhat different method that has the benefit of finding any attached peripheral:

-- Returns a table with the sides and peripheral types
function getPeripheralList()
local sides = peripheral.getNames()
local pTable = {}

for k,side in pairs(sides) do
pTable[side] = peripheral.getType(side)
end

return pTable
end

-- finds the first peripheral of type 'peripheralType' and wraps it
function getPeripheral(peripheralType)
local pTable = getPeripheralList()
for side, pType in pairs(pTable) do
if(peripheralType == pType) then
return peripheral.wrap(side)
end
end
return nil
end

-- finds all peripherals of type 'peripheralType' and wraps them
function getAllPeripherals(peripheralType)
local pTable = getPeripheralList()
local wrappedTable = {}
for side, pType in pairs(pTable) do
if(peripheralType == pType) then
wrappedTable[side] = peripheral.wrap(side)
end
end
return wrappedTable
end


3 functions from a private library I use in all my projects. peripheral.getNames() returns the names of all attached peripherals, even if they're remote. So if you use OpenPeripherals this will also show you any attached tanks or boilers.

getPeripheral(peripheralType) returns a single wrapped peripheral. Example:


local monitor =  getPeripheral("monitor")
monitor.write("Hello!")

getAllPeripherals(peripheralType) returns a table of all wrapper peripherals of that type. Example:


local cells = getAllPeripherals("redstone_energy_cell")

for k,cell in pairs(cells) do
  print(cell.getEnergyStored())[font=Monaco, Menlo, Consolas,]getEnergyStored[/font][font=Monaco, Menlo, Consolas,]()[/font]
end