Skip to content

Instantly share code, notes, and snippets.

@cpq
Last active June 9, 2021 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpq/719a5d0f633d7f1b418e20055d255fb3 to your computer and use it in GitHub Desktop.
Save cpq/719a5d0f633d7f1b418e20055d255fb3 to your computer and use it in GitHub Desktop.
// This file contains two sketches for the end-user networking API that implements
// a simple WS service: WS message with JSON input {"pin": 12, "val": 0}, and JSON response {"status": true}
// WS handler, streaming API (think AVR)
// We don't buffer an incoming WS message. Instead, we feed
// TCP stack, and user handler, byte-by-byte.
// Some important values from the parsed HTTP header gets stored
// and passed to the user handler.
void ws_handler(struct conn *c, int event, size_t content_len, size_t receided_so_far, uint8_t byte) {
if (event == EVENT_INCOMING_BYTE) {
// Assume we have some sort of a streaming JSON parser. We feed it
if (received_so_far == 0) {
struct context *context = calloc(1, sizeof(*context));
set_user_data(c, context);
}
struct context *context = get_user_data(c);
// E.g. for parsing JSON, this state machine is quite complex, see any JSON library.
switch (context->state) {
case STATE_FOO:
....
break;
case BAR:
...
break;
case BAZ:
...
break;
case BLAH:
...
break;
default:
...
break;
}
if (received_so_far >= content_len) {
if (context->pin < 0 || context->val < 0) ....
gpio_write(context->pin, context->value);
conn_send("{\"status\":true}");
free(context);
set_user_data(NULL);
}
} else if (event == EVENT_ABNORMAL_TERMINATION) {
...
}
}
// API handler, buffered API.
// We don't need an event here, cause we call this only when full WS message gets buffered.
void ws_handler(struct conn *c, char *buf, size_t len) {
int pin = json_fetch_int(buf, len, "$.pin");
int val = json_fetch_int(buf, len, "$.val");
gpio_write(pin, val);
conn_send("{\"status\":true}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment