forked from Longan-Labs/Serial_CAN_Bus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathat.cpp
111 lines (97 loc) · 1.82 KB
/
at.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
#include "at.h"
#include "board.h"
#include "errors.h"
#include <Arduino.h>
/// Ugly, will move this into AtState later.
static bool g_urc = true;
char g_output[OUTPUT_SIZE];
static bool isCorrectCommand(const char* command, const char* input)
{
size_t i = 0;
for (;;)
{
if (command[i] == '\0' && input[i] == '\0')
return true;
else if (command[i] == '=' && input[i] == '=')
return true;
else if (command[i] != input[i])
return false;
i++;
}
}
static void atExecute(AtState& state)
{
AtCommand* command = state.callbacks;
while (command->name != NULL && command->callback != NULL)
{
if (isCorrectCommand(command->name, state.readBuffer))
{
command->callback(state.callbackArg, state.readBuffer);
return;
}
command++;
}
atError(ERR_UNKNOWN_COMMAND);
}
void atError(int code)
{
Serial.print("ERROR: ");
Serial.print(code);
Serial.print("\n");
}
void atSend(const char* message)
{
Serial.print(message);
Serial.print("\n");
}
void atOk()
{
Serial.print("OK\n");
}
void atUrc(const char* line)
{
if (g_urc)
{
Serial.write("+");
Serial.write(line);
Serial.write("\n");
}
}
void atSetCallback(AtState& state, AtCommand* callbacks, void* arg)
{
state.callbacks = callbacks;
state.callbackArg = arg;
}
void atReadCommand(AtState& state)
{
int data = Serial.read();
if (data == -1 || data == '\r')
return;
ledOff();
if (state.echo)
{
Serial.write(data);
}
ledOn();
if (data == '\n')
{
if (state.readBufferLength == 0)
return;
if (state.readBufferLength < AT_READBUFFER_SIZE)
{
state.readBuffer[state.readBufferLength] = '\0';
atExecute(state);
}
else
{
atError("Command too long");
}
state.readBufferLength = 0;
return;
}
if (state.readBufferLength < AT_READBUFFER_SIZE)
{
state.readBuffer[state.readBufferLength] = data;
state.readBufferLength++;
}
}