Advertisement
ButchAnton

Untitled

Mar 21st, 2017
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import socket
  2. import struct
  3. from network import LoRa
  4. import time
  5.  
  6. # A basic package header
  7. # B: 1 byte for the deviceId
  8. # B: 1 byte for the pkg size
  9. # B: 1 byte for the messageId
  10. # %ds: Formated string for string
  11. _LORA_PKG_FORMAT = "!BBB%ds"
  12.  
  13. # A basic ack package
  14. # B: 1 byte for the deviceId
  15. # B: 1 byte for the pkg size
  16. # B: 1 byte for the messageId
  17. # B: 1 byte for the Ok (200) or error messages
  18. _LORA_PKG_ACK_FORMAT = "BBBB"
  19.  
  20. # Let the world know we're starting up.
  21.  
  22. print("Starting LoRaNanoGateway")
  23.  
  24. # Open a Lora Socket, use rx_iq to avoid listening to our own messages
  25. lora = LoRa(mode=LoRa.LORA, rx_iq=True)
  26. lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
  27. lora_sock.setblocking(False)
  28.  
  29. while (True):
  30.  
  31. # Since the maximum body size in the protocol is 255 the request is limited to 512 bytes
  32. recv_pkg = lora_sock.recv(512)
  33. print("Received message, length = %d" % len(recv_pkg))
  34.  
  35. # If at least a message with the header is received process it
  36. if (len(recv_pkg) > 3):
  37.  
  38. print("+++ Received a message")
  39.  
  40. recv_pkg_len = recv_pkg[1]
  41.  
  42. # If message is corrupted should not continue processing
  43. if (not len(recv_pkg) == recv_pkg_len + 3):
  44. continue
  45.  
  46. # Unpack the message based on the protocol definition
  47. device_id, pkg_len, msg_id, msg = struct.unpack(_LORA_PKG_FORMAT % recv_pkg_len, recv_pkg)
  48.  
  49. # Respond to the device with an acknoledge package
  50. # time.sleep(0.15)
  51. ack_pkg = struct.pack(_LORA_PKG_ACK_FORMAT, device_id, 1, msg_id, 200)
  52. print("------ Sending an ACK")
  53. lora_sock.send(ack_pkg)
  54.  
  55. # Do any extra processing required for the package. Keep in mind it should be as fast as posible
  56. # to make sure that the other clients are not waiting too long for their messages to be acknoleged
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement