Summary
I want to connect an stm32L4 with RFM95) to TTN using ABP mode. This is my lorawan code ( am using the AES and sx1276 libraries )
Logs
<#include “lorawan.h”
#include “main.h”
#include “Encrypt_V31.h”
#include “AES-128_V10.h”
#include “SX1276.h”
#include <stdio.h>
#include <string.h>
#include “math.h”
static uint8_t Buffer[256]; // Global buffer for data
void lorawan_init(lorawan_t *lorawan, SX1276_t *sx1276) {
lorawan->sx1276 = sx1276;
}
void lorawan_set_keys(lorawan_t *lorawan, uint8_t NwkSkey, uint8_t AppSkey, uint8_t DevAddr) {
lorawan->NwkSkey = NwkSkey;
lorawan->AppSkey = AppSkey;
lorawan->DevAddr = DevAddr;
}
uint32_t lorawan_send_data(lorawan_t *lorawan, uint8_t *data, unsigned len, uint16_t frame_counter_up) {
unsigned char i;
unsigned char Direction = 0x00; // Direction of frame is up
unsigned char MIC[4];
unsigned char Mac_Header = 0x40; // Unconfirmed data up
unsigned char Frame_Control = 0x00;
unsigned char Frame_Port = 0x01;
// Test flag: if all data[i] == i then don't send but print encrypted data
int is_test = 1;
for (i = 0; i < len; i++) {
if (data[i] != i) {
is_test = 0;
break;
}
}
// Encrypt the payload
Encrypt_Payload(data, len, frame_counter_up, Direction, lorawan->AppSkey, lorawan->DevAddr);
Println("Data encrypted");
// Build the radio package
Buffer[0] = Mac_Header;
Buffer[1] = lorawan->DevAddr[3];
Buffer[2] = lorawan->DevAddr[2];
Buffer[3] = lorawan->DevAddr[1];
Buffer[4] = lorawan->DevAddr[0];
Buffer[5] = Frame_Control;
Buffer[6] = (frame_counter_up & 0x00FF);
Buffer[7] = ((frame_counter_up >> 8) & 0x00FF);
Buffer[8] = Frame_Port;
unsigned char SX1276_Package_Length = 9;
for (i = 0; i < len; i++) {
Buffer[SX1276_Package_Length + i] = data[i];
}
SX1276_Package_Length += len;
// Calculate MIC
Calculate_MIC(Buffer, MIC, SX1276_Package_Length, frame_counter_up, Direction, lorawan->NwkSkey, lorawan->DevAddr);
Println("MIC calculated");
// Print test package
if (is_test) {
Println("Encrypted data:");
for (i = 0; i < SX1276_Package_Length; i++) {
char temp[10];
sprintf(temp, "%02X ", Buffer[i]);
Println(temp);
}
return 0;
}
// Append MIC to the buffer
for (i = 0; i < 4; i++) {
Buffer[SX1276_Package_Length + i] = MIC[i];
}
SX1276_Package_Length += 4;
// Transmit the package
uint32_t result = SX1276_transmit(lorawan->sx1276, Buffer, SX1276_Package_Length, SX1276_DEFAULT_TIMEOUT);
if (result != 0) {
Println("Transmission failed");
} else {
Println("Transmission succeeded");
}
return result;
}
Hardware
SX1276 + STM32l476RCT