AKM Development Platform. This is the D7.014 version.

Dependencies:   AK09970 AK099XX AK7401 AK7451 AK8963X AK9750 AK9752 AkmSensor BLE_API I2CNano MCP342x SerialNano SpiNano TCA9554A mbed nRF51822

Fork of AKDP by Masahiko Fukasawa

Message.cpp

Committer:
masahikofukasawa
Date:
2017-05-03
Branch:
multi_sensor_test
Revision:
40:24065d634473
Parent:
30:ea67020c9e05

File content as of revision 40:24065d634473:

#include "stdlib.h"
#include "Message.h"
#include "ctype.h"

#define HEXADECIMAL  16

Message::Status Message::asciiToChar(char *out, const char *in) {
    Status status = SUCCESS;
    
    if (isxdigit((int)in[0]) && isxdigit((int)in[1])) {    // Sanity check
        // Given input is valid.
        char tmp[] = {in[0], in[1], '\0'};
        *out = (char)strtol(tmp, NULL, HEXADECIMAL);
    } else if (in[0] == '\0' || in[0] == '\n') {
        // End of the string
        status = END_OF_STR;
    } else {
        // Contained an illegal character.
        status = ERROR_ILLEGAL_CHAR;
    }
    return status;
}

void Message::charToAscii(char *out, const char *in) {
    const char table[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    // higher byte
    out[0] = table[((*in >> 4) & 0x0f)];
    // lower byte
    out[1] = table[(*in & 0x0f)];
}


Message::Command Message::getCommand() const {
    return cmd;
}


int Message::getArgNum() const {
    return num_arg;
}

void Message::getArguments(char *buf, int maxNum) const {
    for (int i=0; i < maxNum; i++) {
        if (i >= num_arg) {
            break;
        }
        buf[i] = arg[i];
    }
}


char Message::getArgument(int index) const {
    char c = 0;
    
    if ( index < num_arg) {
        c = arg[index];
    }
    
    return c;
}

int Message::getMaxMessageLength() {
    return MAX_LEN;
}


Message::Status Message::parse(Message *msg, const char *str) {
    Status status = SUCCESS;
    
    // Parses command
    if ((status=asciiToChar((char*)&msg->cmd, &str[0])) != SUCCESS) {
        return status;
    }
    
    // Parses arguments
    int i = 0;
    while ((status=asciiToChar(&msg->arg[i], &str[2+i*2])) == SUCCESS) {
        i++;
    }
    if (status == ERROR_ILLEGAL_CHAR) {
        // Given string contains illegal character.
        return status;
    } else {
        status = SUCCESS;
    }
    
    msg->num_arg = i;
    
    return status;
}


void Message::setCommand(Message::Command cmd) {
    this->cmd = cmd;
}

void Message::setArguments(const char *arg, int len) {
    if (len > NUM_MAX_ARG) {  // sanity check
        return;
    }
    
    for (int i=0; i < len; i++) {
        this->arg[i] = arg[i];
    }

    num_arg = len;
}


void Message::setArgument(int index, char arg) {
    if (index > (NUM_MAX_ARG - 1)) { // sanity check
        return;
    }
    
    this->arg[index] = arg;
    
    int n = index + 1;
    if (num_arg < n) {
        num_arg = n;
    }
}