# Issue with LoRaWAN Message Transmission via MQTT

**URL:** <https://www.thethingsnetwork.org/forum/t/issue-with-lorawan-message-transmission-via-mqtt/68206>\
**Category:** MQTT\
**Tags:** gateways, end-devices, mqtt\
**Created:** [June 10, 2024, 9:31am UTC](https://www.thethingsnetwork.org/forum/t/issue-with-lorawan-message-transmission-via-mqtt/68206 "2024-06-10T09:31:24Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![marianamador](https://www.thethingsnetwork.org/forum/letter_avatar_proxy/v4/letter/m/da6949/32.png) [@marianamador](https://www.thethingsnetwork.org/forum/u/marianamador)\
**Post date:** [June 10, 2024, 9:31am UTC](https://www.thethingsnetwork.org/forum/t/issue-with-lorawan-message-transmission-via-mqtt/68206/1 "2024-06-10T09:31:25Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![kersing](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/kersing/32/44777_2.png) [@kersing](https://www.thethingsnetwork.org/forum/u/kersing)\
**Post date:** [June 10, 2024, 10:04am UTC](https://www.thethingsnetwork.org/forum/t/issue-with-lorawan-message-transmission-via-mqtt/68206/2 "2024-06-10T10:04:16Z")

</div>

> [@marianamador](#):
>
> 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.

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.

---

<div class="post-metadata">

**Author:** ![marianamador](https://www.thethingsnetwork.org/forum/letter_avatar_proxy/v4/letter/m/da6949/32.png) [@marianamador](https://www.thethingsnetwork.org/forum/u/marianamador)\
**Post date:** [June 10, 2024, 10:23am UTC](https://www.thethingsnetwork.org/forum/t/issue-with-lorawan-message-transmission-via-mqtt/68206/3 "2024-06-10T10:23:15Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![kersing](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/kersing/32/44777_2.png) [@kersing](https://www.thethingsnetwork.org/forum/u/kersing)\
**Post date:** [June 10, 2024, 10:57am UTC](https://www.thethingsnetwork.org/forum/t/issue-with-lorawan-message-transmission-via-mqtt/68206/4 "2024-06-10T10:57:36Z")

</div>

> [@marianamador](#):
>
> MQTT is used to publish the data from the gateway to TTN for further processing.

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.

---

<div class="post-metadata">

**Author:** ![descartes](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/descartes/32/47220_2.png) [@descartes](https://www.thethingsnetwork.org/forum/u/descartes)\
**Post date:** [June 10, 2024, 4:12pm UTC](https://www.thethingsnetwork.org/forum/t/issue-with-lorawan-message-transmission-via-mqtt/68206/5 "2024-06-10T16:12:24Z")

</div>

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

And this:

> [@marianamador](#):
>
> MQTT is used to publish the data from the gateway to TTN for further processing.

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?

---

<div class="post-metadata">

**Author:** ![system](https://www.thethingsnetwork.org/forum/uploads/default/original/3X/6/2/6250ea44fd2b0d6259489e1a92748df681e1f970.png) [@system](https://www.thethingsnetwork.org/forum/u/system)\
**Post date:** [November 27, 2024, 9:19am UTC](https://www.thethingsnetwork.org/forum/t/issue-with-lorawan-message-transmission-via-mqtt/68206/6 "2024-11-27T09:19:33Z")

</div>

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.
