Last active
August 29, 2015 14:27
-
-
Save dpruessner/f4736ecac5db01a27382 to your computer and use it in GitHub Desktop.
Example of framing with UART protocol
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
// | |
#define FRAME_SOF (0xFE) | |
#define FRAME_TYPE_WIFI_CONNECT (0x02) | |
char frame_buf[254]; | |
typedef struct { | |
unsigned char sof; | |
unsigned char flen; | |
unsigned char ftype; | |
} frame_t; | |
// Returns length of frame for marshaling out to UART or other | |
int frame_make_wifi(char* buffer, char* ssid, unsigned char ssid_len, char* pass, unsigned char pass_len) { | |
char *payload; | |
frame_t *frame; | |
int length; | |
unsigned char chksum = 0; | |
frame = (frame*)(buffer); // Allow struct access to directly modify buffer data | |
payload = buffer + sizeof(frame_t); | |
frame->sof = FRAME_SOF; | |
frame->ftype = FRAME_TYPE_WIFI_CONNECT; | |
*payload++ = ssid_len; | |
memcpy(payload, ssid, (size_t) ssid_len); | |
payload += ssid_len; | |
*payload++ = pass_len; | |
memcpy(payload, pass, (size_t) pass_len); | |
payload += pass_len; | |
// Length is FTYPE + 254b PAYLOAD; we remove SOF and FLEN (CHKSUM not included, but not counted so not reomved) | |
frame->flen = (payload - 2 - buffer); | |
payload = buffer + 1; // Skip SOF for checksum, which is (FLEN..PAYLOAD) | |
for (unsigned char c = 0; c < (frame->flen + 1); c++) // Add back FLEN field into length | |
chksum = *payload++; | |
// `payload` points to byte just past PAYLOAD field, where CHKSUM resides | |
*payload++ = chksum; | |
return (int)(payload - buffer); // includes all frame_t, payload, and CHKSUM | |
} | |
int main(void) { | |
/// do stuff. | |
int frame_length = frame_make_wifi(frame_buf, (char*)ssid /* from JSON */, (unsigned char)ssid_len, (char*)pass /* from JSON */, (unsigned char)pass_len); | |
uart_send(frame_buf, frame_length); // or something. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment