uartp.c 1.69 KB
Newer Older
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
#include <stdint.h>
#include "uartp.h"

extern void uart_write(uint8_t x);
extern uint8_t uart_read();

// Simple serial protocol with packets and checksum
const uint8_t AMUX_TAG = 0xf9;
const uint8_t AMUX_END = 0xf3;
const uint8_t AMUX_EXT = 0x80;

void uartp_send(const void *src, uint16_t len) {
    uint8_t len_ind_0, len_ind_1, fcs, info;
    const uint8_t *buf = (const uint8_t *) src;

    uart_write(AMUX_TAG);
    len_ind_0 = (uint8_t) (0xff & len);
    len_ind_1 = (uint8_t) (0xff & (len >> 7));
    if (len < 128) {
        uart_write(len_ind_0);
    } else {
        uart_write(len_ind_0 | AMUX_EXT);
        uart_write(len_ind_1);
    }
    fcs = 0;
    for (uint16_t i = 0; i < len; i++) {
        info = buf[i];
        fcs += info;
        uart_write(buf[i]);
    }
    fcs = 255 - fcs;
    uart_write(fcs);
    uart_write(AMUX_END);
}


uint16_t uartp_recv(void *dst, uint16_t buf_len) {
    uint8_t *buf = (uint8_t *) dst;
    uint8_t tag_old, tag, info, cs;
    uint16_t len;

    tag = AMUX_END;
    while (1) {

        do {
            tag_old = tag;
            tag = uart_read();
        } while(tag != AMUX_TAG || tag_old != AMUX_END);

        len = (uint16_t) uart_read();
        if (len & AMUX_EXT) {
            len &= (~AMUX_EXT);
            len |= (uint16_t) (uart_read() << 7);
        }
        if (len > buf_len) {
            return len;
        }

        uint16_t i = 0;
        cs = 0;
        for (i = 0; i < len; i++) {
            info = uart_read();
            buf[i] = info;
            cs += info;
        }
        cs += uart_read();
        tag = uart_read();
        if (0xff == cs) {
            if (AMUX_END == tag) {
                return len;
            }
        }

    }
}