Command processor to access I2C and SPI Takes URI coded commands and returns JSON array
Fork of SerialInterface by
SerialInterface.cpp
- Committer:
- switches
- Date:
- 2016-12-08
- Revision:
- 4:0bd9ec504040
- Parent:
- 3:601b78524967
- Child:
- 5:9e27e2a46fa6
File content as of revision 4:0bd9ec504040:
/* Pmod Interface Library * */ #include "mbed.h" #include "SerialInterface.h" SerialInterface::SerialInterface() { } SerialInterface::~SerialInterface() { } // Initialize SerialInterface void SerialInterface::init(I2C* i2c, SPI* spi, DigitalOut* ssel) { _i2c = i2c; // save pointer to I2C interface _spi = spi; // save pointer to SPI interface _ssel = ssel; // save pointer to Select pin *_ssel = 1; // deselect SPI port } /* I2C * /i/[even]/[data]... write * /i/[odd]/[cnt]/[data]... read * [even] = even I2C address used for writes * [odd] = odd I2C address used for reads * [data] = data to be writen, if data is included with a read, the data * will be written prior to the read to set the register address * [cnt] = number of bytes to read * returns data read in JSON array */ void SerialInterface::fnc_i2c(char* resp) { int dcnt=0; if (_args[IA_CNT] < 2) { sprintf(resp, "[-1]"); } else { if (_args[IA_ADD] & 1) { sprintf(resp, "["); resp +=1; if (_args[IA_CNT] > 2) { for (dcnt = 0; dcnt < (_args[IA_CNT] -2) ; dcnt++) { _dbuf[dcnt] = _args[(dcnt +3)]; } if ((*_i2c).write(_args[IA_ADD], _dbuf, dcnt, true) != 0) { sprintf(resp, "-1,"); resp +=3; } } if ((*_i2c).read(_args[IA_ADD], _dbuf, _args[IA_DATA])!=0) { sprintf(resp, "-1]"); } else { for (dcnt = 0; dcnt < _args[IA_DATA]; dcnt++) { sprintf(resp,"0x%02X,", _dbuf[dcnt]); resp +=5; } sprintf((resp-1), "]"); } } else { for (dcnt = 0; dcnt < (_args[IA_CNT] -1) ; dcnt++) { _dbuf[dcnt] = _args[(dcnt +2)]; } if ((*_i2c).write(_args[IA_ADD], _dbuf, dcnt) == 0) { sprintf(resp,"[%d]", dcnt); } else { sprintf(resp, "[-1]"); } } } } /* SPI * /s/[data]... read+write * [data] = data to be writen * this shifts out each data byte provided and * returns each byte read in a JSON array */ void SerialInterface::fnc_spi(char* resp) { int dcnt=0; int dataIn; if (_args[0] < 1) { sprintf(resp, "[-1]"); } else { sprintf(resp, "["); resp++; *_ssel = 0; while(dcnt < _args[0]) { dcnt++; dataIn = (*_spi).write(_args[dcnt]); sprintf(resp, "0x%02X,", dataIn); resp += 5; } *_ssel = 1; sprintf((resp-1), "]"); } } void SerialInterface::call(char* input, char* output) { char cmd; _args[0] = 0; if (*input == '/') { input++; cmd = *input; input = strchr(input, '/'); while (*input == '/') { input++; _args[(_args[0]+1)] = strtol(input, &input, 0); if (input) { _args[0]++; } } switch (cmd) { case 'i': case 'I': fnc_i2c(output); break; case 's': case 'S': fnc_spi(output); break; default: sprintf(output, "!commands: i2c spi"); break; } } else { sprintf(output, "!format: /cmd/arg1/arg2..."); } }