matthijskooijman / arduino-lmic

:warning: This library is deprecated, see the README for alternatives.
705 stars 651 forks source link

LMIC.seqnoUp counts wrong #250

Open NullP0int opened 4 years ago

NullP0int commented 4 years ago

Hi everyone,

I want to send multiple messages with the LMIC library in one run of my code until I'll spend my esp32 some deepsleep.

When the esp wakes up, the counter is set to the value after my last send:

Preferences pref;   
pref.begin(PREFERENCES_KEY, false);   
uint8_t sequenceNum = pref.getUInt("counter", 1);   
LMIC.seqnoUp = sequenceNum;
pref.end()

After that, I want to send my data which will received by a queue (multiple sends). I set a sendPending flag so ensure that my other send will not override the actual one. In the EV_TXCOMPLETE I set the sendPending flag to 0 if the send is complete.

MessageBuffer_t sendBuffer;
  if(sendPending == 1) {
    // do nothing just wait...
    ESP_LOGD(TAG, "waiting for TXComplete");
  } else {
    if (xQueueReceive(loraSendQueue, &sendBuffer, (TickType_t)0) == pdTRUE) {
      Preferences pref;
      pref.begin(PREFERENCES_KEY, false);
      ESP_LOGD(TAG, "counter before: %d", LMIC.seqnoUp);
      sendPending = 1;
      LMIC_setTxData2(sendBuffer.port, sendBuffer.payload, sendBuffer.size, 0);
      pref.putUInt("counter", LMIC.seqnoUp);
      ESP_LOGD(LORA_TAG, "msg=\"sending packet\" port=%d loraseq=%d bytes=%d",
              sendBuffer.port, LMIC.seqnoUp, sendBuffer.size);
      pref.end();
    }
  }

But for some reasons the sends don't do well. Sometimes they do not appear in TTN and sometimes they are tagged with the retry flag. I disabled the frame counter checks because I think the counter don't work well. Here are some output of the logged stuff:

The first send

[D][lorawan.cpp:177] processSendBuffer(): counter before: 36
[D][lorawan.cpp:182] processSendBuffer(): msg="sending packet" port=1 loraseq=37 bytes=2

The second one

[D][lorawan.cpp:177] processSendBuffer(): counter before: 37
[D][lorawan.cpp:182] processSendBuffer(): msg="sending packet" port=2 loraseq=37 bytes=11

So I think here is a problem because the counter count up at the first send but not in the second one. So the first and the second send tagged with the same sequence number.

Somebody got a clue why this problem appears? Thanks!

cstratton commented 4 years ago

It's unclear what exactly is going wrong here, but your attempt to use an 8-bit variable to persist LMIC.seqnoUp is going to fail quite quickly, as the LoRaWAN protocol requires that this be a 32 bit value. Even though only 16 bits are transmitted in the packet, both ends must keep track of the full 32 bit value and use it for the encryption and checksum operations.

The downlink sequence number is similarly 32 bits and must also be persisted.