Created
August 15, 2018 15:33
-
-
Save xentec/444301a6202950881b8b7451d35d444a to your computer and use it in GitHub Desktop.
Arduino AT command mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef __AVR_ATmega328P__ | |
# define __AVR_ATmega328P__ // IDE helper | |
#endif | |
#include <Arduino.h> | |
struct cmd_pair | |
{ | |
const char *query, *response, *err; | |
}; | |
static const cmd_pair cmd_lk_tbl[] = { | |
// needs to stay sorted alphanumerically! | |
{ "AT", "", "" }, | |
{ "ATI", "Arduino", "" }, | |
}; | |
const size_t cmd_lk_len = sizeof(cmd_lk_tbl) / sizeof(cmd_lk_tbl[0]); | |
static int cmd_lk_cmp(const void *a, const void *b) | |
{ | |
return strcmp(((cmd_pair *) a)->query, ((cmd_pair *) b)->query); | |
} | |
String cmd_str; | |
// Main logic | |
//############ | |
void setup() | |
{ | |
cmd_str.reserve(128); | |
Serial.begin(9600); | |
randomSeed(analogRead(0)); | |
} | |
void loop() | |
{ | |
if(!Serial.available()) | |
return; | |
cmd_str = Serial.readStringUntil('\r'); | |
// if first char ist't uppercase, make the whole cmd_str upper case | |
// allows lowercase commands | |
if(!isupper(cmd_str[0])) | |
{ | |
for(auto &c : cmd_str) | |
c = toupper(c); | |
} | |
bool err = false; | |
const cmd_pair k = { cmd_str.c_str(), "", "NOT FOUND" }; | |
const cmd_pair *v = (cmd_pair *) bsearch(&k, cmd_lk_tbl, cmd_lk_len, sizeof(cmd_pair), &cmd_lk_cmp); | |
if(!v) | |
{ | |
err = true; | |
v = &k; | |
} | |
const char *resp, *stat; | |
if(err) | |
{ | |
resp = v->err; | |
stat = "ERROR"; | |
} | |
else | |
{ | |
resp = v->response; | |
stat = "OK"; | |
} | |
if(resp && resp[0]) | |
{ | |
Serial.write(resp); | |
Serial.write("\r\n"); | |
} | |
Serial.write(stat); | |
Serial.write("\r\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment