add optimizations

This commit is contained in:
sessionm21 2020-05-14 08:33:50 +01:00
parent 33f56ddd7d
commit 54af722760
2 changed files with 317 additions and 104 deletions

View File

@ -128,7 +128,7 @@ $(OUT)$(NAME).elf: protobufg bin $(OBJDIRS) $(OBJS)
$(CC) $(CFLAGS) -o $(OUT)$(NAME).elf collar.cpp $(INC_DIRS) $(OBJS) $(CC) $(CFLAGS) -o $(OUT)$(NAME).elf collar.cpp $(INC_DIRS) $(OBJS)
test: test:
g++ -o $(OUT)test prototest.cpp $(INC_DIRS) $(SRC_FILES_COMMON) g++ -o $(OUT)test test.c $(INC_DIRS) $(SRC_FILES_COMMON)
$(OUT)test $(OUT)test
protobufg: protobufg:

View File

@ -1,18 +1,30 @@
// Hello LoRa - ABP TTN Packet Sender (Multi-Channel) /*******************************************************************************
// Tutorial Link: https://learn.adafruit.com/the-things-network-for-feather/using-a-feather-32u4 * The Things Network - ABP Feather
// *
// Adafruit invests time and resources providing this open source code. * Example of using an Adafruit Feather M0 and DHT22 with a
// Please support Adafruit and open source hardware by purchasing * single-channel TheThingsNetwork gateway.
// products from Adafruit! *
// * This uses ABP (Activation by Personalization), where session keys for
// Copyright 2015, 2016 Ideetron B.V. * communication would be assigned/generated by TTN and hard-coded on the device.
// *
// Modified by Brent Rubell for Adafruit Industries, 2018 * Learn Guide: https://learn.adafruit.com/lora-pi
/************************** Configuration ***********************************/ *
* Copyright (c) 2015 Thomas Telkamp and Matthijs Kooijman
* Copyright (c) 2018 Terry Moore, MCCI
* Copyright (c) 2018 Brent Rubell, Adafruit Industries
*
* Permission is hereby granted, free of charge, to anyone
* obtaining a copy of this document and accompanying files,
* to do whatever they want with them without any restriction,
* including, but not limited to, copying, modification and redistribution.
* NO WARRANTY OF ANY KIND IS PROVIDED.
*******************************************************************************/
#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
#include <TinyGPS++.h> #include <TinyGPS++.h>
#include <SoftwareSerial.h> #include <SoftwareSerial.h>
#include <TinyLoRa.h>
#include <SPI.h>
#include "Base64.h" #include "Base64.h"
#include "gateway/message.pb.h" #include "gateway/message.pb.h"
@ -21,26 +33,75 @@
#include "pb_encode.h" #include "pb_encode.h"
#include "pb_decode.h" #include "pb_decode.h"
#include "lmic_project_config.h"
#include "gateway/message.pb.h" #include "gateway/message.pb.h"
// Visit your thethingsnetwork.org device console // DHT digital pin and sensor type
// to create an account, or if you need your session keys. #define DHTPIN 10
#define DHTTYPE DHT22
// Network Session Key (MSB) //
uint8_t NwkSkey[16] = {0x52, 0x92, 0xC0, 0x72, 0x2D, 0x3C, 0x55, 0x5E, 0xE4, 0xB9, 0x9E, 0x9B, 0x88, 0x66, 0x47, 0xF1}; // For normal use, we require that you edit the sketch to replace FILLMEIN
// with values assigned by the TTN console. However, for regression tests,
// we want to be able to compile these scripts. The regression tests define
// COMPILE_REGRESSION_TEST, and in that case we define FILLMEIN to a non-
// working but innocuous value.
//
/*
#ifdef COMPILE_REGRESSION_TEST
# define FILLMEIN 0
#else
# warning "You must replace the values marked FILLMEIN with real values from the TTN control panel!"
# define FILLMEIN (#dont edit this, edit the lines that use FILLMEIN)
#endif
*/
// LoRaWAN NwkSKey, network session key
static const PROGMEM u1_t NWKSKEY[16] = { 0x52, 0x92, 0xC0, 0x72, 0x2D, 0x3C, 0x55, 0x5E, 0xE4, 0xB9, 0x9E, 0x9B, 0x88, 0x66, 0x47, 0xF1 };
// Application Session Key (MSB) // LoRaWAN AppSKey, application session key
uint8_t AppSkey[16] = {0xC4, 0x30, 0xEF, 0x56, 0x4F, 0x6D, 0xA2, 0x56, 0x1F, 0x15, 0x2F, 0xB8, 0x62, 0xC7, 0xCA, 0xC2}; static const u1_t PROGMEM APPSKEY[16] = { 0xC4, 0x30, 0xEF, 0x56, 0x4F, 0x6D, 0xA2, 0x56, 0x1F, 0x15, 0x2F, 0xB8, 0x62, 0xC7, 0xCA, 0xC2 };
// Device Address (MSB) // LoRaWAN end-device address (DevAddr)
uint8_t DevAddr[4] = {0x26, 0x02, 0x12, 0xB6}; // See http://thethingsnetwork.org/wiki/AddressSpace
// The library converts the address to network byte order as needed.
#ifndef COMPILE_REGRESSION_TEST
static const u4_t DEVADDR = 0x260212B6;
#else
static const u4_t DEVADDR = 0;
#endif
// These callbacks are only used in over-the-air activation, so they are
// left empty here (we cannot leave them out completely unless
// DISABLE_JOIN is set in arduino-lmic/project_config/lmic_project_config.h,
// otherwise the linker will complain).
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
// payload to send to TTN gateway
//static uint8_t payload[] = "Hello, world!";
/************************** Example Begins Here ***********************************/
// Data Packet to Send to TTN // Data Packet to Send to TTN
unsigned char loraData[Fenceless_CollarResponse_size+1] = {0}; u1_t loraData[Fenceless_CollarResponse_size+1] = {0};
static osjob_t sendjob;
// How many times data transfer should occur, in seconds // Schedule TX every this many seconds (might become longer due to duty
const unsigned int sendInterval = 3000; // cycle limitations).
const unsigned TX_INTERVAL = 60;
// Pin mapping for Adafruit Feather M0 LoRa
const lmic_pinmap lmic_pins = {
.nss = 10,
.rxtx = LMIC_UNUSED_PIN,
.rst = 9,
.dio = {2, 3, LMIC_UNUSED_PIN},
.rxtx_rx_active = 0,
.rssi_cal = 8, // LBT cal for the Adafruit Feather M0 LoRa, in dB
.spi_freq = 8000000,
};
// init. DHT
//DHT dht(DHTPIN, DHTTYPE);
/**************************************************** /****************************************************
* Arduino drivers * Arduino drivers
@ -48,7 +109,6 @@ const unsigned int sendInterval = 3000;
* - GPS * - GPS
* - Software Serial * - Software Serial
***************************************************/ ***************************************************/
TinyLoRa lora = TinyLoRa(2, 10, 9);
TinyGPSPlus gps; TinyGPSPlus gps;
SoftwareSerial ss(6, 7); SoftwareSerial ss(6, 7);
@ -79,6 +139,7 @@ int push_vert(float x, float y) {
void clear_verts() { void clear_verts() {
n_poly=0; n_poly=0;
} }
/**************************************************** /****************************************************
* Check a pair of coordinates against two lists * Check a pair of coordinates against two lists
* of vertices * of vertices
@ -100,21 +161,6 @@ int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
int check_bounds(float x, float y) { int check_bounds(float x, float y) {
return pnpoly(n_poly, polyx, polyy, x, y); return pnpoly(n_poly, polyx, polyy, x, y);
} }
/****************************************************
* nanopb callback
***************************************************/
bool Fenceless_Coordinates_callback(pb_istream_t *stream, const pb_field_iter_t *field, void **arg) {
Serial.println("Called");
while(stream->bytes_left) {
Fenceless_Coordinate m = Fenceless_Coordinate_init_zero;
if(!pb_decode(stream, Fenceless_Coordinate_fields, &m)) {
return false;
}
push_vert(m.x,m.y);
return true;
}
return false;
}
/**************************************************** /****************************************************
* Load coordinates from protobuff stream * Load coordinates from protobuff stream
* - currently a maximum of 10 coordinates * - currently a maximum of 10 coordinates
@ -123,7 +169,7 @@ bool Fenceless_Coordinates_callback(pb_istream_t *stream, const pb_field_iter_t
***************************************************/ ***************************************************/
void import_protobuf(uint8_t *protobuffer, uint32_t size) { void import_protobuf(uint8_t *protobuffer, uint32_t size) {
Fenceless_Coordinates m; Fenceless_Coordinates m;
pb_istream_t stream = pb_istream_from_buffer(protobuffer, size); pb_istream_t stream = pb_istream_from_buffer(protobuffer, size);
int status = pb_decode(&stream, Fenceless_Coordinates_fields, &m); int status = pb_decode(&stream, Fenceless_Coordinates_fields, &m);
if(!status){ if(!status){
Serial.println("Failed to decode"); Serial.println("Failed to decode");
@ -150,48 +196,199 @@ void import_protobuf(uint8_t *protobuffer, uint32_t size) {
push_vert(m.coord0.x, m.coord0.y); push_vert(m.coord0.x, m.coord0.y);
} }
} }
/****************************************************
* Initialize values
***************************************************/
void setup()
{
// give GPS time to start up
delay(3000);
/****************************************************
* Configure USART void onEvent (ev_t ev) {
* - onboard serial to usb Serial.print(os_getTime());
* - software serial connected to GPS module Serial.print(": ");
***************************************************/ switch(ev) {
case EV_SCAN_TIMEOUT:
Serial.println(F("EV_SCAN_TIMEOUT"));
break;
case EV_BEACON_FOUND:
Serial.println(F("EV_BEACON_FOUND"));
break;
case EV_BEACON_MISSED:
Serial.println(F("EV_BEACON_MISSED"));
break;
case EV_BEACON_TRACKED:
Serial.println(F("EV_BEACON_TRACKED"));
break;
case EV_JOINING:
Serial.println(F("EV_JOINING"));
break;
case EV_JOINED:
Serial.println(F("EV_JOINED"));
break;
/*
|| This event is defined but not used in the code. No
|| point in wasting codespace on it.
||
|| case EV_RFU1:
|| Serial.println(F("EV_RFU1"));
|| break;
*/
case EV_JOIN_FAILED:
Serial.println(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
Serial.println(F("EV_REJOIN_FAILED"));
break;
case EV_TXCOMPLETE:
Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
/*
if (LMIC.txrxFlags & TXRX_ACK)
Serial.println(F("Received ack"));
if (LMIC.dataLen) {
Serial.println(F("Received "));
Serial.println(LMIC.dataLen);
Serial.println(F(" bytes of payload"));
for (int k=0; k<LMIC.dataLen; k++) {
Serial.print(LMIC.frame[k]);
}
}*/
// Schedule next transmission
//os_setTimedCallback(&sendjob, os_getTime()+sec2osticks(TX_INTERVAL), do_send);
break;
case EV_LOST_TSYNC:
Serial.println(F("EV_LOST_TSYNC"));
break;
case EV_RESET:
Serial.println(F("EV_RESET"));
break;
case EV_RXCOMPLETE:
// data received in ping slot
Serial.println(F("EV_RXCOMPLETE"));
break;
case EV_LINK_DEAD:
Serial.println(F("EV_LINK_DEAD"));
break;
case EV_LINK_ALIVE:
Serial.println(F("EV_LINK_ALIVE"));
break;
/*
|| This event is defined but not used in the code. No
|| point in wasting codespace on it.
||
|| case EV_SCAN_FOUND:
|| Serial.println(F("EV_SCAN_FOUND"));
|| break;
*/
case EV_TXSTART:
Serial.println(F("EV_TXSTART"));
break;
case EV_TXCANCELED:
Serial.println(F("EV_TXCANCELED"));
break;
case EV_RXSTART:
/* do not print anything -- it wrecks timing */
break;
case EV_JOIN_TXCOMPLETE:
Serial.println(F("EV_JOIN_TXCOMPLETE: no JoinAccept"));
break;
default:
Serial.print(F("Unknown event: "));
Serial.println((unsigned) ev);
break;
}
}
#define TYPE_STRING 0x0A
#define TYPE_VARIANT 0x10
#define PROTO_LEN 0x0A
#define FIELD_ONE_FLOAT 0x0D
#define FIELD_TWO_FLOAT 0x15
#define FIELD_TWO_VARIANT 0x10
uint8_t buffer[15] = {
TYPE_STRING,
PROTO_LEN,
FIELD_ONE_FLOAT, 0x00, 0x00, 0x48, 0x43,
FIELD_TWO_FLOAT, 0x00, 0x00, 0xc8, 0x42,
FIELD_TWO_VARIANT, 0, 0};
void do_send(osjob_t* j){
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Serial.println(F("OP_TXRXPEND, not sending"));
} else {
// prepare upstream data transmission at the next possible time.
// transmit on port 1 (the first parameter); you can use any value from 1 to 223 (others are reserved).
// don't request an ack (the last parameter, if not zero, requests an ack from the network).
// Remember, acks consume a lot of network resources; don't ask for an ack unless you really need it.
double a = 100.0;
for(int i=0;i<4;i++)
{
char buff[20];
sprintf(buff, "%04x", (uint8_t)a<<8*i);
Serial.println(buff);
}
float latitude = 123;
float longitude = 456;
memcpy(buffer+3, (void*)&latitude, 4);
memcpy(buffer+8, (void*)&longitude, 4);
LMIC_setTxData2(1, buffer, sizeof(buffer)-1, 0);
}
// Next TX is scheduled after TX_COMPLETE event.
}
void setup() {
delay(5000);
Serial.begin(9600); Serial.begin(9600);
ss.begin(4800); ss.begin(4800);
while (! Serial); while (! Serial);
delay(100);
Serial.println(F("Starting"));
pinMode(LED_BUILTIN, OUTPUT); pinMode(LED_BUILTIN, OUTPUT);
push_vert(44.55818, -123.28341); push_vert(44.55818, -123.28341);
push_vert(44.55818, -123.28332); push_vert(44.55818, -123.28332);
push_vert(44.558308, -123.28332); push_vert(44.558308, -123.28332);
push_vert(44.558308, -123.28341); push_vert(44.558308, -123.28341);
/****************************************************
* Configure LoRa
* - set to multi-channel
* - set datarate
* - start communication
* - set transmission power
***************************************************/
Serial.print("Starting LoRa...");
lora.setChannel(MULTI);
lora.setDatarate(SF12BW125); // SF7BW125
if(!lora.begin())
{
Serial.println("Failed");
Serial.println("Check your radio");
while(true);
}
lora.setPower(15); // 1
Serial.println("OK"); // LMIC init
os_init();
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
// Set static session parameters. Instead of dynamically establishing a session
// by joining the network, precomputed session parameters are be provided.
// On AVR, these values are stored in flash and only copied to RAM
// once. Copy them to a temporary buffer here, LMIC_setSession will
// copy them into a buffer of its own again.
uint8_t appskey[sizeof(APPSKEY)];
uint8_t nwkskey[sizeof(NWKSKEY)];
memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
LMIC_setSession (0x13, DEVADDR, nwkskey, appskey);
/*
// We'll disable all 72 channels used by TTN
for (int c = 0; c < 72; c++){
LMIC_disableChannel(c);
}
// We'll only enable Channel 16 (905.5Mhz) since we're transmitting on a single-channel
LMIC_enableChannel(16);
*/
LMIC_selectSubBand(1);
// Disable link check validation
LMIC_setLinkCheckMode(0);
// TTN uses SF9 for its RX2 window.
LMIC.dn2Dr = DR_SF9;
// Set data rate and transmit power for uplink
LMIC_setDrTxpow(DR_SF7,14);
// Start job
//do_send(&sendjob);
} }
/**************************************************** /****************************************************
@ -229,36 +426,34 @@ enum STATE_ {
WAITING_LORA, WAITING_LORA,
LORA_DONE LORA_DONE
}; };
int state = START_GPS; int state = SENDING_LORA;
int loopCounter = 0; int loopCounter = 0;
int startTime = 0; int startTime = 0;
/****************************************************
* Main loop
* - feeds data to GPS module as it is made void loop() {
* available
***************************************************/
void loop()
{
if(state == START_GPS) { if(state == START_GPS) {
Serial.println("Waiting for GPS"); Serial.println("Waiting for GPS");
state = WAITING_GPS; state = WAITING_GPS;
} }
else if(state == WAITING_GPS) { else if(state == WAITING_GPS) {
int got_data = read_gps(); //int got_data =
read_gps();
/**************************************************** /****************************************************
* loading bar animation * loading bar animation
***************************************************/ ***************************************************/
if(got_data) { //if(got_data) {
if(loopCounter%100==0) // if(loopCounter%100==0)
Serial.write('.'); // Serial.write('.');
if(loopCounter>PROGRESS_BAR_COUNT*100) { if(loopCounter>PROGRESS_BAR_COUNT*100) {
clear_line(); // clear_line();
loopCounter=0; // loopCounter=0;
//
state = VERIFYING_GPS; state = VERIFYING_GPS;
}
loopCounter++;
} }
// loopCounter++;
//}
} }
else if(state == VERIFYING_GPS) { else if(state == VERIFYING_GPS) {
/**************************************************** /****************************************************
@ -284,23 +479,33 @@ void loop()
* encode device information into a buffer using * encode device information into a buffer using
* protobuf * protobuf
***************************************************/ ***************************************************/
Fenceless_CollarResponse coord; // Fenceless_CollarResponse coord;
coord.loc.x = gps.location.lat(); // coord.loc.x = gps.location.lat();
coord.loc.y = gps.location.lng(); // coord.loc.y = gps.location.lng();
coord.oob = check_bounds(coord.loc.x, coord.loc.y); // coord.oob = check_bounds(coord.loc.x, coord.loc.y);
pb_ostream_t stream;
stream = pb_ostream_from_buffer(loraData, sizeof(loraData)); // pb_ostream_t stream;
pb_encode(&stream, Fenceless_CollarResponse_fields, &coord); // stream = pb_ostream_from_buffer(loraData, sizeof(loraData));
// pb_encode(&stream, Fenceless_CollarResponse_fields, &coord);
/**************************************************** /****************************************************
* send encoded buffer over LoRaWAN * send encoded buffer over LoRaWAN
***************************************************/ ***************************************************/
Serial.println("Sending LoRa Data..."); Serial.println("Sending LoRa Data...");
lora.sendData(loraData, stream.bytes_written, lora.frameCounter); do_send(&sendjob);
//lora.sendData(loraData, stream.bytes_written, lora.frameCounter);
Serial.print("Frame Counter: "); //lora.sendData(buffer, sizeof(buffer), lora.frameCounter);
Serial.println(lora.frameCounter);
if (LMIC.dataLen) {
Serial.println("Received data back from the gateway: ");
for (int i=0; i<LMIC.dataLen; i++)
Serial.print(LMIC.frame[i]);
}
//Serial.print("Frame Counter: ");
//Serial.println(lora.frameCounter);
/**************************************************** /****************************************************
* set reference time for LoRaWAN transmission delay * set reference time for LoRaWAN transmission delay
@ -319,11 +524,19 @@ void loop()
* if enough seconds have been delayed then move to * if enough seconds have been delayed then move to
* next state * next state
***************************************************/ ***************************************************/
if(millis()/1000 - startTime >= sendInterval) { if(millis()/1000 - startTime >= TX_INTERVAL) {
state = LORA_DONE; state = LORA_DONE;
} }
} }
else if(state == LORA_DONE) { else if(state == LORA_DONE) {
state = VERIFYING_GPS; state = VERIFYING_GPS;
} }
//os_runloop_once();
} }