collar/collar.cpp

132 lines
2.6 KiB
C++
Raw Normal View History

2020-02-17 19:32:58 -08:00
#include <SPI.h>
#include <LoRa.h>
2020-02-22 16:39:33 -08:00
#include <TinyGPS++.h>
2020-02-17 19:32:58 -08:00
#include <SoftwareSerial.h>
#include "pb_common.h"
#include "pb.h"
#include "pb_encode.h"
#include "gateway/message.pb.h"
2020-02-17 19:32:58 -08:00
unsigned long previousMillis = 0;
const long interval = 5000;
float lat = 0;
float lng = 0;
2020-04-07 15:23:50 -07:00
bool sending = false;
2020-02-17 19:32:58 -08:00
TinyGPSPlus gps;
2020-02-22 16:39:33 -08:00
SoftwareSerial ss(6, 7);
2020-02-17 19:32:58 -08:00
2020-04-07 15:23:50 -07:00
typedef struct lora_status_s {
int sleep;
} lora_status_t;
static lora_status_t lora_status;
void transmitLora() {
// Encode as protobuf packet
if (lat && lng) {
uint8_t buffer[50] = {0};
Fenceless_CollarResponse m = Fenceless_CollarResponse_init_zero;
pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
m.loc.x = lat;
m.loc.y = lng;
int status = pb_encode(&stream, Fenceless_CollarResponse_fields, &m);
if (!status) {
Serial.println("Failed to encode");
}
Serial.print("Sending packet Lat / Long: ");
Serial.println(lat);
Serial.println(lng);
// send packet
LoRa.beginPacket();
LoRa.print((char *) buffer);
LoRa.endPacket();
}
}
void updateGPS() {
// Gather GPS data
if (gps.location.isValid()) {
lat = gps.location.lat();
lng = gps.location.lng();
} else {
lat = 0;
lng = 0;
}
}
ISR(TIMER1_OVF_vect) {
// handle timer overflow interrupt at 1 per second
updateGPS();
if(!gps.location.isValid()) {
Serial.println("Seeking GPS");
}
if(sending && gps.location.isValid()) {
if(lora_status.sleep) {
}
transmitLora();
}
}
void initialize_timer() {
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 34286; // timer preload
TCCR1B |= (1<<CS12); // prescale: 256 bits
TIMSK1 |= (1<<TOIE1); // overflow interrupt
interrupts();
}
2020-02-17 19:32:58 -08:00
void setup() {
Serial.begin(9600);
ss.begin(9600);
2020-04-07 15:23:50 -07:00
2020-02-17 19:32:58 -08:00
while (!Serial);
Serial.println("LoRa Transceiver");
if (!LoRa.begin(915E6)) {
Serial.println("Starting LoRa failed!");
while (1);
}
2020-04-07 15:23:50 -07:00
LoRa.setSpreadingFactor(7);
lora_status.sleep = 1;
//lora.sleep();
initialize_timer();
2020-02-17 19:32:58 -08:00
}
void loop() {
2020-04-07 15:23:50 -07:00
/* Get user input
*/
if(Serial.available()) {
char n = Serial.read();
if(n=='p') {
sending ? Serial.println("Sending is: disabled") : Serial.println("Sending is: enabled");
sending = !sending;
} else {
Serial.println("Type the letter 'p' to toggle sending");
}
}
/* GPS data recieved */
while (ss.available() > 0) {
gps.encode(ss.read());
}
/* Lora data recieved */
2020-02-17 19:32:58 -08:00
int packetSize = LoRa.parsePacket();
if (packetSize) {
Serial.print("Received Packet: ");
while (LoRa.available()) {
Serial.print((char) LoRa.read());
}
Serial.println();
}
}