Issue with LoRaWAN Message Transmission via MQTT

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?

TTN does not provide a generic MQTT broker. It can only be used to receive uplink LoRaWAN packets from LoRaWAN devices or send downlink packets to a LoRaWAN device (limited to 10 a day!)
You can not publish messages to the uplink channel, TTN will ignore all messages published to it.

If you want a MQTT broker you need to either deploy your own or use another cloud service.

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’m using an SX1262-based end device configured to transmit data using LoRa modulation.
  • A Lorank8 gateway is employed to capture and forward the LoRaWAN messages to the network server.
  • MQTT is used to publish the data from the gateway to TTN for further processing.
  • The connection to the MQTT broker on TTN is established using the appropriate credentials (username and password).

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.
import os
import sys
import time
import base64
import json
import paho.mqtt.client as mqtt
from LoRaRF import SX126x

Configuraciones de 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

Has anyone encountered a similar problem before, or does anyone have any insights or suggestions on what might be causing this issue?

Can’t be done. Read my previous message above.

BTW, please learn to format your messages. Use code blocks for code, makes your messages readable.

I’m confused - is this a repeat or just a different version of the same question?

And this:

can’t be correct as the Lorank8 uses the Poly Packet Forwarder which uses UDP not MQTT - although it’s “open source” the code isn’t actually shared so it’s hard to be definitive.

And if you subscribe to the ‘up’ topic, you get uplinks sent from the device, that’s one way only, what are you hoping to do by sending a message to that topic?