CAN message container. Defines "<<" and ">>" operators to simplify adding/getting data to/from a CAN message.

Dependents:   CAN_Hello EinlesenSensorabstand_digital_2 CAN_STABLE_EINSTEIN CAN_ex_STM32F103C8T6 ... more

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers CANMsg.h Source File

CANMsg.h

00001 #ifndef CANMSG_H
00002 #define CANMSG_H
00003 
00004 /* CAN message container.
00005  * Provides "<<" (append) and ">>" (extract) operators to simplyfy
00006  * adding/getting data items to/from a CAN message.
00007  * Usage is similar to the C++ io-stream operators.
00008  * Data length of CAN message is automatically updated when using "<<" or ">>" operators.
00009  *
00010  * See Wiki page <https://developer.mbed.org/users/hudakz/code/CAN_Hello/> for demo.
00011  */
00012 
00013 #include "CAN.h"
00014 
00015 class CANMsg : public mbed::CANMessage
00016 {
00017 public:
00018     /** Creates empty CAN message.
00019      */
00020     CANMsg() :
00021         CANMessage(){ }
00022 
00023     /** Creates CAN message with specific content.
00024      */
00025     CANMsg(int _id, const char *_data, char _len = 8, CANType _type = CANData, CANFormat _format = CANStandard) :
00026         CANMessage(_id, _data, _len, _type, _format){ }
00027 
00028     /** Creates CAN remote message.
00029      */
00030     CANMsg(int _id, CANFormat _format = CANStandard) :
00031         CANMessage(_id, _format){ }
00032 
00033     /** Clears CAN message content
00034      */
00035     void clear(void) {
00036         len    = 0;
00037         type   = CANData;
00038         format = CANStandard;
00039         id     = 0;
00040         memset(data, 0, 8);
00041     };
00042 
00043     /** Append operator: Appends data (value) to CAN message
00044      */
00045     template<class T>
00046     CANMsg &operator<<(const T val) {
00047         MBED_ASSERT(len + sizeof(T) <= 8);
00048         memcpy(&data[len], &val, sizeof(T));
00049         len += sizeof(T);
00050         return *this;
00051     }
00052 
00053     /** Extract operator: Extracts data (value) from CAN message
00054      */
00055     template<class T>
00056     CANMsg &operator>>(T& val) {
00057         MBED_ASSERT(sizeof(T) <= len);
00058         if (sizeof(T) > len) {
00059             memcpy(&val, data, len);
00060             len = 0;
00061         }
00062         else {
00063             memcpy(&val, data, sizeof(T));
00064             len -= sizeof(T);
00065         }
00066         memcpy(data, data + sizeof(T), len);
00067         return *this;
00068     }
00069 };
00070 
00071 #endif // CANMSG_H