Hello everyone,
I hope you’re doing well. I’m currently facing an issue with transmitting LoRaWAN messages via MQTT to The Things Network (TTN), and I’m seeking some assistance to troubleshoot the problem.
Here’s a brief overview of the setup:
- I have a LoRaWAN device configured to transmit data using LoRa modulation.
- MQTT is used to publish the data to TTN for further processing.
- The connection to the MQTT broker on TTN is established using the appropriate credentials (username and password).
import os
import sys
import time
import base64
import json
import paho.mqtt.client as mqtt
from LoRaRF import SX126x
LoRaWAN
DEVADDR = “”
DEVEUI = “”
NWKSKEY = “”
APPSKEY = “”
APPID = “”
API_KEY = “”
TTN_REGION = “eu1”
Configurar MQTT
MQTT_BROKER = f"{TTN_REGION}.cloud.thethings.network"
MQTT_PORT = 1883
MQTT_TOPIC = f"v3/{APPID}@{TTN_REGION}/devices/{DEVEUI}/up"
MQTT_USERNAME = f"{APPID}@{TTN_REGION}"
MQTT_PASSWORD = API_KEY
Callbacks de MQTT
def on_connect(client, userdata, flags, rc, properties=None):
if rc == 0:
print(“Connected to MQTT Broker!”)
else:
print(f"Failed to connect, return code {rc}")
def on_publish(client, userdata, mid, properties=None):
print(f"Message {mid} published.")
def on_log(client, userdata, level, buf):
print(f"MQTT Log: {buf}")
def on_disconnect(client, userdata, rc):
print(“Disconnected from MQTT Broker”)
Inicializar MQTT
mqtt_client = mqtt.Client()
mqtt_client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
mqtt_client.on_connect = on_connect
mqtt_client.on_publish = on_publish
mqtt_client.on_log = on_log
mqtt_client.on_disconnect = on_disconnect
mqtt_client.connect(MQTT_BROKER, MQTT_PORT, 60)
Inicializar LoRa
busId = 0; csId = 0
resetPin = 18; busyPin = 20; irqPin = 16; txenPin = 6; rxenPin = -1
LoRa = SX126x()
print(“Begin LoRa radio”)
if not LoRa.begin(busId, csId, resetPin, busyPin, irqPin, txenPin, rxenPin):
raise Exception(“Something wrong, can’t begin LoRa radio”)
LoRa.setDio2RfSwitch()
print(“Set frequency to 868 Mhz”)
LoRa.setFrequency(868000000)
print(“Set TX power to +22 dBm”)
LoRa.setTxPower(22, LoRa.TX_POWER_SX1262)
print(“Set modulation parameters:\n\tSpreading factor = 7\n\tBandwidth = 125 kHz\n\tCoding rate = 4/5”)
sf = 7
bw = 125000
cr = 5
LoRa.setLoRaModulation(sf, bw, cr)
print(“Set packet parameters:\n\tExplicit header type\n\tPreamble length = 12\n\tPayload Length = 15\n\tCRC on”)
headerType = LoRa.HEADER_EXPLICIT
preambleLength = 12
payloadLength = 15
crcType = True
LoRa.setLoRaPacket(headerType, preambleLength, payloadLength, crcType)
print(“Set syncronize word to 0x3444”)
LoRa.setSyncWord(0x3444)
print(“\n– LoRa Transmitter –\n”)
message = “HeLoRa World!\0”
messageList = list(message)
for i in range(len(messageList)):
messageList[i] = ord(messageList[i])
counter = 0
Transmit message continuously
while True:
try:
# Preparar el payload
payload = message.encode() + bytes([counter])
payload_b64 = base64.b64encode(payload).decode(‘utf-8’)
print(f"Prepared payload: {payload_b64}")
# Construir el mensaje MQTT
mqtt_message = {
"end_device_ids": {
"device_id": DEVEUI,
"application_ids": {
"application_id": APPID
},
"dev_eui": DEVEUI,
"join_eui": DEVEUI
},
"uplink_message": {
"f_port": 1,
"frm_payload": payload_b64
}
}
print(f"MQTT message: {json.dumps(mqtt_message)}")
# Publicar el mensaje MQTT
result = mqtt_client.publish(MQTT_TOPIC, json.dumps(mqtt_message))
status = result.rc
if status == 0:
print(f"Sent message {message} with counter {counter} via MQTT")
else:
print(f"Failed to send message to MQTT, return code {status}")
# Transmitir mensaje via LoRa
LoRa.beginPacket()
LoRa.write(messageList, len(messageList))
LoRa.write([counter], 1)
LoRa.endPacket()
print(f"{message} {counter}")
# Wait until modulation process for transmitting packet finish
LoRa.wait()
# Print transmit time and data rate
print("Transmit time: {0:0.2f} ms | Data rate: {1:0.2f} byte/s".format(LoRa.transmitTime(), LoRa.dataRate()))
# Wait before next transmission
time.sleep(20)
counter = (counter + 1) % 256
except Exception as e:
print(f"An error occurred: {e}")
LoRa.end()
break
However, despite successful connection establishment to the MQTT broker (confirmed by “Connected to MQTT Broker!” message), I’m not seeing any messages being received on the TTN console. Strangely, when intentionally providing incorrect credentials, I receive a “Failed to connect to MQTT” message, indicating that the connection is being attempted with the correct credentials.
I’ve checked the LoRaWAN device’s configuration, the MQTT connection parameters, and the LoRa modulation settings, but I haven’t been able to identify the root cause of the issue.
Has anyone encountered a similar problem before, or does anyone have any insights or suggestions on what might be causing this issue?