1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-06-17 22:23:10 +03:00

Run new astyle formatter against libs Bridge, SpacebrewYun and Temboo

This commit is contained in:
Federico Fissore
2013-10-21 10:13:31 +02:00
parent b4c68b3dff
commit 00bdd3df03
19 changed files with 841 additions and 805 deletions

View File

@ -28,17 +28,17 @@ void BridgeClass::begin() {
if (started) if (started)
return; return;
started = true; started = true;
// Wait for U-boot to finish startup // Wait for U-boot to finish startup
do { do {
dropAll(); dropAll();
delay(1000); delay(1000);
} while (stream.available()>0); } while (stream.available() > 0);
while (true) { while (true) {
// Bridge interrupt: // Bridge interrupt:
// - Ask the bridge to close itself // - Ask the bridge to close itself
uint8_t quit_cmd[] = {'X','X','X','X','X'}; uint8_t quit_cmd[] = {'X', 'X', 'X', 'X', 'X'};
max_retries = 1; max_retries = 1;
transfer(quit_cmd, 5); transfer(quit_cmd, 5);
@ -55,9 +55,9 @@ void BridgeClass::begin() {
stream.print(F("run-bridge\n")); stream.print(F("run-bridge\n"));
delay(500); delay(500);
dropAll(); dropAll();
// Reset the brigde to check if it is running // Reset the brigde to check if it is running
uint8_t cmd[] = {'X','X', '1','0','0'}; uint8_t cmd[] = {'X', 'X', '1', '0', '0'};
uint8_t res[1]; uint8_t res[1];
max_retries = 50; max_retries = 50;
uint16_t l = transfer(cmd, 5, res, 1); uint16_t l = transfer(cmd, 5, res, 1);
@ -70,7 +70,7 @@ void BridgeClass::begin() {
continue; continue;
} }
if (res[0] != 0) if (res[0] != 0)
while (true); while (true);
max_retries = 50; max_retries = 50;
return; return;
@ -95,7 +95,7 @@ unsigned int BridgeClass::get(const char *key, uint8_t *value, unsigned int maxl
} }
void BridgeClass::crcUpdate(uint8_t c) { void BridgeClass::crcUpdate(uint8_t c) {
CRC = _crc_ccitt_update(CRC, c); CRC = _crc_ccitt_update(CRC, c);
//CRC = CRC ^ c; //CRC = CRC ^ c;
//CRC = (CRC >> 8) + (CRC << 8); //CRC = (CRC >> 8) + (CRC << 8);
@ -115,13 +115,13 @@ bool BridgeClass::crcCheck(uint16_t _CRC) {
} }
uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1, uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1,
const uint8_t *buff2, uint16_t len2, const uint8_t *buff2, uint16_t len2,
const uint8_t *buff3, uint16_t len3, const uint8_t *buff3, uint16_t len3,
uint8_t *rxbuff, uint16_t rxlen) uint8_t *rxbuff, uint16_t rxlen)
{ {
uint16_t len = len1 + len2 + len3; uint16_t len = len1 + len2 + len3;
uint8_t retries = 0; uint8_t retries = 0;
for ( ; retries<max_retries; retries++, delay(100), dropAll() /* Delay for retransmission */) { for ( ; retries < max_retries; retries++, delay(100), dropAll() /* Delay for retransmission */) {
// Send packet // Send packet
crcReset(); crcReset();
stream.write((char)0xFF); // Start of packet (0xFF) stream.write((char)0xFF); // Start of packet (0xFF)
@ -132,31 +132,31 @@ uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1,
crcUpdate((len >> 8) & 0xFF); crcUpdate((len >> 8) & 0xFF);
stream.write((char)(len & 0xFF)); // Message length (lo) stream.write((char)(len & 0xFF)); // Message length (lo)
crcUpdate(len & 0xFF); crcUpdate(len & 0xFF);
for (uint16_t i=0; i<len1; i++) { // Payload for (uint16_t i = 0; i < len1; i++) { // Payload
stream.write((char)buff1[i]); stream.write((char)buff1[i]);
crcUpdate(buff1[i]); crcUpdate(buff1[i]);
} }
for (uint16_t i=0; i<len2; i++) { // Payload for (uint16_t i = 0; i < len2; i++) { // Payload
stream.write((char)buff2[i]); stream.write((char)buff2[i]);
crcUpdate(buff2[i]); crcUpdate(buff2[i]);
} }
for (uint16_t i=0; i<len3; i++) { // Payload for (uint16_t i = 0; i < len3; i++) { // Payload
stream.write((char)buff3[i]); stream.write((char)buff3[i]);
crcUpdate(buff3[i]); crcUpdate(buff3[i]);
} }
crcWrite(); // CRC crcWrite(); // CRC
// Wait for ACK in 100ms // Wait for ACK in 100ms
if (timedRead(100) != 0xFF) if (timedRead(100) != 0xFF)
continue; continue;
crcReset(); crcReset();
crcUpdate(0xFF); crcUpdate(0xFF);
// Check packet index // Check packet index
if (timedRead(5) != index) if (timedRead(5) != index)
continue; continue;
crcUpdate(index); crcUpdate(index);
// Recv len // Recv len
int lh = timedRead(10); int lh = timedRead(10);
if (lh < 0) if (lh < 0)
@ -171,7 +171,7 @@ uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1,
l += ll; l += ll;
// Recv data // Recv data
for (uint16_t i=0; i<l; i++) { for (uint16_t i = 0; i < l; i++) {
int c = timedRead(5); int c = timedRead(5);
if (c < 0) if (c < 0)
continue; continue;
@ -180,7 +180,7 @@ uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1,
rxbuff[i] = c; rxbuff[i] = c;
crcUpdate(c); crcUpdate(c);
} }
// Check CRC // Check CRC
int crc_hi = timedRead(5); int crc_hi = timedRead(5);
if (crc_hi < 0) if (crc_hi < 0)
@ -188,12 +188,12 @@ uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1,
int crc_lo = timedRead(5); int crc_lo = timedRead(5);
if (crc_lo < 0) if (crc_lo < 0)
continue; continue;
if (!crcCheck((crc_hi<<8)+crc_lo)) if (!crcCheck((crc_hi << 8) + crc_lo))
continue; continue;
// Increase index // Increase index
index++; index++;
// Return bytes received // Return bytes received
if (l > rxlen) if (l > rxlen)
return rxlen; return rxlen;
@ -210,7 +210,7 @@ int BridgeClass::timedRead(unsigned int timeout) {
do { do {
c = stream.read(); c = stream.read();
if (c >= 0) return c; if (c >= 0) return c;
} while(millis() - _startMillis < timeout); } while (millis() - _startMillis < timeout);
return -1; // -1 indicates timeout return -1; // -1 indicates timeout
} }
@ -222,8 +222,8 @@ void BridgeClass::dropAll() {
// Bridge instance // Bridge instance
#ifdef __AVR_ATmega32U4__ #ifdef __AVR_ATmega32U4__
// Leonardo variants (where HardwareSerial is Serial1) // Leonardo variants (where HardwareSerial is Serial1)
SerialBridgeClass Bridge(Serial1); SerialBridgeClass Bridge(Serial1);
#else #else
SerialBridgeClass Bridge(Serial); SerialBridgeClass Bridge(Serial);
#endif #endif

View File

@ -23,70 +23,80 @@
#include <Stream.h> #include <Stream.h>
class BridgeClass { class BridgeClass {
public: public:
BridgeClass(Stream &_stream); BridgeClass(Stream &_stream);
void begin(); void begin();
// Methods to handle key/value datastore
void put(const char *key, const char *value);
void put(const String &key, const String &value)
{ put(key.c_str(), value.c_str()); }
unsigned int get(const char *key, uint8_t *buff, unsigned int size);
unsigned int get(const char *key, char *value, unsigned int maxlen)
{ get(key, reinterpret_cast<uint8_t *>(value), maxlen); }
// Trasnfer a frame (with error correction and response)
uint16_t transfer(const uint8_t *buff1, uint16_t len1,
const uint8_t *buff2, uint16_t len2,
const uint8_t *buff3, uint16_t len3,
uint8_t *rxbuff, uint16_t rxlen);
// multiple inline versions of the same function to allow efficient frame concatenation
uint16_t transfer(const uint8_t *buff1, uint16_t len1)
{ return transfer(buff1, len1, NULL, 0); }
uint16_t transfer(const uint8_t *buff1, uint16_t len1,
uint8_t *rxbuff, uint16_t rxlen)
{ return transfer(buff1, len1, NULL, 0, rxbuff, rxlen); }
uint16_t transfer(const uint8_t *buff1, uint16_t len1,
const uint8_t *buff2, uint16_t len2,
uint8_t *rxbuff, uint16_t rxlen)
{ return transfer(buff1, len1, buff2, len2, NULL, 0, rxbuff, rxlen); }
static const int TRANSFER_TIMEOUT = 0xFFFF; // Methods to handle key/value datastore
void put(const char *key, const char *value);
void put(const String &key, const String &value)
{
put(key.c_str(), value.c_str());
}
unsigned int get(const char *key, uint8_t *buff, unsigned int size);
unsigned int get(const char *key, char *value, unsigned int maxlen)
{
get(key, reinterpret_cast<uint8_t *>(value), maxlen);
}
private: // Trasnfer a frame (with error correction and response)
uint8_t index; uint16_t transfer(const uint8_t *buff1, uint16_t len1,
int timedRead(unsigned int timeout); const uint8_t *buff2, uint16_t len2,
void dropAll(); const uint8_t *buff3, uint16_t len3,
uint8_t *rxbuff, uint16_t rxlen);
private: // multiple inline versions of the same function to allow efficient frame concatenation
void crcUpdate(uint8_t c); uint16_t transfer(const uint8_t *buff1, uint16_t len1)
void crcReset(); {
void crcWrite(); return transfer(buff1, len1, NULL, 0);
bool crcCheck(uint16_t _CRC); }
uint16_t CRC; uint16_t transfer(const uint8_t *buff1, uint16_t len1,
uint8_t *rxbuff, uint16_t rxlen)
private: {
static const char CTRL_C = 3; return transfer(buff1, len1, NULL, 0, rxbuff, rxlen);
Stream &stream; }
bool started; uint16_t transfer(const uint8_t *buff1, uint16_t len1,
uint8_t max_retries; const uint8_t *buff2, uint16_t len2,
uint8_t *rxbuff, uint16_t rxlen)
{
return transfer(buff1, len1, buff2, len2, NULL, 0, rxbuff, rxlen);
}
static const int TRANSFER_TIMEOUT = 0xFFFF;
private:
uint8_t index;
int timedRead(unsigned int timeout);
void dropAll();
private:
void crcUpdate(uint8_t c);
void crcReset();
void crcWrite();
bool crcCheck(uint16_t _CRC);
uint16_t CRC;
private:
static const char CTRL_C = 3;
Stream &stream;
bool started;
uint8_t max_retries;
}; };
// This subclass uses a serial port Stream // This subclass uses a serial port Stream
class SerialBridgeClass : public BridgeClass { class SerialBridgeClass : public BridgeClass {
public: public:
SerialBridgeClass(HardwareSerial &_serial) SerialBridgeClass(HardwareSerial &_serial)
: BridgeClass(_serial), serial(_serial) { : BridgeClass(_serial), serial(_serial) {
// Empty // Empty
} }
void begin(unsigned long baudrate = 250000) { void begin(unsigned long baudrate = 250000) {
serial.begin(baudrate); serial.begin(baudrate);
BridgeClass::begin(); BridgeClass::begin();
} }
private: private:
HardwareSerial &serial; HardwareSerial &serial;
}; };
extern SerialBridgeClass Bridge; extern SerialBridgeClass Bridge;

View File

@ -19,7 +19,7 @@
#include <Console.h> #include <Console.h>
// Default constructor uses global Bridge instance // Default constructor uses global Bridge instance
ConsoleClass::ConsoleClass() : ConsoleClass::ConsoleClass() :
bridge(Bridge), inBuffered(0), inReadPos(0), inBuffer(NULL), bridge(Bridge), inBuffered(0), inReadPos(0), inBuffer(NULL),
autoFlush(true) autoFlush(true)
{ {
@ -27,7 +27,7 @@ ConsoleClass::ConsoleClass() :
} }
// Constructor with a user provided BridgeClass instance // Constructor with a user provided BridgeClass instance
ConsoleClass::ConsoleClass(BridgeClass &_b) : ConsoleClass::ConsoleClass(BridgeClass &_b) :
bridge(_b), inBuffered(0), inReadPos(0), inBuffer(NULL), bridge(_b), inBuffered(0), inReadPos(0), inBuffer(NULL),
autoFlush(true) autoFlush(true)
{ {
@ -53,10 +53,10 @@ size_t ConsoleClass::write(uint8_t c) {
size_t ConsoleClass::write(const uint8_t *buff, size_t size) { size_t ConsoleClass::write(const uint8_t *buff, size_t size) {
if (autoFlush) { if (autoFlush) {
// TODO: do it in a more efficient way // TODO: do it in a more efficient way
uint8_t *tmp = new uint8_t[size+1]; uint8_t *tmp = new uint8_t[size + 1];
tmp[0] = 'P'; tmp[0] = 'P';
memcpy(tmp+1, buff, size); memcpy(tmp + 1, buff, size);
bridge.transfer(tmp, size+1); bridge.transfer(tmp, size + 1);
delete[] tmp; delete[] tmp;
return size; return size;
} else { } else {
@ -72,25 +72,25 @@ size_t ConsoleClass::write(const uint8_t *buff, size_t size) {
void ConsoleClass::flush() { void ConsoleClass::flush() {
if (autoFlush) if (autoFlush)
return; return;
bridge.transfer(outBuffer, outBuffered); bridge.transfer(outBuffer, outBuffered);
outBuffered = 1; outBuffered = 1;
} }
void ConsoleClass::noBuffer() { void ConsoleClass::noBuffer() {
if (autoFlush) if (autoFlush)
return; return;
delete[] outBuffer; delete[] outBuffer;
autoFlush = true; autoFlush = true;
} }
void ConsoleClass::buffer(uint8_t size) { void ConsoleClass::buffer(uint8_t size) {
noBuffer(); noBuffer();
if (size==0) if (size == 0)
return; return;
outBuffer = new uint8_t[size+1]; outBuffer = new uint8_t[size + 1];
outBuffer[0] = 'P'; // WRITE tag outBuffer[0] = 'P'; // WRITE tag
outBufferSize = size+1; outBufferSize = size + 1;
outBuffered = 1; outBuffered = 1;
autoFlush = false; autoFlush = false;
} }
@ -98,7 +98,7 @@ void ConsoleClass::buffer(uint8_t size) {
bool ConsoleClass::connected() { bool ConsoleClass::connected() {
uint8_t tmp = 'a'; uint8_t tmp = 'a';
bridge.transfer(&tmp, 1, &tmp, 1); bridge.transfer(&tmp, 1, &tmp, 1);
return tmp==1; return tmp == 1;
} }
int ConsoleClass::available() { int ConsoleClass::available() {

View File

@ -22,46 +22,48 @@
#include <Bridge.h> #include <Bridge.h>
class ConsoleClass : public Stream { class ConsoleClass : public Stream {
public: public:
// Default constructor uses global Bridge instance // Default constructor uses global Bridge instance
ConsoleClass(); ConsoleClass();
// Constructor with a user provided BridgeClass instance // Constructor with a user provided BridgeClass instance
ConsoleClass(BridgeClass &_b); ConsoleClass(BridgeClass &_b);
~ConsoleClass(); ~ConsoleClass();
void begin();
void end();
void buffer(uint8_t size); void begin();
void noBuffer(); void end();
bool connected(); void buffer(uint8_t size);
void noBuffer();
// Stream methods bool connected();
// (read from console socket)
int available();
int read();
int peek();
// (write to console socket)
size_t write(uint8_t);
size_t write(const uint8_t *buffer, size_t size);
void flush();
operator bool () { return connected(); }
private:
BridgeClass &bridge;
void doBuffer(); // Stream methods
uint8_t inBuffered; // (read from console socket)
uint8_t inReadPos; int available();
static const int BUFFER_SIZE = 32; int read();
uint8_t *inBuffer; int peek();
// (write to console socket)
bool autoFlush; size_t write(uint8_t);
uint8_t outBuffered; size_t write(const uint8_t *buffer, size_t size);
uint8_t outBufferSize; void flush();
uint8_t *outBuffer;
operator bool () {
return connected();
}
private:
BridgeClass &bridge;
void doBuffer();
uint8_t inBuffered;
uint8_t inReadPos;
static const int BUFFER_SIZE = 32;
uint8_t *inBuffer;
bool autoFlush;
uint8_t outBuffered;
uint8_t outBufferSize;
uint8_t *outBuffer;
}; };
extern ConsoleClass Console; extern ConsoleClass Console;

View File

@ -26,7 +26,7 @@ File::File(BridgeClass &b) : mode(255), bridge(b) {
File::File(const char *_filename, uint8_t _mode, BridgeClass &b) : mode(_mode), bridge(b) { File::File(const char *_filename, uint8_t _mode, BridgeClass &b) : mode(_mode), bridge(b) {
filename = _filename; filename = _filename;
char modes[] = {'r','w','a'}; char modes[] = {'r', 'w', 'a'};
uint8_t cmd[] = {'F', modes[mode]}; uint8_t cmd[] = {'F', modes[mode]};
uint8_t res[2]; uint8_t res[2];
dirPosition = 1; dirPosition = 1;
@ -53,12 +53,12 @@ size_t File::write(uint8_t c) {
size_t File::write(const uint8_t *buf, size_t size) { size_t File::write(const uint8_t *buf, size_t size) {
if (mode == 255) if (mode == 255)
return -1; return -1;
uint8_t cmd[] = {'g', handle}; uint8_t cmd[] = {'g', handle};
uint8_t res[1]; uint8_t res[1];
bridge.transfer(cmd, 2, buf, size, res, 1); bridge.transfer(cmd, 2, buf, size, res, 1);
if (res[0] != 0) // res[0] contains error code if (res[0] != 0) // res[0] contains error code
return -res[0]; return -res[0];
return size; return size;
} }
@ -91,7 +91,7 @@ boolean File::seek(uint32_t position) {
}; };
uint8_t res[1]; uint8_t res[1];
bridge.transfer(cmd, 6, res, 1); bridge.transfer(cmd, 6, res, 1);
if (res[0]==0) { if (res[0] == 0) {
// If seek succeed then flush buffers // If seek succeed then flush buffers
buffered = 0; buffered = 0;
return true; return true;
@ -121,10 +121,10 @@ void File::doBuffer() {
uint8_t cmd[] = {'G', handle, BUFFER_SIZE - 1}; uint8_t cmd[] = {'G', handle, BUFFER_SIZE - 1};
buffered = bridge.transfer(cmd, 3, buffer, BUFFER_SIZE) - 1; buffered = bridge.transfer(cmd, 3, buffer, BUFFER_SIZE) - 1;
//err = buff[0]; // First byte is error code //err = buff[0]; // First byte is error code
if (buffered>0) { if (buffered > 0) {
// Shift the reminder of buffer // Shift the reminder of buffer
for (uint8_t i=0; i<buffered; i++) for (uint8_t i = 0; i < buffered; i++)
buffer[i] = buffer[i+1]; buffer[i] = buffer[i + 1];
} }
} }
@ -166,7 +166,7 @@ boolean File::isDirectory() {
} }
File File::openNextFile(uint8_t mode){ File File::openNextFile(uint8_t mode) {
Process awk; Process awk;
char tmp; char tmp;
String command; String command;
@ -178,26 +178,26 @@ File File::openNextFile(uint8_t mode){
command += " | awk 'NR=="; command += " | awk 'NR==";
command += dirPosition; command += dirPosition;
command += "'"; command += "'";
awk.runShellCommand(command); awk.runShellCommand(command);
while(awk.running()); while (awk.running());
command = ""; command = "";
while (awk.available()){ while (awk.available()) {
tmp = awk.read(); tmp = awk.read();
if (tmp!='\n') command += tmp; if (tmp != '\n') command += tmp;
} }
if (command.length() == 0) if (command.length() == 0)
return File(); return File();
dirPosition++; dirPosition++;
filepath = filename + "/" + command; filepath = filename + "/" + command;
return File(filepath.c_str(),mode); return File(filepath.c_str(), mode);
}
void File::rewindDirectory(void){ }
void File::rewindDirectory(void) {
dirPosition = 1; dirPosition = 1;
} }

View File

@ -26,76 +26,76 @@
#define FILE_APPEND 2 #define FILE_APPEND 2
class File : public Stream { class File : public Stream {
public:
File(BridgeClass &b = Bridge);
File(const char *_filename, uint8_t _mode, BridgeClass &b = Bridge);
~File();
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buf, size_t size);
virtual int read();
virtual int peek();
virtual int available();
virtual void flush();
int read(void *buf, uint16_t nbyte);
boolean seek(uint32_t pos);
uint32_t position();
uint32_t size();
void close();
operator bool();
const char * name();
boolean isDirectory();
File openNextFile(uint8_t mode = FILE_READ);
void rewindDirectory(void);
//using Print::write;
private: public:
void doBuffer(); File(BridgeClass &b = Bridge);
uint8_t buffered; File(const char *_filename, uint8_t _mode, BridgeClass &b = Bridge);
uint8_t readPos; ~File();
uint16_t dirPosition;
static const int BUFFER_SIZE = 64; virtual size_t write(uint8_t);
uint8_t buffer[BUFFER_SIZE]; virtual size_t write(const uint8_t *buf, size_t size);
virtual int read();
virtual int peek();
private: virtual int available();
BridgeClass &bridge; virtual void flush();
String filename; int read(void *buf, uint16_t nbyte);
uint8_t mode; boolean seek(uint32_t pos);
uint8_t handle; uint32_t position();
uint32_t size();
void close();
operator bool();
const char * name();
boolean isDirectory();
File openNextFile(uint8_t mode = FILE_READ);
void rewindDirectory(void);
//using Print::write;
private:
void doBuffer();
uint8_t buffered;
uint8_t readPos;
uint16_t dirPosition;
static const int BUFFER_SIZE = 64;
uint8_t buffer[BUFFER_SIZE];
private:
BridgeClass &bridge;
String filename;
uint8_t mode;
uint8_t handle;
}; };
class FileSystemClass { class FileSystemClass {
public: public:
FileSystemClass() : bridge(Bridge) { } FileSystemClass() : bridge(Bridge) { }
FileSystemClass(BridgeClass &_b) : bridge(_b) { } FileSystemClass(BridgeClass &_b) : bridge(_b) { }
boolean begin();
// Open the specified file/directory with the supplied mode (e.g. read or
// write, etc). Returns a File object for interacting with the file.
// Note that currently only one file can be open at a time.
File open(const char *filename, uint8_t mode = FILE_READ);
// Methods to determine if the requested file path exists. boolean begin();
boolean exists(const char *filepath);
// Create the requested directory heirarchy--if intermediate directories // Open the specified file/directory with the supplied mode (e.g. read or
// do not exist they will be created. // write, etc). Returns a File object for interacting with the file.
boolean mkdir(const char *filepath); // Note that currently only one file can be open at a time.
File open(const char *filename, uint8_t mode = FILE_READ);
// Delete the file.
boolean remove(const char *filepath);
boolean rmdir(const char *filepath);
private: // Methods to determine if the requested file path exists.
friend class File; boolean exists(const char *filepath);
BridgeClass &bridge; // Create the requested directory heirarchy--if intermediate directories
// do not exist they will be created.
boolean mkdir(const char *filepath);
// Delete the file.
boolean remove(const char *filepath);
boolean rmdir(const char *filepath);
private:
friend class File;
BridgeClass &bridge;
}; };
extern FileSystemClass FileSystem; extern FileSystemClass FileSystem;

View File

@ -22,14 +22,14 @@
#include <Process.h> #include <Process.h>
class HttpClient : public Process { class HttpClient : public Process {
public: public:
unsigned int get(String &url); unsigned int get(String &url);
unsigned int get(const char * url); unsigned int get(const char * url);
void getAsynchronously(String &url); void getAsynchronously(String &url);
void getAsynchronously(const char * url); void getAsynchronously(const char * url);
boolean ready(); boolean ready();
unsigned int getResult(); unsigned int getResult();
}; };

View File

@ -26,7 +26,7 @@ unsigned int MailboxClass::readMessage(uint8_t *buff, unsigned int size) {
void MailboxClass::readMessage(String &str, unsigned int maxLength) { void MailboxClass::readMessage(String &str, unsigned int maxLength) {
uint8_t tmp[] = { 'm' }; uint8_t tmp[] = { 'm' };
// XXX: Is there a better way to create the string? // XXX: Is there a better way to create the string?
uint8_t buff[maxLength+1]; uint8_t buff[maxLength + 1];
int l = bridge.transfer(tmp, 1, buff, maxLength); int l = bridge.transfer(tmp, 1, buff, maxLength);
buff[l] = 0; buff[l] = 0;
str = (const char *)buff; str = (const char *)buff;

View File

@ -22,30 +22,30 @@
#include <Bridge.h> #include <Bridge.h>
class MailboxClass { class MailboxClass {
public: public:
MailboxClass(BridgeClass &b = Bridge) : bridge(b) { } MailboxClass(BridgeClass &b = Bridge) : bridge(b) { }
void begin() { } void begin() { }
void end() { } void end() { }
// Receive a message and store it inside a buffer // Receive a message and store it inside a buffer
unsigned int readMessage(uint8_t *buffer, unsigned int size); unsigned int readMessage(uint8_t *buffer, unsigned int size);
// Receive a message and store it inside a String // Receive a message and store it inside a String
void readMessage(String &str, unsigned int maxLength=128); void readMessage(String &str, unsigned int maxLength = 128);
// Send a message // Send a message
void writeMessage(const uint8_t *buffer, unsigned int size); void writeMessage(const uint8_t *buffer, unsigned int size);
// Send a message // Send a message
void writeMessage(const String& str); void writeMessage(const String& str);
// Send a JSON message // Send a JSON message
void writeJSON(const String& str); void writeJSON(const String& str);
// Return the size of the next available message, 0 if there are // Return the size of the next available message, 0 if there are
// no messages in queue. // no messages in queue.
unsigned int messageAvailable(); unsigned int messageAvailable();
private: private:
BridgeClass &bridge; BridgeClass &bridge;
}; };
extern MailboxClass Mailbox; extern MailboxClass Mailbox;

View File

@ -84,8 +84,8 @@ void Process::runAsynchronously() {
delete cmdline; delete cmdline;
cmdline = NULL; cmdline = NULL;
if (res[0]==0) // res[0] contains error code if (res[0] == 0) // res[0] contains error code
started = true; started = true;
} }

View File

@ -22,48 +22,50 @@
#include <Bridge.h> #include <Bridge.h>
class Process : public Stream { class Process : public Stream {
public: public:
// Constructor with a user provided BridgeClass instance // Constructor with a user provided BridgeClass instance
Process(BridgeClass &_b = Bridge) : Process(BridgeClass &_b = Bridge) :
bridge(_b), started(false), buffered(0), readPos(0) { } bridge(_b), started(false), buffered(0), readPos(0) { }
~Process(); ~Process();
void begin(const String &command);
void addParameter(const String &param);
unsigned int run();
void runAsynchronously();
boolean running();
unsigned int exitValue();
void close();
unsigned int runShellCommand(const String &command); void begin(const String &command);
void runShellCommandAsynchronously(const String &command); void addParameter(const String &param);
unsigned int run();
void runAsynchronously();
boolean running();
unsigned int exitValue();
void close();
operator bool () { return started; } unsigned int runShellCommand(const String &command);
void runShellCommandAsynchronously(const String &command);
// Stream methods operator bool () {
// (read from process stdout) return started;
int available(); }
int read();
int peek(); // Stream methods
// (write to process stdin) // (read from process stdout)
size_t write(uint8_t); int available();
void flush(); int read();
// TODO: add optimized function for block write int peek();
// (write to process stdin)
private: size_t write(uint8_t);
BridgeClass &bridge; void flush();
unsigned int handle; // TODO: add optimized function for block write
String *cmdline;
boolean started; private:
BridgeClass &bridge;
unsigned int handle;
String *cmdline;
boolean started;
private:
void doBuffer();
uint8_t buffered;
uint8_t readPos;
static const int BUFFER_SIZE = 64;
uint8_t buffer[BUFFER_SIZE];
private:
void doBuffer();
uint8_t buffered;
uint8_t readPos;
static const int BUFFER_SIZE = 64;
uint8_t buffer[BUFFER_SIZE];
}; };
#endif #endif

View File

@ -30,9 +30,9 @@ YunClient::~YunClient() {
} }
YunClient& YunClient::operator=(const YunClient &_x) { YunClient& YunClient::operator=(const YunClient &_x) {
opened = _x.opened; opened = _x.opened;
handle = _x.handle; handle = _x.handle;
return *this; return *this;
} }
void YunClient::stop() { void YunClient::stop() {
@ -73,13 +73,13 @@ int YunClient::read() {
int YunClient::read(uint8_t *buff, size_t size) { int YunClient::read(uint8_t *buff, size_t size) {
int readed = 0; int readed = 0;
do { do {
if (buffered == 0) { if (buffered == 0) {
doBuffer(); doBuffer();
if (buffered == 0) if (buffered == 0)
return readed; return readed;
} }
buff[readed++] = buffer[readPos++]; buff[readed++] = buffer[readPos++];
buffered--; buffered--;
} while (readed < size); } while (readed < size);
return readed; return readed;
} }
@ -141,7 +141,7 @@ int YunClient::connect(const char *host, uint16_t port) {
}; };
uint8_t res[1]; uint8_t res[1];
int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1);
if (l==0) if (l == 0)
return 0; return 0;
handle = res[0]; handle = res[0];

View File

@ -23,46 +23,48 @@
#include <Client.h> #include <Client.h>
class YunClient : public Client { class YunClient : public Client {
public: public:
// Constructor with a user provided BridgeClass instance // Constructor with a user provided BridgeClass instance
YunClient(int _h, BridgeClass &_b = Bridge); YunClient(int _h, BridgeClass &_b = Bridge);
YunClient(BridgeClass &_b = Bridge); YunClient(BridgeClass &_b = Bridge);
~YunClient(); ~YunClient();
// Stream methods
// (read message)
virtual int available();
virtual int read();
virtual int read(uint8_t *buf, size_t size);
virtual int peek();
// (write response)
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buf, size_t size);
virtual void flush();
// TODO: add optimized function for block write
virtual operator bool () { return opened; }
YunClient& operator=(const YunClient &_x); // Stream methods
// (read message)
virtual int available();
virtual int read();
virtual int read(uint8_t *buf, size_t size);
virtual int peek();
// (write response)
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buf, size_t size);
virtual void flush();
// TODO: add optimized function for block write
virtual void stop(); virtual operator bool () {
virtual uint8_t connected(); return opened;
}
virtual int connect(IPAddress ip, uint16_t port); YunClient& operator=(const YunClient &_x);
virtual int connect(const char *host, uint16_t port);
private: virtual void stop();
BridgeClass &bridge; virtual uint8_t connected();
unsigned int handle;
boolean opened; virtual int connect(IPAddress ip, uint16_t port);
virtual int connect(const char *host, uint16_t port);
private:
BridgeClass &bridge;
unsigned int handle;
boolean opened;
private:
void doBuffer();
uint8_t buffered;
uint8_t readPos;
static const int BUFFER_SIZE = 64;
uint8_t buffer[BUFFER_SIZE];
private:
void doBuffer();
uint8_t buffered;
uint8_t readPos;
static const int BUFFER_SIZE = 64;
uint8_t buffer[BUFFER_SIZE];
}; };
#endif // _YUN_CLIENT_H_ #endif // _YUN_CLIENT_H_

View File

@ -41,7 +41,7 @@ YunClient YunServer::accept() {
uint8_t cmd[] = {'k'}; uint8_t cmd[] = {'k'};
uint8_t res[1]; uint8_t res[1];
unsigned int l = bridge.transfer(cmd, 1, res, 1); unsigned int l = bridge.transfer(cmd, 1, res, 1);
if (l==0) if (l == 0)
return YunClient(); return YunClient();
return YunClient(res[0]); return YunClient(res[0]);
} }

View File

@ -25,23 +25,27 @@
class YunClient; class YunClient;
class YunServer : public Server { class YunServer : public Server {
public: public:
// Constructor with a user provided BridgeClass instance // Constructor with a user provided BridgeClass instance
YunServer(uint16_t port = 5555, BridgeClass &_b = Bridge); YunServer(uint16_t port = 5555, BridgeClass &_b = Bridge);
void begin(); void begin();
YunClient accept(); YunClient accept();
virtual size_t write(uint8_t c); virtual size_t write(uint8_t c);
void listenOnLocalhost() { useLocalhost = true; } void listenOnLocalhost() {
void noListenOnLocalhost() { useLocalhost = false; } useLocalhost = true;
}
void noListenOnLocalhost() {
useLocalhost = false;
}
private: private:
uint16_t port; uint16_t port;
bool listening; bool listening;
bool useLocalhost; bool useLocalhost;
BridgeClass &bridge; BridgeClass &bridge;
}; };
#endif // _YUN_SERVER_H_ #endif // _YUN_SERVER_H_

View File

@ -2,34 +2,34 @@
SpacebrewYun::SpacebrewYun(const String& _name, const String& _description) { SpacebrewYun::SpacebrewYun(const String& _name, const String& _description) {
name = _name; name = _name;
description = _description; description = _description;
subscribers = NULL; subscribers = NULL;
publishers = NULL; publishers = NULL;
server = "sandbox.spacebrew.cc"; server = "sandbox.spacebrew.cc";
port = 9000; port = 9000;
_connected = false; _connected = false;
_verbose = false; _verbose = false;
_error_msg = false; _error_msg = false;
sub_name = ""; sub_name = "";
sub_msg = ""; sub_msg = "";
sub_type = ""; sub_type = "";
read_name = false; read_name = false;
read_msg = false; read_msg = false;
for ( int i = 0; i < pidLength; i++ ) { for ( int i = 0; i < pidLength; i++ ) {
pid [i] = '\0'; pid [i] = '\0';
} }
for ( int i = 0; i < sbPidsLen; i++ ) { for ( int i = 0; i < sbPidsLen; i++ ) {
sbPids [i] = '\0'; sbPids [i] = '\0';
} }
Console.buffer(64); Console.buffer(64);
} }
@ -45,346 +45,348 @@ SpacebrewYun::OnSBOpen SpacebrewYun::_onOpen = NULL;
SpacebrewYun::OnSBClose SpacebrewYun::_onClose = NULL; SpacebrewYun::OnSBClose SpacebrewYun::_onClose = NULL;
SpacebrewYun::OnSBError SpacebrewYun::_onError = NULL; SpacebrewYun::OnSBError SpacebrewYun::_onError = NULL;
void SpacebrewYun::onOpen(OnSBOpen function){ void SpacebrewYun::onOpen(OnSBOpen function) {
_onOpen = function; _onOpen = function;
} }
void SpacebrewYun::onClose(OnSBClose function){ void SpacebrewYun::onClose(OnSBClose function) {
_onClose = function; _onClose = function;
} }
void SpacebrewYun::onRangeMessage(OnRangeMessage function){ void SpacebrewYun::onRangeMessage(OnRangeMessage function) {
_onRangeMessage = function; _onRangeMessage = function;
} }
void SpacebrewYun::onStringMessage(OnStringMessage function){ void SpacebrewYun::onStringMessage(OnStringMessage function) {
_onStringMessage = function; _onStringMessage = function;
} }
void SpacebrewYun::onBooleanMessage(OnBooleanMessage function){ void SpacebrewYun::onBooleanMessage(OnBooleanMessage function) {
_onBooleanMessage = function; _onBooleanMessage = function;
} }
void SpacebrewYun::onCustomMessage(OnCustomMessage function){ void SpacebrewYun::onCustomMessage(OnCustomMessage function) {
_onCustomMessage = function; _onCustomMessage = function;
} }
void SpacebrewYun::onError(OnSBError function){ void SpacebrewYun::onError(OnSBError function) {
_onError = function; _onError = function;
} }
void SpacebrewYun::addPublish(const String& name, const String& type) { void SpacebrewYun::addPublish(const String& name, const String& type) {
struct Publisher *p = new Publisher(); struct Publisher *p = new Publisher();
p->name = createString(name.length() + 1); p->name = createString(name.length() + 1);
p->type = createString(type.length() + 1); p->type = createString(type.length() + 1);
p->confirmed = false; p->confirmed = false;
p->time = 0; p->time = 0;
if (type == "range") { if (type == "range") {
p->lastMsg = createString(sub_msg_int_max); p->lastMsg = createString(sub_msg_int_max);
emptyString(p->lastMsg, sub_msg_int_max); emptyString(p->lastMsg, sub_msg_int_max);
} }
else if (type == "boolean") { else if (type == "boolean") {
p->lastMsg = createString(sub_msg_bool_max); p->lastMsg = createString(sub_msg_bool_max);
emptyString(p->lastMsg, sub_msg_bool_max); emptyString(p->lastMsg, sub_msg_bool_max);
} }
else { else {
p->lastMsg = createString(sub_msg_str_max); p->lastMsg = createString(sub_msg_str_max);
emptyString(p->lastMsg, sub_msg_str_max); emptyString(p->lastMsg, sub_msg_str_max);
} }
name.toCharArray(p->name, name.length() + 1); name.toCharArray(p->name, name.length() + 1);
type.toCharArray(p->type, type.length() + 1); type.toCharArray(p->type, type.length() + 1);
if (publishers == NULL){ if (publishers == NULL) {
publishers = p; publishers = p;
} }
else { else {
struct Publisher *curr = publishers; struct Publisher *curr = publishers;
int counter = 1; int counter = 1;
while(curr->next != NULL){ while (curr->next != NULL) {
curr = curr->next; curr = curr->next;
counter++; counter++;
} }
curr->next = p; curr->next = p;
} }
p->next = NULL; p->next = NULL;
} }
void SpacebrewYun::addSubscribe(const String& name, const String& type) { void SpacebrewYun::addSubscribe(const String& name, const String& type) {
Subscriber *s = new Subscriber(); Subscriber *s = new Subscriber();
s->name = createString(name.length() + 1); s->name = createString(name.length() + 1);
s->type = createString(type.length() + 1); s->type = createString(type.length() + 1);
name.toCharArray(s->name, name.length() + 1); name.toCharArray(s->name, name.length() + 1);
type.toCharArray(s->type, type.length() + 1); type.toCharArray(s->type, type.length() + 1);
if (subscribers == NULL){ if (subscribers == NULL) {
subscribers = s; subscribers = s;
} }
else { else {
struct Subscriber *curr = subscribers; struct Subscriber *curr = subscribers;
while(curr->next != NULL){ while (curr->next != NULL) {
curr = curr->next; curr = curr->next;
} }
curr->next = s; curr->next = s;
} }
} }
void SpacebrewYun::connect(String _server, int _port) { void SpacebrewYun::connect(String _server, int _port) {
server = _server; server = _server;
port = _port; port = _port;
killPids();
brew.begin("run-spacebrew"); // Process should launch the "curl" command killPids();
// brew.begin("python"); // Process should launch the "curl" command
// brew.addParameter("/usr/lib/python2.7/spacebrew/spacebrew.py"); // Process should launch the "curl" command
brew.addParameter("--server");
brew.addParameter(server);
brew.addParameter("--port");
brew.addParameter(String(port));
brew.addParameter("-n");
brew.addParameter(name);
brew.addParameter("-d");
brew.addParameter(description);
if (subscribers != NULL) { brew.begin("run-spacebrew"); // Process should launch the "curl" command
struct Subscriber *curr = subscribers; // brew.begin("python"); // Process should launch the "curl" command
while(curr != NULL){ // brew.addParameter("/usr/lib/python2.7/spacebrew/spacebrew.py"); // Process should launch the "curl" command
if (_verbose) { brew.addParameter("--server");
Serial.print(F("Creating subscribers: ")); brew.addParameter(server);
Serial.print(curr->name); brew.addParameter("--port");
Serial.print(F(" of type: ")); brew.addParameter(String(port));
Serial.println(curr->type); brew.addParameter("-n");
} brew.addParameter(name);
brew.addParameter("-d");
brew.addParameter(description);
brew.addParameter("-s"); // Add the URL parameter to "curl" if (subscribers != NULL) {
brew.addParameter(curr->name); // Add the URL parameter to "curl" struct Subscriber *curr = subscribers;
brew.addParameter(","); // Add the URL parameter to "curl" while (curr != NULL) {
brew.addParameter(curr->type); // Add the URL parameter to "curl" if (_verbose) {
Serial.print(F("Creating subscribers: "));
Serial.print(curr->name);
Serial.print(F(" of type: "));
Serial.println(curr->type);
}
// if (curr->next == NULL) curr = NULL; brew.addParameter("-s"); // Add the URL parameter to "curl"
// else curr = curr->next; brew.addParameter(curr->name); // Add the URL parameter to "curl"
brew.addParameter(","); // Add the URL parameter to "curl"
brew.addParameter(curr->type); // Add the URL parameter to "curl"
curr = curr->next; // if (curr->next == NULL) curr = NULL;
} // else curr = curr->next;
}
if (publishers != NULL) {
struct Publisher *curr = publishers;
while(curr != NULL){
if (_verbose) {
Serial.print(F("Creating publishers: "));
Serial.print(curr->name);
Serial.print(F(" of type: "));
Serial.println(curr->type);
}
brew.addParameter("-p"); // Add the URL parameter to "curl"
brew.addParameter(curr->name); // Add the URL parameter to "curl"
brew.addParameter(","); // Add the URL parameter to "curl"
brew.addParameter(curr->type); // Add the URL parameter to "curl"
curr = curr->next; curr = curr->next;
} }
} }
if (publishers != NULL) {
struct Publisher *curr = publishers;
while (curr != NULL) {
if (_verbose) {
Serial.print(F("Creating publishers: "));
Serial.print(curr->name);
Serial.print(F(" of type: "));
Serial.println(curr->type);
}
brew.addParameter("-p"); // Add the URL parameter to "curl"
brew.addParameter(curr->name); // Add the URL parameter to "curl"
brew.addParameter(","); // Add the URL parameter to "curl"
brew.addParameter(curr->type); // Add the URL parameter to "curl"
Console.begin(); curr = curr->next;
if (_verbose) { }
Serial.println(F("Console started ")); }
}
brew.runAsynchronously(); Console.begin();
if (_verbose) {
Serial.println(F("Console started "));
}
if (_verbose) { brew.runAsynchronously();
Serial.println(F("Brew started "));
} if (_verbose) {
while (!Console) { ; } Serial.println(F("Brew started "));
}
while (!Console) {
;
}
} }
void SpacebrewYun::monitor() { void SpacebrewYun::monitor() {
while (Console.available() > 0) { while (Console.available() > 0) {
char c = Console.read(); char c = Console.read();
if (c == char(CONNECTION_START) && !_connected) { if (c == char(CONNECTION_START) && !_connected) {
if (_verbose) { if (_verbose) {
Serial.print(F("Connected to spacebrew server at: ")); Serial.print(F("Connected to spacebrew server at: "));
Serial.println(server); Serial.println(server);
Serial.print(F("Application name set to: ")); Serial.print(F("Application name set to: "));
Serial.println(name); Serial.println(name);
} }
if (_onOpen != NULL){ if (_onOpen != NULL) {
_onOpen(); _onOpen();
} }
_connected = true; _connected = true;
} }
else if (c == char(CONNECTION_END) && _connected) { else if (c == char(CONNECTION_END) && _connected) {
_connected = false; _connected = false;
if (_verbose) { if (_verbose) {
Serial.print(F("Disconnected from spacebrew server at: ")); Serial.print(F("Disconnected from spacebrew server at: "));
Serial.println(server); Serial.println(server);
} }
if (_onClose != NULL){ if (_onClose != NULL) {
_onClose(); _onClose();
} }
} }
if (_verbose) { if (_verbose) {
if (c == char(CONNECTION_ERROR)) { if (c == char(CONNECTION_ERROR)) {
_error_msg = true; _error_msg = true;
Serial.println(F("ERROR :: with Spacebrew.py Connection ::")); Serial.println(F("ERROR :: with Spacebrew.py Connection ::"));
} }
else if (_error_msg && c == char(MSG_END)) { else if (_error_msg && c == char(MSG_END)) {
_error_msg = false; _error_msg = false;
Serial.println(); Serial.println();
} }
if (_error_msg) { if (_error_msg) {
Serial.print(c); Serial.print(c);
} }
} }
if (_connected) { if (_connected) {
if (c == char(MSG_START)) { if (c == char(MSG_START)) {
read_name = true; read_name = true;
} else if (c == char(MSG_DIV) || sub_name.length() > sub_name_max) { } else if (c == char(MSG_DIV) || sub_name.length() > sub_name_max) {
read_name = false; read_name = false;
read_msg = true; read_msg = true;
} else if (c == char(MSG_END) || sub_msg.length() > sub_msg_str_max) { } else if (c == char(MSG_END) || sub_msg.length() > sub_msg_str_max) {
if (read_msg == true) { if (read_msg == true) {
read_msg = false; read_msg = false;
onMessage(); onMessage();
// delay(2); // delay(2);
} }
if (read_confirm == true) { if (read_confirm == true) {
read_confirm = false; read_confirm = false;
onConfirm(); onConfirm();
delay(2); delay(2);
} }
} else if (c == char(MSG_CONFIRM)) { } else if (c == char(MSG_CONFIRM)) {
read_confirm = true; read_confirm = true;
} else { } else {
if (read_name == true) { if (read_name == true) {
sub_name += c; sub_name += c;
} else if (read_confirm == true) { } else if (read_confirm == true) {
sub_name += c; sub_name += c;
} else if (read_msg == true) { } else if (read_msg == true) {
sub_msg += c; sub_msg += c;
} }
else if (_verbose) { else if (_verbose) {
Serial.print(c); Serial.print(c);
} }
} }
} }
} }
if (publishers != NULL) { if (publishers != NULL) {
struct Publisher *curr = publishers; struct Publisher *curr = publishers;
while((curr != NULL)){ while ((curr != NULL)) {
if ( (curr->confirmed == 0) && ((millis() - curr->time) > 50) ) { if ( (curr->confirmed == 0) && ((millis() - curr->time) > 50) ) {
if (_verbose) { if (_verbose) {
Serial.print(F("resending msg: ")); Serial.print(F("resending msg: "));
Serial.println(curr->name); Serial.println(curr->name);
} }
send(curr->name, curr->lastMsg); send(curr->name, curr->lastMsg);
} }
curr = curr->next; curr = curr->next;
} }
} }
} }
void SpacebrewYun::onConfirm() { void SpacebrewYun::onConfirm() {
if (publishers != NULL) { if (publishers != NULL) {
struct Publisher *curr = publishers; struct Publisher *curr = publishers;
while((curr != NULL)){ while ((curr != NULL)) {
if (sub_name.equals(curr->name) == true) { if (sub_name.equals(curr->name) == true) {
curr->confirmed = true; curr->confirmed = true;
// if (_verbose) { // if (_verbose) {
// Serial.print(F("confirmed ")); // Serial.print(F("confirmed "));
// Serial.println(curr->name); // Serial.println(curr->name);
// } // }
break; break;
} }
curr = curr->next; curr = curr->next;
} }
} }
sub_name = ""; sub_name = "";
sub_msg = ""; sub_msg = "";
sub_type = ""; sub_type = "";
} }
boolean SpacebrewYun::connected() { boolean SpacebrewYun::connected() {
return SpacebrewYun::_connected; return SpacebrewYun::_connected;
} }
void SpacebrewYun::verbose(boolean verbose = true) { void SpacebrewYun::verbose(boolean verbose = true) {
_verbose = verbose; _verbose = verbose;
} }
void SpacebrewYun::onMessage() { void SpacebrewYun::onMessage() {
if (subscribers != NULL) { if (subscribers != NULL) {
struct Subscriber *curr = subscribers; struct Subscriber *curr = subscribers;
while((curr != NULL) && (sub_type == "")){ while ((curr != NULL) && (sub_type == "")) {
if (sub_name.equals(curr->name) == true) { if (sub_name.equals(curr->name) == true) {
sub_type = curr->type; sub_type = curr->type;
} }
curr = curr->next; curr = curr->next;
} }
} }
if ( sub_type.equals("range") ) { if ( sub_type.equals("range") ) {
if (_onRangeMessage != NULL) { if (_onRangeMessage != NULL) {
_onRangeMessage( sub_name, int(sub_msg.toInt()) ); _onRangeMessage( sub_name, int(sub_msg.toInt()) );
} else { } else {
Serial.println(F("ERROR :: Range message received, no callback method is registered")); Serial.println(F("ERROR :: Range message received, no callback method is registered"));
} }
} else if ( sub_type.equals("boolean") ) { } else if ( sub_type.equals("boolean") ) {
if (_onBooleanMessage != NULL) { if (_onBooleanMessage != NULL) {
_onBooleanMessage( sub_name, ( sub_msg.equals("false") ? false : true ) ); _onBooleanMessage( sub_name, ( sub_msg.equals("false") ? false : true ) );
} else { } else {
Serial.println(F("ERROR :: Boolean message received, no callback method is registered")); Serial.println(F("ERROR :: Boolean message received, no callback method is registered"));
} }
} else if ( sub_type.equals("string") ) { } else if ( sub_type.equals("string") ) {
if (_onStringMessage != NULL) { if (_onStringMessage != NULL) {
_onStringMessage( sub_name, sub_msg ); _onStringMessage( sub_name, sub_msg );
} else { } else {
Serial.println(F("ERROR :: String message received, no callback method is registered")); Serial.println(F("ERROR :: String message received, no callback method is registered"));
} }
} else { } else {
if (_onCustomMessage != NULL) { if (_onCustomMessage != NULL) {
_onCustomMessage( sub_name, sub_msg, sub_type ); _onCustomMessage( sub_name, sub_msg, sub_type );
} else { } else {
Serial.println(F("ERROR :: Custom message received, no callback method is registered")); Serial.println(F("ERROR :: Custom message received, no callback method is registered"));
} }
} }
sub_name = ""; sub_name = "";
sub_msg = ""; sub_msg = "";
sub_type = ""; sub_type = "";
} }
void SpacebrewYun::send(const String& name, const String& value){ void SpacebrewYun::send(const String& name, const String& value) {
if (publishers != NULL) { if (publishers != NULL) {
Console.print(char(29)); Console.print(char(29));
Console.print(name); Console.print(name);
Console.print(char(30)); Console.print(char(30));
Console.print(value); Console.print(value);
Console.print(char(31)); Console.print(char(31));
Console.flush(); Console.flush();
struct Publisher *curr = publishers; struct Publisher *curr = publishers;
while(curr != NULL){ while (curr != NULL) {
if (name.equals(curr->name) == true) { if (name.equals(curr->name) == true) {
int msg_len = 0; int msg_len = 0;
if (curr->type == "range") msg_len = sub_msg_int_max; if (curr->type == "range") msg_len = sub_msg_int_max;
else if (curr->type == "boolean") msg_len = sub_msg_bool_max; else if (curr->type == "boolean") msg_len = sub_msg_bool_max;
else msg_len = sub_msg_str_max; else msg_len = sub_msg_str_max;
if (value.length() < msg_len) msg_len = value.length() + 1; if (value.length() < msg_len) msg_len = value.length() + 1;
value.toCharArray(curr->lastMsg, msg_len); value.toCharArray(curr->lastMsg, msg_len);
curr->confirmed = false; curr->confirmed = false;
curr->time = millis(); curr->time = millis();
} }
curr = curr->next; curr = curr->next;
} }
} }
} }
@ -393,67 +395,67 @@ void SpacebrewYun::send(const String& name, const String& value){
*/ */
void SpacebrewYun::getPids() { void SpacebrewYun::getPids() {
// request the pid of all python processes // request the pid of all python processes
// brew.begin("run-getsbpids"); // Process should launch the "curl" command // brew.begin("run-getsbpids"); // Process should launch the "curl" command
pids.begin("python"); pids.begin("python");
pids.addParameter("/usr/lib/python2.7/spacebrew/getprocpid.py"); // Process should launch the "curl" command pids.addParameter("/usr/lib/python2.7/spacebrew/getprocpid.py"); // Process should launch the "curl" command
pids.run(); pids.run();
if (_verbose) { if (_verbose) {
Serial.println(F("Checking if spacebrew process already running")); Serial.println(F("Checking if spacebrew process already running"));
} }
int sbPidsIndex = 0; int sbPidsIndex = 0;
int pidCharIndex = 0; int pidCharIndex = 0;
char c = '\0'; char c = '\0';
while ( pids.available() > 0 ) { while ( pids.available() > 0 ) {
c = pids.read(); c = pids.read();
if ( c >= '0' && c <= '9' ) { if ( c >= '0' && c <= '9' ) {
pid[pidCharIndex] = c; pid[pidCharIndex] = c;
pidCharIndex = (pidCharIndex + 1) % pidLength; pidCharIndex = (pidCharIndex + 1) % pidLength;
} }
else if ( (c == ' ' || c == '\n') && pidCharIndex > 0) { else if ( (c == ' ' || c == '\n') && pidCharIndex > 0) {
sbPids[sbPidsIndex] = atoi(pid); sbPids[sbPidsIndex] = atoi(pid);
if ( sbPidsIndex < (sbPidsLen - 1) ) sbPidsIndex = (sbPidsIndex + 1); if ( sbPidsIndex < (sbPidsLen - 1) ) sbPidsIndex = (sbPidsIndex + 1);
for( int i = 0; i < pidLength; i++ ){ for ( int i = 0; i < pidLength; i++ ) {
pid[i] = '\0'; pid[i] = '\0';
pidCharIndex = 0; pidCharIndex = 0;
} }
} }
} }
} }
/** /**
* method that kills all of the spacebrew.py instances that are running * method that kills all of the spacebrew.py instances that are running
* on the linino. * on the linino.
*/ */
void SpacebrewYun::killPids() { void SpacebrewYun::killPids() {
getPids(); getPids();
delay(400); delay(400);
for (int i = 0; i < sbPidsLen; i ++) { for (int i = 0; i < sbPidsLen; i ++) {
if (sbPids[i] > 0) { if (sbPids[i] > 0) {
char * newPID = itoa(sbPids[i], pid, 10); char * newPID = itoa(sbPids[i], pid, 10);
if (_verbose) { if (_verbose) {
Serial.print(F("Stopping existing spacebrew processes with pids: ")); Serial.print(F("Stopping existing spacebrew processes with pids: "));
Serial.println(newPID); Serial.println(newPID);
} }
Process p; Process p;
p.begin("kill"); p.begin("kill");
p.addParameter("-9"); p.addParameter("-9");
p.addParameter(newPID); // Process should launch the "curl" command p.addParameter(newPID); // Process should launch the "curl" command
p.run(); // Run the process and wait for its termination p.run(); // Run the process and wait for its termination
delay(400); delay(400);
} }
} }
} }

View File

@ -7,29 +7,29 @@
#include <Console.h> #include <Console.h>
#include <Process.h> #include <Process.h>
enum SBmsg { enum SBmsg {
CONNECTION_START = char(28), CONNECTION_START = char(28),
CONNECTION_END = char(27), CONNECTION_END = char(27),
CONNECTION_ERROR = char(26), CONNECTION_ERROR = char(26),
MSG_CONFIRM = char(7), MSG_CONFIRM = char(7),
MSG_START = char(29), MSG_START = char(29),
MSG_DIV = char(30), MSG_DIV = char(30),
MSG_END = char(31) MSG_END = char(31)
}; };
struct Publisher { struct Publisher {
char *name; char *name;
char *type; char *type;
char *lastMsg; char *lastMsg;
Publisher *next; Publisher *next;
int confirmed; int confirmed;
long time; long time;
}; };
struct Subscriber{ struct Subscriber {
char *name; char *name;
char *type; char *type;
Subscriber *next; Subscriber *next;
}; };
int const pidLength = 6; int const pidLength = 6;
@ -37,100 +37,114 @@ int const sbPidsLen = 4;
class SpacebrewYun { class SpacebrewYun {
public: public:
SpacebrewYun(const String&, const String&); SpacebrewYun(const String&, const String&);
void addPublish(const String&, const String&); void addPublish(const String&, const String&);
void addSubscribe(const String&, const String&); void addSubscribe(const String&, const String&);
void connect(String, int); void connect(String, int);
void connect() { connect(server, port); }; void connect() {
void connect(String _server) { connect(String(_server), port); }; connect(server, port);
};
void connect(String _server) {
connect(String(_server), port);
};
void monitor(); void monitor();
void onMessage(); void onMessage();
void onConfirm(); void onConfirm();
boolean connected(); boolean connected();
void send(const String&, const String&); void send(const String&, const String&);
void send(const String& name, char * value) { send(name, String(value)); } void send(const String& name, char * value) {
void send(const String& name, bool value){ send(name, (value ? String("true") : String("false"))); }; send(name, String(value));
void send(const String& name, int value) { send(name, String(value)); }; }
void send(const String& name, long value) { send(name, String(value)); }; void send(const String& name, bool value) {
void send(const String& name, float value) { send(name, String(value)); }; send(name, (value ? String("true") : String("false")));
};
void send(const String& name, int value) {
send(name, String(value));
};
void send(const String& name, long value) {
send(name, String(value));
};
void send(const String& name, float value) {
send(name, String(value));
};
void verbose(boolean); void verbose(boolean);
typedef void (*OnBooleanMessage)(String name, boolean value); typedef void (*OnBooleanMessage)(String name, boolean value);
typedef void (*OnRangeMessage)(String name, int value); typedef void (*OnRangeMessage)(String name, int value);
typedef void (*OnStringMessage)(String name, String value); typedef void (*OnStringMessage)(String name, String value);
typedef void (*OnCustomMessage)(String name, String value, String type); typedef void (*OnCustomMessage)(String name, String value, String type);
typedef void (*OnSBOpen)(); typedef void (*OnSBOpen)();
typedef void (*OnSBClose)(); typedef void (*OnSBClose)();
typedef void (*OnSBError)(int code, String message); typedef void (*OnSBError)(int code, String message);
void onOpen(OnSBOpen function); void onOpen(OnSBOpen function);
void onClose(OnSBClose function); void onClose(OnSBClose function);
void onRangeMessage(OnRangeMessage function); void onRangeMessage(OnRangeMessage function);
void onStringMessage(OnStringMessage function); void onStringMessage(OnStringMessage function);
void onBooleanMessage(OnBooleanMessage function); void onBooleanMessage(OnBooleanMessage function);
void onCustomMessage(OnCustomMessage function); void onCustomMessage(OnCustomMessage function);
void onError(OnSBError function); void onError(OnSBError function);
private: private:
Process brew; Process brew;
String name; String name;
String server; String server;
String description; String description;
boolean _connected; boolean _connected;
boolean _error_msg; boolean _error_msg;
boolean _verbose; boolean _verbose;
int port; int port;
/**Output should be at least 5 cells**/ /**Output should be at least 5 cells**/
static OnBooleanMessage _onBooleanMessage; static OnBooleanMessage _onBooleanMessage;
static OnRangeMessage _onRangeMessage; static OnRangeMessage _onRangeMessage;
static OnStringMessage _onStringMessage; static OnStringMessage _onStringMessage;
static OnCustomMessage _onCustomMessage; static OnCustomMessage _onCustomMessage;
static OnSBOpen _onOpen; static OnSBOpen _onOpen;
static OnSBClose _onClose; static OnSBClose _onClose;
static OnSBError _onError; static OnSBError _onError;
Subscriber * subscribers; Subscriber * subscribers;
Publisher * publishers; Publisher * publishers;
String sub_name; String sub_name;
String sub_msg; String sub_msg;
String sub_type; String sub_type;
boolean read_name; boolean read_name;
boolean read_msg; boolean read_msg;
boolean read_confirm; boolean read_confirm;
static int sub_name_max; static int sub_name_max;
static int sub_msg_str_max; static int sub_msg_str_max;
static int sub_msg_int_max; static int sub_msg_int_max;
static int sub_msg_bool_max; static int sub_msg_bool_max;
// int sub_name_max; // int sub_name_max;
// int sub_msg_str_max; // int sub_msg_str_max;
Process pids; Process pids;
char pid [6]; char pid [6];
int sbPids [4]; int sbPids [4];
void killPids(); void killPids();
void getPids(); void getPids();
static char * createString(int len){ static char * createString(int len) {
char * out = ( char * ) malloc ( len + 1 ); char * out = ( char * ) malloc ( len + 1 );
return out; return out;
} }
static void emptyString(char * str, int len){ static void emptyString(char * str, int len) {
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
str[i] = '\0'; str[i] = '\0';
} }
} }
}; };

View File

@ -4,13 +4,13 @@
# Temboo Arduino Yun library # Temboo Arduino Yun library
# #
# Copyright 2013, Temboo Inc. # Copyright 2013, Temboo Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at # You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, # Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an # software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
@ -23,42 +23,42 @@
#include <Temboo.h> #include <Temboo.h>
void TembooChoreo::begin() { void TembooChoreo::begin() {
Process::begin("temboo"); Process::begin("temboo");
} }
void TembooChoreo::setAccountName(const String& accountName) { void TembooChoreo::setAccountName(const String& accountName) {
addParameter("-a" + accountName); addParameter("-a" + accountName);
} }
void TembooChoreo::setAppKeyName(const String& appKeyName) { void TembooChoreo::setAppKeyName(const String& appKeyName) {
addParameter("-u" + appKeyName); addParameter("-u" + appKeyName);
} }
void TembooChoreo::setAppKey(const String& appKey) { void TembooChoreo::setAppKey(const String& appKey) {
addParameter("-p" + appKey); addParameter("-p" + appKey);
} }
void TembooChoreo::setChoreo(const String& choreo) { void TembooChoreo::setChoreo(const String& choreo) {
addParameter("-c" + choreo); addParameter("-c" + choreo);
} }
void TembooChoreo::setCredential(const String& credentialName) { void TembooChoreo::setCredential(const String& credentialName) {
addParameter("-e" + credentialName); addParameter("-e" + credentialName);
} }
void TembooChoreo::addInput(const String& inputName, const String& inputValue) { void TembooChoreo::addInput(const String& inputName, const String& inputValue) {
addParameter("-i" + inputName + ":" + inputValue); addParameter("-i" + inputName + ":" + inputValue);
} }
void TembooChoreo::addOutputFilter(const String& outputName, const String& filterPath, const String& variableName) { void TembooChoreo::addOutputFilter(const String& outputName, const String& filterPath, const String& variableName) {
addParameter("-o" + outputName + ":" + filterPath + ":" + variableName); addParameter("-o" + outputName + ":" + filterPath + ":" + variableName);
} }
void TembooChoreo::setSettingsFileToWrite(const String& filePath) { void TembooChoreo::setSettingsFileToWrite(const String& filePath) {
addParameter("-w" + filePath); addParameter("-w" + filePath);
} }
void TembooChoreo::setSettingsFileToRead(const String& filePath) { void TembooChoreo::setSettingsFileToRead(const String& filePath) {
addParameter("-r" + filePath); addParameter("-r" + filePath);
} }

View File

@ -4,13 +4,13 @@
# Temboo Arduino Yun library # Temboo Arduino Yun library
# #
# Copyright 2013, Temboo Inc. # Copyright 2013, Temboo Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at # You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, # Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an # software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
@ -27,18 +27,18 @@
class TembooChoreo : public Process { class TembooChoreo : public Process {
public: public:
void begin(); void begin();
void setAccountName(const String& accountName); void setAccountName(const String& accountName);
void setAppKeyName(const String& appKeyName); void setAppKeyName(const String& appKeyName);
void setAppKey(const String& appKey); void setAppKey(const String& appKey);
void setChoreo(const String& choreo); void setChoreo(const String& choreo);
void setCredential(const String& credentialName); void setCredential(const String& credentialName);
void addInput(const String& inputName, const String& inputValue); void addInput(const String& inputName, const String& inputValue);
void addOutputFilter(const String& filterName, const String& filterPath, const String& variableName); void addOutputFilter(const String& filterName, const String& filterPath, const String& variableName);
void setSettingsFileToWrite(const String& filePath); void setSettingsFileToWrite(const String& filePath);
void setSettingsFileToRead(const String& filePath); void setSettingsFileToRead(const String& filePath);
}; };
#endif #endif