simple serial protocol
Dependents: AwsomeStation LoRaBaseStation LoRaTerminal
CommandPacket2.cpp
- Committer:
- rba90
- Date:
- 2016-09-02
- Revision:
- 11:390476907bfc
File content as of revision 11:390476907bfc:
#include "CommandPacket2.h" #include <stdlib.h> #include <stdint.h> #include <string.h> #include <stdio.h> CommandPacket2::CommandPacket2() { // initialize payload memset(_payload, 0x0, sizeof(_payload)); // reset is verified state _isVerified = false; } CommandPacket2::~CommandPacket2() { } void CommandPacket2::setSFlag(uint8_t sflag) { _sflag = sflag; _isVerified = false; } void CommandPacket2::setCommand(uint8_t command) { _command = command; _isVerified = false; } void CommandPacket2::setLength(uint8_t length) { _length = length; _isVerified = false; } void CommandPacket2::setPayload(uint8_t idx, uint8_t payload) { _payload[idx] = payload; _isVerified = false; } void CommandPacket2::setChecksum(uint8_t checksum) { _checksum = checksum; _isVerified = false; } void CommandPacket2::setEFlag(uint8_t eflag) { _eflag = eflag; _isVerified = false; } uint8_t CommandPacket2::getSFlag() { return _sflag; } uint8_t CommandPacket2::getCommand() { return _command; } uint8_t CommandPacket2::getLength() { return _length; } uint8_t CommandPacket2::getPayload(uint8_t idx) { return _payload[idx]; } uint8_t CommandPacket2::getEFlag() { return _eflag; } uint8_t CommandPacket2::getChecksum() { return _checksum; } bool CommandPacket2::verify() { if (_isVerified) { return true; } else { return _checksum == calculate_checksum(); } } uint8_t CommandPacket2::calculate_checksum() { // take the sum of all user defined data bytes preceding checksum field uint8_t s = 0; // add command s += _command; // add length s += _length; // add payload for (uint8_t i = 0; i < _length; i++) { s += _payload[i]; } // calculate two's complement of the remainder s = 0xff - s + 1; return s; } void CommandPacket2::generateChecksum() { _checksum = calculate_checksum(); _isVerified = true; } int CommandPacket2::serialize(uint8_t *buffer) { // the user need to make sure that they have enough space for buffer if (!buffer) return 0; char octet[3]; int offset = 0; // cast content to output buffer // sflag buffer[offset] = _sflag; offset += 1; // command memset(octet, 0x0, sizeof(octet)); sprintf(octet, "%02X", _command); memcpy(buffer + offset, octet, 2); offset += 2; // length memset(octet, 0x0, sizeof(octet)); sprintf(octet, "%02X", _length); memcpy(buffer + offset, octet, 2); offset += 2; // payload for (uint8_t i = 0; i < _length; i++) { memset(octet, 0x0, sizeof(octet)); sprintf(octet, "%02X", _payload[i]); memcpy(buffer + offset, octet, 2); offset += 2; } // checksum memset(octet, 0x0, sizeof(octet)); sprintf(octet, "%02X", _checksum); memcpy(buffer + offset, octet, 2); offset += 2; // eflag buffer[offset] = _eflag; offset += 1; return offset; }