Sirshark10

Radio Receiver

Jun 18th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local modem = peripheral.find("modem")
  2. local tape = peripheral.find("tape_drive")
  3. local blockSize = 32768
  4. local control = {1200,1500,1800}
  5. local state = {0,0}
  6. for k,v in pairs(control) do
  7.   modem.open(v)
  8. end
  9.  
  10. local function backSeek()
  11.     print("Seeking to start")
  12.     tape.seek(-tape.getPosition())
  13. end
  14.  
  15.  
  16.  
  17. local function write(url)
  18.     state[2] = 1
  19.     backSeek()
  20.     print("Writing: "..url)
  21.     local reply = http.get(url, nil, true)
  22.     repeat
  23.         local bytes = {}
  24.         for i=1, blockSize do
  25.             local byte = reply.read()
  26.             if not byte then
  27.                 break
  28.             else
  29.                 bytes[#bytes+1] = byte
  30.             end
  31.         end
  32.         if #bytes > 0  then
  33.             for i=1, #bytes do
  34.                 tape.write(bytes[i])
  35.             end
  36.             sleep(0)
  37.         end
  38.     until not bytes or #bytes <= 0
  39.     endPos = tape.getPosition()
  40.     print("End: "..endPos)
  41.     backSeek()
  42.     print("End of Write")
  43.     state[2] = 0
  44. end
  45.  
  46. local function stop()
  47.   print("Stopping")
  48.   tape.stop()
  49. end
  50.  
  51. local function play()
  52.   print("Playing..." )
  53.   tape.play()
  54.   state[1] = 1
  55. end
  56.  
  57. local function fin()
  58.   print("Awaiting song..")
  59.   tape.stop()
  60.   modem.transmit(control[3],control[3],"ready")
  61. end
  62.  
  63.  
  64. local function main()
  65.   fin()
  66.   while true do
  67.     local evnt, side, sChan, rChan, msg, dist = os.pullEvent("modem_message")
  68.     if rChan == control[1] and string.find(msg,".dfpwm") then
  69.       backSeek()
  70.       write(msg)
  71.       play()
  72.     elseif rChan == control[2] and msg == "stop" then
  73.       stop()
  74.     end
  75.   end
  76. end
  77.  
  78. local function secondary()
  79.   while true do
  80.     if tape.getPosition() >= endPos and state[1] == 1 and state[2] ~= 1 then
  81.       print("End Of Song")
  82.       fin()
  83.       backSeek()
  84.     end
  85.     sleep(0.5)
  86.   end
  87. end
  88. parallel.waitForAny(mainLoop,secondary)
Add Comment
Please, Sign In to add comment