-
Notifications
You must be signed in to change notification settings - Fork 0
/
lora.ino
116 lines (87 loc) · 2.09 KB
/
lora.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <LoRa.h>
void loRa_setup(long freq, int sf, int cs, int rst, int irq, String key) {
encryption_setup(key);
LoRa.setPins(cs, rst, irq);
if (!LoRa.begin(freq)) {
if (debug > 0) {
Serial.println("Starting LoRa failed!");
}
while (1);
}
LoRa.setSpreadingFactor(sf);
loRa_sleep();
if (debug > 0) {
Serial.println("Lora Started");
Serial.print("Frequency ");
Serial.print(freq);
Serial.print(" SF ");
Serial.println(sf);
}
}
String loRa_receiveMessage() {
int messageSize = LoRa.parsePacket();
String message = "";
if (messageSize) {
if (debug > 0) {
Serial.println("RECEIVED: ");
}
while (LoRa.available()) {
message += (char)LoRa.read();
}
}
if (message == "") {
return "";
}
return loRa_decrypt(message);
}
String loRa_receiveMessageAndConfirm() {
String message = loRa_receiveMessage();
if (message.length() > 0 && message != "-FAIL-" && message != "1" && message != "0") {
loRa_sendMessage("1");
}
loRa_sleep();
return message;
}
bool loRa_receiveConfirmMessage(String message) {
bool properMessageReceived = false;
unsigned long entry = millis();
while (properMessageReceived == false && millis() - entry < 2000) {
if (loRa_receiveMessage() == message) {
properMessageReceived = true;
}
delay(50);
}
loRa_sleep();
return properMessageReceived;
}
void loRa_sendMessage(String message) {
message = loRa_encrypt(message);
LoRa.beginPacket();
LoRa.print(message);
LoRa.endPacket();
loRa_sleep();
}
void loRa_sendMessageWithConfirm(String message) {
loRa_sendMessage(message);
int notReceivedCount = 0;
if (debug > 0) {
Serial.println("Sending message");
}
while (!loRa_receiveConfirmMessage("1") && notReceivedCount < 4) {
if (debug > 0) {
Serial.println("Retrying sending message...");
}
loRa_sendMessage(message);
notReceivedCount++;
}
if (notReceivedCount < 4) {
Serial.print("DONE");
} else {
Serial.print("FAILED");
}
}
void loRa_sleep() {
if (loraSleepEnabled > 0) {
LoRa.sleep();
}
}