Benjamin Hepp / ait_link
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ait_link.h Source File

ait_link.h

00001 //
00002 // HDLC based serial communication class.
00003 //
00004 // Adapted by Benjamin Hepp from ArduHDLC library (see LICENSE.txt)
00005 // Original work Copyright (c) 2015 Jarkko Hautakorpi et al.
00006 // Modified work Copyright (c) 2016 Benjamin Hepp.
00007 
00008 #pragma once
00009 
00010 #include <stdint.h>
00011 #include <stdbool.h>
00012 #include <stddef.h>
00013 
00014 namespace ait {
00015 
00016   class AITLink {
00017   public:
00018     /* HDLC Asynchronous framing */
00019     /* The frame boundary octet is 01111110, (7E in hexadecimal notation) */
00020     const static uint8_t FRAME_BOUNDARY_OCTET = 0x7E;
00021 
00022     /* A "control escape octet", has the bit sequence '01111101', (7D hexadecimal) */
00023     const static uint8_t CONTROL_ESCAPE_OCTET = 0x7D;
00024 
00025     /* If either of these two octets appears in the transmitted data, an escape octet is sent, */
00026     /* followed by the original data octet with bit 5 inverted */
00027     const static uint8_t INVERT_OCTET = 0x20;
00028 
00029     /* The frame check sequence (FCS) is a 16-bit CRC-CCITT */
00030     /* AVR Libc CRC function is _crc_ccitt_update() */
00031     /* Corresponding CRC function in Qt (www.qt.io) is qChecksum() */
00032     const static uint16_t CRC16_CCITT_INIT_VAL = 0xFFFF;
00033 
00034     AITLink(size_t max_frame_length = 1024);
00035     virtual ~AITLink();
00036 
00037     bool sendFrame(const uint8_t* frame_buffer, size_t frame_length);
00038     void inputReceivedChar(uint8_t data);
00039 
00040     /* User must define a function, that will process the valid received frame */
00041     /* This function can act like a command router/dispatcher */
00042     void registerFrameHandler(void (*callback)(void* user_data, const uint8_t* frame_buffer, size_t frame_length), void* user_data);
00043 
00044   protected:
00045     virtual void handleFrame(const uint8_t* frame_buffer, size_t frame_length);
00046     /* User must define a function to send a byte throug USART, I2C, SPI etc.*/
00047     virtual void sendChar(uint8_t data) = 0;
00048 
00049   private:
00050     uint16_t crcCcittUpdate(uint16_t crc, uint8_t data);
00051 
00052     bool escape_character;
00053     size_t frame_position;
00054     // 16bit CRC sum for crcCcittUpdate
00055     uint16_t frame_checksum;
00056     size_t max_frame_length;
00057     uint8_t* receive_frame_buffer;
00058     void (*handle_frame_callback)(void* user_data, const uint8_t* frame_buffer, size_t frame_length);
00059     void* callback_user_data;
00060   };
00061 
00062 }