def connectionLoRa(self): # Function to create LoRa socket try: self.s_right = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.loramac = binascii.hexlify(network.LoRa().mac()) if (self.modep == 1): print ("Socket Created") # AM: Acquisition socket LoRa except socket.error: exit('Error creating socket.')
def connectionLoRa(self):#Funcion para crear socket LoRa try: self.s_right = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.loramac = binascii.hexlify(network.LoRa().mac()) print("Socket Created") # AM: Adquisicion socket LoRa except socket.error: exit('Error creating socket.')
def LoRaRec(data,socket,source_address): bandera = 0 mensaje = b"" tabla = BaseDatos(mode_print) my_lora_address = binascii.hexlify(network.LoRa().mac()) if (mode_print == 1): #print ("DEBUG Server: Content in reception LoRa", data) # KN: Enable this print to see the content in reception LoRa in debug mode print ("DEBUG Server: Source Address in LoRaRec ", source_address) if (source_address == ANY_ADDR): content2 = str(data) # Capturing the data, and changing the format IPlora,user_raw = content2.split(",") if (IPlora == "b'FFFFFFFraspbsend'") or (IPlora == b'FFFFFFFraspberry'): if (mode_print == 1): print ("DEBUG Server: It's the raspberry IP") if (mode_print == 1): print ("DEBUG Server: IP Lora: ", str(IPlora)) lenght = len(user_raw) userf = user_raw[:lenght - 1] if (userf == "broadcast"): # Message to all users message_broadcast = str(IPlora[2:]) tabla = BaseDatos(mode_print) if (mode_print == 1): print ("DEBUG Server: Message Broadcast received", message_broadcast) posthandler.broadcast(message_broadcast, mode_print) # Function to save the broadcast message IPloraf = IPlora[4:] if (mode_print == 1): print ("DEBUG Server: User ", userf) bandera = posthandler.consultat(userf, mode_print) # Checking if the user is in the database if (mode_print == 1): print ("DEBUG Server: Flag ", bandera) if bandera == 1: # The user is in the database, I'm going to respond if (mode_print == 1): print ("DEBUG Server: Lora Address ", IPloraf) sent, retrans, sent, notsend = swlp.tsend(my_lora_address, socket, my_lora_address, IPloraf, mode_print) # Function to send a LoRa Message using the protocol elif (source_address == my_lora_address[8:]): # The message is for me, I'm going to save it message_raw = data #if (mode_print == 1): print ("DEBUG Server: Message in server", message_raw) # KN: Enable this print to see the message in server in debug mode if (mode_print == 2): print ("Receiving message") if (message_raw == b"Failed"): print ("Reception Failed, Discarding") elif (message_raw != b"") and (message_raw != b"Failed"): mensajet = str(message_raw) print("XXXYYYraw", message_raw) # handling sensors data... there must be a better way to send and receive json if (mensajet[-10:-1] == "mqttproxy"): aaa = mensajet.find("{") zzz = mensajet.find("}") user_final = "mqttproxy" messagef = str(mensajet[aaa:zzz+1]) idEmisor = str(mensajet[2:aaa-1]) if (mode_print == 1): print ("Sender: " + idEmisor) print ("Message: " + messagef) # KN: Enable this print to see the message in debug mode print ("User: "******",") if (mode_print == 1): print ("Sender: " + str(idEmisor[1:])) #print ("Message: " + str(messagef)) # KN: Enable this print to see the message in debug mode print ("User: " + str(user_final)) lenght = len(user_final) userf = user_final[:lenght - 1] tabla.ingreso(idEmisor[2:],userf,messagef) # Function to save the message in the database
def reconocimiento(the_sock, tbs, message, flag_broadcast): # AM: We send a broadcast message looking for the user mensaje = "" content = "" cuenta = 0 address = b"" m_broadcast = 0 lora = LoRa(mode=LoRa.LORA, frequency=freq, tx_power=tx_pow, bandwidth=band, sf=spreadf, preamble=prea, coding_rate=cod_rate, power_mode=pow_mode, tx_iq=tx_iq_inv, rx_iq=rx_iq_inv, adr=ada_dr, public=pub, tx_retries=tx_retr, device_class=dev_class) my_lora_address = binascii.hexlify(network.LoRa().mac()) dest_lora_address = b'FFFFFFFFFFFFFFFF' if (tbs == "broadcast"): content = message + "," + str(tbs) else: content = str(str(my_lora_address) + "," + str(tbs)) if DEBUG_MODE: print("DEBUG: Content: ", content) if DEBUG_MODE: print("DEBUG: Searching: ", tbs) # AM: We wait 20 seconds for the user while True: if (tbs == "broadcast"): #We check if the message is broadcast if DEBUG_MODE: print("DEBUG: Sending Message broadcast") sent, retrans, nsent = swlp.tsend(content, the_sock, my_lora_address, dest_lora_address) mensaje = b"" m_broadcast = 1 break elif (flag_broadcast == 2): #When is a message via telegram dest_lora_address = b'FFFFFFFraspberry' if DEBUG_MODE: print("DEBUG: Searching Via Telegram to: ", tbs) if DEBUG_MODE: print("DEBUG: Searching: ", cuenta) sent, retrans, nsent = swlp.tsend(content, the_sock, my_lora_address, dest_lora_address) mensaje, address = swlp.trecvcontrol(the_sock, my_lora_address, dest_lora_address) if DEBUG_MODE: print("DEBUG: Message: ", mensaje) if DEBUG_MODE: print("DEBUG: Retransmisions", retrans) cuenta += 1 if (mensaje != b""): #We found the user receiver break elif (cuenta == 3 and mensaje == b""): if DEBUG_MODE: print("DEBUG: Message when destination not found: ", mensaje) break return mensaje, m_broadcast
def join_dingnet(app_eui, app_key): lora = network.LoRa(mode=network.LoRa.LORAWAN) app_eui = binascii.unhexlify(app_eui) app_key = binascii.unhexlify(app_key) # connect with OTAA-authentication (only supported method with Dingnet) lora.join(activation=network.LoRa.OTAA, auth=(app_eui, app_key), timeout=0) return lora
def __init__(self, host, port, ssid, wpa, log_path): self.host = host self.port = port self.ssid = ssid self.wpa = wpa self.path = log_path self.gps_buffer = None self.log_time = None self.log_file = None self.rxnb = 0 self.loramac = binascii.hexlify(network.LoRa().mac()) # to be refactored self.end = False self.lock = _thread.allocate_lock() # Create proper directory for log file self._init_log() # Setup wypy/lopy as a station self.wlan = network.WLAN(mode=network.WLAN.STA) self.wlan.connect(self.ssid, auth=(network.WLAN.WPA2, self.wpa)) while not self.wlan.isconnected(): print('Connecting to Android WIFI HOTPOST...') time.sleep(1) print('Connected to Android WIFI HOTPOST') # Lora socket self.lora = None self.lora_sock = None # TCP socket self.tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect self.tcp_sock.connect((self.host, self.port))
def LoRaRec(data,socket,source_address): bandera=0 mensaje = b"" tabla=BaseDatos() my_lora_address = binascii.hexlify(network.LoRa().mac()) print("DEBUG: Content in reception LoRa",data) if DEBUG_MODE: print("DEBUG: Source Address in LoRaRec ", source_address) if (source_address == ANY_ADDR): content2 = str(data) #Capturing the data, and changing the format IPlora,user_raw = content2.split(",") if(IPlora=="b'FFFFFFFraspbsend'") or (IPlora==b'FFFFFFFraspberry'): if DEBUG_MODE: print("DEBUG: It's the raspberry IP") if DEBUG_MODE: print("DEBUG: IP Lora: ",str(IPlora)) lenght = len(user_raw) userf = user_raw[:lenght-1] if(userf=="broadcast"): #Message to all users message_broadcast = str(IPlora[2:]) tabla=BaseDatos() if DEBUG_MODE: print("DEBUG: Message Broadcast received",message_broadcast) posthandler.broadcast(message_broadcast) #Function to save the broadcast message IPloraf = IPlora[4:] if DEBUG_MODE: print("DEBUG: User ", userf) bandera=posthandler.consultat(userf) #Checking if the user is in the database #bandera=tabla.consultaControl(userf) if DEBUG_MODE: print("DEBUG: Flag ", bandera) if bandera == 1: #The user is in the database, I'm going to respond if DEBUG_MODE: print("DEBUG: Lora Address ", IPloraf) sent, retrans,sent = swlp.tsend(my_lora_address, socket, my_lora_address, IPloraf)#Function to send a LoRa Message using the protocol elif(source_address== my_lora_address[8:]): #The message is for me, I'm going to save it message_raw = data if DEBUG_MODE: print("DEBUG: message in server", message_raw) if(message_raw !=b""): mensajet = str(message_raw) idEmisor, messagef,user_final = mensajet.split(",") print("Sender: "+str(idEmisor[1:])) print("Message: "+str(messagef)) print("User: "+str(user_final)) lenght = len(user_final) userf = user_final[:lenght-1] tabla.ingreso(idEmisor[2:],userf,messagef)#Function to save the message in the database
def __init__(self): self.lora = LoRa(mode = LoRa.LORA, frequency = 868000000, tx_power = 14, bandwidth = LoRa.BW_125KHZ, sf = 7, preamble = 8, coding_rate = LoRa.CODING_4_5, power_mode = LoRa.ALWAYS_ON, tx_iq = False, rx_iq = False, public = True, tx_retries = 1, device_class = LoRa.CLASS_A) # Get lora mac address self.lora_mac = binascii.hexlify(network.LoRa().mac()) self.my_addr = self.lora_mac[8:] # Create a raw LoRa socket self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
def loratest(): button = machine.Pin('G17', pull=machine.Pin.PULL_UP) lora = network.LoRa(mode=network.LoRa.LORA, sf=12, bandwidth=network.LoRa.BW_250KHZ, coding_rate=network.LoRa.CODING_4_8, preamble=24) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.settimeout(5) me = lora.mac() sawother = 0 sawresponsetome = 0 sawnoise = 0 pycom.heartbeat(False) got = None while button(): rs, ws, es = select.select([s], [], [], 5) if rs: got = s.recv(64) if got.startswith(b"PING") and got[4:] != me: sawother = 5 s.send(b"PONG" + got[4:] + me) elif got.startswith(b"PONG" + me): sawresponsetome = 5 else: sawnoise = 5 else: s.send(b"PING" + me) pycom.rgbled(0x40000 * sawnoise + 0x400 * sawresponsetome + 0x4 * sawother) if sawother: sawother -= 1 if sawnoise: sawnoise -= 1 if sawresponsetome: sawresponsetome -= 1 #print(sawother, sawnoise, sawresponsetome, got) print("Exiting due to button press.")
import socket import sys import time import swlpv2 import Descubrimiento ANY_ADDR = b'FFFFFFFFFFFFFFFF' # PM_lora_device = b'70b3d549964a4de5' lora = LoRa(mode=LoRa.LORA) try: the_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) except socket.error: exit('Error creating socket.') my_lora_address = binascii.hexlify(network.LoRa().mac()) print(my_lora_address) sender_lora_address = ANY_ADDR print("listo para recibir") #ipor=Descubrimiento.responder(the_sock,my_lora_address,sender_lora_address) #print(ipor) while True: rcvd = swlpv2.trecv(the_sock, my_lora_address, sender_lora_address) print(rcvd) #if(rcvd!=sender_lora_address) # sender_lora_address=rcvd print(sender_lora_address) print("The End.")
pycom.heartbeat(False) # Disable the heartbeat LED pycom.rgbled(color) def flash_led_to(color=GREEN, t1=1): set_led_to(color) time.sleep(t1) set_led_to(OFF) # initialize LoRa in LORA mode # more params can also be given, like frequency, tx power and spreading factor lora = LoRa(mode=LoRa.LORA) # get LoRa MAC address loramac = binascii.hexlify(network.LoRa().mac()) print(loramac) loramac2 = binascii.unhexlify(loramac) # create a raw LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) while True: # get any data received... s.setblocking(False) data = s.recv(64) data2 = str(data) if data != b'': macorigen, sender, receiver, message = data2.split(",") print(data) largo = len(message) messagef = message[:largo - 1]
# Use the MQTT protocol to connect to Bluemix print("Try to connect to IBM iot") myiotorg="5q6gu4" client = MQTTClient("d:"+myiotorg+":playbulb:playbulb30", myiotorg+".messaging.internetofthings.ibmcloud.com",port=1883,user="******", password="******") #client = MQTTClient(“d:<ORG Id>:<Device Type>:<Device Id>“, “<ORG Id>.messaging.internetofthings.ibmcloud.com”,user=”use-token-auth”, password=”<TOKEN>“, port=1883) #print(client) # Subscribed messages will be delivered to this callback client.set_callback(sub_cb) client.connect() #client.subscribe(AIO_CONTROL_FEED) #print("Connected to %s, subscribed to %s topic" % (AIO_SERVER, AIO_CONTROL_FEED)) print("Connected to Bluemix") pycom.rgbled(0x00f000) # Status green: online to Bluemix #Publish a Hallo print("Send a Hello to Bluemix") client.publish(topic="iot-2/evt/random/fmt/json", msg='{"id":'+ubinascii.hexlify(network.LoRa().mac()).decode("utf-8")+',"value":"hello","type":"GW","msgid": -1}' ) #client.publish(topic="iot-2/evt/random/fmt/json", msg='{"id": 0, "h": 0, "t": 0, "ot":0, "w":0, "ts":0, "type":"GW","msgid": -1}' ) try: while (True): pycom.rgbled(0x000000) # Since the maximum body size in the protocol is 255 the request is limited to 512 bytes recv_pkg = lora_sock.recv(512) if (len(recv_pkg) >4 and len(recv_pkg) < 160): print("Received message FROM PI, length = %d" % len(recv_pkg)) #print(recv_pkg.decode("utf-8")) #a = bytearray(recv_pkg) #print(len(a)) #Remove the byte pakc unpack could be used 2 b= recv_pkg[4:] print("Received a message: %s" % b) db=b.decode("utf-8")
import network, select, socket, machine, binascii import gc, pycom, crypto name = binascii.hexlify(machine.unique_id()) uart = machine.UART(0, 115200) lora = network.LoRa(mode=network.LoRa.LORA) # turn off the green LED (default makes it shine weakly) greenled = machine.Pin('P9', mode=machine.Pin.OUT) greenled.value(1) # turn off the RGB LED pycom.heartbeat(False) pycom.rgbled(0) send_tries = 3 msg_seq = 0 log = [] bt_log_readout = 0 send_counter = 0 def send_unsent_log(): global send_counter if send_counter < len(log): msg = log[send_counter] tries = msg[0] if tries: msg[0] -= 1
import lora import logic # Start to blink: pycom.heartbeat(True) # Setup network & sensors if machine.reset_cause() == machine.DEEPSLEEP_RESET: mode = 'eco' print('DEVICE [POWER]: Woke up from deepsleep') else: mode = 'power' print('DEVICE [POWER]: Started after a reset') # Detect device: eid = binascii.hexlify(network.LoRa().mac()).decode().upper() print("DEVICE [EUI={}]: EUI detected".format(eid)) # Node/Application Key: target = './data/lora.json' try: with open(target) as fh: creds = json.load(fh) except OSError: creds = {eid: lora.generate_keys()} print("CREDENTIALS: {}".format(json.dumps(creds))) with open(target, 'w') as fh: json.dump(creds, fh) keys = creds.get(eid)
##################################################### # Commands to get Devide EUI # # Created by Group_3 # ##################################################### import binascii import network print("Device EUI: " + str(binascii.hexlify(network.LoRa().mac())))
#from L76GNSS import L76GNSS from L76GNSV4 import L76GNSS from pytrack import Pytrack time.sleep(2) gc.enable() #setup LoRa lora = network.LoRa(mode=LoRa.LORA, region=LoRa.AS923, frequency=923000000, tx_power=14, bandwidth=LoRa.BW_125KHZ, sf=12, preamble=6, coding_rate=LoRa.CODING_4_5, power_mode=LoRa.ALWAYS_ON, tx_iq=False, rx_iq=False, adr=False, public=True, tx_retries=1, device_class=LoRa.CLASS_A) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setblocking(False) # setup rtc rtc = machine.RTC() rtc.ntp_sync("pool.ntp.org") utime.sleep_ms(750) print('\nRTC Set from NTP to UTC:', rtc.now())
if (len(recv_pkg) > 4): print(recv_pkg.decode("utf-8")) if (len(recv_pkg) > 4 and len(recv_pkg) < 160): print("Received message FROM PI, length = %d" % len(recv_pkg)) #print(recv_pkg.decode("utf-8")) #a = bytearray(recv_pkg) #print(len(a)) #Remove the byte pakc unpack could be used 2 b = recv_pkg[4:] print("Received a message: %s" % b) db = b.decode("utf-8") o = json.loads(db) print(o['id']) o['type'] = "dev" o['gwid'] = ubinascii.hexlify(network.LoRa().mac()).decode("utf-8") #print(o) c = json.dumps(o) print(c) if o['id'] == 10: print("publish node msg to cloud ") client.publish(topic="iot-2/evt/raspi/fmt/json", msg=c) pycom.rgbled(colorgreen) # green time.sleep(1) else: print("Error -- Only Device 10 - Wrong device id =" + str(o['id'])) pycom.rgbled(colorred) # green time.sleep(1) # Unpack the message based on the protocol definition # msg = struct.unpack(_LORA_PKG_FORMAT2 % recv_pkg_len, recv_pkg)
frequency=freq, tx_power=tx_pow, bandwidth=band, sf=spreadf, preamble=prea, coding_rate=cod_rate, power_mode=pow_mode, tx_iq=tx_iq_inv, rx_iq=rx_iq_inv, adr=ada_dr, public=pub, tx_retries=tx_retr, device_class=dev_class) # Get loramac as id to be sent in message lora_mac = binascii.hexlify(network.LoRa().mac()).decode('utf8') print(lora_mac) # Create a raw LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # mr add 27/07 # s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) tStartMsec = time.ticks_ms() LoraStats = "" # init lora stats print("Start lora rx") while True: #### # get any data received... #s.setblocking(True) print("Recibiendo")