View difference between Paste ID: H3G51hyU and FvJawsAi
SHOW: | | - or go back to the newest paste.
1
local channel = 0
2
local modem 
3
4
5
function setModem(side)
6
    modem = peripheral.wrap(side)
7
end
8
9
function setChannel(ch)
10
    channel = ch
11
end
12
13
function openModem(ch)
14
    ch = ch or channel
15
    if not modem.isOpen(ch) then
16
        modem.open(ch)
17
        print("Opened modem: " .. ch)
18
    else
19
        print("Modem already opened: " .. ch)
20
    end
21
end
22
23
function closeModem(ch)
24
    ch = ch or channel
25
    if modem.isOpen(ch) then
26
        modem.close(ch)
27
        print("Closed modem: " .. ch)
28
    else
29
        print("Modem already closed: " .. ch)
30
    end
31
end
32
33
function modemSetup(side, ch)
34
    modem = peripheral.wrap(side)
35
    setChannel(ch)
36
    openModem()
37
end
38
39
function sendMessage(msg, ch, returnCh)
40
    ch = ch or channel
41
    returnCh = returnCh or channel
42
43
    if type(msg) == "table" then
44
        msg = textutils.serialize(msg)
45
    end
46
    
47
    modem.transmit(ch, returnCh, msg)
48
end
49
50
51
function waitForMessage(ch, timeout)
52
    ch = ch or channel
53
    local myTimer
54
    if timeout then
55
        myTimer = os.startTimer(timeout)
56
    end
57
    while true do
58
        local event, par1, senderChannel, 
59
        replyChannel, message, senderDistance = os.pullEvent()
60
61
        if event == "timer" and par1 == myTimer then
62
            print("message timeout")
63
            return false
64
        end
65
66
        if senderChannel == ch then
67
            return true, message, replyChannel
68
        end
69
    end
70
end
71
72
function sendAndWaitForResponse(msg, ch, returnCh, timeout)
73
    sendMessage(msg, ch, returnCh)
74
75
    local worked, message, replyChannel = waitForMessage(returnCh, timeout)
76
    return worked, message, replyChannel    
77
end