Skip to content

Instantly share code, notes, and snippets.

@noman-land
Last active January 27, 2023 05:07
Show Gist options
  • Save noman-land/e15a86ebda392100d84f497e04256308 to your computer and use it in GitHub Desktop.
Save noman-land/e15a86ebda392100d84f497e04256308 to your computer and use it in GitHub Desktop.
from network import Bluetooth
from network import LoRa
import socket
## CONSTANTS ##
# Increment this to setup more devices
VERSION = 1
## Bluetooth ##
# Initialize
bt = Bluetooth()
# Set a name for the device
bt.set_advertisement(name='Brucely{}'.format(VERSION), service_uuid=VERSION)
# Create a service
service = bt.service(uuid=b'b000000000000000', isprimary=True)
# Create a characteristic
# This is the data channel for the chat
characteristic = service.characteristic(uuid=b'c000000000000000', value='')
# Scan for devices forever
bt.start_scan(-1)
## LoRa ##
# Set mode and frequency
lora = LoRa(mode=LoRa.LORA, region=LoRa.US915)
# Create raw socket for send and receive
socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
socket.setblocking(False)
## CALLBACKS ##
def handle_ble_connect(bt_obj):
events = bt_obj.events()
if events & Bluetooth.CLIENT_CONNECTED:
print("Client connected")
elif events & Bluetooth.CLIENT_DISCONNECTED:
print("Client disconnected")
def send_lora_tx(message):
print('From my LoPy to the sky (LoRa): {}'.format(message))
socket.send(message)
def send_ble_tx(message):
print('From my LoPy to my phone (BLE): {}'.format(message))
characteristic.value(message)
def handle_ble_rx(char, data):
events, value = data
if events:
print('From my phone to my LoPy (BLE): {}'.format(value))
send_lora_tx(value)
def handle_lora_rx(lora):
if lora.events():
message = socket.recv(64)
print('From the sky to my LoPy (LoRa): {}'.format(message))
send_ble_tx(message)
# Register callback for BLE connection events from the phone
bt.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=handle_ble_connect)
# Register callback for receiving BLE messages from the phone
characteristic.callback(trigger=Bluetooth.CHAR_WRITE_EVENT, handler=handle_ble_rx)
# Register callback for receiving LoRa messages from the sky
lora.callback(trigger=(LoRa.RX_PACKET_EVENT), handler=handle_lora_rx)
# Start advertising BLE service so a phone can connect
bt.advertise(True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment