Advertisement
ButchAnton

Untitled

Mar 21st, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. import os
  2. import socket
  3. import time
  4. import struct
  5. from network import LoRa
  6. from uos import urandom
  7.  
  8. # A basic package header
  9. # B: 1 byte for the deviceId
  10. # B: 1 byte for the pkg size
  11. # B: 1 byte for the messageId
  12. # %ds: Formated string for string
  13. _LORA_PKG_FORMAT = "!BBB%ds"
  14.  
  15. # A basic ack package
  16. # B: 1 byte for the deviceId
  17. # B: 1 byte for the pkg size
  18. # B: 1 byte for the messageId
  19. # B: 1 byte for the Ok (200) or error messages
  20. _LORA_PKG_ACK_FORMAT = "BBBB"
  21.  
  22. # This device ID, use different device id for each device
  23. _DEVICE_ID = 0x01
  24. _MAX_ACK_TIME = 5000
  25. _RETRY_COUNT = 3
  26.  
  27. # Let the world know we're starting up.
  28.  
  29. print("Starting LoRaNanoNode on device %d" % _DEVICE_ID)
  30.  
  31. # Open a Lora Socket, use tx_iq to avoid listening to our own messages
  32. lora = LoRa(mode=LoRa.LORA, tx_iq=True)
  33. lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
  34. lora_sock.setblocking(False)
  35.  
  36. # Method to increase message id and keep in between 1 and 255
  37. msg_id = 0
  38. def increase_msg_id():
  39. global msg_id
  40. msg_id = (msg_id + 1) & 0xFF
  41.  
  42. # Method for acknoledge waiting time keep
  43. def check_ack_time(from_time):
  44. current_time = time.ticks_ms()
  45. return (current_time - from_time > _MAX_ACK_TIME)
  46.  
  47. # Method to send messages
  48. def send_msg(msg):
  49. global msg_id
  50. retry = _RETRY_COUNT
  51. while (retry > 0 and not retry == -1):
  52. retry -= 1
  53. pkg = struct.pack(_LORA_PKG_FORMAT % len(msg), _DEVICE_ID, len(msg), msg_id, msg)
  54. lora_sock.send(pkg)
  55.  
  56. # Wait for the response from the server.
  57. start_time = time.ticks_ms()
  58.  
  59. while(not check_ack_time(start_time)):
  60. recv_ack = lora_sock.recv(256)
  61. # If a message of the size of the acknoledge message is received
  62. if (len(recv_ack) == 4):
  63. device_id, pkg_len, recv_msg_id, status = struct.unpack(_LORA_PKG_ACK_FORMAT, recv_ack)
  64. if (device_id == _DEVICE_ID and recv_msg_id == msg_id):
  65. if (status == 200):
  66. # Do some code if your message arrived at the central
  67. return True
  68. else:
  69. return False
  70. time.sleep_ms(urandom(1)[0] << 2)
  71. return False
  72.  
  73. # Main Loop
  74. while(True):
  75.  
  76. print("Sending a message from device %d" % _DEVICE_ID)
  77.  
  78. success = send_msg("DEVICE %d HERE" % _DEVICE_ID)
  79. if (success):
  80. print("ACK RECEIVED: %d" % msg_id)
  81. increase_msg_id()
  82. else:
  83. print("MESSAGE FAILED")
  84. # Manage the error message
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement