-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJsonHandler.cpp
115 lines (97 loc) · 2.35 KB
/
JsonHandler.cpp
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 <JsonHandler.h>
#include <HardwareSerial.h>
#include <SD.h>
#define END_CMD_CHAR '!'
HardwareSerial Uart = HardwareSerial();
#define UART_BUFFER_SIZE 50
char response[200];
JsonHandler::JsonHandler(){
}
void JsonHandler::setup(){
Uart.begin(9600); // start Uart communication at 9600bps
}
bool JsonHandler::inputAvailable(){
return Uart.available() || Serial.available();
}
void JsonHandler::readChar(char &c){
if(Uart.available()){
c = Uart.read();
}
if(Serial.available()){
c = Serial.read();
}
}
void JsonHandler::readCommand(char* buffer, char* data){
bool dataInfo = false;
int i = 0;
//wait a some time to allow the input stream to buffer so we can read whole commands in.
delay(UART_BUFFER_SIZE);
while(inputAvailable()){
char inChar;
readChar(inChar);
if (inChar == END_CMD_CHAR){
return;
}
if(!dataInfo){
if (inChar == ','){
i=0;
dataInfo=true;
continue;
}
buffer[i] = inChar;
i++;
if( i > UART_BUFFER_SIZE ){
buffer[i-1] = '\0';
Uart.print("Command too long.");
}
buffer[i] = '\0';
}
else{
data[i] = inChar;
i++;
data[i] = '\0';
}
}
}
void JsonHandler::addKeyValuePair(const char* key, const char* val, bool firstPair){
char* appendChars = ",\"";
int offset = 1;
if (firstPair){
strcpy(response, "{}");
offset = 0;
appendChars = "\"";
}
int len = strlen(response);
int lenKey = strlen(key);
int lenVal = strlen(val);
strcpy(response+len-1, appendChars);
strcpy(response+len+offset, key);
strcpy(response+len+offset+lenKey, "\":\"");
strcpy(response+len+offset+lenKey+3, val);
strcpy(response+len+offset+lenKey+3+lenVal, "\"}");
response[strlen(response)+1] = '\0';
}
void JsonHandler::addKeyValuePair(const char* key, const char* val){
addKeyValuePair(key, val, false);
}
void JsonHandler::addKeyValuePair(const char* key, int val){
char buff[5];
itoa(val, buff, 10);
addKeyValuePair(key, buff, false);
}
void JsonHandler::respondString(char* data){
Uart.print(data);
Serial.print(data);
}
void JsonHandler::respond(){
respond(true);
}
void JsonHandler::respond(bool endChar){
//Serial.println(strlen(response));
Serial.println(response);
Uart.print(response);
if(endChar){
Uart.print(END_CMD_CHAR);
}
response[0] = '\0';
}