Skip to content

Instantly share code, notes, and snippets.

@benjaminchodroff
Created February 18, 2017 05:55
Show Gist options
  • Save benjaminchodroff/4fff658b50ceaedc70c47e034ee0d59f to your computer and use it in GitHub Desktop.
Save benjaminchodroff/4fff658b50ceaedc70c47e034ee0d59f to your computer and use it in GitHub Desktop.
LoPy LoRa range test - listener
# Benjamin Chodroff, 2017
# This is the main listening gateway
# It's job is to receive LoRa messages and, if a color, set the LED to that color
# Otherwise, it will set unknown messages or errors as "white"
import machine
button=machine.Pin("G17",machine.Pin.IN, pull=machine.Pin.PULL_UP)
led=machine.Pin("G16", machine.Pin.OUT)
led.value(1)
#If the dev button is not pressed (0) then run this device in broadcast mode
if button():
led.value(0)
import node1
print(str(node1.DEVICE_ID))
print("failure")
else:
led.value(1)
import socket
import struct
from network import LoRa
import time
import pycom
pycom.heartbeat(False)
pycom.rgbled(0xffffff) #white
time.sleep(1)
# A basic package header, B: 1 byte for the deviceId, B: 1 byte for the pkg size, %ds: Formated string for string
_LORA_PKG_FORMAT = "!BB%ds"
# A basic ack package, B: 1 byte for the deviceId, B: 1 bytes for the pkg size, B: 1 byte for the Ok (200) or error messages
_LORA_PKG_ACK_FORMAT = "BBB"
# Open a LoRa Socket, use rx_iq to avoid listening to our own messages
lora = LoRa(mode=LoRa.LORA, rx_iq=True, tx_power=14, power_mode=LoRa.ALWAYS_ON, public=True, tx_retries=1)
lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
lora_sock.setblocking(False)
while (True):
try:
recv_pkg = lora_sock.recv(512)
if (len(recv_pkg) > 2):
recv_pkg_len = recv_pkg[1]
device_id, pkg_len, msg = struct.unpack(_LORA_PKG_FORMAT % recv_pkg_len, recv_pkg)
# If the uart = machine.UART(0, 115200) and os.dupterm(uart) are set in the boot.py this print should appear in the serial port
print('Device: %d - Pkg: %s' % (device_id, msg))
ack_pkg = struct.pack(_LORA_PKG_ACK_FORMAT, device_id, 1, 200)
lora_sock.send(ack_pkg)
pycom.rgbled(int(msg))
time.sleep(0.1)
except:
print("exception encountered")
pycom.rgbled(0xffffff) #white
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment