wiring-sucks

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

commit 4e73095989086cbccb1bf9bbc6d086d2b27de217
parent fc64aa1ca488c80f467196c01c246d988dbbaf72
Author: Elecon-rou <quest90spin@gmail.com>
Date:   Wed,  1 Jul 2020 01:33:00 +0400

remove unsupported libraries

Diffstat:
Dinclude/Bridge/Bridge.h | 125-------------------------------------------------------------------------------
Dinclude/Bridge/BridgeClient.h | 71-----------------------------------------------------------------------
Dinclude/Bridge/BridgeSSLClient.h | 36------------------------------------
Dinclude/Bridge/BridgeServer.h | 51---------------------------------------------------
Dinclude/Bridge/BridgeUdp.h | 65-----------------------------------------------------------------
Dinclude/Bridge/Console.h | 71-----------------------------------------------------------------------
Dinclude/Bridge/FileIO.h | 120-------------------------------------------------------------------------------
Dinclude/Bridge/HttpClient.h | 59-----------------------------------------------------------
Dinclude/Bridge/Mailbox.h | 53-----------------------------------------------------
Dinclude/Bridge/Process.h | 71-----------------------------------------------------------------------
Dinclude/Bridge/YunClient.h | 27---------------------------
Dinclude/Bridge/YunServer.h | 27---------------------------
Dinclude/Esplora/Esplora.h | 177-------------------------------------------------------------------------------
Dinclude/HID/HID.h | 125-------------------------------------------------------------------------------
Dinclude/Keyboard/Keyboard.h | 99-------------------------------------------------------------------------------
Dinclude/Mouse/Mouse.h | 61-------------------------------------------------------------
Dinclude/RobotIRremote/IRremote.h | 94-------------------------------------------------------------------------------
Dinclude/RobotIRremote/IRremoteInt.h | 446-------------------------------------------------------------------------------
Dinclude/RobotIRremote/IRremoteTools.h | 13-------------
Dinclude/Robot_Control/ArduinoRobot.h | 375-------------------------------------------------------------------------------
Dinclude/Robot_Control/Arduino_LCD.h | 141-------------------------------------------------------------------------------
Dinclude/Robot_Control/Compass.h | 25-------------------------
Dinclude/Robot_Control/EEPROM_I2C.h | 32--------------------------------
Dinclude/Robot_Control/EasyTransfer2.h | 77-----------------------------------------------------------------------------
Dinclude/Robot_Control/Fat16.h | 378-------------------------------------------------------------------------------
Dinclude/Robot_Control/Fat16Config.h | 38--------------------------------------
Dinclude/Robot_Control/Fat16mainpage.h | 209-------------------------------------------------------------------------------
Dinclude/Robot_Control/Fat16util.h | 74--------------------------------------------------------------------------
Dinclude/Robot_Control/FatStructs.h | 418-------------------------------------------------------------------------------
Dinclude/Robot_Control/Multiplexer.h | 24------------------------
Dinclude/Robot_Control/SdCard.h | 192-------------------------------------------------------------------------------
Dinclude/Robot_Control/SdInfo.h | 117-------------------------------------------------------------------------------
Dinclude/Robot_Control/Squawk.h | 266-------------------------------------------------------------------------------
Dinclude/Robot_Control/SquawkSD.h | 18------------------
Dinclude/Robot_Motor/ArduinoRobotMotorBoard.h | 127-------------------------------------------------------------------------------
Dinclude/Robot_Motor/EasyTransfer2.h | 77-----------------------------------------------------------------------------
Dinclude/Robot_Motor/LineFollow.h | 41-----------------------------------------
Dinclude/Robot_Motor/Multiplexer.h | 24------------------------
Dinclude/SpacebrewYun/SpacebrewYun.h | 139-------------------------------------------------------------------------------
Dinclude/TFT/TFT.h | 58----------------------------------------------------------
Dinclude/TFT/utility/Adafruit_GFX.h | 372-------------------------------------------------------------------------------
Dinclude/TFT/utility/Adafruit_ST7735.h | 155-------------------------------------------------------------------------------
Dinclude/TFT/utility/PImage.h | 65-----------------------------------------------------------------
Dinclude/Temboo/Temboo.h | 181-------------------------------------------------------------------------------
Dinclude/Temboo/TembooCoAPEdgeDevice.h | 307-------------------------------------------------------------------------------
Dinclude/Temboo/TembooMQTTEdgeDevice.h | 238-------------------------------------------------------------------------------
Dinclude/Temboo/TembooMonitoring.h | 83-------------------------------------------------------------------------------
Dinclude/Temboo/TembooYunShield.h | 60------------------------------------------------------------
Dinclude/Temboo/utility/ArduinoTimer.h | 62--------------------------------------------------------------
Dinclude/Temboo/utility/BaseFormatter.h | 46----------------------------------------------
Dinclude/Temboo/utility/ChoreoInput.h | 41-----------------------------------------
Dinclude/Temboo/utility/ChoreoInputFormatter.h | 58----------------------------------------------------------
Dinclude/Temboo/utility/ChoreoInputSet.h | 43-------------------------------------------
Dinclude/Temboo/utility/ChoreoOutput.h | 44--------------------------------------------
Dinclude/Temboo/utility/ChoreoOutputFormatter.h | 66------------------------------------------------------------------
Dinclude/Temboo/utility/ChoreoOutputSet.h | 43-------------------------------------------
Dinclude/Temboo/utility/ChoreoPreset.h | 40----------------------------------------
Dinclude/Temboo/utility/ChoreoPresetFormatter.h | 50--------------------------------------------------
Dinclude/Temboo/utility/CoapMessageLayer.h | 128-------------------------------------------------------------------------------
Dinclude/Temboo/utility/CoapMsg.h | 192-------------------------------------------------------------------------------
Dinclude/Temboo/utility/CoapRRLayer.h | 82-------------------------------------------------------------------------------
Dinclude/Temboo/utility/DataFormatter.h | 63---------------------------------------------------------------
Dinclude/Temboo/utility/FP.h | 208-------------------------------------------------------------------------------
Dinclude/Temboo/utility/MQTTClient.h | 954-------------------------------------------------------------------------------
Dinclude/Temboo/utility/MQTTConnect.h | 136-------------------------------------------------------------------------------
Dinclude/Temboo/utility/MQTTFormat.h | 37-------------------------------------
Dinclude/Temboo/utility/MQTTLogging.h | 41-----------------------------------------
Dinclude/Temboo/utility/MQTTPacket.h | 133-------------------------------------------------------------------------------
Dinclude/Temboo/utility/MQTTPublish.h | 38--------------------------------------
Dinclude/Temboo/utility/MQTTSubscribe.h | 39---------------------------------------
Dinclude/Temboo/utility/MQTTUnsubscribe.h | 38--------------------------------------
Dinclude/Temboo/utility/StackTrace.h | 78------------------------------------------------------------------------------
Dinclude/Temboo/utility/TembooCoAPIPStack.h | 101-------------------------------------------------------------------------------
Dinclude/Temboo/utility/TembooCoAPSession.h | 111-------------------------------------------------------------------------------
Dinclude/Temboo/utility/TembooGlobal.h | 53-----------------------------------------------------
Dinclude/Temboo/utility/TembooMQTTIPStack.h | 96-------------------------------------------------------------------------------
Dinclude/Temboo/utility/TembooMQTTSession.h | 108-------------------------------------------------------------------------------
Dinclude/Temboo/utility/TembooSession.h | 134-------------------------------------------------------------------------------
Dinclude/Temboo/utility/TembooTags.h | 37-------------------------------------
Dinclude/Temboo/utility/TembooTimer.h | 62--------------------------------------------------------------
Dinclude/Temboo/utility/TembooWebSocketRequestHandles.h | 66------------------------------------------------------------------
Dinclude/Temboo/utility/tmbhmac.h | 57---------------------------------------------------------
Dinclude/Temboo/utility/tmbmd5.h | 72------------------------------------------------------------------------
Dlib/Bridge/Bridge.cpp | 281-------------------------------------------------------------------------------
Dlib/Bridge/BridgeClient.cpp | 208-------------------------------------------------------------------------------
Dlib/Bridge/BridgeSSLClient.cpp | 37-------------------------------------
Dlib/Bridge/BridgeServer.cpp | 54------------------------------------------------------
Dlib/Bridge/BridgeUdp.cpp | 198-------------------------------------------------------------------------------
Dlib/Bridge/Console.cpp | 150-------------------------------------------------------------------------------
Dlib/Bridge/FileIO.cpp | 283-------------------------------------------------------------------------------
Dlib/Bridge/HttpClient.cpp | 204-------------------------------------------------------------------------------
Dlib/Bridge/Mailbox.cpp | 56--------------------------------------------------------
Dlib/Bridge/Process.cpp | 142-------------------------------------------------------------------------------
Dlib/Esplora/Esplora.cpp | 184-------------------------------------------------------------------------------
Dlib/HID/HID.cpp | 162-------------------------------------------------------------------------------
Dlib/Keyboard/Keyboard.cpp | 322-------------------------------------------------------------------------------
Dlib/Mouse/Mouse.cpp | 123-------------------------------------------------------------------------------
Dlib/RobotIRremote/IRremote.cpp | 777-------------------------------------------------------------------------------
Dlib/RobotIRremote/IRremoteTools.cpp | 24------------------------
Dlib/Robot_Control/ArduinoRobot.cpp | 41-----------------------------------------
Dlib/Robot_Control/Arduino_LCD.cpp | 707-------------------------------------------------------------------------------
Dlib/Robot_Control/Compass.cpp | 35-----------------------------------
Dlib/Robot_Control/EEPROM_I2C.cpp | 63---------------------------------------------------------------
Dlib/Robot_Control/EasyTransfer2.cpp | 153-------------------------------------------------------------------------------
Dlib/Robot_Control/Fat16.cpp | 990-------------------------------------------------------------------------------
Dlib/Robot_Control/Melody.cpp | 100-------------------------------------------------------------------------------
Dlib/Robot_Control/Motors.cpp | 114-------------------------------------------------------------------------------
Dlib/Robot_Control/Multiplexer.cpp | 37-------------------------------------
Dlib/Robot_Control/RobotSdCard.cpp | 23-----------------------
Dlib/Robot_Control/SdCard.cpp | 279-------------------------------------------------------------------------------
Dlib/Robot_Control/Sensors.cpp | 275-------------------------------------------------------------------------------
Dlib/Robot_Control/Squawk.cpp | 601-------------------------------------------------------------------------------
Dlib/Robot_Control/SquawkSD.cpp | 182-------------------------------------------------------------------------------
Dlib/Robot_Control/communication.cpp | 29-----------------------------
Dlib/Robot_Control/helper.cpp | 45---------------------------------------------
Dlib/Robot_Control/information.cpp | 42------------------------------------------
Dlib/Robot_Control/keyboard.cpp | 66------------------------------------------------------------------
Dlib/Robot_Control/lcd.cpp | 279-------------------------------------------------------------------------------
Dlib/Robot_Motor/ArduinoRobotMotorBoard.cpp | 270-------------------------------------------------------------------------------
Dlib/Robot_Motor/EasyTransfer2.cpp | 176-------------------------------------------------------------------------------
Dlib/Robot_Motor/Multiplexer.cpp | 38--------------------------------------
Dlib/Robot_Motor/lineFollow.cpp | 152-------------------------------------------------------------------------------
Dlib/SpacebrewYun/SpacebrewYun.cpp | 491-------------------------------------------------------------------------------
Dlib/TFT/TFT.cpp | 51---------------------------------------------------
Dlib/TFT/utility/Adafruit_GFX.cpp | 715-------------------------------------------------------------------------------
Dlib/TFT/utility/Adafruit_ST7735.cpp | 751-------------------------------------------------------------------------------
Dlib/Temboo/Temboo.cpp | 363-------------------------------------------------------------------------------
Dlib/Temboo/TembooCoAPEdgeDevice.cpp | 935-------------------------------------------------------------------------------
Dlib/Temboo/TembooMQTTEdgeDevice.cpp | 861-------------------------------------------------------------------------------
Dlib/Temboo/TembooMonitoring.cpp | 334-------------------------------------------------------------------------------
Dlib/Temboo/utility/BaseFormatter.cpp | 96-------------------------------------------------------------------------------
Dlib/Temboo/utility/ChoreoInput.cpp | 34----------------------------------
Dlib/Temboo/utility/ChoreoInputFormatter.cpp | 125-------------------------------------------------------------------------------
Dlib/Temboo/utility/ChoreoInputSet.cpp | 80-------------------------------------------------------------------------------
Dlib/Temboo/utility/ChoreoOutput.cpp | 37-------------------------------------
Dlib/Temboo/utility/ChoreoOutputFormatter.cpp | 181-------------------------------------------------------------------------------
Dlib/Temboo/utility/ChoreoOutputSet.cpp | 73-------------------------------------------------------------------------
Dlib/Temboo/utility/ChoreoPreset.cpp | 23-----------------------
Dlib/Temboo/utility/ChoreoPresetFormatter.cpp | 84-------------------------------------------------------------------------------
Dlib/Temboo/utility/CoapMessageLayer.cpp | 400-------------------------------------------------------------------------------
Dlib/Temboo/utility/CoapMsg.cpp | 714-------------------------------------------------------------------------------
Dlib/Temboo/utility/CoapRRLayer.cpp | 176-------------------------------------------------------------------------------
Dlib/Temboo/utility/DataFormatter.cpp | 114-------------------------------------------------------------------------------
Dlib/Temboo/utility/TembooCoAPSession.cpp | 199-------------------------------------------------------------------------------
Dlib/Temboo/utility/TembooMQTTSession.cpp | 189-------------------------------------------------------------------------------
Dlib/Temboo/utility/TembooSession.cpp | 263-------------------------------------------------------------------------------
Dlib/Temboo/utility/tmbhmac.cpp | 107-------------------------------------------------------------------------------
Dlib/Temboo/utility/tmbmd5.cpp | 213-------------------------------------------------------------------------------
148 files changed, 0 insertions(+), 25170 deletions(-)

diff --git a/include/Bridge/Bridge.h b/include/Bridge/Bridge.h @@ -1,125 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef BRIDGE_H_ -#define BRIDGE_H_ - -#ifndef BRIDGE_BAUDRATE -#define BRIDGE_BAUDRATE 250000 -#endif - -#include <Arduino.h> -#include <Stream.h> - -class BridgeClass { - public: - BridgeClass(Stream &_stream); - 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) - { - return 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); - } - - uint16_t getBridgeVersion() - { - return bridgeVersion; - } - - static const uint16_t TRANSFER_TIMEOUT = 0xFFFF; - - private: - uint8_t index; - int timedRead(unsigned int timeout); - void dropAll(); - uint16_t bridgeVersion; - - 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 -class SerialBridgeClass : public BridgeClass { - public: - SerialBridgeClass(HardwareSerial &_serial) - : BridgeClass(_serial), serial(_serial) { - // Empty - } - - void begin(unsigned long baudrate = BRIDGE_BAUDRATE) { - serial.begin(baudrate); - BridgeClass::begin(); - } - - private: - HardwareSerial &serial; -}; - -extern SerialBridgeClass Bridge; - -// Some microcrontrollers don't start the bootloader after a reset. -// This function is intended to let the microcontroller erase its -// flash after checking a specific signal coming from the external -// device without the need to press the erase button on the board. -// The purpose is to enable a software update that does not require -// a manual interaction with the board. -extern void checkForRemoteSketchUpdate(uint8_t pin = 7); - -#endif /* BRIDGE_H_ */ - -#include <Console.h> -#include <Process.h> diff --git a/include/Bridge/BridgeClient.h b/include/Bridge/BridgeClient.h @@ -1,71 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _BRIDGE_CLIENT_H_ -#define _BRIDGE_CLIENT_H_ - -#include <Bridge.h> -#include <Client.h> - -class BridgeClient : public Client { - public: - // Constructor with a user provided BridgeClass instance - BridgeClient(uint8_t _h, BridgeClass &_b = Bridge); - BridgeClient(BridgeClass &_b = Bridge); - ~BridgeClient(); - - // 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; - } - - virtual BridgeClient& operator=(const BridgeClient &_x); - - virtual void stop(); - virtual uint8_t connected(); - - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char *host, uint16_t port); - int connectSSL(const char* host, uint16_t port); - - private: - BridgeClass &bridge; - uint8_t handle; - boolean opened; - - private: - void doBuffer(); - uint8_t buffered; - uint8_t readPos; - static const int BUFFER_SIZE = 64; - uint8_t buffer[BUFFER_SIZE]; - -}; - -#endif // _BRIDGE_CLIENT_H_ diff --git a/include/Bridge/BridgeSSLClient.h b/include/Bridge/BridgeSSLClient.h @@ -1,36 +0,0 @@ -/* - Copyright (c) 2016 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _BRIDGE_SSL_CLIENT_H_ -#define _BRIDGE_SSL_CLIENT_H_ - -#include <Bridge.h> -#include <Client.h> -#include <BridgeClient.h> - -class BridgeSSLClient : public BridgeClient { - public: - // Constructor with a user provided BridgeClass instance - BridgeSSLClient(uint8_t _h, BridgeClass &_b = Bridge); - BridgeSSLClient(BridgeClass &_b = Bridge); - ~BridgeSSLClient(); - - virtual int connect(const char* host, uint16_t port); -}; - -#endif // _BRIDGE_SSL_CLIENT_H_ diff --git a/include/Bridge/BridgeServer.h b/include/Bridge/BridgeServer.h @@ -1,51 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _BRIDGE_SERVER_H_ -#define _BRIDGE_SERVER_H_ - -#include <Bridge.h> -#include <Server.h> - -class BridgeClient; - -class BridgeServer : public Server { - public: - // Constructor with a user provided BridgeClass instance - BridgeServer(uint16_t port = 5555, BridgeClass &_b = Bridge); - - void begin(); - BridgeClient accept(); - - virtual size_t write(uint8_t c); - - void listenOnLocalhost() { - useLocalhost = true; - } - void noListenOnLocalhost() { - useLocalhost = false; - } - - private: - BridgeClass &bridge; - uint16_t port; - bool listening; - bool useLocalhost; -}; - -#endif // _BRIDGE_SERVER_H_ diff --git a/include/Bridge/BridgeUdp.h b/include/Bridge/BridgeUdp.h @@ -1,65 +0,0 @@ -/* - Copyright (c) 2015 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#pragma once - -#include <Udp.h> -#include "Bridge.h" - -class BridgeUDP : public UDP { - - public: - BridgeUDP(BridgeClass &_b = Bridge); - virtual uint8_t begin(uint16_t); - virtual void stop(); - - virtual int beginPacket(IPAddress ip, uint16_t port); - virtual int beginPacket(const char *host, uint16_t port); - virtual int beginBroadcastPacket(uint16_t port); - virtual int endPacket(); - virtual size_t write(uint8_t d) { return write(&d, 1); } - virtual size_t write(const uint8_t *buffer, size_t size); - - using Print::write; - - virtual int parsePacket(); - /* return number of bytes available in the current packet, - will return zero if parsePacket hasn't been called yet */ - virtual int available() { return avail; } - virtual int read(); - virtual int read(unsigned char* buffer, size_t len); - virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; - virtual int peek(); - virtual void flush() { avail = 0; } - - virtual IPAddress remoteIP(); - virtual uint16_t remotePort(); - - private: - BridgeClass &bridge; - uint8_t handle; - boolean opened; - - private: - void doBuffer(); - uint16_t avail; - uint8_t buffered; - uint8_t readPos; - static const int BUFFER_SIZE = 64; - uint8_t buffer[BUFFER_SIZE]; -}; diff --git a/include/Bridge/Console.h b/include/Bridge/Console.h @@ -1,71 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef CONSOLE_H_ -#define CONSOLE_H_ - -#include <Bridge.h> - -class ConsoleClass : public Stream { - public: - // Default constructor uses global Bridge instance - ConsoleClass(); - // Constructor with a user provided BridgeClass instance - ConsoleClass(BridgeClass &_b); - ~ConsoleClass(); - - void begin(); - void end(); - - void buffer(uint8_t size); - void noBuffer(); - - bool connected(); - - // Stream methods - // (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(); - 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; - -#endif diff --git a/include/Bridge/FileIO.h b/include/Bridge/FileIO.h @@ -1,120 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef __FILEIO_H__ -#define __FILEIO_H__ - -#include <Process.h> - -#define FILE_READ 0 -#define FILE_WRITE 1 -#define FILE_APPEND 2 - -namespace BridgeLib { - -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: - 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 { - public: - FileSystemClass() : bridge(Bridge) { } - 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 exists(const char *filepath); - - // Create the requested directory hierarchy--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; - -}; - -// We enclose File and FileSystem classes in namespace BridgeLib to avoid -// conflicts with legacy SD library. - -// This ensure compatibility with older sketches that uses only Bridge lib -// (the user can still use File instead of BridgeFile) -using namespace BridgeLib; - -// This allows sketches to use BridgeLib::File together with SD library -// (you must use BridgeFile instead of File when needed to disambiguate) -typedef BridgeLib::File BridgeFile; -typedef BridgeLib::FileSystemClass BridgeFileSystemClass; -#define BridgeFileSystem BridgeLib::FileSystem - -#endif diff --git a/include/Bridge/HttpClient.h b/include/Bridge/HttpClient.h @@ -1,59 +0,0 @@ -/* - Copyright (c) 2013-2014 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef HTTPCLIENT_H_ -#define HTTPCLIENT_H_ - -#include <Process.h> - -class HttpClient : public Process { - public: - HttpClient(); - - unsigned int get(String &url); - unsigned int get(const char * url); - void getAsynchronously(String &url); - void getAsynchronously(const char * url); - unsigned int post(String &url, String &data); - unsigned int post(const char * url, const char * data); - void postAsynchronously(String &url, String &data); - void postAsynchronously(const char * url, const char * data); - unsigned int patch(String &url, String &data); - unsigned int patch(const char * url, const char * data); - void patchAsynchronously(String &url, String &data); - void patchAsynchronously(const char * url, const char * data); - unsigned int put(String &url, String &data); - unsigned int put(const char * url, const char * data); - void putAsynchronously(String &url, String &data); - void putAsynchronously(const char * url, const char * data); - void setHeader(String &header); - void setHeader(const char * header); - boolean ready(); - unsigned int getResult(); - void noCheckSSL(); - void checkSSL(); - - private: - boolean insecure; - - private: - void addHeader(); - String header; -}; - -#endif /* HTTPCLIENT_H_ */ diff --git a/include/Bridge/Mailbox.h b/include/Bridge/Mailbox.h @@ -1,53 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _MAILBOX_CLASS_H_INCLUDED_ -#define _MAILBOX_CLASS_H_INCLUDED_ - -#include <Bridge.h> - -class MailboxClass { - public: - MailboxClass(BridgeClass &b = Bridge) : bridge(b) { } - - void begin() { } - void end() { } - - // Receive a message and store it inside a buffer - unsigned int readMessage(uint8_t *buffer, unsigned int size); - // Receive a message and store it inside a String - void readMessage(String &str, unsigned int maxLength = 128); - - // Send a message - void writeMessage(const uint8_t *buffer, unsigned int size); - // Send a message - void writeMessage(const String& str); - // Send a JSON message - void writeJSON(const String& str); - - // Return the size of the next available message, 0 if there are - // no messages in queue. - unsigned int messageAvailable(); - - private: - BridgeClass &bridge; -}; - -extern MailboxClass Mailbox; - -#endif // _MAILBOX_CLASS_H_INCLUDED_ diff --git a/include/Bridge/Process.h b/include/Bridge/Process.h @@ -1,71 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef PROCESS_H_ -#define PROCESS_H_ - -#include <Bridge.h> - -class Process : public Stream { - public: - // Constructor with a user provided BridgeClass instance - Process(BridgeClass &_b = Bridge) : - bridge(_b), started(false), buffered(0), readPos(0) { } - ~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 runShellCommandAsynchronously(const String &command); - - operator bool () { - return started; - } - - // Stream methods - // (read from process stdout) - int available(); - int read(); - int peek(); - // (write to process stdin) - size_t write(uint8_t); - void flush(); - // TODO: add optimized function for block write - - private: - BridgeClass &bridge; - uint8_t 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]; - -}; - -#endif diff --git a/include/Bridge/YunClient.h b/include/Bridge/YunClient.h @@ -1,27 +0,0 @@ -/* - Copyright (c) 2014 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _YUN_CLIENT_H_ -#define _YUN_CLIENT_H_ - -#include <BridgeClient.h> - -#warning "The use of YunClient is deprecated. Use BridgeClient instead!" -typedef BridgeClient YunClient; - -#endif // _YUN_CLIENT_H_ diff --git a/include/Bridge/YunServer.h b/include/Bridge/YunServer.h @@ -1,27 +0,0 @@ -/* - Copyright (c) 2014 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _YUN_SERVER_H_ -#define _YUN_SERVER_H_ - -#include <BridgeServer.h> - -#warning "The use of YunServer is deprecated. Use BridgeServer instead!" -typedef BridgeServer YunServer; - -#endif // _YUN_SERVER_H_ diff --git a/include/Esplora/Esplora.h b/include/Esplora/Esplora.h @@ -1,177 +0,0 @@ -/* - Esplora.h - Arduino Esplora board library - Written by Enrico Gueli - Copyright (c) 2012 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef ESPLORA_H_ -#define ESPLORA_H_ - -#include <Arduino.h> - -/* - * The following constants are used internally by the Esplora - * library code. - */ - -const byte JOYSTICK_BASE = 16; // it's a "virtual" channel: its ID won't conflict with real ones - -const byte MAX_CHANNELS = 13; - -const byte CH_SWITCH_1 = 0; -const byte CH_SWITCH_2 = 1; -const byte CH_SWITCH_3 = 2; -const byte CH_SWITCH_4 = 3; -const byte CH_SLIDER = 4; -const byte CH_LIGHT = 5; -const byte CH_TEMPERATURE = 6; -const byte CH_MIC = 7; -const byte CH_TINKERKIT_A = 8; -const byte CH_TINKERKIT_B = 9; -const byte CH_JOYSTICK_SW = 10; -const byte CH_JOYSTICK_X = 11; -const byte CH_JOYSTICK_Y = 12; - -/* - * The following constants can be used with the readButton() - * method. - */ - -const byte SWITCH_1 = 1; -const byte SWITCH_2 = 2; -const byte SWITCH_3 = 3; -const byte SWITCH_4 = 4; - -const byte SWITCH_DOWN = SWITCH_1; -const byte SWITCH_LEFT = SWITCH_2; -const byte SWITCH_UP = SWITCH_3; -const byte SWITCH_RIGHT = SWITCH_4; - -const byte JOYSTICK_DOWN = JOYSTICK_BASE; -const byte JOYSTICK_LEFT = JOYSTICK_BASE+1; -const byte JOYSTICK_UP = JOYSTICK_BASE+2; -const byte JOYSTICK_RIGHT = JOYSTICK_BASE+3; - -/* - * These constants can be use for comparison with the value returned - * by the readButton() method. - */ -const boolean PRESSED = LOW; -const boolean RELEASED = HIGH; - -/* - * The following constants can be used with the readTemperature() - * method to specify the desired scale. - */ -const byte DEGREES_C = 0; -const byte DEGREES_F = 1; - -/* - * The following constants can be used with the readAccelerometer() - * method to specify the desired axis to return. - */ -const byte X_AXIS = 0; -const byte Y_AXIS = 1; -const byte Z_AXIS = 2; - - -class _Esplora { -private: - byte lastRed; - byte lastGreen; - byte lastBlue; - - unsigned int readChannel(byte channel); - - boolean joyLowHalf(byte joyCh); - boolean joyHighHalf(byte joyCh); - -public: - _Esplora(); - - /* - * Returns a number corresponding to the position of the - * linear potentiometer. 0 means full right, 1023 means - * full left. - */ - inline unsigned int readSlider() { return readChannel(CH_SLIDER); } - - /* - * Returns a number corresponding to the amount of ambient - * light sensed by the light sensor. - */ - inline unsigned int readLightSensor() { return readChannel(CH_LIGHT); } - - /* - * Returns the current ambient temperature, expressed either in Celsius - * or Fahreneit scale. - */ - int readTemperature(const byte scale); - - /* - * Returns a number corresponding to the amount of ambient noise. - */ - inline unsigned int readMicrophone() { return readChannel(CH_MIC); } - - inline unsigned int readJoystickSwitch() { return readChannel(CH_JOYSTICK_SW); } - - inline int readJoystickX() { - return readChannel(CH_JOYSTICK_X) - 512; - } - inline int readJoystickY() { - return readChannel(CH_JOYSTICK_Y) - 512; - } - - int readAccelerometer(const byte axis); - - /* - * Reads the current state of a button. It will return - * LOW if the button is pressed, and HIGH otherwise. - */ - boolean readButton(byte channel); - - boolean readJoystickButton(); - - void writeRGB(byte red, byte green, byte blue); - void writeRed(byte red); - void writeGreen(byte green); - void writeBlue(byte blue); - - byte readRed(); - byte readGreen(); - byte readBlue(); - - void tone(unsigned int freq); - void tone(unsigned int freq, unsigned long duration); - void noTone(); - - inline unsigned int readTinkerkitInput(byte whichInput) { - return readChannel(whichInput + CH_TINKERKIT_A); - } - inline unsigned int readTinkerkitInputA() { - return readChannel(CH_TINKERKIT_A); - } - inline unsigned int readTinkerkitInputB() { - return readChannel(CH_TINKERKIT_B); - } -}; - - - -extern _Esplora Esplora; - -#endif // ESPLORA_H_ diff --git a/include/HID/HID.h b/include/HID/HID.h @@ -1,125 +0,0 @@ -/* - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - Permission to use, copy, modify, and/or distribute this software for - any purpose with or without fee is hereby granted, provided that the - above copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL - WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR - BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES - OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, - WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, - ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS - SOFTWARE. - */ - -#ifndef HID_h -#define HID_h - -#include <stdint.h> -#include <Arduino.h> -#include "PluggableUSB.h" - -#if defined(USBCON) - -#define _USING_HID - -// HID 'Driver' -// ------------ -#define HID_GET_REPORT 0x01 -#define HID_GET_IDLE 0x02 -#define HID_GET_PROTOCOL 0x03 -#define HID_SET_REPORT 0x09 -#define HID_SET_IDLE 0x0A -#define HID_SET_PROTOCOL 0x0B - -#define HID_HID_DESCRIPTOR_TYPE 0x21 -#define HID_REPORT_DESCRIPTOR_TYPE 0x22 -#define HID_PHYSICAL_DESCRIPTOR_TYPE 0x23 - -// HID subclass HID1.11 Page 8 4.2 Subclass -#define HID_SUBCLASS_NONE 0 -#define HID_SUBCLASS_BOOT_INTERFACE 1 - -// HID Keyboard/Mouse bios compatible protocols HID1.11 Page 9 4.3 Protocols -#define HID_PROTOCOL_NONE 0 -#define HID_PROTOCOL_KEYBOARD 1 -#define HID_PROTOCOL_MOUSE 2 - -// Normal or bios protocol (Keyboard/Mouse) HID1.11 Page 54 7.2.5 Get_Protocol Request -// "protocol" variable is used for this purpose. -#define HID_BOOT_PROTOCOL 0 -#define HID_REPORT_PROTOCOL 1 - -// HID Request Type HID1.11 Page 51 7.2.1 Get_Report Request -#define HID_REPORT_TYPE_INPUT 1 -#define HID_REPORT_TYPE_OUTPUT 2 -#define HID_REPORT_TYPE_FEATURE 3 - -typedef struct -{ - uint8_t len; // 9 - uint8_t dtype; // 0x21 - uint8_t addr; - uint8_t versionL; // 0x101 - uint8_t versionH; // 0x101 - uint8_t country; - uint8_t desctype; // 0x22 report - uint8_t descLenL; - uint8_t descLenH; -} HIDDescDescriptor; - -typedef struct -{ - InterfaceDescriptor hid; - HIDDescDescriptor desc; - EndpointDescriptor in; -} HIDDescriptor; - -class HIDSubDescriptor { -public: - HIDSubDescriptor *next = NULL; - HIDSubDescriptor(const void *d, const uint16_t l) : data(d), length(l) { } - - const void* data; - const uint16_t length; -}; - -class HID_ : public PluggableUSBModule -{ -public: - HID_(void); - int begin(void); - int SendReport(uint8_t id, const void* data, int len); - void AppendDescriptor(HIDSubDescriptor* node); - -protected: - // Implementation of the PluggableUSBModule - int getInterface(uint8_t* interfaceCount); - int getDescriptor(USBSetup& setup); - bool setup(USBSetup& setup); - uint8_t getShortName(char* name); - -private: - uint8_t epType[1]; - - HIDSubDescriptor* rootNode; - uint16_t descriptorSize; - - uint8_t protocol; - uint8_t idle; -}; - -// Replacement for global singleton. -// This function prevents static-initialization-order-fiasco -// https://isocpp.org/wiki/faq/ctors#static-init-order-on-first-use -HID_& HID(); - -#define D_HIDREPORT(length) { 9, 0x21, 0x01, 0x01, 0, 1, 0x22, lowByte(length), highByte(length) } - -#endif // USBCON - -#endif // HID_h diff --git a/include/Keyboard/Keyboard.h b/include/Keyboard/Keyboard.h @@ -1,99 +0,0 @@ -/* - Keyboard.h - - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef KEYBOARD_h -#define KEYBOARD_h - -#include "HID.h" - -#if !defined(_USING_HID) - -#warning "Using legacy HID core (non pluggable)" - -#else - -//================================================================================ -//================================================================================ -// Keyboard - -#define KEY_LEFT_CTRL 0x80 -#define KEY_LEFT_SHIFT 0x81 -#define KEY_LEFT_ALT 0x82 -#define KEY_LEFT_GUI 0x83 -#define KEY_RIGHT_CTRL 0x84 -#define KEY_RIGHT_SHIFT 0x85 -#define KEY_RIGHT_ALT 0x86 -#define KEY_RIGHT_GUI 0x87 - -#define KEY_UP_ARROW 0xDA -#define KEY_DOWN_ARROW 0xD9 -#define KEY_LEFT_ARROW 0xD8 -#define KEY_RIGHT_ARROW 0xD7 -#define KEY_BACKSPACE 0xB2 -#define KEY_TAB 0xB3 -#define KEY_RETURN 0xB0 -#define KEY_ESC 0xB1 -#define KEY_INSERT 0xD1 -#define KEY_DELETE 0xD4 -#define KEY_PAGE_UP 0xD3 -#define KEY_PAGE_DOWN 0xD6 -#define KEY_HOME 0xD2 -#define KEY_END 0xD5 -#define KEY_CAPS_LOCK 0xC1 -#define KEY_F1 0xC2 -#define KEY_F2 0xC3 -#define KEY_F3 0xC4 -#define KEY_F4 0xC5 -#define KEY_F5 0xC6 -#define KEY_F6 0xC7 -#define KEY_F7 0xC8 -#define KEY_F8 0xC9 -#define KEY_F9 0xCA -#define KEY_F10 0xCB -#define KEY_F11 0xCC -#define KEY_F12 0xCD - -// Low level key report: up to 6 keys and shift, ctrl etc at once -typedef struct -{ - uint8_t modifiers; - uint8_t reserved; - uint8_t keys[6]; -} KeyReport; - -class Keyboard_ : public Print -{ -private: - KeyReport _keyReport; - void sendReport(KeyReport* keys); -public: - Keyboard_(void); - void begin(void); - void end(void); - size_t write(uint8_t k); - size_t press(uint8_t k); - size_t release(uint8_t k); - void releaseAll(void); -}; -extern Keyboard_ Keyboard; - -#endif -#endif diff --git a/include/Mouse/Mouse.h b/include/Mouse/Mouse.h @@ -1,60 +0,0 @@ -/* - Mouse.h - - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef MOUSE_h -#define MOUSE_h - -#include "HID.h" - -#if !defined(_USING_HID) - -#warning "Using legacy HID core (non pluggable)" - -#else - -//================================================================================ -//================================================================================ -// Mouse - -#define MOUSE_LEFT 1 -#define MOUSE_RIGHT 2 -#define MOUSE_MIDDLE 4 -#define MOUSE_ALL (MOUSE_LEFT | MOUSE_RIGHT | MOUSE_MIDDLE) - -class Mouse_ -{ -private: - uint8_t _buttons; - void buttons(uint8_t b); -public: - Mouse_(void); - void begin(void); - void end(void); - void click(uint8_t b = MOUSE_LEFT); - void move(signed char x, signed char y, signed char wheel = 0); - void press(uint8_t b = MOUSE_LEFT); // press LEFT by default - void release(uint8_t b = MOUSE_LEFT); // release LEFT by default - bool isPressed(uint8_t b = MOUSE_LEFT); // check LEFT by default -}; -extern Mouse_ Mouse; - -#endif -#endif- \ No newline at end of file diff --git a/include/RobotIRremote/IRremote.h b/include/RobotIRremote/IRremote.h @@ -1,94 +0,0 @@ -/* - * IRremote - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.htm http://arcfn.com - * Edited by Mitra to add new controller SANYO - * - * Interrupt code based on NECIRrcv by Joe Knapp - * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 - * Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ - * - * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) - */ - -#ifndef IRremote_h -#define IRremote_h - -// The following are compile-time library options. -// If you change them, recompile the library. -// If DEBUG is defined, a lot of debugging output will be printed during decoding. -// TEST must be defined for the IRtest unittests to work. It will make some -// methods virtual, which will be slightly slower, which is why it is optional. -// #define DEBUG -// #define TEST - -// Results returned from the decoder -class decode_results { -public: - int decode_type; // NEC, SONY, RC5, UNKNOWN - unsigned int panasonicAddress; // This is only used for decoding Panasonic data - unsigned long value; // Decoded value - int bits; // Number of bits in decoded value - volatile unsigned int *rawbuf; // Raw intervals in .5 us ticks - int rawlen; // Number of records in rawbuf. -}; - -// Values for decode_type -#define NEC 1 -#define SONY 2 -#define RC5 3 -#define RC6 4 -#define DISH 5 -#define SHARP 6 -#define PANASONIC 7 -#define JVC 8 -#define SANYO 9 -#define MITSUBISHI 10 -#define UNKNOWN -1 - -// Decoded value for NEC when a repeat code is received -#define REPEAT 0xffffffff - -// main class for receiving IR -class IRrecv -{ -public: - IRrecv(int recvpin); - void blink13(int blinkflag); - int decode(decode_results *results); - void enableIRIn(); - void resume(); -private: - // These are called by decode - int getRClevel(decode_results *results, int *offset, int *used, int t1); - long decodeNEC(decode_results *results); - //long decodeSony(decode_results *results); - //long decodeSanyo(decode_results *results); - //long decodeMitsubishi(decode_results *results); - //long decodeRC5(decode_results *results); - //long decodeRC6(decode_results *results); - //long decodePanasonic(decode_results *results); - //long decodeJVC(decode_results *results); - long decodeHash(decode_results *results); - int compare(unsigned int oldval, unsigned int newval); - -} -; - -// Only used for testing; can remove virtual for shorter code -#ifdef TEST -#define VIRTUAL virtual -#else -#define VIRTUAL -#endif -// Some useful constants - -#define USECPERTICK 50 // microseconds per clock interrupt tick -#define RAWBUF 100 // Length of raw duration buffer - -// Marks tend to be 100us too long, and spaces 100us too short -// when received due to sensor lag. -#define MARK_EXCESS 100 - -#endif diff --git a/include/RobotIRremote/IRremoteInt.h b/include/RobotIRremote/IRremoteInt.h @@ -1,446 +0,0 @@ -/* - * IRremote - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html - * - * Modified by Paul Stoffregen <paul@pjrc.com> to support other boards and timers - * - * Interrupt code based on NECIRrcv by Joe Knapp - * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 - * Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ - * - * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) - */ - -#ifndef IRremoteint_h -#define IRremoteint_h - -#if defined(ARDUINO) && ARDUINO >= 100 -#include <Arduino.h> -#else -#include <WProgram.h> -#endif - -// define which timer to use -// -// Uncomment the timer you wish to use on your board. If you -// are using another library which uses timer2, you have options -// to switch IRremote to use a different timer. - -// Arduino Mega -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - //#define IR_USE_TIMER1 // tx = pin 11 - #define IR_USE_TIMER2 // tx = pin 9 - //#define IR_USE_TIMER3 // tx = pin 5 - //#define IR_USE_TIMER4 // tx = pin 6 - //#define IR_USE_TIMER5 // tx = pin 46 - -// Teensy 1.0 -#elif defined(__AVR_AT90USB162__) - #define IR_USE_TIMER1 // tx = pin 17 - -// Teensy 2.0 -#elif defined(__AVR_ATmega32U4__) - //#define IR_USE_TIMER1 // tx = pin 14 - //#define IR_USE_TIMER3 // tx = pin 9 - #define IR_USE_TIMER4_HS // tx = pin 10 - -// Teensy++ 1.0 & 2.0 -#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) - //#define IR_USE_TIMER1 // tx = pin 25 - #define IR_USE_TIMER2 // tx = pin 1 - //#define IR_USE_TIMER3 // tx = pin 16 - -// Sanguino -#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) - //#define IR_USE_TIMER1 // tx = pin 13 - #define IR_USE_TIMER2 // tx = pin 14 - -// Atmega8 -#elif defined(__AVR_ATmega8P__) || defined(__AVR_ATmega8__) - #define IR_USE_TIMER1 // tx = pin 9 - -// Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, etc -#else - //#define IR_USE_TIMER1 // tx = pin 9 - #define IR_USE_TIMER2 // tx = pin 3 -#endif - - - -#ifdef F_CPU -#define SYSCLOCK F_CPU // main Arduino clock -#else -#define SYSCLOCK 16000000 // main Arduino clock -#endif - -#define ERR 0 -#define DECODED 1 - - -// defines for setting and clearing register bits -#ifndef cbi -#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) -#endif -#ifndef sbi -#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) -#endif - -// Pulse parms are *50-100 for the Mark and *50+100 for the space -// First MARK is the one after the long gap -// pulse parameters in usec -#define NEC_HDR_MARK 9000 -#define NEC_HDR_SPACE 4500 -#define NEC_BIT_MARK 560 -#define NEC_ONE_SPACE 1600 -#define NEC_ZERO_SPACE 560 -#define NEC_RPT_SPACE 2250 - -#define SONY_HDR_MARK 2400 -#define SONY_HDR_SPACE 600 -#define SONY_ONE_MARK 1200 -#define SONY_ZERO_MARK 600 -#define SONY_RPT_LENGTH 45000 -#define SONY_DOUBLE_SPACE_USECS 500 // usually ssee 713 - not using ticks as get number wrapround - -// SA 8650B -#define SANYO_HDR_MARK 3500 // seen range 3500 -#define SANYO_HDR_SPACE 950 // seen 950 -#define SANYO_ONE_MARK 2400 // seen 2400 -#define SANYO_ZERO_MARK 700 // seen 700 -#define SANYO_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround -#define SANYO_RPT_LENGTH 45000 - -// Mitsubishi RM 75501 -// 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7 - -// #define MITSUBISHI_HDR_MARK 250 // seen range 3500 -#define MITSUBISHI_HDR_SPACE 350 // 7*50+100 -#define MITSUBISHI_ONE_MARK 1950 // 41*50-100 -#define MITSUBISHI_ZERO_MARK 750 // 17*50-100 -// #define MITSUBISHI_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround -// #define MITSUBISHI_RPT_LENGTH 45000 - - -#define RC5_T1 889 -#define RC5_RPT_LENGTH 46000 - -#define RC6_HDR_MARK 2666 -#define RC6_HDR_SPACE 889 -#define RC6_T1 444 -#define RC6_RPT_LENGTH 46000 - -#define SHARP_BIT_MARK 245 -#define SHARP_ONE_SPACE 1805 -#define SHARP_ZERO_SPACE 795 -#define SHARP_GAP 600000 -#define SHARP_TOGGLE_MASK 0x3FF -#define SHARP_RPT_SPACE 3000 - -#define DISH_HDR_MARK 400 -#define DISH_HDR_SPACE 6100 -#define DISH_BIT_MARK 400 -#define DISH_ONE_SPACE 1700 -#define DISH_ZERO_SPACE 2800 -#define DISH_RPT_SPACE 6200 -#define DISH_TOP_BIT 0x8000 - -#define PANASONIC_HDR_MARK 3502 -#define PANASONIC_HDR_SPACE 1750 -#define PANASONIC_BIT_MARK 502 -#define PANASONIC_ONE_SPACE 1244 -#define PANASONIC_ZERO_SPACE 400 - -#define JVC_HDR_MARK 8000 -#define JVC_HDR_SPACE 4000 -#define JVC_BIT_MARK 600 -#define JVC_ONE_SPACE 1600 -#define JVC_ZERO_SPACE 550 -#define JVC_RPT_LENGTH 60000 - -#define SHARP_BITS 15 -#define DISH_BITS 16 - -#define TOLERANCE 25 // percent tolerance in measurements -#define LTOL (1.0 - TOLERANCE/100.) -#define UTOL (1.0 + TOLERANCE/100.) - -#define _GAP 5000 // Minimum map between transmissions -#define GAP_TICKS (_GAP/USECPERTICK) - -#define TICKS_LOW(us) (int) (((us)*LTOL/USECPERTICK)) -#define TICKS_HIGH(us) (int) (((us)*UTOL/USECPERTICK + 1)) - -// receiver states -#define STATE_IDLE 2 -#define STATE_MARK 3 -#define STATE_SPACE 4 -#define STATE_STOP 5 - -// information for the interrupt handler -typedef struct { - uint8_t recvpin; // pin for IR data from detector - uint8_t rcvstate; // state machine - uint8_t blinkflag; // TRUE to enable blinking of pin 13 on IR processing - unsigned int timer; // state timer, counts 50uS ticks. - unsigned int rawbuf[RAWBUF]; // raw data - uint8_t rawlen; // counter of entries in rawbuf -} -irparams_t; - -// Defined in IRremote.cpp -extern volatile irparams_t irparams; - -// IR detector output is active low -#define MARK 0 -#define SPACE 1 - -#define TOPBIT 0x80000000 - -#define NEC_BITS 32 -#define SONY_BITS 12 -#define SANYO_BITS 12 -#define MITSUBISHI_BITS 16 -#define MIN_RC5_SAMPLES 11 -#define MIN_RC6_SAMPLES 1 -#define PANASONIC_BITS 48 -#define JVC_BITS 16 - - - - -// defines for timer2 (8 bits) -#if defined(IR_USE_TIMER2) -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR2A |= _BV(COM2B1)) -#define TIMER_DISABLE_PWM (TCCR2A &= ~(_BV(COM2B1))) -#define TIMER_ENABLE_INTR (TIMSK2 = _BV(OCIE2A)) -#define TIMER_DISABLE_INTR (TIMSK2 = 0) -#define TIMER_INTR_NAME TIMER2_COMPA_vect -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint8_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR2A = _BV(WGM20); \ - TCCR2B = _BV(WGM22) | _BV(CS20); \ - OCR2A = pwmval; \ - OCR2B = pwmval / 3; \ -}) -#define TIMER_COUNT_TOP (SYSCLOCK * USECPERTICK / 1000000) -#if (TIMER_COUNT_TOP < 256) -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR2A = _BV(WGM21); \ - TCCR2B = _BV(CS20); \ - OCR2A = TIMER_COUNT_TOP; \ - TCNT2 = 0; \ -}) -#else -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR2A = _BV(WGM21); \ - TCCR2B = _BV(CS21); \ - OCR2A = TIMER_COUNT_TOP / 8; \ - TCNT2 = 0; \ -}) -#endif -#if defined(CORE_OC2B_PIN) -#define TIMER_PWM_PIN CORE_OC2B_PIN /* Teensy */ -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define TIMER_PWM_PIN 9 /* Arduino Mega */ -#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) -#define TIMER_PWM_PIN 14 /* Sanguino */ -#else -#define TIMER_PWM_PIN 3 /* Arduino Duemilanove, Diecimila, LilyPad, etc */ -#endif - - -// defines for timer1 (16 bits) -#elif defined(IR_USE_TIMER1) -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR1A |= _BV(COM1A1)) -#define TIMER_DISABLE_PWM (TCCR1A &= ~(_BV(COM1A1))) -#if defined(__AVR_ATmega8P__) || defined(__AVR_ATmega8__) - #define TIMER_ENABLE_INTR (TIMSK = _BV(OCIE1A)) - #define TIMER_DISABLE_INTR (TIMSK = 0) -#else - #define TIMER_ENABLE_INTR (TIMSK1 = _BV(OCIE1A)) - #define TIMER_DISABLE_INTR (TIMSK1 = 0) -#endif -#define TIMER_INTR_NAME TIMER1_COMPA_vect -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR1A = _BV(WGM11); \ - TCCR1B = _BV(WGM13) | _BV(CS10); \ - ICR1 = pwmval; \ - OCR1A = pwmval / 3; \ -}) -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR1A = 0; \ - TCCR1B = _BV(WGM12) | _BV(CS10); \ - OCR1A = SYSCLOCK * USECPERTICK / 1000000; \ - TCNT1 = 0; \ -}) -#if defined(CORE_OC1A_PIN) -#define TIMER_PWM_PIN CORE_OC1A_PIN /* Teensy */ -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define TIMER_PWM_PIN 11 /* Arduino Mega */ -#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) -#define TIMER_PWM_PIN 13 /* Sanguino */ -#else -#define TIMER_PWM_PIN 9 /* Arduino Duemilanove, Diecimila, LilyPad, etc */ -#endif - - -// defines for timer3 (16 bits) -#elif defined(IR_USE_TIMER3) -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR3A |= _BV(COM3A1)) -#define TIMER_DISABLE_PWM (TCCR3A &= ~(_BV(COM3A1))) -#define TIMER_ENABLE_INTR (TIMSK3 = _BV(OCIE3A)) -#define TIMER_DISABLE_INTR (TIMSK3 = 0) -#define TIMER_INTR_NAME TIMER3_COMPA_vect -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR3A = _BV(WGM31); \ - TCCR3B = _BV(WGM33) | _BV(CS30); \ - ICR3 = pwmval; \ - OCR3A = pwmval / 3; \ -}) -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR3A = 0; \ - TCCR3B = _BV(WGM32) | _BV(CS30); \ - OCR3A = SYSCLOCK * USECPERTICK / 1000000; \ - TCNT3 = 0; \ -}) -#if defined(CORE_OC3A_PIN) -#define TIMER_PWM_PIN CORE_OC3A_PIN /* Teensy */ -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define TIMER_PWM_PIN 5 /* Arduino Mega */ -#else -#error "Please add OC3A pin number here\n" -#endif - - -// defines for timer4 (10 bits, high speed option) -#elif defined(IR_USE_TIMER4_HS) -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1)) -#define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1))) -#define TIMER_ENABLE_INTR (TIMSK4 = _BV(TOIE4)) -#define TIMER_DISABLE_INTR (TIMSK4 = 0) -#define TIMER_INTR_NAME TIMER4_OVF_vect -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR4A = (1<<PWM4A); \ - TCCR4B = _BV(CS40); \ - TCCR4C = 0; \ - TCCR4D = (1<<WGM40); \ - TCCR4E = 0; \ - TC4H = pwmval >> 8; \ - OCR4C = pwmval; \ - TC4H = (pwmval / 3) >> 8; \ - OCR4A = (pwmval / 3) & 255; \ -}) -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR4A = 0; \ - TCCR4B = _BV(CS40); \ - TCCR4C = 0; \ - TCCR4D = 0; \ - TCCR4E = 0; \ - TC4H = (SYSCLOCK * USECPERTICK / 1000000) >> 8; \ - OCR4C = (SYSCLOCK * USECPERTICK / 1000000) & 255; \ - TC4H = 0; \ - TCNT4 = 0; \ -}) -#if defined(CORE_OC4A_PIN) -#define TIMER_PWM_PIN CORE_OC4A_PIN /* Teensy */ -#elif defined(__AVR_ATmega32U4__) -#define TIMER_PWM_PIN 13 /* Leonardo */ -#else -#error "Please add OC4A pin number here\n" -#endif - - -// defines for timer4 (16 bits) -#elif defined(IR_USE_TIMER4) -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1)) -#define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1))) -#define TIMER_ENABLE_INTR (TIMSK4 = _BV(OCIE4A)) -#define TIMER_DISABLE_INTR (TIMSK4 = 0) -#define TIMER_INTR_NAME TIMER4_COMPA_vect -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR4A = _BV(WGM41); \ - TCCR4B = _BV(WGM43) | _BV(CS40); \ - ICR4 = pwmval; \ - OCR4A = pwmval / 3; \ -}) -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR4A = 0; \ - TCCR4B = _BV(WGM42) | _BV(CS40); \ - OCR4A = SYSCLOCK * USECPERTICK / 1000000; \ - TCNT4 = 0; \ -}) -#if defined(CORE_OC4A_PIN) -#define TIMER_PWM_PIN CORE_OC4A_PIN -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define TIMER_PWM_PIN 6 /* Arduino Mega */ -#else -#error "Please add OC4A pin number here\n" -#endif - - -// defines for timer5 (16 bits) -#elif defined(IR_USE_TIMER5) -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR5A |= _BV(COM5A1)) -#define TIMER_DISABLE_PWM (TCCR5A &= ~(_BV(COM5A1))) -#define TIMER_ENABLE_INTR (TIMSK5 = _BV(OCIE5A)) -#define TIMER_DISABLE_INTR (TIMSK5 = 0) -#define TIMER_INTR_NAME TIMER5_COMPA_vect -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR5A = _BV(WGM51); \ - TCCR5B = _BV(WGM53) | _BV(CS50); \ - ICR5 = pwmval; \ - OCR5A = pwmval / 3; \ -}) -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR5A = 0; \ - TCCR5B = _BV(WGM52) | _BV(CS50); \ - OCR5A = SYSCLOCK * USECPERTICK / 1000000; \ - TCNT5 = 0; \ -}) -#if defined(CORE_OC5A_PIN) -#define TIMER_PWM_PIN CORE_OC5A_PIN -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define TIMER_PWM_PIN 46 /* Arduino Mega */ -#else -#error "Please add OC5A pin number here\n" -#endif - - -#else // unknown timer -#error "Internal code configuration error, no known IR_USE_TIMER# defined\n" -#endif - - -// defines for blinking the LED -#if defined(CORE_LED0_PIN) -#define BLINKLED CORE_LED0_PIN -#define BLINKLED_ON() (digitalWrite(CORE_LED0_PIN, HIGH)) -#define BLINKLED_OFF() (digitalWrite(CORE_LED0_PIN, LOW)) -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define BLINKLED 13 -#define BLINKLED_ON() (PORTB |= B10000000) -#define BLINKLED_OFF() (PORTB &= B01111111) -#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) -#define BLINKLED 0 -#define BLINKLED_ON() (PORTD |= B00000001) -#define BLINKLED_OFF() (PORTD &= B11111110) -#else -#define BLINKLED 13 -#define BLINKLED_ON() (PORTB |= B00100000) -#define BLINKLED_OFF() (PORTB &= B11011111) -#endif - -#endif diff --git a/include/RobotIRremote/IRremoteTools.h b/include/RobotIRremote/IRremoteTools.h @@ -1,12 +0,0 @@ -#ifndef IRREMOTETOOLS_H -#define IRREMOTETOOLS_H - -extern void beginIRremote(); - -extern bool IRrecived(); - -extern void resumeIRremote(); - -extern unsigned long getIRresult(); - -#endif- \ No newline at end of file diff --git a/include/Robot_Control/ArduinoRobot.h b/include/Robot_Control/ArduinoRobot.h @@ -1,374 +0,0 @@ -#ifndef ArduinoRobot_h -#define ArduinoRobot_h - -#include "Arduino_LCD.h" // Hardware-specific library -//#include "FormattedText.h" -#include "SquawkSD.h" -#include "Multiplexer.h" -#include "EasyTransfer2.h" -#include "EEPROM_I2C.h" -#include "Compass.h" -#include "Fat16.h" - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - - -#define BUTTON_NONE -1 -#define BUTTON_LEFT 0 -#define BUTTON_DOWN 1 -#define BUTTON_UP 2 -#define BUTTON_RIGHT 3 -#define BUTTON_MIDDLE 4 -#define NUMBER_BUTTONS 5 - -//beep length -#define BEEP_SIMPLE 0 -#define BEEP_DOUBLE 1 -#define BEEP_LONG 2 - -// image locations on the EEPROM - #define HOME_BMP 0 -#define BATTERY_BMP 2048 -#define COMPASS_BMP 4096 -#define CONTROL_BMP 6144 -#define GEARS_BMP 8192 -#define LIGHT_BMP 10240 -#define OSCILLO_BMP 12288 -#define VOLT_BMP 14336 -#define INICIO_BMP 16384 // this is a full screen splash - -//Command code -#define COMMAND_SWITCH_MODE 0 -#define COMMAND_RUN 10 -#define COMMAND_MOTORS_STOP 11 -#define COMMAND_ANALOG_WRITE 20 -#define COMMAND_DIGITAL_WRITE 30 -#define COMMAND_ANALOG_READ 40 -#define COMMAND_ANALOG_READ_RE 41 -#define COMMAND_DIGITAL_READ 50 -#define COMMAND_DIGITAL_READ_RE 51 -#define COMMAND_READ_IR 60 -#define COMMAND_READ_IR_RE 61 -#define COMMAND_ACTION_DONE 70 -#define COMMAND_READ_TRIM 80 -#define COMMAND_READ_TRIM_RE 81 -#define COMMAND_PAUSE_MODE 90 -#define COMMAND_LINE_FOLLOW_CONFIG 100 - -//component codename -#define CN_LEFT_MOTOR 0 -#define CN_RIGHT_MOTOR 1 -#define CN_IR 2 - -//motor board modes -#define MODE_SIMPLE 0 -#define MODE_LINE_FOLLOW 1 -#define MODE_ADJUST_MOTOR 2 -#define MODE_IR_CONTROL 3 - -//port types, for R/W -#define TYPE_TOP_TK 0 -#define TYPE_TOP_TKD 1 -#define TYPE_BOTTOM_TK 2 - -//top TKs -#define TK0 100 -#define TK1 101 -#define TK2 102 -#define TK3 103 -#define TK4 104 -#define TK5 105 -#define TK6 106 -#define TK7 107 - -#define M0 TK0 -#define M1 TK1 -#define M2 TK2 -#define M3 TK3 -#define M4 TK4 -#define M5 TK5 -#define M6 TK6 -#define M7 TK7 - -//bottom TKs, just for communication purpose -#define B_TK1 201 -#define B_TK2 202 -#define B_TK3 203 -#define B_TK4 204 - -#define D10 B_TK1 -#define D9 B_TK2 -#define D8 B_TK4 -#define D7 B_TK3 - -//bottom IRs, for communication purpose -#define B_IR0 210 -#define B_IR1 211 -#define B_IR2 212 -#define B_IR3 213 -#define B_IR4 214 - -#ifndef LED1 -#define LED1 17 -#endif - -//320 - 337 username, -#define ADDRESS_USERNAME 320 -//338 - 355 robotname, -#define ADDRESS_ROBOTNAME 338 -//356 - 373 cityname, -#define ADDRESS_CITYNAME 356 - //374- 391 countryname, -#define ADDRESS_COUNTRYNAME 374 -//508-511 robot info -#define ADDRESS_ROBOTINFO 508 - -#define BLACK ILI9163C_BLACK -#define BLUE ILI9163C_BLUE -#define RED ILI9163C_RED -#define GREEN ILI9163C_GREEN -#define CYAN ILI9163C_CYAN -#define MAGENTA ILI9163C_MAGENTA -#define YELLOW ILI9163C_YELLOW -#define WHITE ILI9163C_WHITE - -//A data structure for storing the current state of motor board -struct MOTOR_BOARD_DATA{ - int _B_TK1; - int _B_TK2; - int _B_TK3; - int _B_TK4; - - /*int _B_IR0; - int _B_IR1; - int _B_IR2; - int _B_IR3; - int _B_IR4;*/ -}; - -/* -A message structure will be: -switch mode: - byte COMMAND_SWITCH_MODE, byte mode -run: - byte COMMAND_RUN, int speedL, int speedR -analogWrite: - byte COMMAND_ANALOG_WRITE, byte codename, byte value; -digitalWrite: - byte COMMAND_DIGITAL_WRITE, byte codename, byte value; -analogRead: - byte COMMAND_ANALOG_READ, byte codename; -analogRead return: - byte COMMAND_ANALOG_READ_RE, byte codename, int value; -digitalRead return: - byte COMMAND_DIGITAL_READ_RE, byte codename, byte value; -read IR: - byte COMMAND_READ_IR, int valueA, int valueB, int valueC, int valueD; - - -*/ -#define NUM_EEPROM_BMP 10 -struct EEPROM_BMP{ - char name[8]; - uint8_t width; - uint8_t height; - uint16_t address; -}; - -//if you call #undef USE_SQUAWK_SYNTH_SD at the beginning of your sketch, -//it's going to remove anything regarding sound playing - -class RobotControl:public Multiplexer, -public EEPROM_I2C, -public Compass, -public SquawkSynthSD, -//public FormattedText -public Arduino_LCD -{ - public: - RobotControl(); - void begin(); - void setMode(uint8_t mode); - - //Read & Write, TK0 - TK7, TKD0 - TKD1, bottom TK0 - TK4 - bool digitalRead(uint8_t port); - int analogRead(uint8_t port); - void digitalWrite(uint8_t port, bool value); - void analogWrite(uint8_t port, uint8_t value);//It's not available, as there's no pin can be used for analog write - - //IR sensors from the bottom board - //define an array as "int arr[4];", and supply the arry name here - uint16_t IRarray[5]; - void updateIR(); - - //on board Potentiometor - int knobRead(); - //Potentiometor of the motor board - int trimRead(); - - //on board piezo - void beginSpeaker(uint16_t frequency=44100); - void playMelody(char* script); - void playFile(char* filename); - void stopPlayFile(); - void beep(int beep_length=BEEP_SIMPLE); - void tempoWrite(int tempo); - void tuneWrite(float tune); - - //compass - uint16_t compassRead(); - void drawCompass(uint16_t value); - void drawBase(); - void drawDire(int16_t dire); - - //keyboard - void keyboardCalibrate(int *vals); - int8_t keyboardRead();//return the key that is being pressed?Has been pressed(with _processKeyboard)? - - //movement - void moveForward(int speed); - void moveBackward(int speed); - void turnLeft(int speed); - void turnRight(int speed); - void motorsStop(); - void motorsWritePct(int speedLeftPct, int speedRightPct); - - void motorsWrite(int speedLeft,int speedRight); - void pointTo(int degrees);//turn to an absolute angle from the compass - void turn(int degress);//turn certain degrees from the current heading - - //Line Following - void lineFollowConfig(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime);//default 11 5 50 10 - - //TFT LCD - //use the same commands as Arduino_LCD - void beginTFT(uint16_t foreGround=BLACK, uint16_t background=WHITE); - /*void text(int value, uint8_t posX, uint8_t posY, bool EW); - void text(long value, uint8_t posX, uint8_t posY, bool EW); - void text(char* value, uint8_t posX, uint8_t posY, bool EW); - void text(char value, uint8_t posX, uint8_t posY, bool EW);*/ - void debugPrint(long value, uint8_t x=0, uint8_t y=0); - void clearScreen(); - - void drawBMP(char* filename, uint8_t x, uint8_t y);//detect if draw with EEPROM or SD, and draw it - void _drawBMP(uint32_t iconOffset, uint8_t x, uint8_t y, uint8_t width, uint8_t height);//draw from EEPROM - void _drawBMP(char* filename, uint8_t x, uint8_t y);//draw from SD - void beginBMPFromEEPROM(); - void endBMPFromEEPROM(); - - uint16_t foreGround;//foreground color - uint16_t backGround;//background color - - - //SD card - void beginSD(); - - //Information - void userNameRead(char* container); - void robotNameRead(char* container); - void cityNameRead(char* container); - void countryNameRead(char* container); - - void userNameWrite(char* text); - void robotNameWrite(char* text); - void cityNameWrite(char* text); - void countryNameWrite(char* text); - - //Others - bool isActionDone(); - void pauseMode(uint8_t onOff); - void displayLogos(); - void waitContinue(uint8_t key=BUTTON_MIDDLE); - - private: - //Read & Write - uint8_t _getTypeCode(uint8_t port);//different ports need different actions - uint8_t _portToTopMux(uint8_t port);//get the number for multiplexer within top TKs - uint8_t _topDPortToAPort(uint8_t port);//get the corrensponding analogIn pin for top TKDs - - bool _digitalReadTopMux(uint8_t port);//TK0 - TK7 - int _analogReadTopMux(uint8_t port); - - bool _digitalReadTopPin(uint8_t port); - int _analogReadTopPin(uint8_t port); - void _digitalWriteTopPin(uint8_t port, bool value); - - MOTOR_BOARD_DATA motorBoardData; - int* parseMBDPort(uint8_t port); - int get_motorBoardData(uint8_t port); - void set_motorBoardData(uint8_t port, int value); - - bool _requestDigitalRead(uint8_t port); - int _requestAnalogRead(uint8_t port); - void _requestDigitalWrite(uint8_t port, uint8_t value); - - //LCD - void _enableLCD(); - void _setWrite(uint8_t posX, uint8_t posY); - void _setErase(uint8_t posX, uint8_t posY); - - - //SD - SdCard card; - Fat16 file; - Fat16 melody; - void _enableSD(); - - //keyboard - void _processKeyboard(); //need to run in loop, detect if the key is actually pressed - int averageAnalogInput(int pinNum); - - //Ultrasonic ranger - //uint8_t pinTrigger_UR; - //uint8_t pinEcho_UR; - - //Melody - void playNote(byte period, word length, char modifier); - - //Communication - - EasyTransfer2 messageOut; - EasyTransfer2 messageIn; - - //TFT LCD - bool _isEEPROM_BMP_Allocated; - EEPROM_BMP * _eeprom_bmp; - void _drawBMP_EEPROM(uint16_t address, uint8_t width, uint8_t height); - void _drawBMP_SD(char* filename, uint8_t x, uint8_t y); - - -}; - -inline void RobotControl::userNameRead(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_USERNAME,(uint8_t*)container,18); -} -inline void RobotControl::robotNameRead(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_ROBOTNAME,(uint8_t*)container,18); -} -inline void RobotControl::cityNameRead(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_CITYNAME,(uint8_t*)container,18); -} -inline void RobotControl::countryNameRead(char* container){ - EEPROM_I2C::readBuffer(ADDRESS_COUNTRYNAME,(uint8_t*)container,18); -} - -inline void RobotControl::userNameWrite(char* text){ - EEPROM_I2C::writePage(ADDRESS_USERNAME,(uint8_t*)text,18); -} -inline void RobotControl::robotNameWrite(char* text){ - EEPROM_I2C::writePage(ADDRESS_ROBOTNAME,(uint8_t*)text,18); -} -inline void RobotControl::cityNameWrite(char* text){ - EEPROM_I2C::writePage(ADDRESS_CITYNAME,(uint8_t*)text,18); -} -inline void RobotControl::countryNameWrite(char* text){ - EEPROM_I2C::writePage(ADDRESS_COUNTRYNAME,(uint8_t*)text,18); -} - -extern RobotControl Robot; - -#endif- \ No newline at end of file diff --git a/include/Robot_Control/Arduino_LCD.h b/include/Robot_Control/Arduino_LCD.h @@ -1,141 +0,0 @@ -/*************************************************** - This is a library for the Adafruit 1.8" SPI display. - This library works with the Adafruit 1.8" TFT Breakout w/SD card - ----> http://www.adafruit.com/products/358 - as well as Adafruit raw 1.8" TFT display - ----> http://www.adafruit.com/products/618 - - Check out the links above for our tutorials and wiring diagrams - These displays use SPI to communicate, 4 or 5 pins are required to - interface (RST is optional) - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - MIT license, all text above must be included in any redistribution - ****************************************************/ - -#ifndef _ARDUINO_LCDH_ -#define _ARDUINO_LCDH_ - -#if ARDUINO >= 100 - #include "Arduino.h" - #include "Print.h" -#else - #include "WProgram.h" -#endif -#include "utility/Adafruit_GFX.h" -//#include <avr/pgmspace.h> - -// some flags for initR() :( -#define INITR_GREENTAB 0x0 -#define INITR_REDTAB 0x1 - -#define ILI9163C_TFTWIDTH 128 -#define ILI9163C_TFTHEIGHT 160 - -#define ILI9163C_NOP 0x00 -#define ILI9163C_SWRESET 0x01 -#define ILI9163C_RDDID 0x04 -#define ILI9163C_RDDST 0x09 - -#define ILI9163C_SLPIN 0x10 -#define ILI9163C_SLPOUT 0x11 -#define ILI9163C_PTLON 0x12 -#define ILI9163C_NORON 0x13 - -#define ILI9163C_INVOFF 0x20 -#define ILI9163C_INVON 0x21 -#define ILI9163C_DISPOFF 0x28 -#define ILI9163C_DISPON 0x29 -#define ILI9163C_CASET 0x2A -#define ILI9163C_RASET 0x2B -#define ILI9163C_RAMWR 0x2C -#define ILI9163C_RAMRD 0x2E - -#define ILI9163C_PTLAR 0x30 -#define ILI9163C_COLMOD 0x3A // this is interface pixel format, this might be the issue -#define ILI9163C_MADCTL 0x36 - -#define ILI9163C_FRMCTR1 0xB1 -#define ILI9163C_FRMCTR2 0xB2 -#define ILI9163C_FRMCTR3 0xB3 -#define ILI9163C_INVCTR 0xB4 -#define ILI9163C_DISSET5 0xB6 - -#define ILI9163C_PWCTR1 0xC0 -#define ILI9163C_PWCTR2 0xC1 -#define ILI9163C_PWCTR3 0xC2 -#define ILI9163C_PWCTR4 0xC3 -#define ILI9163C_PWCTR5 0xC4 -#define ILI9163C_VMCTR1 0xC5 - -#define ILI9163C_RDID1 0xDA -#define ILI9163C_RDID2 0xDB -#define ILI9163C_RDID3 0xDC -#define ILI9163C_RDID4 0xDD - -#define ILI9163C_PWCTR6 0xFC - -#define ILI9163C_GMCTRP1 0xE0 -#define ILI9163C_GMCTRN1 0xE1 - -// Color definitions -#define ILI9163C_BLACK 0x0000 -#define ILI9163C_BLUE 0x001F -#define ILI9163C_RED 0xF800 -#define ILI9163C_GREEN 0x07E0 -#define ILI9163C_CYAN 0x07FF -#define ILI9163C_MAGENTA 0xF81F -#define ILI9163C_YELLOW 0xFFE0 -#define ILI9163C_WHITE 0xFFFF - - -class Arduino_LCD : public Adafruit_GFX { - - public: - - Arduino_LCD(uint8_t CS, uint8_t RS, uint8_t SID, uint8_t SCLK, uint8_t RST); - Arduino_LCD(uint8_t CS, uint8_t RS, uint8_t RST); - - void initB(void), // for ST7735B displays - initR(uint8_t options = INITR_GREENTAB), // for ST7735R - setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1), - pushColor(uint16_t color), - fillScreen(uint16_t color), - drawPixel(int16_t x, int16_t y, uint16_t color), - drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), - drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), - fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), - setRotation(uint8_t r), - invertDisplay(boolean i); - uint16_t Color565(uint8_t r, uint8_t g, uint8_t b); - - /* These are not for current use, 8-bit protocol only! - uint8_t readdata(void), - readcommand8(uint8_t); - uint16_t readcommand16(uint8_t); - uint32_t readcommand32(uint8_t); - void dummyclock(void); - */ - - private: - - void spiwrite(uint8_t), - writecommand(uint8_t c), - writedata(uint8_t d), -// commandList(prog_uchar *addr), -// commonInit(prog_uchar *cmdList); - commandList(uint8_t *addr), - commonInit(uint8_t *cmdList); -//uint8_t spiread(void); - - boolean hwSPI; - volatile uint8_t *dataport, *clkport, *csport, *rsport; - uint8_t _cs, _rs, _rst, _sid, _sclk, - datapinmask, clkpinmask, cspinmask, rspinmask, - colstart, rowstart; // some displays need this changed -}; - -#endif diff --git a/include/Robot_Control/Compass.h b/include/Robot_Control/Compass.h @@ -1,24 +0,0 @@ -#ifndef Compass_h -#define Compass_h - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -//0x21==0x42>>1, from bildr's code -#define HMC6352SlaveAddress 0x21 -#define HMC6352ReadAddress 0x41 - -class Compass{ - public: - void begin(); - float getReading(); - private: - void _beginTransmission(); - void _endTransmission(); - -}; - -#endif- \ No newline at end of file diff --git a/include/Robot_Control/EEPROM_I2C.h b/include/Robot_Control/EEPROM_I2C.h @@ -1,31 +0,0 @@ -#ifndef EEPROM_I2C_h -#define EEPROM_I2C_h - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -#define EE24LC512MAXBYTES 64000 -#define DEVICEADDRESS 0x50 - -class EEPROM_I2C{ - public: - void begin(); - - void writeByte(unsigned int eeaddresspage, byte data); - byte readByte(unsigned int eeaddresspage); - - void writePage(unsigned int eeaddresspage, byte* data, byte length ); - void readBuffer(unsigned int eeaddress, byte *buffer, int length ); - - //uint16_t readPixel(uint16_t theMemoryAddress); - //void readImage(uint16_t theMemoryAddress, int width, int height); - - protected: - void _beginTransmission(unsigned int eeaddress); - void _endTransmission(); -}; - -#endif- \ No newline at end of file diff --git a/include/Robot_Control/EasyTransfer2.h b/include/Robot_Control/EasyTransfer2.h @@ -1,76 +0,0 @@ -/****************************************************************** -* EasyTransfer Arduino Library -* details and example sketch: -* http://www.billporter.info/easytransfer-arduino-library/ -* -* Brought to you by: -* Bill Porter -* www.billporter.info -* -* See Readme for other info and version history -* -* -*This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or(at your option) any later version. -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. -<http://www.gnu.org/licenses/> -* -*This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. -*To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or -*send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. -******************************************************************/ -#ifndef EasyTransfer2_h -#define EasyTransfer2_h - - -//make it a little prettier on the front end. -#define details(name) (byte*)&name,sizeof(name) - -//Not neccessary, but just in case. -#if ARDUINO > 22 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif -#include "HardwareSerial.h" -//#include <NewSoftSerial.h> -#include <math.h> -#include <stdio.h> -#include <stdint.h> -#include <avr/io.h> - -class EasyTransfer2 { -public: -void begin(HardwareSerial *theSerial); -//void begin(uint8_t *, uint8_t, NewSoftSerial *theSerial); -void sendData(); -boolean receiveData(); - -void writeByte(uint8_t dat); -void writeInt(int dat); -uint8_t readByte(); -int readInt(); - - -private: -HardwareSerial *_serial; - -void resetData(); - -uint8_t data[20]; //data storage, for both read and send -uint8_t position; -uint8_t size; //size of data in bytes. Both for read and send -//uint8_t * address; //address of struct -//uint8_t size; //size of struct -//uint8_t * rx_buffer; //address for temporary storage and parsing buffer -//uint8_t rx_buffer[20]; -uint8_t rx_array_inx; //index for RX parsing buffer -uint8_t rx_len; //RX packet length according to the packet -uint8_t calc_CS; //calculated Chacksum -}; - - - -#endif- \ No newline at end of file diff --git a/include/Robot_Control/Fat16.h b/include/Robot_Control/Fat16.h @@ -1,378 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * <http://www.gnu.org/licenses/>. - */ -#ifndef Fat16_h -#define Fat16_h -/** - * \file - * Fat16 class - */ -#include <string.h> -#include <avr/pgmspace.h> -#include <Print.h> -#include <SdCard.h> -#include <FatStructs.h> -#include <Fat16Config.h> -//------------------------------------------------------------------------------ -/** Fat16 version YYYYMMDD */ -#define FAT16_VERSION 20111205 -//------------------------------------------------------------------------------ -// flags for ls() -/** ls() flag to print modify date */ -uint8_t const LS_DATE = 1; -/** ls() flag to print file size */ -uint8_t const LS_SIZE = 2; - -// use the gnu style oflags -/** open for reading */ -uint8_t const O_READ = 0X01; -/** same as O_READ */ -uint8_t const O_RDONLY = O_READ; -/** open for write */ -uint8_t const O_WRITE = 0X02; -/** same as O_WRITE */ -uint8_t const O_WRONLY = O_WRITE; -/** open for reading and writing */ -uint8_t const O_RDWR = O_READ | O_WRITE; -/** mask for access modes */ -uint8_t const O_ACCMODE = O_READ | O_WRITE; -/** The file offset shall be set to the end of the file prior to each write. */ -uint8_t const O_APPEND = 0X04; -/** synchronous writes - call sync() after each write */ -uint8_t const O_SYNC = 0X08; -/** create the file if nonexistent */ -uint8_t const O_CREAT = 0X10; -/** If O_CREAT and O_EXCL are set, open() shall fail if the file exists */ -uint8_t const O_EXCL = 0X20; -/** truncate the file to zero length */ -uint8_t const O_TRUNC = 0X40; - -// flags for timestamp -/** set the file's last access date */ -uint8_t const T_ACCESS = 1; -/** set the file's creation date and time */ -uint8_t const T_CREATE = 2; -/** Set the file's write date and time */ -uint8_t const T_WRITE = 4; - -/** date field for FAT directory entry */ -static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { - return (year - 1980) << 9 | month << 5 | day; -} -/** year part of FAT directory date field */ -static inline uint16_t FAT_YEAR(uint16_t fatDate) { - return 1980 + (fatDate >> 9); -} -/** month part of FAT directory date field */ -static inline uint8_t FAT_MONTH(uint16_t fatDate) { - return (fatDate >> 5) & 0XF; -} -/** day part of FAT directory date field */ -static inline uint8_t FAT_DAY(uint16_t fatDate) { - return fatDate & 0X1F; -} -/** time field for FAT directory entry */ -static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { - return hour << 11 | minute << 5 | second >> 1; -} -/** hour part of FAT directory time field */ -static inline uint8_t FAT_HOUR(uint16_t fatTime) { - return fatTime >> 11; -} -/** minute part of FAT directory time field */ -static inline uint8_t FAT_MINUTE(uint16_t fatTime) { - return(fatTime >> 5) & 0X3F; -} -/** second part of FAT directory time field */ -static inline uint8_t FAT_SECOND(uint16_t fatTime) { - return 2*(fatTime & 0X1F); -} -/** Default date for file timestamps is 1 Jan 2000 */ -uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; -/** Default time for file timestamp is 1 am */ -uint16_t const FAT_DEFAULT_TIME = (1 << 11); -//------------------------------------------------------------------------------ -/** - * \typedef fat_t - * - * \brief Type for FAT16 entry - */ -typedef uint16_t fat_t; -/** - * \union cache16_t - * - * \brief Cache buffer data type - * - */ -union cache16_t { - /** Used to access cached file data blocks. */ - uint8_t data[512]; - /** Used to access cached FAT entries. */ - fat_t fat[256]; - /** Used to access cached directory entries. */ - dir_t dir[16]; - /** Used to access a cached Master Boot Record. */ - mbr_t mbr; - /** Used to access to a cached FAT16 boot sector. */ - fbs_t fbs; -}; -//------------------------------------------------------------------------------ -/** \class Fat16 - * \brief Fat16 implements a minimal Arduino FAT16 Library - * - * Fat16 does not support subdirectories or long file names. - */ -class Fat16 : public Print { - public: - /* - * Public functions - */ - /** create with file closed */ - Fat16(void) : flags_(0) {} - /** \return The current cluster number. */ - fat_t curCluster(void) const {return curCluster_;} - uint8_t close(void); - /** \return The count of clusters in the FAT16 volume. */ - static fat_t clusterCount(void) {return clusterCount_;} - /** \return The number of 512 byte blocks in a cluster */ - static uint8_t clusterSize(void) {return blocksPerCluster_;} - /** \return The current file position. */ - uint32_t curPosition(void) const {return curPosition_;} - /** - * Set the date/time callback function - * - * \param[in] dateTime The user's callback function. The callback - * function is of the form: - * - * \code - * void dateTime(uint16_t* date, uint16_t* time) { - * uint16_t year; - * uint8_t month, day, hour, minute, second; - * - * // User gets date and time from GPS or real-time clock here - * - * // return date using FAT_DATE macro to format fields - * *date = FAT_DATE(year, month, day); - * - * // return time using FAT_TIME macro to format fields - * *time = FAT_TIME(hour, minute, second); - * } - * \endcode - * - * Sets the function that is called when a file is created or when - * a file's directory entry is modified by sync(). All timestamps, - * access, creation, and modify, are set when a file is created. - * sync() maintains the last access date and last modify date/time. - * - * See the timestamp() function. - */ - static void dateTimeCallback( - void (*dateTime)(uint16_t* date, uint16_t* time)) { - dateTime_ = dateTime; - } - /** - * Cancel the date/time callback function. - */ - static void dateTimeCallbackCancel(void) {dateTime_ = NULL;} - uint8_t dirEntry(dir_t* dir); - - /** \return The file's size in bytes. */ - uint32_t fileSize(void) const {return fileSize_;} - static uint8_t init(SdCard* dev, uint8_t part); - /** - * Initialize a FAT16 volume. - * - * First try partition 1 then try super floppy format. - * - * \param[in] dev The SdCard where the volume is located. - * - * \return The value one, true, is returned for success and - * the value zero, false, is returned for failure. reasons for - * failure include not finding a valid FAT16 file system, a call - * to init() after a volume has been successful initialized or - * an I/O error. - * - */ - static uint8_t init(SdCard* dev) { - return init(dev, 1) ? true : init(dev, 0); - } - /** - * Checks the file's open/closed status for this instance of Fat16. - * \return The value true if a file is open otherwise false; - */ - uint8_t isOpen(void) const {return (flags_ & O_ACCMODE) != 0;} - static void ls(uint8_t flags = 0); - uint8_t open(const char* fileName, uint8_t oflag); - uint8_t open(uint16_t entry, uint8_t oflag); - static void printDirName(const dir_t& dir, uint8_t width); - static void printFatDate(uint16_t fatDate); - static void printFatTime(uint16_t fatTime); - static void printTwoDigits(uint8_t v); - int16_t read(void); - int16_t read(void* buf, uint16_t nbyte); - static uint8_t readDir(dir_t* dir, uint16_t* index, - uint8_t skip = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY)); - - uint8_t remove(void); - static uint8_t remove(const char* fileName); - /** Sets the file's current position to zero. */ - void rewind(void) {curPosition_ = curCluster_ = 0;} - /** \return The number of entries in the root directory. */ - static uint16_t rootDirEntryCount(void) {return rootDirEntryCount_;} - /** Seek to current position plus \a pos bytes. See Fat16::seekSet(). */ - uint8_t seekCur(uint32_t pos) {return seekSet(curPosition_ + pos);} - /** Seek to end of file. See Fat16::seekSet(). */ - uint8_t seekEnd(void) {return seekSet(fileSize_);} - uint8_t seekSet(uint32_t pos); - uint8_t sync(void); - uint8_t timestamp(uint8_t flag, uint16_t year, uint8_t month, uint8_t day, - uint8_t hour, uint8_t minute, uint8_t second); - uint8_t truncate(uint32_t size); - /** Fat16::writeError is set to true if an error occurs during a write(). - * Set Fat16::writeError to false before calling print() and/or write() and check - * for true after calls to write() and/or print(). - */ - bool writeError; - int16_t write(const void *buf, uint16_t nbyte); -#if ARDUINO < 100 - void write(uint8_t b); - void write(const char* str); -#else // ARDUINO < 100 - size_t write(uint8_t b); - int16_t write(const char* str); -#endif // ARDUINO < 100 - void write_P(PGM_P str); - void writeln_P(PGM_P str); -//------------------------------------------------------------------------------ -#if FAT16_DEBUG_SUPPORT - /** For debug only. Do not use in applications. */ - static cache16_t* dbgBufAdd(void) {return &cacheBuffer_;} - /** For debug only. Do not use in applications. */ - static void dbgSetDev(SdCard* dev) {rawDev_ = dev;} - /** For debug only. Do not use in applications. */ - static uint8_t* dbgCacheBlock(uint32_t blockNumber) { - return cacheRawBlock(blockNumber) ? cacheBuffer_.data : 0; } - /** For debug only. Do not use in applications. */ - static dir_t* dbgCacheDir(uint16_t index) { - return cacheDirEntry(index);} -#endif // FAT16_DEBUG_SUPPORT -//------------------------------------------------------------------------------ -#if ALLOW_DEPRECATED_FUNCTIONS -// Deprecated functions - suppress cpplint messages with NOLINT comment - public: - /** - * Deprecated - Use: - * static void Fat16::dateTimeCallback( - * void (*dateTime)(uint16_t* date, uint16_t* time)); - */ - static void dateTimeCallback( - void (*dateTime)(uint16_t& date, uint16_t& time)) { // NOLINT - oldDateTime_ = dateTime; - dateTime_ = dateTime ? oldToNew : 0; - } - /** Deprecated - Use: uint8_t Fat16::dirEntry(dir_t* dir); */ - uint8_t dirEntry(dir_t& dir) { // NOLINT - return dirEntry(&dir); - } - /** Deprecated - Use: static uint8_t Fat16::init(SdCard *dev); */ - static uint8_t init(SdCard& dev) {return init(&dev);} // NOLINT - - /** Deprecated - Use: static uint8_t Fat16::init(SdCard *dev, uint8_t part) */ - static uint8_t init(SdCard& dev, uint8_t part) { // NOLINT - return init(&dev, part); - } - /** - * Deprecated - Use: - * uint8_t Fat16::readDir(dir_t* dir, uint16_t* index, uint8_t skip); - */ - static uint8_t readDir(dir_t& dir, uint16_t& index, // NOLINT - uint8_t skip = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY)) { - return readDir(&dir, &index, skip); - } -//------------------------------------------------------------------------------ - private: - static void (*oldDateTime_)(uint16_t& date, uint16_t& time); // NOLINT - static void oldToNew(uint16_t *date, uint16_t *time) { - uint16_t d; - uint16_t t; - oldDateTime_(d, t); - *date = d; - *time = t; - } -#endif // ALLOW_DEPRECATED_FUNCTIONS -//------------------------------------------------------------------------------ - private: - // Volume info - static uint8_t volumeInitialized_; // true if volume has been initialized - static uint8_t fatCount_; // number of FATs - static uint8_t blocksPerCluster_; // must be power of 2 - static uint16_t rootDirEntryCount_; // should be 512 for FAT16 - static fat_t blocksPerFat_; // number of blocks in one FAT - static fat_t clusterCount_; // total clusters in volume - static uint32_t fatStartBlock_; // start of first FAT - static uint32_t rootDirStartBlock_; // start of root dir - static uint32_t dataStartBlock_; // start of data clusters - - // block cache - static uint8_t const CACHE_FOR_READ = 0; // cache a block for read - static uint8_t const CACHE_FOR_WRITE = 1; // cache a block and set dirty - static SdCard *rawDev_; // Device - static cache16_t cacheBuffer_; // 512 byte cache for raw blocks - static uint32_t cacheBlockNumber_; // Logical number of block in the cache - static uint8_t cacheDirty_; // cacheFlush() will write block if true - static uint32_t cacheMirrorBlock_; // mirror block for second FAT - - // callback function for date/time - static void (*dateTime_)(uint16_t* date, uint16_t* time); - - // define fields in flags_ - static uint8_t const F_OFLAG = O_ACCMODE | O_APPEND | O_SYNC; - static uint8_t const F_FILE_DIR_DIRTY = 0X80; // require sync directory entry - - uint8_t flags_; // see above for bit definitions - int16_t dirEntryIndex_; // index of directory entry for open file - fat_t firstCluster_; // first cluster of file - uint32_t fileSize_; // fileSize - fat_t curCluster_; // current cluster - uint32_t curPosition_; // current byte offset - - // private functions for cache - static uint8_t blockOfCluster(uint32_t position) { - // depends on blocks per cluster being power of two - return (position >> 9) & (blocksPerCluster_ - 1); - } - static uint16_t cacheDataOffset(uint32_t position) {return position & 0X1FF;} - static dir_t* cacheDirEntry(uint16_t index, uint8_t action = 0); - static uint8_t cacheRawBlock(uint32_t blockNumber, uint8_t action = 0); - static uint8_t cacheFlush(void); - static void cacheSetDirty(void) {cacheDirty_ |= CACHE_FOR_WRITE;} - static uint32_t dataBlockLba(fat_t cluster, uint8_t blockOfCluster) { - return dataStartBlock_ + (uint32_t)(cluster - 2) * blocksPerCluster_ - + blockOfCluster; - } - static uint8_t fatGet(fat_t cluster, fat_t* value); - static uint8_t fatPut(fat_t cluster, fat_t value); - // end of chain test - static uint8_t isEOC(fat_t cluster) {return cluster >= 0XFFF8;} - // allocate a cluster to a file - uint8_t addCluster(void); - // free a cluster chain - uint8_t freeChain(fat_t cluster); -}; -#endif // Fat16_h diff --git a/include/Robot_Control/Fat16Config.h b/include/Robot_Control/Fat16Config.h @@ -1,38 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * <http://www.gnu.org/licenses/>. - */ - /** - * \file - * Configuration file - */ -#ifndef Fat16Config_h -#define Fat16Config_h -/** - * Allow use of deprecated functions if non-zero - */ -#define ALLOW_DEPRECATED_FUNCTIONS 1 -/** - * SdCard::writeBlock will protect block zero if set non-zero - */ -#define SD_PROTECT_BLOCK_ZERO 1 -/** - * Set non-zero to allow access to Fat16 internals by cardInfo debug sketch - */ -#define FAT16_DEBUG_SUPPORT 1 -#endif // Fat16Config_h diff --git a/include/Robot_Control/Fat16mainpage.h b/include/Robot_Control/Fat16mainpage.h @@ -1,208 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * <http://www.gnu.org/licenses/>. - */ - -/** -\mainpage Arduino Fat16 Library -<CENTER>Copyright &copy; 2008 by William Greiman -</CENTER> - -\section Intro Introduction -The Arduino Fat16 Library is a minimal implementation of the FAT16 file system -on standard SD flash memory cards. Fat16 supports read, write, file -creation, deletion, and truncation. - -The Fat16 class only supports access to files in the root directory and only -supports short 8.3 names. Directory time and date fields for creation -and modification can be maintained by providing a date/time callback -function \link Fat16::dateTimeCallback() dateTimeCallback()\endlink -or calling \link Fat16::timestamp() timestamp()\endlink. - -Fat16 was designed to use the Arduino Print class which -allows files to be written with \link Print::print() print() \endlink and -\link Print::println() println()\endlink. - -\section comment Bugs and Comments - -If you wish to report bugs or have comments, send email to fat16lib@sbcglobal.net. - - -\section SDcard SD Cards - -Arduinos access SD cards using the cards SPI protocol. PCs, Macs, and -most consumer devices use the 4-bit parallel SD protocol. A card that -functions well on A PC or Mac may not work well on the Arduino. - -Most cards have good SPI read performance but cards vary widely in SPI -write performance. Write performance is limited by how efficiently the -card manages internal erase/remapping operations. The Arduino cannot -optimize writes to reduce erase operations because of its limit RAM. - -SanDisk cards generally have good write performance. They seem to have -more internal RAM buffering than other cards and therefore can limit -the number of flash erase operations that the Arduino forces due to its -limited RAM. - -Some Dane-Elec cards have a write speed that is only 20% as fast as -a good SanDisk card. - - -\section Hardware Hardware Configuration -Fat16 was developed using an <A HREF = "http://www.adafruit.com/"> Adafruit Industries</A> -<A HREF = "http://ladyada.net/make/gpsshield/modules.html"> GPS Shield</A>. - -The hardware interface to the SD card should not use a resistor based level -shifter. SdCard::init() sets the SPI bus frequency to 8 MHz which results in -signal rise times that are too slow for the edge detectors in many newer SD card -controllers when resistor voltage dividers are used. - -The 5 to 3.3 V level shifter for 5 V arduinos should be IC based like the -74HC4050N based circuit shown in the file SdLevel.png. The Adafruit Wave Shield -uses a 74AHC125N. Gravitech sells SD and MicroSD Card Adapters based on the -74LCX245. - -If you are using a resistor based level shifter and are having problems try -setting the SPI bus frequency to 4 MHz. This can be done by using -card.init(true) to initialize the SD card. - - -\section Fat16Class Fat16 Usage - -The class Fat16 is a minimal implementation of FAT16 on standard SD cards. -High Capacity SD cards, SDHC, are not supported. It should work on all -standard cards from 8MB to 2GB formatted with a FAT16 file system. - -\note - The Arduino Print class uses character -at a time writes so it was necessary to use a \link Fat16::sync() sync() \endlink -function to control when data is written to the SD card. - -\par -An application which writes to a file using \link Print::print() print()\endlink, -\link Print::println() println() \endlink -or \link Fat16::write write() \endlink must call \link Fat16::sync() sync() \endlink -at the appropriate time to force data and directory information to be written -to the SD Card. Data and directory information are also written to the SD card -when \link Fat16::close() close() \endlink is called. - -\par -Applications must use care calling \link Fat16::sync() sync() \endlink -since 2048 bytes of I/O is required to update file and -directory information. This includes writing the current data block, reading -the block that contains the directory entry for update, writing the directory -block back and reading back the current data block. - -Fat16 only supports access to files in the root directory and only supports -short 8.3 names. - -It is possible to open a file with two or more instances of Fat16. A file may -be corrupted if data is written to the file by more than one instance of Fat16. - -Short names are limited to 8 characters followed by an optional period (.) -and extension of up to 3 characters. The characters may be any combination -of letters and digits. The following special characters are also allowed: - -$ % ' - _ @ ~ ` ! ( ) { } ^ # & - -Short names are always converted to upper case and their original case -value is lost. - -Fat16 uses a slightly restricted form of short names. -Only printable ASCII characters are supported. No characters with code point -values greater than 127 are allowed. Space is not allowed even though space -was allowed in the API of early versions of DOS. - -Fat16 has been optimized for The Arduino ATmega168. Minimizing RAM use is the -highest priority goal followed by flash use and finally performance. -Most SD cards only support 512 byte block write operations so a 512 byte -cache buffer is used by Fat16. This is the main use of RAM. A small -amount of RAM is used to store key volume and file information. -Flash memory usage can be controlled by selecting options in Fat16Config.h. - -\section HowTo How to format SD Cards as FAT16 Volumes - -Microsoft operating systems support removable media formatted with a -Master Boot Record, MBR, or formatted as a super floppy with a FAT Boot Sector -in block zero. - -Microsoft operating systems expect MBR formatted removable media -to have only one partition. The first partition should be used. - -Microsoft operating systems do not support partitioning SD flash cards. -If you erase an SD card with a program like KillDisk, Most versions of -Windows will format the card as a super floppy. - -The best way to restore an SD card's MBR is to use SDFormatter -which can be downloaded from: - -http://www.sdcard.org/consumers/formatter/ - -SDFormatter does not have an option for FAT type so it may format -small cards as FAT12. - -After the MBR is restored by SDFormatter you may need to reformat small -cards that have been formatted FAT12 to force the volume type to be FAT16. - -The FAT type, FAT12, FAT16, or FAT32, is determined by the count -of clusters on the volume and nothing else. - -Microsoft published the following code for determining FAT type: - -\code -if (CountOfClusters < 4085) { - // Volume is FAT12 -} -else if (CountOfClusters < 65525) { - // Volume is FAT16 -} -else { - // Volume is FAT32 -} - -\endcode -If you format a FAT volume with an OS utility , choose a cluster size that -will result in: - -4084 < CountOfClusters && CountOfClusters < 65525 - -The volume will then be FAT16. - -If you are formatting an SD card on OS X or Linux, be sure to use the first -partition. Format this partition with a cluster count in above range. - -\section References References - -The Arduino site: - -http://www.arduino.cc/ - -For more information about FAT file systems see: - -http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx - -For information about using SD cards as SPI devices see: - -http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf - -The ATmega328 datasheet: - -http://www.atmel.com/dyn/resources/prod_documents/doc8161.pdf - - - */ - \ No newline at end of file diff --git a/include/Robot_Control/Fat16util.h b/include/Robot_Control/Fat16util.h @@ -1,74 +0,0 @@ -#ifndef Fat16util_h -#define Fat16util_h -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * <http://www.gnu.org/licenses/>. - */ -/** - * \file - * Useful utility functions. - */ -#if ARDUINO < 100 -#include <WProgram.h> -#else // ARDUINO -#include <Arduino.h> -#endif // ARDUINO -#include <avr/pgmspace.h> -/** Store and print a string in flash memory.*/ -#define PgmPrint(x) SerialPrint_P(PSTR(x)) -/** Store and print a string in flash memory followed by a CR/LF.*/ -#define PgmPrintln(x) SerialPrintln_P(PSTR(x)) -/** Defined so doxygen works for function definitions. */ -#define NOINLINE __attribute__((noinline)) -//------------------------------------------------------------------------------ -/** Return the number of bytes currently free in RAM. */ -static int FreeRam(void) { - extern int __bss_end; - extern int* __brkval; - int free_memory; - if (reinterpret_cast<int>(__brkval) == 0) { - // if no heap use from end of bss section - free_memory = reinterpret_cast<int>(&free_memory) - - reinterpret_cast<int>(&__bss_end); - } else { - // use from top of stack to heap - free_memory = reinterpret_cast<int>(&free_memory) - - reinterpret_cast<int>(__brkval); - } - return free_memory; -} -//------------------------------------------------------------------------------ -/** - * %Print a string in flash memory to the serial port. - * - * \param[in] str Pointer to string stored in flash memory. - */ -static NOINLINE void SerialPrint_P(PGM_P str) { - for (uint8_t c; (c = pgm_read_byte(str)); str++) Serial.write(c); -} -//------------------------------------------------------------------------------ -/** - * %Print a string in flash memory followed by a CR/LF. - * - * \param[in] str Pointer to string stored in flash memory. - */ -static NOINLINE void SerialPrintln_P(PGM_P str) { - SerialPrint_P(str); - Serial.println(); -} -#endif // #define Fat16util_h diff --git a/include/Robot_Control/FatStructs.h b/include/Robot_Control/FatStructs.h @@ -1,418 +0,0 @@ -/* Arduino Fat16 Library - * Copyright (C) 2009 by William Greiman - * - * This file is part of the Arduino Fat16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * <http://www.gnu.org/licenses/>. - */ -#ifndef FatStructs_h -#define FatStructs_h -/** - * \file - * FAT file structures - */ -/* - * mostly from Microsoft document fatgen103.doc - * http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx - */ -//------------------------------------------------------------------------------ -/** Value for byte 510 of boot block or MBR */ -uint8_t const BOOTSIG0 = 0X55; -/** Value for byte 511 of boot block or MBR */ -uint8_t const BOOTSIG1 = 0XAA; -//------------------------------------------------------------------------------ -/** - * \struct partitionTable - * \brief MBR partition table entry - * - * A partition table entry for a MBR formatted storage device. - * The MBR partition table has four entries. - */ -struct partitionTable { - /** - * Boot Indicator . Indicates whether the volume is the active - * partition. Legal values include: 0X00. Do not use for booting. - * 0X80 Active partition. - */ - uint8_t boot; - /** - * Head part of Cylinder-head-sector address of the first block in - * the partition. Legal values are 0-255. Only used in old PC BIOS. - */ - uint8_t beginHead; - /** - * Sector part of Cylinder-head-sector address of the first block in - * the partition. Legal values are 1-63. Only used in old PC BIOS. - */ - unsigned beginSector : 6; - /** High bits cylinder for first block in partition. */ - unsigned beginCylinderHigh : 2; - /** - * Combine beginCylinderLow with beginCylinderHigh. Legal values - * are 0-1023. Only used in old PC BIOS. - */ - uint8_t beginCylinderLow; - /** - * Partition type. See defines that begin with PART_TYPE_ for - * some Microsoft partition types. - */ - uint8_t type; - /** - * head part of cylinder-head-sector address of the last sector in the - * partition. Legal values are 0-255. Only used in old PC BIOS. - */ - uint8_t endHead; - /** - * Sector part of cylinder-head-sector address of the last sector in - * the partition. Legal values are 1-63. Only used in old PC BIOS. - */ - unsigned endSector : 6; - /** High bits of end cylinder */ - unsigned endCylinderHigh : 2; - /** - * Combine endCylinderLow with endCylinderHigh. Legal values - * are 0-1023. Only used in old PC BIOS. - */ - uint8_t endCylinderLow; - /** Logical block address of the first block in the partition. */ - uint32_t firstSector; - /** Length of the partition, in blocks. */ - uint32_t totalSectors; -}; -/** Type name for partitionTable */ -typedef struct partitionTable part_t; -//------------------------------------------------------------------------------ -/** - * \struct masterBootRecord - * - * \brief Master Boot Record - * - * The first block of a storage device that is formatted with a MBR. - */ -struct masterBootRecord { - /** Code Area for master boot program. */ - uint8_t codeArea[440]; - /** Optional WindowsNT disk signature. May contain more boot code. */ - uint32_t diskSignature; - /** Usually zero but may be more boot code. */ - uint16_t usuallyZero; - /** Partition tables. */ - part_t part[4]; - /** First MBR signature byte. Must be 0X55 */ - uint8_t mbrSig0; - /** Second MBR signature byte. Must be 0XAA */ - uint8_t mbrSig1; -}; -/** Type name for masterBootRecord */ -typedef struct masterBootRecord mbr_t; -//------------------------------------------------------------------------------ -/** - * \struct biosParmBlock - * - * \brief BIOS parameter block - * - * The BIOS parameter block describes the physical layout of a FAT volume. - */ -struct biosParmBlock { - /** - * Count of bytes per sector. This value may take on only the - * following values: 512, 1024, 2048 or 4096 - */ - uint16_t bytesPerSector; - /** - * Number of sectors per allocation unit. This value must be a - * power of 2 that is greater than 0. The legal values are - * 1, 2, 4, 8, 16, 32, 64, and 128. - */ - uint8_t sectorsPerCluster; - /** - * Number of sectors before the first FAT. - * This value must not be zero. - */ - uint16_t reservedSectorCount; - /** The count of FAT data structures on the volume. This field should - * always contain the value 2 for any FAT volume of any type. - */ - uint8_t fatCount; - /** - * For FAT12 and FAT16 volumes, this field contains the count of - * 32-byte directory entries in the root directory. For FAT32 volumes, - * this field must be set to 0. For FAT12 and FAT16 volumes, this - * value should always specify a count that when multiplied by 32 - * results in a multiple of bytesPerSector. FAT16 volumes should - * use the value 512. - */ - uint16_t rootDirEntryCount; - /** - * This field is the old 16-bit total count of sectors on the volume. - * This count includes the count of all sectors in all four regions - * of the volume. This field can be 0; if it is 0, then totalSectors32 - * must be non-zero. For FAT32 volumes, this field must be 0. For - * FAT12 and FAT16 volumes, this field contains the sector count, and - * totalSectors32 is 0 if the total sector count fits - * (is less than 0x10000). - */ - uint16_t totalSectors16; - /** - * This dates back to the old MS-DOS 1.x media determination and is - * no longer usually used for anything. 0xF8 is the standard value - * for fixed (non-removable) media. For removable media, 0xF0 is - * frequently used. Legal values are 0xF0 or 0xF8-0xFF. - */ - uint8_t mediaType; - /** - * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. - * On FAT32 volumes this field must be 0, and sectorsPerFat32 - * contains the FAT size count. - */ - uint16_t sectorsPerFat16; - /** Sectors per track for interrupt 0x13. Not used otherwise. */ - uint16_t sectorsPerTrtack; - /** Number of heads for interrupt 0x13. Not used otherwise. */ - uint16_t headCount; - /** - * Count of hidden sectors preceding the partition that contains this - * FAT volume. This field is generally only relevant for media - * visible on interrupt 0x13. - */ - uint32_t hidddenSectors; - /** - * This field is the new 32-bit total count of sectors on the volume. - * This count includes the count of all sectors in all four regions - * of the volume. This field can be 0; if it is 0, then - * totalSectors16 must be non-zero. - */ - uint32_t totalSectors32; - /** - * Count of sectors occupied by one FAT on FAT32 volumes. - */ - uint32_t sectorsPerFat32; - /** - * This field is only defined for FAT32 media and does not exist on - * FAT12 and FAT16 media. - * Bits 0-3 -- Zero-based number of active FAT. - * Only valid if mirroring is disabled. - * Bits 4-6 -- Reserved. - * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. - * -- 1 means only one FAT is active; it is the one referenced in bits 0-3. - * Bits 8-15 -- Reserved. - */ - uint16_t fat32Flags; - /** - * FAT32 version. High byte is major revision number. - * Low byte is minor revision number. Only 0.0 define. - */ - uint16_t fat32Version; - /** - * Cluster number of the first cluster of the root directory for FAT32. - * This usually 2 but not required to be 2. - */ - uint32_t fat32RootCluster; - /** - * Sector number of FSINFO structure in the reserved area of the - * FAT32 volume. Usually 1. - */ - uint16_t fat32FSInfo; - /** - * If non-zero, indicates the sector number in the reserved area - * of the volume of a copy of the boot record. Usually 6. - * No value other than 6 is recommended. - */ - uint16_t fat32BackBootBlock; - /** - * Reserved for future expansion. Code that formats FAT32 volumes - * should always set all of the bytes of this field to 0. - */ - uint8_t fat32Reserved[12]; -}; -/** Type name for biosParmBlock */ -typedef struct biosParmBlock bpb_t; -//------------------------------------------------------------------------------ -/** - * \struct fat32BootSector - * - * \brief Boot sector for a FAT16 or FAT32 volume. - * - */ -struct fat32BootSector { - /** X86 jmp to boot program */ - uint8_t jmpToBootCode[3]; - /** informational only - don't depend on it */ - char oemName[8]; - /** BIOS Parameter Block */ - bpb_t bpb; - /** for int0x13 use value 0X80 for hard drive */ - uint8_t driveNumber; - /** used by Windows NT - should be zero for FAT */ - uint8_t reserved1; - /** 0X29 if next three fields are valid */ - uint8_t bootSignature; - /** usually generated by combining date and time */ - uint32_t volumeSerialNumber; - /** should match volume label in root dir */ - char volumeLabel[11]; - /** informational only - don't depend on it */ - char fileSystemType[8]; - /** X86 boot code */ - uint8_t bootCode[420]; - /** must be 0X55 */ - uint8_t bootSectorSig0; - /** must be 0XAA */ - uint8_t bootSectorSig1; -}; -//------------------------------------------------------------------------------ -// End Of Chain values for FAT entries -/** FAT16 end of chain value used by Microsoft. */ -uint16_t const FAT16EOC = 0XFFFF; -/** Minimum value for FAT16 EOC. Use to test for EOC. */ -uint16_t const FAT16EOC_MIN = 0XFFF8; -/** FAT32 end of chain value used by Microsoft. */ -uint32_t const FAT32EOC = 0X0FFFFFFF; -/** Minimum value for FAT32 EOC. Use to test for EOC. */ -uint32_t const FAT32EOC_MIN = 0X0FFFFFF8; -/** Mask a for FAT32 entry. Entries are 28 bits. */ -uint32_t const FAT32MASK = 0X0FFFFFFF; - -/** Type name for fat32BootSector */ -typedef struct fat32BootSector fbs_t; -//------------------------------------------------------------------------------ -/** - * \struct directoryEntry - * \brief FAT short directory entry - * - * Short means short 8.3 name, not the entry size. - * - * Date Format. A FAT directory entry date stamp is a 16-bit field that is - * basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the - * format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the - * 16-bit word): - * - * Bits 9-15: Count of years from 1980, valid value range 0-127 - * inclusive (1980-2107). - * - * Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. - * - * Bits 0-4: Day of month, valid value range 1-31 inclusive. - * - * Time Format. A FAT directory entry time stamp is a 16-bit field that has - * a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the - * 16-bit word, bit 15 is the MSB of the 16-bit word). - * - * Bits 11-15: Hours, valid value range 0-23 inclusive. - * - * Bits 5-10: Minutes, valid value range 0-59 inclusive. - * - * Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). - * - * The valid time range is from Midnight 00:00:00 to 23:59:58. - */ -struct directoryEntry { - /** - * Short 8.3 name. - * The first eight bytes contain the file name with blank fill. - * The last three bytes contain the file extension with blank fill. - */ - uint8_t name[11]; - /** Entry attributes. - * - * The upper two bits of the attribute byte are reserved and should - * always be set to 0 when a file is created and never modified or - * looked at after that. See defines that begin with DIR_ATT_. - */ - uint8_t attributes; - /** - * Reserved for use by Windows NT. Set value to 0 when a file is - * created and never modify or look at it after that. - */ - uint8_t reservedNT; - /** - * The granularity of the seconds part of creationTime is 2 seconds - * so this field is a count of tenths of a second and its valid - * value range is 0-199 inclusive. (WHG note - seems to be hundredths) - */ - uint8_t creationTimeTenths; - /** Time file was created. */ - uint16_t creationTime; - /** Date file was created. */ - uint16_t creationDate; - /** - * Last access date. Note that there is no last access time, only - * a date. This is the date of last read or write. In the case of - * a write, this should be set to the same date as lastWriteDate. - */ - uint16_t lastAccessDate; - /** - * High word of this entry's first cluster number (always 0 for a - * FAT12 or FAT16 volume). - */ - uint16_t firstClusterHigh; - /** Time of last write. File creation is considered a write. */ - uint16_t lastWriteTime; - /** Date of last write. File creation is considered a write. */ - uint16_t lastWriteDate; - /** Low word of this entry's first cluster number. */ - uint16_t firstClusterLow; - /** 32-bit unsigned holding this file's size in bytes. */ - uint32_t fileSize; -}; -//------------------------------------------------------------------------------ -// Definitions for directory entries -// -/** Type name for directoryEntry */ -typedef struct directoryEntry dir_t; -/** escape for name[0] = 0XE5 */ -uint8_t const DIR_NAME_0XE5 = 0X05; -/** name[0] value for entry that is free after being "deleted" */ -uint8_t const DIR_NAME_DELETED = 0XE5; -/** name[0] value for entry that is free and no allocated entries follow */ -uint8_t const DIR_NAME_FREE = 0X00; -/** file is read-only */ -uint8_t const DIR_ATT_READ_ONLY = 0X01; -/** File should hidden in directory listings */ -uint8_t const DIR_ATT_HIDDEN = 0X02; -/** Entry is for a system file */ -uint8_t const DIR_ATT_SYSTEM = 0X04; -/** Directory entry contains the volume label */ -uint8_t const DIR_ATT_VOLUME_ID = 0X08; -/** Entry is for a directory */ -uint8_t const DIR_ATT_DIRECTORY = 0X10; -/** Old DOS archive bit for backup support */ -uint8_t const DIR_ATT_ARCHIVE = 0X20; -/** Test value for long name entry. Test is - (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ -uint8_t const DIR_ATT_LONG_NAME = 0X0F; -/** Test mask for long name entry */ -uint8_t const DIR_ATT_LONG_NAME_MASK = 0X3F; -/** defined attribute bits */ -uint8_t const DIR_ATT_DEFINED_BITS = 0X3F; -/** Directory entry is part of a long name */ -static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { - return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; -} -/** Mask for file/subdirectory tests */ -uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); -/** Directory entry is for a file */ -static inline uint8_t DIR_IS_FILE(const dir_t* dir) { - return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; -} -/** Directory entry is for a subdirectory */ -static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { - return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; -} -/** Directory entry is for a file or subdirectory */ -static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { - return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; -} -#endif // FatStructs_h diff --git a/include/Robot_Control/Multiplexer.h b/include/Robot_Control/Multiplexer.h @@ -1,24 +0,0 @@ -#ifndef Multiplexer_h -#define Multiplexer_h - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -class Multiplexer{ - public: - void begin(uint8_t* selectors, uint8_t Z, uint8_t length); - void selectPin(uint8_t num); - int getAnalogValue(); - int getAnalogValueAt(uint8_t num); - bool getDigitalValue(); - bool getDigitalValueAt(uint8_t num); - private: - uint8_t selectors[4]; - uint8_t pin_Z; - uint8_t length; -}; - -#endif diff --git a/include/Robot_Control/SdCard.h b/include/Robot_Control/SdCard.h @@ -1,192 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * <http://www.gnu.org/licenses/>. - */ -#ifndef SdCard_h -#define SdCard_h - /** - * \file - * SdCard class - */ -#include <SdInfo.h> -//------------------------------------------------------------------------------ -// Warning only SD_CHIP_SELECT_PIN, the SD card select pin, may be redefined. -// define hardware SPI pins -#if defined(__AVR_ATmega168__)\ -||defined(__AVR_ATmega168P__)\ -||defined(__AVR_ATmega328P__) -// 168 and 328 Arduinos -/** Slave Select pin */ -uint8_t const SPI_SS_PIN = 10; -/** Master Out Slave In pin */ -uint8_t const SPI_MOSI_PIN = 11; -/** Master In Slave Out pin */ -uint8_t const SPI_MISO_PIN = 12; -/** Serial Clock */ -uint8_t const SPI_SCK_PIN = 13; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega1280__)\ -|| defined(__AVR_ATmega2560__) -// pins for Arduino Mega -uint8_t const SPI_SS_PIN = 53; -uint8_t const SPI_MOSI_PIN = 51; -uint8_t const SPI_MISO_PIN = 50; -uint8_t const SPI_SCK_PIN = 52; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega644P__)\ -|| defined(__AVR_ATmega644__)\ -|| defined(__AVR_ATmega1284P__) -// pins for Sanguino -uint8_t const SPI_SS_PIN = 4; -uint8_t const SPI_MOSI_PIN = 5; -uint8_t const SPI_MISO_PIN = 6; -uint8_t const SPI_SCK_PIN = 7; -//------------------------------------------------------------------------------ -#elif defined(__AVR_ATmega32U4__) -// pins for Teensy 2.0 -uint8_t const SPI_SS_PIN = 8; -uint8_t const SPI_MOSI_PIN = 16; -uint8_t const SPI_MISO_PIN = 14; -uint8_t const SPI_SCK_PIN = 15; -//------------------------------------------------------------------------------ -#elif defined(__AVR_AT90USB646__)\ -|| defined(__AVR_AT90USB1286__) -// pins for Teensy++ 1.0 & 2.0 -uint8_t const SPI_SS_PIN = 20; -uint8_t const SPI_MOSI_PIN = 22; -uint8_t const SPI_MISO_PIN = 23; -uint8_t const SPI_SCK_PIN = 21; -//------------------------------------------------------------------------------ -#else // SPI pins -#error unknown CPU -#endif // SPI pins -//------------------------------------------------------------------------------ -/** - * SD Chip Select pin - * - * Warning if this pin is redefined the hardware SS pin will be enabled - * as an output by init(). An avr processor will not function as an SPI - * master unless SS is set to output mode. - * - * For example to set SD_CHIP_SELECT_PIN to 8 for the SparkFun microSD shield: - * uint8_t const SD_CHIP_SELECT_PIN = 8; - * - * The default chip select pin for the SD card is SS. - */ -uint8_t const SD_CHIP_SELECT_PIN = SPI_SS_PIN; -//------------------------------------------------------------------------------ -/** command timeout ms */ -uint16_t const SD_COMMAND_TIMEOUT = 300; -/** init timeout ms */ -uint16_t const SD_INIT_TIMEOUT = 2000; -/** read timeout ms */ -uint16_t const SD_READ_TIMEOUT = 300; -/** write timeout ms */ -uint16_t const SD_WRITE_TIMEOUT = 600; -//------------------------------------------------------------------------------ -// error codes -/** Card did not go into SPI mode */ -uint8_t const SD_ERROR_CMD0 = 1; -/** Card did not go ready */ -uint8_t const SD_ERROR_ACMD41 = 2; -/** Write command not accepted */ -uint8_t const SD_ERROR_CMD24 = 3; -/** Read command not accepted */ -uint8_t const SD_ERROR_CMD17 = 4; -/** timeout waiting for read data */ -uint8_t const SD_ERROR_READ_TIMEOUT = 5; -/** write error occurred */ -uint8_t const SD_ERROR_WRITE_RESPONSE = 6; -/** timeout waiting for write status */ -uint8_t const SD_ERROR_WRITE_TIMEOUT = 7; -/** attempt to write block zero */ -uint8_t const SD_ERROR_BLOCK_ZERO_WRITE = 8; -/** card returned an error to a CMD13 status check after a write */ -uint8_t const SD_ERROR_WRITE_PROGRAMMING = 9; -/** invalid SPI speed in init() call */ -uint8_t const SD_ERROR_SPI_SPEED = 10; -//------------------------------------------------------------------------------ -// SD command codes -/** SEND OPERATING CONDITIONS */ -uint8_t const ACMD41 = 0X29; -/** GO_IDLE_STATE - init card in spi mode if CS low */ -uint8_t const CMD0 = 0X00; -/** SEND_CSD - Card Specific Data */ -uint8_t const CMD9 = 0X09; -/** SEND_CID - Card IDentification */ -uint8_t const CMD10 = 0X0A; -/** SEND_STATUS - read the card status register */ -uint8_t const CMD13 = 0X0D; -/** READ_BLOCK */ -uint8_t const CMD17 = 0X11; -/** WRITE_BLOCK */ -uint8_t const CMD24 = 0X18; -/** APP_CMD - escape for application specific command */ -uint8_t const CMD55 = 0X37; -//------------------------------------------------------------------------------ -/** - * \class SdCard - * \brief Hardware access class for SD flash cards - * - * Supports raw access to a standard SD flash memory card. - * - */ -class SdCard { - public: - /** Code for a SD error. See SdCard.h for definitions. */ - uint8_t errorCode; - /** Data that may be helpful in determining the cause of an error */ - uint8_t errorData; - uint32_t cardSize(void); - /** - * Initialize an SD flash memory card with default clock rate and chip - * select pin. See SdCard::init(uint8_t sckRateID, uint8_t chipSelectPin). - */ - uint8_t init(void) { - return init(0, SD_CHIP_SELECT_PIN); - } - /** - * Initialize an SD flash memory card with the selected SPI clock rate - * and the default SD chip select pin. - * See SdCard::init(uint8_t slow, uint8_t chipSelectPin). - */ - uint8_t init(uint8_t speed) { - return init(speed, SD_CHIP_SELECT_PIN); - } - uint8_t init(uint8_t speed, uint8_t chipselectPin); - uint8_t readBlock(uint32_t block, uint8_t* dst); - /** Read the CID register which contains info about the card. - * This includes Manufacturer ID, OEM ID, product name, version, - * serial number, and manufacturing date. */ - uint8_t readCID(cid_t* cid) { - return readReg(CMD10, cid); - } - uint8_t writeBlock(uint32_t block, const uint8_t* src); - private: - uint8_t cardAcmd(uint8_t cmd, uint32_t arg); - uint8_t cardCommand(uint8_t cmd, uint32_t arg); - uint8_t chipSelectPin_; - uint8_t speed_; - void chipSelectHigh(void); - void chipSelectLow(void); - void error(uint8_t code, uint8_t data); - void error(uint8_t code); - uint8_t readReg(uint8_t cmd, void* buf); - uint8_t readTransfer(uint8_t* dst, uint16_t count); -}; -#endif // SdCard_h diff --git a/include/Robot_Control/SdInfo.h b/include/Robot_Control/SdInfo.h @@ -1,117 +0,0 @@ -/* Arduino FAT16 Library - * Copyright (C) 2008 by William Greiman - * - * This file is part of the Arduino FAT16 Library - * - * This Library is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with the Arduino Fat16 Library. If not, see - * <http://www.gnu.org/licenses/>. - */ -#ifndef SdInfo_h -#define SdInfo_h -#include <stdint.h> -// Based on the document: -// -// SD Specifications -// Part 1 -// Physical Layer -// Simplified Specification -// Version 2.00 -// September 25, 2006 -// -// www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf -// -// Card IDentification (CID) register -typedef struct CID { - // byte 0 - uint8_t mid; // Manufacturer ID - // byte 1-2 - char oid[2]; // OEM/Application ID - // byte 3-7 - char pnm[5]; // Product name - // byte 8 - unsigned prv_m : 4; // Product revision n.m - unsigned prv_n : 4; - // byte 9-12 - uint32_t psn; // Product serial number - // byte 13 - unsigned mdt_year_high : 4; // Manufacturing date - unsigned reserved : 4; - // byte 14 - unsigned mdt_month : 4; - unsigned mdt_year_low :4; - // byte 15 - unsigned always1 : 1; - unsigned crc : 7; -}cid_t; -// Card-Specific Data register -typedef struct CSD { - // byte 0 - unsigned reserved1 : 6; - unsigned csd_ver : 2; - // byte 1 - uint8_t taac; - // byte 2 - uint8_t nsac; - // byte 3 - uint8_t tran_speed; - // byte 4 - uint8_t ccc_high; - // byte 5 - unsigned read_bl_len : 4; - unsigned ccc_low : 4; - // byte 6 - unsigned c_size_high : 2; - unsigned reserved2 : 2; - unsigned dsr_imp : 1; - unsigned read_blk_misalign :1; - unsigned write_blk_misalign : 1; - unsigned read_bl_partial : 1; - // byte 7 - uint8_t c_size_mid; - // byte 8 - unsigned vdd_r_curr_max : 3; - unsigned vdd_r_curr_min : 3; - unsigned c_size_low :2; - // byte 9 - unsigned c_size_mult_high : 2; - unsigned vdd_w_cur_max : 3; - unsigned vdd_w_curr_min : 3; - // byte 10 - unsigned sector_size_high : 6; - unsigned erase_blk_en : 1; - unsigned c_size_mult_low : 1; - // byte 11 - unsigned wp_grp_size : 7; - unsigned sector_size_low : 1; - // byte 12 - unsigned write_bl_len_high : 2; - unsigned r2w_factor : 3; - unsigned reserved3 : 2; - unsigned wp_grp_enable : 1; - // byte 13 - unsigned reserved4 : 5; - unsigned write_partial : 1; - unsigned write_bl_len_low : 2; - // byte 14 - unsigned reserved5: 2; - unsigned file_format : 2; - unsigned tmp_write_protect : 1; - unsigned perm_write_protect : 1; - unsigned copy : 1; - unsigned file_format_grp : 1; - // byte 15 - unsigned always1 : 1; - unsigned crc : 7; -}csd_t; -#endif // SdInfo_h diff --git a/include/Robot_Control/Squawk.h b/include/Robot_Control/Squawk.h @@ -1,265 +0,0 @@ -// Squawk Soft-Synthesizer Library for Arduino -// -// Davey Taylor 2013 -// d.taylor@arduino.cc - -#ifndef _SQUAWK_H_ -#define _SQUAWK_H_ -#include <stddef.h> -#include <inttypes.h> -#include "Arduino.h" - -#define Melody const uint8_t PROGMEM - -class SquawkStream { - public: - virtual ~SquawkStream() = 0; - virtual uint8_t read() = 0; - virtual void seek(size_t offset) = 0; -}; -inline SquawkStream::~SquawkStream() { } - -class SquawkSynth { - -protected: - // Load and play specified melody - void play(SquawkStream *melody); - -public: - SquawkSynth() {}; - - // Initialize Squawk to generate samples at sample_rate Hz - void begin(uint16_t sample_rate); - - // Load and play specified melody - // melody needs to point to PROGMEM data - void play(const uint8_t *melody); - - // Resume currently loaded melody (or enable direct osc manipulation by sketch) - void play(); - - // Pause playback - void pause(); - - // Stop playback (unloads song) - void stop(); - - // Tune Squawk to a different frequency - default is 1.0 - void tune(float tuning); - - // Change the tempo - default is 50 - void tempo(uint16_t tempo); -}; - -extern SquawkSynth Squawk; - -// oscillator structure -typedef struct { - uint8_t vol; - uint16_t freq; - uint16_t phase; -} osc_t; - -typedef osc_t Oscillator; - -// oscillator memory -extern osc_t osc[4]; -extern uint8_t pcm; -// channel 0 is pulse wave @ 25% duty -// channel 1 is square wave -// channel 2 is triangle wave -// channel 3 is noise - -// For channel 3, freq is used as part of its LFSR and should not be changed. -// LFSR: Linear feedback shift register, a method of producing a -// pseudo-random bit sequence, used to generate nasty noise. - -#ifdef __AVR_ATmega32U4__ -// Supported configurations for ATmega32U4 -#define SQUAWK_PWM_PIN5 OCR3AL -#define SQUAWK_PWM_PIN11 OCR0A -#define SQUAWK_PWM_PIN3 OCR0B -/* -// NOT SUPPORTED YET -#define SQUAWK_PWM_PIN6 OCR4D -#define SQUAWK_PWM_PIN9 OCR4B -#define SQUAWK_PWM_PIN10 OCR4B -*/ -#endif - -#ifdef __AVR_ATmega168__ -// Supported configurations for ATmega168 -#define SQUAWK_PWM_PIN6 OCR0A -#define SQUAWK_PWM_PIN5 OCR0B -#define SQUAWK_PWM_PIN11 OCR2A -#define SQUAWK_PWM_PIN3 OCR2B -#endif - -#ifdef __AVR_ATmega328P__ -// Supported configurations for ATmega328P -#define SQUAWK_PWM_PIN6 OCR0A -#define SQUAWK_PWM_PIN5 OCR0B -#define SQUAWK_PWM_PIN11 OCR2A -#define SQUAWK_PWM_PIN3 OCR2B -#endif - -/* -// NOT SUPPORTED YET -#define SQUAWK_SPI SPDR -#define SQUAWK_RLD_PORTB PORTB -#define SQUAWK_RLD_PORTC PORTC -*/ - -extern void squawk_playroutine() asm("squawk_playroutine"); - -// SAMPLE GRINDER -// generates samples and updates oscillators -// uses 132 cycles (not counting playroutine) -// ~1/3 CPU @ 44kHz on 16MHz -#define SQUAWK_CONSTRUCT_ISR(TARGET_REGISTER) \ -uint16_t cia, cia_count; \ -intptr_t squawk_register = (intptr_t)&TARGET_REGISTER; \ -ISR(TIMER1_COMPA_vect, ISR_NAKED) { \ - asm volatile( \ - "push r2 " "\n\t" \ - "in r2, __SREG__ " "\n\t" \ - "push r18 " "\n\t" \ - "push r27 " "\n\t" \ - "push r26 " "\n\t" \ - "push r0 " "\n\t" \ - "push r1 " "\n\t" \ -\ - "lds r18, osc+2*%[mul]+%[fre] " "\n\t" \ - "lds r0, osc+2*%[mul]+%[pha] " "\n\t" \ - "add r0, r18 " "\n\t" \ - "sts osc+2*%[mul]+%[pha], r0 " "\n\t" \ - "lds r18, osc+2*%[mul]+%[fre]+1" "\n\t" \ - "lds r1, osc+2*%[mul]+%[pha]+1" "\n\t" \ - "adc r1, r18 " "\n\t" \ - "sts osc+2*%[mul]+%[pha]+1, r1 " "\n\t" \ -\ - "mov r27, r1 " "\n\t" \ - "sbrc r27, 7 " "\n\t" \ - "com r27 " "\n\t" \ - "lsl r27 " "\n\t" \ - "lds r26, osc+2*%[mul]+%[vol] " "\n\t" \ - "subi r27, 128 " "\n\t" \ - "muls r27, r26 " "\n\t" \ - "lsl r1 " "\n\t" \ - "mov r26, r1 " "\n\t" \ -\ - "lds r18, osc+0*%[mul]+%[fre] " "\n\t" \ - "lds r0, osc+0*%[mul]+%[pha] " "\n\t" \ - "add r0, r18 " "\n\t" \ - "sts osc+0*%[mul]+%[pha], r0 " "\n\t" \ - "lds r18, osc+0*%[mul]+%[fre]+1" "\n\t" \ - "lds r1, osc+0*%[mul]+%[pha]+1" "\n\t" \ - "adc r1, r18 " "\n\t" \ - "sts osc+0*%[mul]+%[pha]+1, r1 " "\n\t" \ -\ - "mov r18, r1 " "\n\t" \ - "lsl r18 " "\n\t" \ - "and r18, r1 " "\n\t" \ - "lds r27, osc+0*%[mul]+%[vol] " "\n\t" \ - "sbrc r18, 7 " "\n\t" \ - "neg r27 " "\n\t" \ - "add r26, r27 " "\n\t" \ -\ - "lds r18, osc+1*%[mul]+%[fre] " "\n\t" \ - "lds r0, osc+1*%[mul]+%[pha] " "\n\t" \ - "add r0, r18 " "\n\t" \ - "sts osc+1*%[mul]+%[pha], r0 " "\n\t" \ - "lds r18, osc+1*%[mul]+%[fre]+1" "\n\t" \ - "lds r1, osc+1*%[mul]+%[pha]+1" "\n\t" \ - "adc r1, r18 " "\n\t" \ - "sts osc+1*%[mul]+%[pha]+1, r1 " "\n\t" \ -\ - "lds r27, osc+1*%[mul]+%[vol] " "\n\t" \ - "sbrc r1, 7 " "\n\t" \ - "neg r27 " "\n\t" \ - "add r26, r27 " "\n\t" \ -\ - "ldi r27, 1 " "\n\t" \ - "lds r0, osc+3*%[mul]+%[fre] " "\n\t" \ - "lds r1, osc+3*%[mul]+%[fre]+1" "\n\t" \ - "add r0, r0 " "\n\t" \ - "adc r1, r1 " "\n\t" \ - "sbrc r1, 7 " "\n\t" \ - "eor r0, r27 " "\n\t" \ - "sbrc r1, 6 " "\n\t" \ - "eor r0, r27 " "\n\t" \ - "sts osc+3*%[mul]+%[fre], r0 " "\n\t" \ - "sts osc+3*%[mul]+%[fre]+1, r1 " "\n\t" \ -\ - "lds r27, osc+3*%[mul]+%[vol] " "\n\t" \ - "sbrc r1, 7 " "\n\t" \ - "neg r27 " "\n\t" \ - "add r26, r27 " "\n\t" \ -\ - "lds r27, pcm " "\n\t" \ - "add r26, r27 " "\n\t" \ - "sts %[reg], r26 " "\n\t" \ -\ - "lds r27, cia_count+1 " "\n\t" \ - "lds r26, cia_count " "\n\t" \ - "sbiw r26, 1 " "\n\t" \ - "breq call_playroutine " "\n\t" \ - "sts cia_count+1, r27 " "\n\t" \ - "sts cia_count, r26 " "\n\t" \ - "pop r1 " "\n\t" \ - "pop r0 " "\n\t" \ - "pop r26 " "\n\t" \ - "pop r27 " "\n\t" \ - "pop r18 " "\n\t" \ - "out __SREG__, r2 " "\n\t" \ - "pop r2 " "\n\t" \ - "reti " "\n\t" \ - "call_playroutine: " "\n\t" \ -\ - "lds r27, cia+1 " "\n\t" \ - "lds r26, cia " "\n\t" \ - "sts cia_count+1, r27 " "\n\t" \ - "sts cia_count, r26 " "\n\t" \ -\ - "sei " "\n\t" \ - "push r19 " "\n\t" \ - "push r20 " "\n\t" \ - "push r21 " "\n\t" \ - "push r22 " "\n\t" \ - "push r23 " "\n\t" \ - "push r24 " "\n\t" \ - "push r25 " "\n\t" \ - "push r30 " "\n\t" \ - "push r31 " "\n\t" \ -\ - "clr r1 " "\n\t" \ - "call squawk_playroutine " "\n\t" \ -\ - "pop r31 " "\n\t" \ - "pop r30 " "\n\t" \ - "pop r25 " "\n\t" \ - "pop r24 " "\n\t" \ - "pop r23 " "\n\t" \ - "pop r22 " "\n\t" \ - "pop r21 " "\n\t" \ - "pop r20 " "\n\t" \ - "pop r19 " "\n\t" \ -\ - "pop r1 " "\n\t" \ - "pop r0 " "\n\t" \ - "pop r26 " "\n\t" \ - "pop r27 " "\n\t" \ - "pop r18 " "\n\t" \ - "out __SREG__, r2 " "\n\t" \ - "pop r2 " "\n\t" \ - "reti " "\n\t" \ - : \ - : [reg] "M" _SFR_MEM_ADDR(TARGET_REGISTER), \ - [mul] "M" (sizeof(Oscillator)), \ - [pha] "M" (offsetof(Oscillator, phase)), \ - [fre] "M" (offsetof(Oscillator, freq)), \ - [vol] "M" (offsetof(Oscillator, vol)) \ - ); \ -} - -#endif- \ No newline at end of file diff --git a/include/Robot_Control/SquawkSD.h b/include/Robot_Control/SquawkSD.h @@ -1,17 +0,0 @@ -#ifndef _SQUAWKSD_H_ -#define _SQUAWKSD_H_ -#include <Squawk.h> -#include "Fat16.h" - -class SquawkSynthSD : public SquawkSynth { - private: - Fat16 f; - public: - inline void play() { Squawk.play(); }; - void play(Fat16 file); - //void convert(Fat16 in, Fat16 out); -}; - -extern SquawkSynthSD SquawkSD; - -#endif- \ No newline at end of file diff --git a/include/Robot_Motor/ArduinoRobotMotorBoard.h b/include/Robot_Motor/ArduinoRobotMotorBoard.h @@ -1,126 +0,0 @@ -#ifndef ArduinoRobot_h -#define ArduinoRobot_h - -#include "EasyTransfer2.h" -#include "Multiplexer.h" -#include "LineFollow.h" -//#include "IRremote.h" - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -//Command code -#define COMMAND_SWITCH_MODE 0 -#define COMMAND_RUN 10 -#define COMMAND_MOTORS_STOP 11 -#define COMMAND_ANALOG_WRITE 20 -#define COMMAND_DIGITAL_WRITE 30 -#define COMMAND_ANALOG_READ 40 -#define COMMAND_ANALOG_READ_RE 41 -#define COMMAND_DIGITAL_READ 50 -#define COMMAND_DIGITAL_READ_RE 51 -#define COMMAND_READ_IR 60 -#define COMMAND_READ_IR_RE 61 -#define COMMAND_ACTION_DONE 70 -#define COMMAND_READ_TRIM 80 -#define COMMAND_READ_TRIM_RE 81 -#define COMMAND_PAUSE_MODE 90 -#define COMMAND_LINE_FOLLOW_CONFIG 100 - - -//component codename -#define CN_LEFT_MOTOR 0 -#define CN_RIGHT_MOTOR 1 -#define CN_IR 2 - -//motor board modes -#define MODE_SIMPLE 0 -#define MODE_LINE_FOLLOW 1 -#define MODE_ADJUST_MOTOR 2 -#define MODE_IR_CONTROL 3 - -//bottom TKs, just for communication purpose -#define B_TK1 201 -#define B_TK2 202 -#define B_TK3 203 -#define B_TK4 204 - -/* -A message structure will be: -switch mode (2): - byte COMMAND_SWITCH_MODE, byte mode -run (5): - byte COMMAND_RUN, int speedL, int speedR -analogWrite (3): - byte COMMAND_ANALOG_WRITE, byte codename, byte value; -digitalWrite (3): - byte COMMAND_DIGITAL_WRITE, byte codename, byte value; -analogRead (2): - byte COMMAND_ANALOG_READ, byte codename; -analogRead _return_ (4): - byte COMMAND_ANALOG_READ_RE, byte codename, int value; -digitalRead (2): - byte COMMAND_DIGITAL_READ, byte codename; -digitalRead _return_ (4): - byte COMMAND_DIGITAL_READ_RE, byte codename, int value; -read IR (1): - byte COMMAND_READ_IR; -read IR _return_ (9): - byte COMMAND_READ_IR_RE, int valueA, int valueB, int valueC, int valueD; - - -*/ - -class RobotMotorBoard:public LineFollow{ - public: - RobotMotorBoard(); - void begin(); - - void process(); - - void parseCommand(); - - int IRread(uint8_t num); - - void setMode(uint8_t mode); - void pauseMode(bool onOff); - - void motorsWrite(int speedL, int speedR); - void motorsWritePct(int speedLpct, int speedRpct);//write motor values in percentage - void motorsStop(); - private: - float motorAdjustment;//-1.0 ~ 1.0, whether left is lowered or right is lowered - - //convert codename to actual pins - uint8_t parseCodename(uint8_t codename); - uint8_t codenameToAPin(uint8_t codename); - - void stopCurrentActions(); - //void sendCommand(byte command,byte codename,int value); - - void _analogWrite(uint8_t codename, int value); - void _digitalWrite(uint8_t codename, bool value); - void _analogRead(uint8_t codename); - void _digitalRead(uint8_t codename); - int _IRread(uint8_t num); - void _readIR(); - void _readTrim(); - - void _refreshMotorAdjustment(); - - Multiplexer IRs; - uint8_t mode; - uint8_t isPaused; - EasyTransfer2 messageIn; - EasyTransfer2 messageOut; - - //Line Following - void reportActionDone(); -}; - -extern RobotMotorBoard RobotMotor; - -#endif- \ No newline at end of file diff --git a/include/Robot_Motor/EasyTransfer2.h b/include/Robot_Motor/EasyTransfer2.h @@ -1,76 +0,0 @@ -/****************************************************************** -* EasyTransfer Arduino Library -* details and example sketch: -* http://www.billporter.info/easytransfer-arduino-library/ -* -* Brought to you by: -* Bill Porter -* www.billporter.info -* -* See Readme for other info and version history -* -* -*This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or(at your option) any later version. -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. -<http://www.gnu.org/licenses/> -* -*This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. -*To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or -*send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. -******************************************************************/ -#ifndef EasyTransfer2_h -#define EasyTransfer2_h - - -//make it a little prettier on the front end. -#define details(name) (byte*)&name,sizeof(name) - -//Not neccessary, but just in case. -#if ARDUINO > 22 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif -#include "HardwareSerial.h" -//#include <NewSoftSerial.h> -#include <math.h> -#include <stdio.h> -#include <stdint.h> -#include <avr/io.h> - -class EasyTransfer2 { -public: -void begin(HardwareSerial *theSerial); -//void begin(uint8_t *, uint8_t, NewSoftSerial *theSerial); -void sendData(); -boolean receiveData(); - -void writeByte(uint8_t dat); -void writeInt(int dat); -uint8_t readByte(); -int readInt(); - - -private: -HardwareSerial *_serial; - -void resetData(); - -uint8_t data[20]; //data storage, for both read and send -uint8_t position; -uint8_t size; //size of data in bytes. Both for read and send -//uint8_t * address; //address of struct -//uint8_t size; //size of struct -//uint8_t * rx_buffer; //address for temporary storage and parsing buffer -//uint8_t rx_buffer[20]; -uint8_t rx_array_inx; //index for RX parsing buffer -uint8_t rx_len; //RX packet length according to the packet -uint8_t calc_CS; //calculated Chacksum -}; - - - -#endif- \ No newline at end of file diff --git a/include/Robot_Motor/LineFollow.h b/include/Robot_Motor/LineFollow.h @@ -1,40 +0,0 @@ -#ifndef LINE_FOLLOW_H -#define LINE_FOLLOW_H - -#if ARDUINO >= 100 - #include "Arduino.h" -#else - #include "WProgram.h" -#endif - -class LineFollow{ - public: - LineFollow(); - - void calibIRs(); - void runLineFollow(); - void config(uint8_t KP, uint8_t KD, uint8_t robotSpeed, uint8_t intergrationTime); - - //These are all pure virtual functions, pure VF needs pure specifier "=0" - //virtual void motorsWrite(int speedL, int speedR)=0; - virtual void motorsWritePct(int speedLpct, int speedRpct)=0; - virtual void motorsStop()=0; - virtual int _IRread(uint8_t num)=0; - protected: - virtual void reportActionDone()=0; - - private: - void doCalibration(int speedPct, int time); - void ajusta_niveles(); - - uint8_t KP; - uint8_t KD; - uint8_t robotSpeed; //percentage - uint8_t intergrationTime; - - int lectura_sensor[5], last_error, acu; - int sensor_blanco[5]; - int sensor_negro[5]; -}; - -#endif- \ No newline at end of file diff --git a/include/Robot_Motor/Multiplexer.h b/include/Robot_Motor/Multiplexer.h @@ -1,24 +0,0 @@ -#ifndef Multiplexer_h -#define Multiplexer_h - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -class Multiplexer{ - public: - void begin(uint8_t* selectors, uint8_t Z, uint8_t length); - void selectPin(uint8_t num); - int getAnalogValue(); - int getAnalogValueAt(uint8_t num); - bool getDigitalValue(); - bool getDigitalValueAt(uint8_t num); - private: - uint8_t selectors[4]; - uint8_t pin_Z; - uint8_t length; -}; - -#endif diff --git a/include/SpacebrewYun/SpacebrewYun.h b/include/SpacebrewYun/SpacebrewYun.h @@ -1,139 +0,0 @@ - -#ifndef YUNSPACEBREW_H -#define YUNSPACEBREW_H - -#include "Arduino.h" -#include <Bridge.h> -#include <Console.h> -#include <Process.h> - -enum SBmsg { - CONNECTION_START = char(28), - CONNECTION_END = char(27), - CONNECTION_ERROR = char(26), - MSG_CONFIRM = char(7), - MSG_START = char(29), - MSG_DIV = char(30), - MSG_END = char(31) -}; - -struct Publisher { - char *name; - char *type; - char *lastMsg; - Publisher *next; - int confirmed; - long time; -}; - -struct Subscriber{ - char *name; - char *type; - Subscriber *next; -}; - -int const pidLength = 6; -int const sbPidsLen = 4; - -class SpacebrewYun { - - public: - - SpacebrewYun(const String&, const String&); - void addPublish(const String&, const String&); - void addSubscribe(const String&, const String&); - - void connect(String, int); - void connect() { connect(server, port); }; - void connect(String _server) { connect(String(_server), port); }; - - void monitor(); - void onMessage(); - void onConfirm(); - - boolean connected(); - - void send(const String&, const String&); - void send(const String& name, char * value) { send(name, String(value)); } - void send(const String& name, bool 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); - - typedef void (*OnBooleanMessage)(String name, boolean value); - typedef void (*OnRangeMessage)(String name, int value); - typedef void (*OnStringMessage)(String name, String value); - typedef void (*OnCustomMessage)(String name, String value, String type); - typedef void (*OnSBOpen)(); - typedef void (*OnSBClose)(); - typedef void (*OnSBError)(int code, String message); - - void onOpen(OnSBOpen function); - void onClose(OnSBClose function); - void onRangeMessage(OnRangeMessage function); - void onStringMessage(OnStringMessage function); - void onBooleanMessage(OnBooleanMessage function); - void onCustomMessage(OnCustomMessage function); - void onError(OnSBError function); - - private: - - Process brew; - String name; - String server; - String description; - boolean _started; - boolean _connected; - boolean _error_msg; - boolean _verbose; - int port; - - /**Output should be at least 5 cells**/ - static OnBooleanMessage _onBooleanMessage; - static OnRangeMessage _onRangeMessage; - static OnStringMessage _onStringMessage; - static OnCustomMessage _onCustomMessage; - static OnSBOpen _onOpen; - static OnSBClose _onClose; - static OnSBError _onError; - - Subscriber * subscribers; - Publisher * publishers; - String sub_name; - String sub_msg; - String sub_type; - - boolean read_name; - boolean read_msg; - boolean read_confirm; - static int sub_name_max; - static int sub_msg_str_max; - static int sub_msg_int_max; - static int sub_msg_bool_max; - - long connect_attempt; - int connect_attempt_inter; - - Process pids; - char pid [6]; - int sbPids [4]; - - void killPids(); - void getPids(); - - static char * createString(int len){ - char * out = ( char * ) malloc ( len + 1 ); - return out; - } - - static void emptyString(char * str, int len){ - for (int i = 0; i < len; i++) { - str[i] = '\0'; - } - } - -}; - -#endif diff --git a/include/TFT/TFT.h b/include/TFT/TFT.h @@ -1,58 +0,0 @@ -/* Copyright (c) 2013, Enrico Gueli <enrico.gueli@gmail.com> All -rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef _ARDUINO_TFT_H -#define _ARDUINO_TFT_H - -#include "Arduino.h" -#include "utility/Adafruit_GFX.h" -#include "utility/Adafruit_ST7735.h" - -/// The Arduino LCD is a ST7735-based device. -/// By default, it is mounted horizontally. -/// TFT class follows the convention of other -/// Arduino library classes by adding a begin() method -/// to be called in the setup() routine. -/// @author Enrico Gueli <enrico.gueli@gmail.com> -class TFT : public Adafruit_ST7735 { -public: - TFT(uint8_t CS, uint8_t RS, uint8_t RST); - - void begin(); -}; - -/// Esplora boards have hard-wired connections with -/// the Arduino LCD if mounted on the onboard connector. -#if ARDUINO_AVR_ESPLORA // are we building for Esplora? -extern TFT EsploraTFT; -#endif - -#endif // _ARDUINO_TFT_H diff --git a/include/TFT/utility/Adafruit_GFX.h b/include/TFT/utility/Adafruit_GFX.h @@ -1,372 +0,0 @@ -/****************************************************************** - This is the core graphics library for all our displays, providing - basic graphics primitives (points, lines, circles, etc.). It needs - to be paired with a hardware-specific library for each display - device we carry (handling the lower-level functions). - - Adafruit invests time and resources providing this open - source code, please support Adafruit and open-source hardware - by purchasing products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - Processing-like API written by Enrico Gueli for Officine Arduino. - BSD license, check license.txt for more information. - All text above must be included in any redistribution. - ******************************************************************/ - -#ifndef _ADAFRUIT_GFX_H -#define _ADAFRUIT_GFX_H - -#if ARDUINO >= 100 - #include "Arduino.h" - #include "Print.h" -#else - #include "WProgram.h" -#endif - -/* - * This library can work with or without the presence of an SD - * reading library (to load images). At the moment, only the - * Arduino SD library is supported; it is included in - * standard Arduino libraries. - * - * The presence of the SD library is detected by looking at the - * __SD_H__ preprocessor variable, defined into - * Arduino SD library to avoid double inclusion. This means - * that in order to use the image-related API of Adafruit_GFX, - * SD.h *must* be included before Adafruit_GFX. - * - * The bottom part of this include file contains the actual image - * loading code; if it was in a separate .cpp file, there were no - * way to check if the SD library was present or not. - * - * A partial solution was to include SD.h anyway, see if that works - * (i.e. it is found in the include search path) and act accordingly. - * But this solution relied on the preprocessor to issue only a - * warning when an include file is not found. Avr-gcc, used for - * Arduino 8-bit MCUs, does that, but the standard gcc-4.4, used for - * Arduino Due, issues a fatal error and stops compilation. - * - * The best solution so far is to put the code here. It works if this - * include is used only in one .cpp file in the build (this is the - * case of most Arduino sketches); if used in multiple .cpp files, - * the linker may complain about duplicate definitions. - * - */ - -#if defined(__SD_H__) // Arduino SD library - #include "PImage.h" -#else - #warning "The SD library was not found. loadImage() and image() won't be supported." -#endif - -#define swap(a, b) { int16_t t = a; a = b; b = t; } - -/* TODO -enum RectMode { - CORNER, - CORNERS, - RADIUS, - CENTER -}; -*/ - -typedef uint16_t color; - -class Adafruit_GFX : public Print { - public: - - Adafruit_GFX(int16_t w, int16_t h); // Constructor - - // This MUST be defined by the subclass - virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0; - - - - // These MAY be overridden by the subclass to provide device-specific - // optimized code. Otherwise 'generic' versions are used. - virtual void - drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, - uint16_t color), - drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), - drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), - drawRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color), - fillRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color), - fillScreen(uint16_t color), - invertDisplay(boolean i); - -// These exist only with Adafruit_GFX (no subclass overrides) - void - drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), - drawCircleHelper(int16_t x0, int16_t y0, - int16_t r, uint8_t cornername, uint16_t color), - fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), - fillCircleHelper(int16_t x0, int16_t y0, int16_t r, - uint8_t cornername, int16_t delta, uint16_t color), - - drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, - int16_t x2, int16_t y2, uint16_t color), - fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, - int16_t x2, int16_t y2, uint16_t color), - drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, - int16_t radius, uint16_t color), - fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, - int16_t radius, uint16_t color), - - drawBitmap(int16_t x, int16_t y, - const uint8_t *bitmap, int16_t w, int16_t h, - uint16_t color), - drawChar(int16_t x, int16_t y, unsigned char c, - uint16_t color, uint16_t bg, uint8_t size), - setCursor(int16_t x, int16_t y), - setTextColor(uint16_t c), - setTextColor(uint16_t c, uint16_t bg), - setTextSize(uint8_t s), - setTextWrap(boolean w), - setRotation(uint8_t r); - -#if ARDUINO >= 100 - virtual size_t write(uint8_t); -#else - virtual void write(uint8_t); -#endif - - int16_t - height(void), - width(void); - - - uint8_t getRotation(void); - - - /* - * Processing-like graphics primitives - */ - - /// transforms a color in 16-bit form given the RGB components. - /// The default implementation makes a 5-bit red, a 6-bit - /// green and a 5-bit blue (MSB to LSB). Devices that use - /// different scheme should override this. - virtual uint16_t newColor(uint8_t red, uint8_t green, uint8_t blue); - - - void - // http://processing.org/reference/background_.html - background(uint8_t red, uint8_t green, uint8_t blue), - background(color c), - - // http://processing.org/reference/fill_.html - fill(uint8_t red, uint8_t green, uint8_t blue), - fill(color c), - - // http://processing.org/reference/noFill_.html - noFill(), - - // http://processing.org/reference/stroke_.html - stroke(uint8_t red, uint8_t green, uint8_t blue), - stroke(color c), - - // http://processing.org/reference/noStroke_.html - noStroke(), - - text(const char * text, int16_t x, int16_t y), - textWrap(const char * text, int16_t x, int16_t y), - - textSize(uint8_t size), - - // similar to ellipse() in Processing, but with - // a single radius. - // http://processing.org/reference/ellipse_.html - circle(int16_t x, int16_t y, int16_t r), - point(int16_t x, int16_t y), - line(int16_t x1, int16_t y1, int16_t x2, int16_t y2), - quad(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3, int16_t x4, int16_t y4), -rect(int16_t x, int16_t y, int16_t width, int16_t height), - rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius), - triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3); - - /* TODO - void rectMode(RectMode mode); - - void pushStyle(); - void popStyle(); - */ - -#if defined(__SD_H__) // Arduino SD library - PImage loadImage(const char * fileName) { return PImage::loadImage(fileName); } - - void image(PImage & img, uint16_t x, uint16_t y); -#endif - - protected: - int16_t - WIDTH, HEIGHT; // this is the 'raw' display w/h - never changes - int16_t - _width, _height, // dependent on rotation - cursor_x, cursor_y; - uint16_t - textcolor, textbgcolor; - uint8_t - textsize, - rotation; - boolean - wrap; // If set, 'wrap' text at right edge of display - - /* - * Processing-style graphics state - */ - - color strokeColor; - bool useStroke; - color fillColor; - bool useFill; -}; - -#if defined(__SD_H__) // Arduino SD library - -#define BUFFPIXEL 20 - -void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { - int w, h, row, col; - uint8_t r, g, b; - uint32_t pos = 0; - uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) - uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer - - // Crop area to be loaded - w = img._bmpWidth; - h = img._bmpHeight; - if((x+w-1) >= width()) w = width() - x; - if((y+h-1) >= height()) h = height() - y; - - /* - // Set TFT address window to clipped image bounds - setAddrWindow(x, y, x+w-1, y+h-1); - */ - - for (row=0; row<h; row++) { // For each scanline... - // Seek to start of scan line. It might seem labor- - // intensive to be doing this on every line, but this - // method covers a lot of gritty details like cropping - // and scanline padding. Also, the seek only takes - // place if the file position actually needs to change - // (avoids a lot of cluster math in SD library). - if(img._flip) // Bitmap is stored bottom-to-top order (normal BMP) - pos = img._bmpImageoffset + (img._bmpHeight - 1 - row) * img._rowSize; - else // Bitmap is stored top-to-bottom - pos = img._bmpImageoffset + row * img._rowSize; - if(img._bmpFile.position() != pos) { // Need seek? - img._bmpFile.seek(pos); - buffidx = sizeof(sdbuffer); // Force buffer reload - } - - for (col=0; col<w; col++) { // For each pixel... - // Time to read more pixel data? - if (buffidx >= sizeof(sdbuffer)) { // Indeed - img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); - buffidx = 0; // Set index to beginning - } - - // Convert pixel from BMP to TFT format, push to display - b = sdbuffer[buffidx++]; - g = sdbuffer[buffidx++]; - r = sdbuffer[buffidx++]; - //pushColor(tft.Color565(r,g,b)); - drawPixel(x + col, y + row, newColor(r, g, b)); - - } // end pixel - } // end scanline - -} - - - - -// These read 16- and 32-bit types from the SD card file. -// BMP data is stored little-endian, Arduino is little-endian too. -// May need to reverse subscript order if porting elsewhere. - -uint16_t PImage::read16(File f) { - uint16_t result; - ((uint8_t *)&result)[0] = f.read(); // LSB - ((uint8_t *)&result)[1] = f.read(); // MSB - return result; -} - -uint32_t PImage::read32(File f) { - uint32_t result; - ((uint8_t *)&result)[0] = f.read(); // LSB - ((uint8_t *)&result)[1] = f.read(); - ((uint8_t *)&result)[2] = f.read(); - ((uint8_t *)&result)[3] = f.read(); // MSB - return result; -} - - -PImage PImage::loadImage(const char * fileName) { - File bmpFile; - int bmpWidth, bmpHeight; // W+H in pixels - uint8_t bmpDepth; // Bit depth (currently must be 24) - uint32_t bmpImageoffset; // Start of image data in file - uint32_t rowSize; // Not always = bmpWidth; may have padding - bool flip = true; // BMP is stored bottom-to-top - - - // Open requested file on SD card - if ((bmpFile = SD.open(fileName)) == NULL) { - Serial.print(F("loadImage: file not found: ")); - Serial.println(fileName); - return PImage(); // load error - } - - - - // Parse BMP header - if(read16(bmpFile) != 0x4D42) { // BMP signature - Serial.println(F("loadImage: file doesn't look like a BMP")); - return PImage(); - } - - Serial.print(F("File size: ")); Serial.println(read32(bmpFile)); - (void)read32(bmpFile); // Read & ignore creator bytes - bmpImageoffset = read32(bmpFile); // Start of image data - Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC); - // Read DIB header - Serial.print(F("Header size: ")); Serial.println(read32(bmpFile)); - bmpWidth = read32(bmpFile); - bmpHeight = read32(bmpFile); - if(read16(bmpFile) != 1) { // # planes -- must be '1' - Serial.println(F("loadImage: invalid n. of planes")); - return PImage(); - } - - bmpDepth = read16(bmpFile); // bits per pixel - Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth); - if((bmpDepth != 24) || (read32(bmpFile) != 0)) { // 0 = uncompressed { - Serial.println(F("loadImage: invalid pixel format")); - return PImage(); - } - - Serial.print(F("Image size: ")); - Serial.print(bmpWidth); - Serial.print('x'); - Serial.println(bmpHeight); - - // BMP rows are padded (if needed) to 4-byte boundary - rowSize = (bmpWidth * 3 + 3) & ~3; - - // If bmpHeight is negative, image is in top-down order. - // This is not canon but has been observed in the wild. - if(bmpHeight < 0) { - bmpHeight = -bmpHeight; - flip = false; - } - - return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip); -} - -#endif - -#endif // _ADAFRUIT_GFX_H diff --git a/include/TFT/utility/Adafruit_ST7735.h b/include/TFT/utility/Adafruit_ST7735.h @@ -1,155 +0,0 @@ -/*************************************************** - This is a library for the Adafruit 1.8" SPI display. - This library works with the Adafruit 1.8" TFT Breakout w/SD card - ----> http://www.adafruit.com/products/358 - as well as Adafruit raw 1.8" TFT display - ----> http://www.adafruit.com/products/618 - - Check out the links above for our tutorials and wiring diagrams - These displays use SPI to communicate, 4 or 5 pins are required to - interface (RST is optional) - Adafruit invests time and resources providing this open source code, - please support Adafruit and open-source hardware by purchasing - products from Adafruit! - - Written by Limor Fried/Ladyada for Adafruit Industries. - MIT license, all text above must be included in any redistribution - ****************************************************/ - -#ifndef _ADAFRUIT_ST7735H_ -#define _ADAFRUIT_ST7735H_ - -#if ARDUINO >= 100 - #include "Arduino.h" - #include "Print.h" -#else - #include "WProgram.h" -#endif -#include "Adafruit_GFX.h" -#include <SPI.h> -#include <avr/pgmspace.h> - -// some flags for initR() :( -#define INITR_GREENTAB 0x0 -#define INITR_REDTAB 0x1 -#define INITR_BLACKTAB 0x2 - -#define ST7735_TFTWIDTH 128 -#define ST7735_TFTHEIGHT 160 - -#define ST7735_NOP 0x00 -#define ST7735_SWRESET 0x01 -#define ST7735_RDDID 0x04 -#define ST7735_RDDST 0x09 - -#define ST7735_SLPIN 0x10 -#define ST7735_SLPOUT 0x11 -#define ST7735_PTLON 0x12 -#define ST7735_NORON 0x13 - -#define ST7735_INVOFF 0x20 -#define ST7735_INVON 0x21 -#define ST7735_DISPOFF 0x28 -#define ST7735_DISPON 0x29 -#define ST7735_CASET 0x2A -#define ST7735_RASET 0x2B -#define ST7735_RAMWR 0x2C -#define ST7735_RAMRD 0x2E - -#define ST7735_PTLAR 0x30 -#define ST7735_COLMOD 0x3A -#define ST7735_MADCTL 0x36 - -#define ST7735_FRMCTR1 0xB1 -#define ST7735_FRMCTR2 0xB2 -#define ST7735_FRMCTR3 0xB3 -#define ST7735_INVCTR 0xB4 -#define ST7735_DISSET5 0xB6 - -#define ST7735_PWCTR1 0xC0 -#define ST7735_PWCTR2 0xC1 -#define ST7735_PWCTR3 0xC2 -#define ST7735_PWCTR4 0xC3 -#define ST7735_PWCTR5 0xC4 -#define ST7735_VMCTR1 0xC5 - -#define ST7735_RDID1 0xDA -#define ST7735_RDID2 0xDB -#define ST7735_RDID3 0xDC -#define ST7735_RDID4 0xDD - -#define ST7735_PWCTR6 0xFC - -#define ST7735_GMCTRP1 0xE0 -#define ST7735_GMCTRN1 0xE1 - -// Color definitions -#define ST7735_BLACK 0x0000 -#define ST7735_BLUE 0x001F -#define ST7735_RED 0xF800 -#define ST7735_GREEN 0x07E0 -#define ST7735_CYAN 0x07FF -#define ST7735_MAGENTA 0xF81F -#define ST7735_YELLOW 0xFFE0 -#define ST7735_WHITE 0xFFFF - - -class Adafruit_ST7735 : public Adafruit_GFX { - - public: - - Adafruit_ST7735(uint8_t CS, uint8_t RS, uint8_t SID, uint8_t SCLK, - uint8_t RST); - Adafruit_ST7735(uint8_t CS, uint8_t RS, uint8_t RST); - - void initB(void), // for ST7735B displays - initG(void), // for ILI9163C displays - initR(uint8_t options = INITR_GREENTAB), // for ST7735R - setAddrWindow(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1), - pushColor(uint16_t color), - fillScreen(uint16_t color), - drawPixel(int16_t x, int16_t y, uint16_t color), - drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), - drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), - fillRect(int16_t x, int16_t y, int16_t w, int16_t h, - uint16_t color), - setRotation(uint8_t r), - invertDisplay(boolean i); - uint16_t Color565(uint8_t r, uint8_t g, uint8_t b) { return newColor(r, g, b);} - - /* These are not for current use, 8-bit protocol only! - uint8_t readdata(void), - readcommand8(uint8_t); - uint16_t readcommand16(uint8_t); - uint32_t readcommand32(uint8_t); - void dummyclock(void); - */ - - private: - uint8_t tabcolor; - - void spiwrite(uint8_t), - writecommand(uint8_t c), - writedata(uint8_t d), - commandList(const uint8_t *addr), - commonInit(const uint8_t *cmdList); -//uint8_t spiread(void); - - boolean hwSPI; -#ifdef SPI_HAS_TRANSACTION - SPISettings spisettings; -#endif -#if defined(ARDUINO_ARCH_SAM) || defined(__ARDUINO_ARC__) - volatile uint32_t *dataport, *clkport, *csport, *rsport; - uint32_t _cs, _rs, _rst, _sid, _sclk, - datapinmask, clkpinmask, cspinmask, rspinmask, - colstart, rowstart; // some displays need this changed - #else - volatile uint8_t *dataport, *clkport, *csport, *rsport; - uint8_t _cs, _rs, _rst, _sid, _sclk, - datapinmask, clkpinmask, cspinmask, rspinmask, - colstart, rowstart; // some displays need this changed - #endif -}; - -#endif diff --git a/include/TFT/utility/PImage.h b/include/TFT/utility/PImage.h @@ -1,65 +0,0 @@ - - -#ifndef _PIMAGE_H -#define _PIMAGE_H - -class Adafruit_GFX; - -#if defined(__SD_H__) // Arduino SD library - - -/// This class mimics Processing's PImage, but with fewer -/// capabilities. It allows an image stored in the SD card to be -/// drawn to the display. -/// @author Enrico Gueli <enrico.gueli@gmail.com> -class PImage { -public: - PImage() : - _valid(false), - _bmpWidth(0), - _bmpHeight(0) { } - - void draw(Adafruit_GFX & glcd, int16_t x, int16_t y); - - static PImage loadImage(const char * fileName); - - void close() { _bmpFile.close(); } - - bool isValid() { return _valid; } - - int width() { return _bmpWidth; } - int height() { return _bmpHeight; } - -private: - friend class Adafruit_GFX; - - File _bmpFile; - int _bmpWidth, _bmpHeight; // W+H in pixels - uint8_t _bmpDepth; // Bit depth (currently must be 24) - uint32_t _bmpImageoffset; // Start of image data in file - uint32_t _rowSize; // Not always = bmpWidth; may have padding - bool _flip; - - bool _valid; - - PImage(File & bmpFile, int bmpWidth, int bmpHeight, uint8_t bmpDepth, uint32_t bmpImageoffset, uint32_t rowSize, bool flip) : - _bmpFile(bmpFile), - _bmpWidth(bmpWidth), - _bmpHeight(bmpHeight), - _bmpDepth(bmpDepth), - _bmpImageoffset(bmpImageoffset), - _rowSize(rowSize), - _flip(flip), - _valid(true) // since Adafruit_GFX is friend, we could just let it write the variables and save some CPU cycles - { } - - static uint16_t read16(File f); - static uint32_t read32(File f); - - // TODO close the file in ~PImage and PImage(const PImage&) - -}; - -#endif - -#endif // _PIMAGE_H diff --git a/include/Temboo/Temboo.h b/include/Temboo/Temboo.h @@ -1,181 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef TEMBOO_H_ -#define TEMBOO_H_ - -#include <Arduino.h> - -#if defined (ARDUINO_AVR_YUN) || defined (ARDUINO_AVR_TRE) -/////////////////////////////////////////////////////// -// BEGIN ARDUINO YUN AND TRE SUPPORT -/////////////////////////////////////////////////////// - -#include <Process.h> - -class TembooChoreo : public Process { - - public: - void begin() {Process::begin("temboo");} - void setAccountName(const String& accountName) { addParameter("-a" + accountName);} - void setAppKeyName(const String& appKeyName) { addParameter("-u" + appKeyName);} - void setAppKey(const String& appKey) { addParameter("-p" + appKey);} - void setChoreo(const String& choreo) { addParameter("-c" + choreo);} - void setCredential(const String& credentialName) { addParameter("-e" + credentialName);} - void setSavedInputs(const String& savedInputsName) { addParameter("-e" + savedInputsName);} - void setProfile(const String& profileName) { addParameter("-e" + profileName);} - void addInput(const String& inputName, const String& inputValue) { addParameter("-i" + inputName + ":" + inputValue);} - void addOutputFilter(const String& filterName, const String& filterPath, const String& variableName) { addParameter("-o" + filterName + ":" + filterPath + ":" + variableName);} - void setSettingsFileToWrite(const String& filePath) { addParameter("-w" + filePath);} - void setSettingsFileToRead(const String& filePath) { addParameter("-r" + filePath);} - void setGatewayAddress(const String& addr) { addParameter("-s" + addr);} - void addInputExpression(const String& inputName, const String& inputValue) { addParameter("-f" + inputName + ":" + inputValue);} - void addSensorInput(const String& sensorName, long sensorValue, const String& conversion) {addParameter("-n" + sensorName + ":" + String(sensorValue) + ":" + conversion);} - void addSensorInput(const String& sensorName, long sensorValue) {addParameter("-v" + sensorName + ":" + String(sensorValue));} - void addSensorInput(const String& sensorName, long sensorValue, const String& rawLow, const String& rawHigh, const String& scaleLow, const String& scaleHigh) {addParameter("-m" + sensorName + ":" + String(sensorValue) + ":" + rawLow+ ":" + rawHigh+ ":" + scaleLow+ ":" + scaleHigh);} - void setDeviceName(const String& deviceName) {addParameter("-d" + deviceName);} - void setDeviceType(const String& deviceType) {addParameter("-t" + deviceType);} -}; - -#else //ARDUINO_AVR_YUN - -/////////////////////////////////////////////////////// -// BEGIN ARDUINO NON-YUN SUPPORT -/////////////////////////////////////////////////////// - -#include <Stream.h> -#include <Client.h> -#include <IPAddress.h> -#include "utility/ChoreoInputSet.h" -#include "utility/ChoreoOutputSet.h" -#include "utility/ChoreoPreset.h" - -#define TEMBOO_ERROR_OK (0) -#define TEMBOO_ERROR_ACCOUNT_MISSING (201) -#define TEMBOO_ERROR_CHOREO_MISSING (203) -#define TEMBOO_ERROR_APPKEY_NAME_MISSING (205) -#define TEMBOO_ERROR_APPKEY_MISSING (207) -#define TEMBOO_ERROR_HTTP_ERROR (223) -#define TEMBOO_ERROR_STREAM_TIMEOUT (225) -#define TEMBOO_CHOREO_DEFAULT_TIMEOUT_SECS (901) //15 minutes and 1 second - -class TembooChoreo : public Stream { - public: - - // Constructor. - // client - an instance of an Arduino Client, usually an EthernetClient - // or a WiFiClient. Used to communicate with Temboo. - TembooChoreo(Client& client); - - // Does nothing. Just for source compatibility with Yun code. - void begin() {}; - - // Sets the account name to use when communicating with Temboo. - // (required) - void setAccountName(const String& accountName); - void setAccountName(const char* accountName); - - // Sets the application key name to use with choreo execution requests. - // (required) - void setAppKeyName(const String& appKeyName); - void setAppKeyName(const char* appKeyName); - - // Sets the application key value to use with choreo execution requests - // (required) - void setAppKey(const String& appKey); - void setAppKey(const char* appKey); - - // sets the name of the choreo to be executed. - // (required) - void setChoreo(const String& choreoPath); - void setChoreo(const char* choreoPath); - - // sets the name of the saved inputs to use when executing the choreo - // (optional) - void setSavedInputs(const String& savedInputsName); - void setSavedInputs(const char* savedInputsName); - - void setCredential(const String& credentialName); - void setCredential(const char* credentialName); - - void setProfile(const String& profileName); - void setProfile(const char* profileName); - - // sets an input to be used when executing a choreo. - // (optional or required, depending on the choreo being executed.) - void addInput(const String& inputName, const String& inputValue); - void addInput(const char* inputName, const char* inputValue); - void addInput(const char* inputName, const String& inputValue); - void addInput(const String& inputName, const char* inputValue); - - // sets an output filter to be used to process the choreo output - // (optional) - void addOutputFilter(const char* filterName, const char* filterPath, const char* variableName); - void addOutputFilter(const String& filterName, const char* filterPath, const char* variableName); - void addOutputFilter(const char* filterName, const String& filterPath, const char* variableName); - void addOutputFilter(const String& filterName, const String& filterPath, const char* variableName); - void addOutputFilter(const char* filterName, const char* filterPath, const String& variableName); - void addOutputFilter(const String& filterName, const char* filterPath, const String& variableName); - void addOutputFilter(const char* filterName, const String& filterPath, const String& variableName); - void addOutputFilter(const String& filterName, const String& filterPath, const String& variableName); - - // run the choreo using the current input info - int run(); - // run the choreo with a user specified timeout - int run(uint16_t timeoutSecs); - - // run the choreo on the Temboo server at the given IP address and port - int run(IPAddress addr, uint16_t port); - int run(IPAddress addr, uint16_t port, uint16_t timeoutSecs); - - void close(); - - // Stream interface - see the Arduino library documentation. - int available(); - int read(); - int peek(); - void flush(); - - //Print interface - see the Arduino library documentation - size_t write(uint8_t data); - - - protected: - ChoreoInputSet m_inputs; - ChoreoOutputSet m_outputs; - ChoreoPreset m_preset; - - const char* m_accountName; - const char* m_appKeyValue; - const char* m_appKeyName; - const char* m_path; - Client& m_client; - char m_httpCodeStr[6]; - const char* m_nextChar; - enum State {START, HTTP_CODE_TAG, HTTP_CODE_VALUE, END}; - State m_nextState; - -}; - -#endif //ARDUINO_AVR_YUN - -#endif //TEMBOO_H_ diff --git a/include/Temboo/TembooCoAPEdgeDevice.h b/include/Temboo/TembooCoAPEdgeDevice.h @@ -1,307 +0,0 @@ -/* - ############################################################################### - # - # Temboo CoAP Edge Device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef TEMBOOCOAP_H_ -#define TEMBOOCOAP_H_ - - -/////////////////////////////////////////////////////// -// BEGIN ARDUINO NON-YUN SUPPORT -/////////////////////////////////////////////////////// - -#include "Arduino.h" -#include "utility/TembooTimer.h" -#include "utility/TembooTags.h" - -#include "utility/TembooCoAPIPStack.h" -#include "utility/ChoreoInputSet.h" -#include "utility/ChoreoOutputSet.h" -#include "utility/ChoreoPreset.h" -#include "utility/CoapMsg.h" -#include "utility/CoapMessageLayer.h" -#include "utility/CoapRRLayer.h" - - -#define IS_EMPTY(s) (NULL == s || '\0' == *s) -#define DEFAULT_CHOREO_TIMEOUT 900 - -class TembooCoAPChoreo; - -class TembooCoAPClient { - public: - TembooCoAPClient(TembooCoAPIPStack& ipStack, IPAddress gatewayAddress, uint16_t gatewayPort = DEFAULT_COAP_PORT); - virtual ~TembooCoAPClient(); - void begin(long seed); - - enum Result { - NO_ERROR = 0, - ERROR_REQUEST_FAILED, - ERROR_BAD_RESPONSE, - ERROR_MSG_TOKEN, - ERROR_MSG_OPTION, - ERROR_MSG_PAYLOAD, - ERROR_SENDING_MSG, - ERROR_RECEIVING_MSG, - ERROR_BUFFER_FULL, - ERROR_INVALID_MSG, - ERROR_RECEIVING_RESPONSE - }; - - enum State { - STATE_IDLE, - STATE_TRANSMIT, - STATE_WAITING_FOR_RESPONSE, - STATE_RESPONSE_STARTED, - STATE_RESPONSE_READY, - STATE_NO_RESPONSE, - STATE_SEND_REQUEST, - STATE_ERROR - }; - - Result write(uint8_t value); - Result write(uint8_t* value, uint16_t len); - void clearData() {m_dataLen = 0;} - Result loop(); - Result sendChoreoRequest(); - uint8_t* getPacketBuffer() {return m_respBuffer;} - int32_t getPacketBufferSize() {return m_respLen;} - int32_t getPacketLength() {return 1000;} - int16_t getRespHttpCode() {return m_respHttpCode;} - State getState() {return m_state;} - Result sendBlockRequest(uint16_t msgID, uint32_t blockNum); - void resetChoreo(); - int getMessageState() {return m_lastResult;} - Result requestTime(uint16_t msgID); - - protected: - static const char URI_PATH[]; - Result m_lastResult; - bool moreBlocksToSend(); - - // MAX_BLOCK_SIZE *MUST* be one of the standard CoAP block sizes - // This size should be set with consideration to any network or - // hardware limitations on UDP packet size. - // (16, 32, 64, 128, 256, 512, or 1024). - static const int MAX_BLOCK_SIZE = 64; - - // MAX_PACKET_SIZE should be at least big enough to hold: - // for outgoing requests: - // 4 header bytes - // 6 token bytes (in our case, Spec says tokens can be up to 8 bytes). - // 1 byte for the URI PATH option (I *think*) - // 4 strlen(URI_PATH) bytes for the URI PATH option value. - // 3 bytes for a block1 option - // 3 bytes for a block1 option value - // 1 bytes for a block2 option (early response size negotiation) - // 1 bytes for a block2 option value - // ? 5 bytes for a size1 or size2 option - // ? 4 bytes for a sizeX option value - // 1 byte for the FF payload marker - // MAX_BLOCK_SIZE for the payload - // - // or 24 + MAX_BLOCK_SIZE - // - // HOWEVER... we need to consider the possibility that the server may - // use more options and thus send more bytes. So we should add as much - // extra space as we can reasonably afford so as to avoid buffer overflows. - - static const size_t MAX_PACKET_SIZE = 90; - - - static const size_t MAX_DATA_SIZE = 1000; - - static const uint16_t DEFAULT_COAP_PORT = 5683; - - CoapMessageLayer m_messageLayer; - CoapRRLayer m_rrLayer; - IPAddress m_gatewayAddress; - uint16_t m_gatewayPort; - uint16_t m_messageID; - State m_state; - uint16_t m_blockSize; - Result m_lastError; - - uint16_t m_dataLen; - uint8_t m_dataBuffer[MAX_DATA_SIZE]; - uint8_t m_respBuffer[MAX_DATA_SIZE]; - - char m_token[9]; - uint8_t m_txBuffer[MAX_PACKET_SIZE]; - uint8_t m_rxBuffer[MAX_PACKET_SIZE]; - uint32_t m_rxBlockNum; - int32_t m_txIndex; - int32_t m_txByteCount; - int32_t m_respLen; - uint32_t m_txBlockNum; - int16_t m_respHttpCode; - - Result generateToken(); - uint16_t getNextMessageID(); - - Result sendBlock(uint16_t msgID, uint8_t* payload, size_t len, uint32_t blockNum, bool moreBlocks); - void adjustRequestBlockSize(CoapMsg& msg); - void cancelWait(); - - int send(CoapMsg* msg); - int sendResetMsg(CoapMsg& msg); - int sendEmptyAckMsg(CoapMsg& msg); - int sendBlock2AckMsg(CoapMsg& msg); - bool isMsgResponse(CoapMsg& msg); - void handleBlockAck(CoapMsg& msg); - void handleBlock1InResponse(CoapMsg& msg); - Result saveResponse(uint8_t* values, uint16_t len); - - friend class TembooCoAPChoreo; -}; - -class TembooCoAPChoreo : public Stream { - public: - - // Constructor. - // client - an instance of a TembooCoAPClient. - // Used to communicate with a Temboo CoAP Gateway. - TembooCoAPChoreo(TembooCoAPClient& client); - ~TembooCoAPChoreo(); - - // Does nothing. Just for source compatibility with Yun code. - void begin() {;}; - - // Sets the account name to use when communicating with Temboo. - // (required) - void setAccountName(const String& accountName); - void setAccountName(const char* accountName); - - // Sets the application key name to use with choreo execution requests. - // (required) - void setAppKeyName(const String& appKeyName); - void setAppKeyName(const char* appKeyName); - - // Sets the application key value to use with choreo execution requests - // (required) - void setAppKey(const String& appKey); - void setAppKey(const char* appKey); - - // sets the name of the choreo to be executed. - // (required) - void setChoreo(const String& choreoPath); - void setChoreo(const char* choreoPath); - - - // sets the name of the saved inputs to use when executing the choreo - // (optional) - void setSavedInputs(const String& savedInputsName); - void setSavedInputs(const char* savedInputsName); - - void setCredential(const String& credentialName); - void setCredential(const char* credentialName); - - void setProfile(const String& profileName); - void setProfile(const char* profileName); - - // sets an input to be used when executing a choreo. - // (optional or required, depending on the choreo being executed.) - void addInput(const String& inputName, const String& inputValue); - void addInput(const char* inputName, const char* inputValue); - void addInput(const char* inputName, const String& inputValue); - void addInput(const String& inputName, const char* inputValue); - - // sets an output filter to be used to process the choreo output - // (optional) - void addOutputFilter(const char* filterName, const char* filterPath, const char* variableName); - void addOutputFilter(const String& filterName, const char* filterPath, const char* variableName); - void addOutputFilter(const char* filterName, const String& filterPath, const char* variableName); - void addOutputFilter(const String& filterName, const String& filterPath, const char* variableName); - void addOutputFilter(const char* filterName, const char* filterPath, const String& variableName); - void addOutputFilter(const String& filterName, const char* filterPath, const String& variableName); - void addOutputFilter(const char* filterName, const String& filterPath, const String& variableName); - void addOutputFilter(const String& filterName, const String& filterPath, const String& variableName); - - // run the choreo using the current input info - int run(uint16_t timeoutSecs = DEFAULT_CHOREO_TIMEOUT); - - char* getResponseData() {return m_respData;} - char* getHTTPResponseCode() {return m_httpCodeStr;} - - - // Stream interface - void close() {}; - int available(); - int read(); - int peek(); - void flush(); - - //Print interface - size_t write(uint8_t data); - - enum Error { - SUCCESS = 0, - FAILURE, - TEMBOO_ERROR_ACCOUNT_MISSING = 201, - TEMBOO_ERROR_CHOREO_MISSING = 203, - TEMBOO_ERROR_APPKEY_NAME_MISSING = 205, - TEMBOO_ERROR_APPKEY_MISSING = 207, - TEMBOO_ERROR_HTTP_ERROR = 223, - TEMBOO_ERROR_TIMEOUT = 225, - TEMBOO_ERROR_MEMORY = 900, - TEMBOO_ERROR_TCPIP_CONNECT_FAIL = 901, - TEMBOO_ERROR_NO_RESPONSE = 0xFFFF - }; - - - - protected: - static const size_t MAX_RESPONSE_SIZE = 900; - - TembooCoAPClient& m_client; - const char* m_accountName; - const char* m_appKeyName; - const char* m_appKeyValue; - const char* m_path; - - ChoreoInputSet m_inputs; - ChoreoOutputSet m_outputs; - ChoreoPreset m_preset; - - char m_httpCodeStr[4]; - char* m_respData; - - uint16_t m_requestId; - static uint16_t s_nextRequestId; - - // variables for the stream interface - size_t m_availableChars; - const char* m_nextChar; - enum State {START, - HTTP_CODE_PRE, - HTTP_CODE_VALUE, - HTTP_CODE_SUF, - RESP_DATA, - END}; - State m_nextState; - - protected: - int waitForResponse(TembooTimer& timer); - uint16_t getRequestId() {return m_requestId;} -}; - - -#endif //TEMBOO_H_ diff --git a/include/Temboo/TembooMQTTEdgeDevice.h b/include/Temboo/TembooMQTTEdgeDevice.h @@ -1,238 +0,0 @@ -/* -############################################################################### -# -# Temboo MQTT edge device library -# -# Copyright (C) 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef TEMBOOMQTT_H_ -#define TEMBOOMQTT_H_ - -#include <Arduino.h> - - -/////////////////////////////////////////////////////// -// BEGIN ARDUINO NON-YUN SUPPORT -/////////////////////////////////////////////////////// - -#include "Arduino.h" -#include "utility/MQTTClient.h" -#include "utility/ArduinoTimer.h" -#include "utility/TembooTags.h" - -#include "utility/TembooMQTTIPStack.h" -#include "utility/ChoreoInputSet.h" -#include "utility/ChoreoOutputSet.h" -#include "utility/ChoreoPreset.h" - -#define IS_EMPTY(s) (NULL == s || '\0' == *s) - -#define TEMBOO_ERROR_OK (0) -#define TEMBOO_ERROR_FAILURE (1) -#define TEMBOO_ERROR_ACCOUNT_MISSING (201) -#define TEMBOO_ERROR_CHOREO_MISSING (203) -#define TEMBOO_ERROR_APPKEY_NAME_MISSING (205) -#define TEMBOO_ERROR_APPKEY_MISSING (207) -#define TEMBOO_ERROR_HTTP_ERROR (223) -#define TEMBOO_ERROR_TIMEOUT (225) -#define TEMBOO_ERROR_MEMORY (900) -#define TEMBOO_ERROR_TCPIP_CONNECT_FAIL (901) -#define TEMBOO_ERROR_MQTT_CONNECT_FAIL (902) -#define TEMBOO_ERROR_MQTT_SUBSCRIBE_FAIL (903) -#define TEMBOO_ERROR_MQTT_DISCONNECT (904) -#define TEMBOO_ERROR_DEVICE_ID_MISSING (905) -/* - * The data from the MQTT is too large to fit in the buffer. - * The MQTT read buffer read as much as it could and discarded - * the rest of the packet data. Increase MAX_MESSAGE_SIZE - * to read more data in MQTT's readbuf - */ -#define TEMBOO_ERROR_MQTT_BUFFER_OVERFLOW (906) -/* - * There was more data to be returned in the packet data than could - * fit in the return buffer. Incease MAX_RESPONSE_SIZE to read more - * of the packet response - */ -#define TEMBOO_ERROR_MQTT_DATA_TRUNCATED (907) -#define TEMBOO_ERROR_NO_RESPONSE (0xFFFF) - - - -static const int MAX_MESSAGE_SIZE = 512; -static const int MAX_RESPONSE_SIZE = 100; -static const int MAX_HANDLERS = 4; -static const int YIELD_TIME_MILLIS = 200; - -typedef MQTT::Client<TembooMQTTIPStack, ArduinoTimer, MAX_MESSAGE_SIZE, MAX_HANDLERS> BaseClient; - -class TembooMQTTClient : public BaseClient { - public: - TembooMQTTClient(TembooMQTTIPStack& ipStack, unsigned int commandTimeoutMs = 30000 ); - virtual ~TembooMQTTClient(); - - using BaseClient::connect; - int connect(const char* hostname, int port=1883); - - using BaseClient::isConnected; - bool isConnected(); - - int sendChoreoRequest(const char* request, size_t len); - int setDeviceId(char* id); - int setDeviceIdFromMac(byte (&mac)[6]); - - protected: - TembooMQTTIPStack& m_ipStack; - char* m_deviceId; - char* m_requestTopic; - char* m_ackTopic; - char* m_responseTopic; - char* m_dataTopic; - - char* strCatNew_P(const char*, const char*); - void makeTopics(); -}; - -class TembooMQTTSession; - -class TembooMQTTChoreo : public Stream { - public: - - // Constructor. - // client - an instance of a TembooMQTTClient. - // Used to communicate with a Temboo Gateway. - TembooMQTTChoreo(TembooMQTTClient& client); - ~TembooMQTTChoreo(); - - // Does nothing. Just for source compatibility with Yun code. - void begin() {}; - - // Sets the account name to use when communicating with Temboo. - // (required) - void setAccountName(const String& accountName); - void setAccountName(const char* accountName); - - // Sets the application key name to use with choreo execution requests. - // (required) - void setAppKeyName(const String& appKeyName); - void setAppKeyName(const char* appKeyName); - - // Sets the application key value to use with choreo execution requests - // (required) - void setAppKey(const String& appKey); - void setAppKey(const char* appKey); - - // sets the name of the choreo to be executed. - // (required) - void setChoreo(const String& choreoPath); - void setChoreo(const char* choreoPath); - - - // sets the name of the saved inputs to use when executing the choreo - // (optional) - void setSavedInputs(const String& savedInputsName); - void setSavedInputs(const char* savedInputsName); - - void setCredential(const String& credentialName); - void setCredential(const char* credentialName); - - void setProfile(const String& profileName); - void setProfile(const char* profileName); - - // sets an input to be used when executing a choreo. - // (optional or required, depending on the choreo being executed.) - void addInput(const String& inputName, const String& inputValue); - void addInput(const char* inputName, const char* inputValue); - void addInput(const char* inputName, const String& inputValue); - void addInput(const String& inputName, const char* inputValue); - - // sets an output filter to be used to process the choreo output - // (optional) - void addOutputFilter(const char* filterName, const char* filterPath, const char* variableName); - void addOutputFilter(const String& filterName, const char* filterPath, const char* variableName); - void addOutputFilter(const char* filterName, const String& filterPath, const char* variableName); - void addOutputFilter(const String& filterName, const String& filterPath, const char* variableName); - void addOutputFilter(const char* filterName, const char* filterPath, const String& variableName); - void addOutputFilter(const String& filterName, const char* filterPath, const String& variableName); - void addOutputFilter(const char* filterName, const String& filterPath, const String& variableName); - void addOutputFilter(const String& filterName, const String& filterPath, const String& variableName); - - // run the choreo using the current input info - int run(uint16_t timeoutSecs); - - char* getResponseData() {return m_respData;} - char* getHTTPResponseCode() {return m_httpCodeStr;} - - - // Stream interface - see the Arduino library documentation. - void close() {}; - int available(); - int read(); - int peek(); - void flush(); - - //Print interface - see the Arduino library documentation - size_t write(uint8_t data); - - - protected: - TembooMQTTClient& m_client; - const char* m_accountName; - const char* m_appKeyName; - const char* m_appKeyValue; - const char* m_path; - - ChoreoInputSet m_inputs; - ChoreoOutputSet m_outputs; - ChoreoPreset m_preset; - - char m_httpCodeStr[4]; - volatile bool m_haveHttpCode; - - uint16_t m_ackCode; - volatile bool m_haveAckCode; - - char m_respData[MAX_RESPONSE_SIZE+1]; - volatile bool m_haveData; - - uint16_t m_requestId; - static uint16_t s_nextRequestId; - - volatile uint16_t m_packetStatus; - - // variables for the stream interface - size_t m_availableChars; - const char* m_nextChar; - enum State {START, HTTP_CODE_PRE, HTTP_CODE_VALUE, HTTP_CODE_SUF, RESP_DATA, END}; - State m_nextState; - - protected: - uint16_t getRequestId() {return m_requestId;} - void setAckCode(uint16_t ackCode); - void setHTTPResponseCode(char* respCode); - void setResponseData(char* data, size_t len); - - int waitForResponse(volatile bool& var, TembooMQTTSession& session, ArduinoTimer& timer); - - friend void handleDataMessage(MQTT::MessageData& md); - friend void handleResponseMessage(MQTT::MessageData& md); - friend void handleAckMessage(MQTT::MessageData& md); - -}; - - -#endif //TEMBOO_H_ diff --git a/include/Temboo/TembooMonitoring.h b/include/Temboo/TembooMonitoring.h @@ -1,82 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2016, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef TEMBOOMESSAGING_H_ -#define TEMBOOMESSAGING_H_ - -#include <Arduino.h> -#include <Process.h> - -#include "utility/TembooWebSocketRequestHandles.h" - -class TembooMessaging : public Process { - -public: - TembooMessaging(TembooPinTable* pinTable, int pinTableSize); - void begin(); - - void setAccountName(const String& accountName); - void setAccountName(const char* accountName); - - void setAppKeyName(const String& appKeyName); - void setAppKeyName(const char* appKeyName); - - void setAppKey(const String& appKey); - void setAppKey(const char* appKey); - - void setDeviceID(const String& appKey); - void setDeviceID(const char* appKey); - - void addPinConfig(int pin, const char* type, int mode, int defaultValue); - - void initiateConnection(); - - WSMessageRequest poll(); - - static void sendData(int pin, int pinVal, bool requestResponse=false); - void sendData(int pin, float pinVal); - void updatePinValue(int pinNum, int pinVal); - int retrievePinValue(int pinNum); - void setPinsToDefaultState(); - - bool isConnected(); - -private: - const char* m_accountName; - const char* m_appKey; - const char* m_appKeyName; - const char* m_deviceID; - bool m_connectionStatus; - int m_pinTableSize; - int m_pinTableDepth; - long int m_connectionAttemptTime; - TembooPinTable* m_pinTable; - unsigned long m_lastPingTime; - - void startMessaging(); - void disconnectWSConnection(int closeCode, const char* closeReason); - void sendError(const char* errorText); - void sendPing(); - -}; - -#endif- \ No newline at end of file diff --git a/include/Temboo/TembooYunShield.h b/include/Temboo/TembooYunShield.h @@ -1,60 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef TEMBOOYUNSHIELD_H_ -#define TEMBOOYUNSHIELD_H_ - -#include <Arduino.h> - -/////////////////////////////////////////////////////// -// BEGIN ARDUINO YUN SHIELD SUPPORT -/////////////////////////////////////////////////////// - -#include <Process.h> - -class TembooYunShieldChoreo : public Process { - - public: - void begin() {Process::begin("temboo");} - void setAccountName(const String& accountName) { addParameter("-a" + accountName);} - void setAppKeyName(const String& appKeyName) { addParameter("-u" + appKeyName);} - void setAppKey(const String& appKey) { addParameter("-p" + appKey);} - void setChoreo(const String& choreo) { addParameter("-c" + choreo);} - void setCredential(const String& credentialName) { addParameter("-e" + credentialName);} - void setSavedInputs(const String& savedInputsName) { addParameter("-e" + savedInputsName);} - void setProfile(const String& profileName) { addParameter("-e" + profileName);} - void addInput(const String& inputName, const String& inputValue) { addParameter("-i" + inputName + ":" + inputValue);} - void addOutputFilter(const String& filterName, const String& filterPath, const String& variableName) { addParameter("-o" + filterName + ":" + filterPath + ":" + variableName);} - void setSettingsFileToWrite(const String& filePath) { addParameter("-w" + filePath);} - void setSettingsFileToRead(const String& filePath) { addParameter("-r" + filePath);} - void setGatewayAddress(const String& addr) { addParameter("-s" + addr);} - void addInputExpression(const String& inputName, const String& inputValue) { addParameter("-f" + inputName + ":" + inputValue);} - void addSensorInput(const String& sensorName, long sensorValue, const String& conversion) {addParameter("-n" + sensorName + ":" + String(sensorValue) + ":" + conversion);} - void addSensorInput(const String& sensorName, long sensorValue) {addParameter("-v" + sensorName + ":" + String(sensorValue));} - void addSensorInput(const String& sensorName, long sensorValue, const String& rawLow, const String& rawHigh, const String& scaleLow, const String& scaleHigh) {addParameter("-m" + sensorName + ":" + String(sensorValue) + ":" + rawLow+ ":" + rawHigh+ ":" + scaleLow+ ":" + scaleHigh);} - void setDeviceName(const String& deviceName) {addParameter("-d" + deviceName);} - void setDeviceType(const String& deviceType) {addParameter("-t" + deviceType);} -}; - - - -#endif //TEMBOOYUNSHIELD_H_ diff --git a/include/Temboo/utility/ArduinoTimer.h b/include/Temboo/utility/ArduinoTimer.h @@ -1,62 +0,0 @@ -/* - ############################################################################### - # - # Temboo MQTT edge device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef ARDUINOTIMER_H_ -#define ARDUINOTIMER_H_ - -class ArduinoTimer { - public: - ArduinoTimer() { - this->startTimeMillis = 0; - this->durationMillis = 0; - } - - ArduinoTimer(unsigned long durationMillis) { - this->countdown_ms(durationMillis); - } - - bool expired() { - return left_ms() == 0; - } - - void countdown_ms(unsigned long durationMillis) { - this->startTimeMillis = millis(); - this->durationMillis = durationMillis; - } - - void countdown(int durationSeconds) { - countdown_ms((unsigned long)durationSeconds * 1000L); - } - - unsigned long left_ms() { - unsigned long elapsedMillis = millis() - this->startTimeMillis; - return elapsedMillis < this->durationMillis ? (this->durationMillis - elapsedMillis) : 0; - } - - private: - unsigned long startTimeMillis; - unsigned long durationMillis; - -}; - - -#endif /* ARDUINOIMER_H_ */ diff --git a/include/Temboo/utility/BaseFormatter.h b/include/Temboo/utility/BaseFormatter.h @@ -1,46 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef BASEFORMATTER_H_ -#define BASEFORMATTER_H_ -#include "TembooGlobal.h" - -class BaseFormatter { - public: - BaseFormatter() {m_escapedChar = '\0';} - - protected: - const char* m_nextChar; - int m_nextState; - char m_escapedChar; - - char escape(char c); - bool isEscaping() {return m_escapedChar != '\0';} - char finishEscape(); - - char readTagChar(int nextState); - char readValueChar(int nextState); - char readStartTagChar(const char* tag, int nextState); - -}; - -#endif diff --git a/include/Temboo/utility/ChoreoInput.h b/include/Temboo/utility/ChoreoInput.h @@ -1,41 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef CHOREOINPUT_H_ -#define CHOREOINPUT_H_ -#include "TembooGlobal.h" -class ChoreoInput { - public: - ChoreoInput(ChoreoInput* prev, const char* name, const char* value); - const char* getName() const {return m_name;} - const char* getValue() const {return m_value;} - void setValue(const char* value) {m_value = value;} - ChoreoInput* getNext() const {return m_next;} - - private: - ChoreoInput* m_next; - const char* m_name; - const char* m_value; -}; - -#endif - diff --git a/include/Temboo/utility/ChoreoInputFormatter.h b/include/Temboo/utility/ChoreoInputFormatter.h @@ -1,58 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef CHOREOINPUTFORMATTER_H_ -#define CHOREOINPUTFORMATTER_H_ -#include "TembooGlobal.h" -#include "BaseFormatter.h" -#include "ChoreoInputSet.h" - -class ChoreoInputFormatter : public BaseFormatter { - - public: - ChoreoInputFormatter(const ChoreoInputSet* inputSet); - bool hasNext(); - char next(); - void reset(); - - protected: - const ChoreoInputSet* m_inputSet; - const ChoreoInput* m_currentInput; - - - enum State { - START, - INPUTS_TAG, - NAME_START, - NAME, - NAME_END, - NAME_VALUE_SEPARATOR, - VALUE_START, - VALUE, - VALUE_END, - NEXT_INPUT, - INPUTS_END, - END - }; -}; - -#endif diff --git a/include/Temboo/utility/ChoreoInputSet.h b/include/Temboo/utility/ChoreoInputSet.h @@ -1,43 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef CHOREOINPUTSET_H_ -#define CHOREOINPUTSET_H_ -#include <stddef.h> -#include "TembooGlobal.h" -#include "ChoreoInput.h" - -class ChoreoInputSet { - - public: - ChoreoInputSet(); - ~ChoreoInputSet(); - void put(const char* name, const char* value); - const char* get(const char* name) const; - bool isEmpty() const {return m_first == NULL;} - const ChoreoInput* getFirstInput() const {return m_first;} - - protected: - ChoreoInput* m_first; -}; - -#endif diff --git a/include/Temboo/utility/ChoreoOutput.h b/include/Temboo/utility/ChoreoOutput.h @@ -1,44 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef CHOREOOUTPUT_H_ -#define CHOREOOUTPUT_H_ -#include "TembooGlobal.h" - -class ChoreoOutput { - public: - ChoreoOutput(ChoreoOutput* prev, const char* name, const char* path, const char* var); - const char* getName() const {return m_name;} - const char* getPath() const {return m_path;} - const char* getVariable() const {return m_var;} - void setPath(const char* path) {m_path = path;} - void setVariable(const char* variable) {m_var = variable;} - ChoreoOutput* getNext() const {return m_next;} - - private: - ChoreoOutput* m_next; - const char* m_name; - const char* m_path; - const char* m_var; -}; - -#endif diff --git a/include/Temboo/utility/ChoreoOutputFormatter.h b/include/Temboo/utility/ChoreoOutputFormatter.h @@ -1,66 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef CHOREOOUTPUTFORMATTER_H_ -#define CHOREOOUTPUTFORMATTER_H_ -#include "TembooGlobal.h" -#include "BaseFormatter.h" -#include "ChoreoOutputSet.h" - -class ChoreoOutputFormatter : public BaseFormatter { - - public: - ChoreoOutputFormatter(const ChoreoOutputSet* outputSet); - bool hasNext(); - char next(); - void reset(); - - protected: - const ChoreoOutputSet* m_outputSet; - const ChoreoOutput* m_currentOutput; - - enum State { - START, - OUTPUTS_TAG, - OUTPUT_START, - NAME_TAG, - NAME_START, - NAME, - NAME_END, - NAME_PATH_SEPARATOR, - PATH_TAG, - PATH_START, - PATH, - PATH_END, - PATH_VAR_SEPARATOR, - VAR_TAG, - VAR_START, - VAR, - VAR_END, - OUTPUT_END, - NEXT_OUTPUT, - OUTPUTS_END, - END - }; -}; - -#endif diff --git a/include/Temboo/utility/ChoreoOutputSet.h b/include/Temboo/utility/ChoreoOutputSet.h @@ -1,43 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef CHOREOOUTPUTSET_H_ -#define CHOREOOUTPUTSET_H_ -#include <stddef.h> -#include "TembooGlobal.h" -#include "ChoreoOutput.h" - -class ChoreoOutputSet { - - public: - ChoreoOutputSet(); - ~ChoreoOutputSet(); - void put(const char* name, const char* path, const char* variable); - const ChoreoOutput* get(const char* name) const; - bool isEmpty() const {return m_first == NULL;} - const ChoreoOutput* getFirstOutput() const {return m_first;} - - protected: - ChoreoOutput* m_first; -}; - -#endif diff --git a/include/Temboo/utility/ChoreoPreset.h b/include/Temboo/utility/ChoreoPreset.h @@ -1,40 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef CHOREOPRESET_H_ -#define CHOREOPRESET_H_ -#include <stddef.h> -#include "TembooGlobal.h" - -class ChoreoPreset { - public: - ChoreoPreset() {m_name = NULL;} - ChoreoPreset(const char* name) {put(name);} - const char* getName() const {return m_name;} - void put(const char* name) {m_name = name;} - bool isEmpty() const {return m_name == NULL || *m_name == '\0';} - - private: - const char* m_name; -}; - -#endif diff --git a/include/Temboo/utility/ChoreoPresetFormatter.h b/include/Temboo/utility/ChoreoPresetFormatter.h @@ -1,50 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef CHOREOPROFILEFORMATTER_H_ -#define CHOREOPROFILEFORMATTER_H_ -#include "TembooGlobal.h" -#include "BaseFormatter.h" -#include "ChoreoPreset.h" - -class ChoreoPresetFormatter : public BaseFormatter { - - public: - ChoreoPresetFormatter(const ChoreoPreset* preset); - bool hasNext(); - char next(); - void reset(); - - protected: - const ChoreoPreset* m_preset; - - enum State { - START, - PRESET_TAG, - NAME_START, - NAME, - NAME_END, - END - }; -}; - -#endif diff --git a/include/Temboo/utility/CoapMessageLayer.h b/include/Temboo/utility/CoapMessageLayer.h @@ -1,128 +0,0 @@ -/* - ############################################################################### - # - # Temboo CoAP Edge Device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef COAPMESSAGELAYER_H_ -#define COAPMESSAGELAYER_H_ - -#include "TembooCoAPIPStack.h" -#include "TembooTimer.h" -#include "CoapMsg.h" - -/** - * CoapMessageLayer is the lowest layer of the CoAP stack. It is responsible for - * transmitting and receiving messages. Specifically, this implementation is - * responsible for handling confirmable (CON) messages and their ACKs. - * It is intended to implement the Message Layer FSM described by Kovatsch et al. in - * https://tools.ietf.org/html/draft-kovatsch-lwig-coap-01 - * - * It can send reliable (confirmable or CON) messages and will maintain the necessary - * state information to wait for an acknowledgement. It will handle any necessary - * retransmissions and timeouts until a CON message has been ACK'd (or rejected.) - * - * It can not send unreliable (non-confirmable or NON) messages as currently designed - * because our application does not use NON messages. - * - * It can receive CON and NON messages and will send ACKs or RESETs as required. - * - * Any non-rejected CON or NON messages received are passed up to the Request/Response - * layer (CoapRRLayer) for processing. - * - * Be sure to note the difference between ACK's and Responses. This layer handles - * ACK's, it does not handle Responses. (Responses are handled by the CoapRRLayer class.) - */ - - -class CoapMessageLayer { - public: - - enum State { - STATE_CLOSED, - STATE_RELIABLE_TX, - STATE_ACK_PENDING, - STATE_WAITING_FOR_CON - }; - - enum Result { - NO_ERROR = 0, - CON_RECEIVED, - NON_RECEIVED, - ACK_RECEIVED, - RESET_RECEIVED, - ERROR_IMPROPER_STATE, - ERROR_NULL_MESSAGE, - ERROR_SENDING_PACKET, - ERROR_RECEIVING_PACKET, - ERROR_RETRANSMIT_COUNT_EXCEEDED, - ERROR_TX_SPAN_TIME_EXCEEDED - }; - - static const uint32_t ACK_TIMEOUT = 2000; - - // MAX_ACK_TIMEOUT = ACK_TIMEOUT * ACK_RANDOM_FACTOR - // RFC7252 suggests ACK_RANDOM_FACTOR = 1.5 - static const uint32_t MAX_ACK_TIMEOUT = 3000; - static const uint8_t MAX_RETRANSMIT = 4; - - // MAX_TRANSMIT_SPAN = ACK_TIMEOUT * ((2^MAX_RETRANSMIT) - 1) * ACK_RANDOM_FACTOR - static const uint32_t MAX_TRANSMIT_SPAN = 45000; - - // MAX_TRANSMIT_WAIT = ACK_TIMEOUT * (2^(MAX_RETRANSMIT + 1) - 1) * ACK_RANDOM_FACTOR - static const uint32_t MAX_TRANSMIT_WAIT = 93000; - - - CoapMessageLayer(uint8_t* rxBuffer, uint16_t rxLen, TembooCoAPIPStack& ipStack); - Result reliableSend(CoapMsg& msg, IPAddress destAddr, uint16_t destPort); - Result cancelReliableSend(); - Result acceptMsg(CoapMsg& msg); - Result acceptMsg(CoapMsg& msg, IPAddress addr, uint16_t port); - Result rejectMsg(CoapMsg& msg); - Result rejectMsg(CoapMsg& msg, IPAddress addr, uint16_t port); - Result loop(); - Result getLastResult() {return m_lastResult;} - uint16_t getRXByteCount() {return m_rxByteCount;} - void setState(State state) {m_state = state;} - - - private: - uint8_t* m_rxBuffer; - uint16_t m_rxLen; - TembooCoAPIPStack& m_ipStack; - - State m_state; - State m_prevState; - int m_retransmitCount; - Result m_lastResult; - IPAddress m_destAddr; - uint16_t m_destPort; - - uint16_t m_msgID; - uint8_t* m_msgBytes; - uint16_t m_msgLen; - int32_t m_rxByteCount; - TembooTimer m_txSpanTimer; - TembooTimer m_retransmitTimer; - uint32_t m_retransmitTimeoutMillis; - - -}; - -#endif diff --git a/include/Temboo/utility/CoapMsg.h b/include/Temboo/utility/CoapMsg.h @@ -1,192 +0,0 @@ -/* - ############################################################################### - # - # Temboo CoAP Edge Device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef COAPMSG_H_ -#define COAPMSG_H_ - -/* - Byte 0 Byte 1 Byte 2 Byte 3 - MSB LSB MSB LSB MSB LSB MSB LSB - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ - |Ver| T | TKL | | Code | | MsgID MSB | | MsgID LSB | - +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ - | Token (if any, TKL bytes) ... - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Options (if any) ... - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - |1 1 1 1 1 1 1 1| Payload (if any) ... - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - -#define RESPONSE_CODE(class, detail) ((class << 5) + detail) - -class CoapMsg { - - public: - enum Type { - COAP_CONFIRMABLE = 0, - COAP_NON_CONFIRMABLE = 1, - COAP_ACK = 2, - COAP_RESET = 3 - }; - - enum Code { - //REQUEST CODES - COAP_EMPTY = 0, - COAP_GET = 1, - COAP_POST = 2, - COAP_PUT = 3, - COAP_DELETE = 4, - - //RESPONSE CODES - COAP_CREATED = RESPONSE_CODE(2,1), - COAP_DELETED = RESPONSE_CODE(2,2), - COAP_VALID = RESPONSE_CODE(2,3), - COAP_CHANGED = RESPONSE_CODE(2,4), - COAP_CONTENT = RESPONSE_CODE(2,5), - COAP_CONTINUE = RESPONSE_CODE(2,31), - COAP_BAD_REQUEST = RESPONSE_CODE(4,0), - COAP_UNAUTHORIZED = RESPONSE_CODE(4,1), - COAP_BAD_OPTION = RESPONSE_CODE(4,2), - COAP_FORBIDDEN = RESPONSE_CODE(4,3), - COAP_NOT_FOUND = RESPONSE_CODE(4,4), - COAP_METHOD_NOT_ALLOWED = RESPONSE_CODE(4,5), - COAP_NOT_ACCEPTABLE = RESPONSE_CODE(4,6), - COAP_REQUEST_ENTITY_INCOMPLETE = RESPONSE_CODE(4,8), - COAP_PRECONDITION_FAILED = RESPONSE_CODE(4,12), - COAP_REQUEST_ENTITY_TOO_LARGE = RESPONSE_CODE(4,13), - COAP_UNSUPPORTED_CONTENT_FORMAT = RESPONSE_CODE(4,15), - COAP_INTERNAL_SERVER_ERROR = RESPONSE_CODE(5,0), - COAP_NOT_IMPLEMENTED = RESPONSE_CODE(5,1), - COAP_BAD_GATEWAY = RESPONSE_CODE(5,2), - COAP_SERVICE_UNAVAILABLE = RESPONSE_CODE(5,3), - COAP_GATEWAY_TIMEOUT = RESPONSE_CODE(5,4), - COAP_PROXYING_NOT_SUPPORTED = RESPONSE_CODE(5,5) - }; - - enum Option { - COAP_OPTION_IF_MATCH = 1, - COAP_OPTION_URI_HOST = 3, - COAP_OPTION_ETAG = 4, - COAP_OPTION_IF_NONE_MATCH = 5, - //TODO: COAP_OPTION_OBSERVE = 6, - COAP_OPTION_URI_PORT = 7, - COAP_OPTION_LOCATION_PATH = 8, - COAP_OPTION_URI_PATH = 11, - COAP_OPTION_CONTENT_FORMAT = 12, - COAP_OPTION_MAX_AGE = 14, - COAP_OPTION_URI_QUERY = 15, - COAP_OPTION_ACCEPT = 17, - COAP_OPTION_LOCATION_QUERY = 20, - COAP_OPTION_BLOCK2 = 23, - COAP_OPTION_BLOCK1 = 27, - COAP_OPTION_SIZE2 = 28, - COAP_OPTION_PROXY_URI = 35, - COAP_OPTION_PROXY_SCHEME = 39, - COAP_OPTION_SIZE1 = 60 - }; - - enum Result { - COAP_RESULT_SUCCESS = 0, // No error. - COAP_RESULT_TOKEN_NULL, // Token length > 0 but NULL pointer given for token value. - COAP_RESULT_TOKEN_LENGTH, // Illegal token length value (> 8). - COAP_RESULT_PAYLOAD_NULL, // Payload length > 0 but NULL pointer given for payload value. - COAP_RESULT_OPTION_UNKNOWN, // An unknown option code was specified. - COAP_RESULT_OPTION_NULL, // Option length > 0 but NULL pointer given for option value. - COAP_RESULT_OPTION_LENGTH, // Illegal length for option specified. - COAP_RESULT_OPTION_NOT_FOUND,// The requested option was not found in the message. - COAP_RESULT_BUFFER_OVERRUN, // Adding data would overrun the packet buffer - COAP_RESULT_BUILD_ORDER, // Message build order incorrect. - COAP_RESULT_INVALID_MSG, // Received message is malformed or invalid. - COAP_RESULT_FAILURE // Operation failed or unspecified error - }; - - CoapMsg(uint8_t* buffer, uint16_t bufferLen); - CoapMsg(uint8_t* buffer, uint16_t bufferLen, uint16_t packetLen); - - void setType(CoapMsg::Type msgType); - CoapMsg::Type getType(); - - void setId(uint16_t msgId); - uint16_t getId(); - - void setCode(CoapMsg::Code code); - CoapMsg::Code getCode(); - uint16_t getHTTPStatus(); - - CoapMsg::Result setToken(const uint8_t* token, uint8_t tokenLen); - uint8_t* getToken(); - uint8_t getTokenLen(); - - CoapMsg::Result addOption(CoapMsg::Option optionCode, const uint8_t* optionValue, uint16_t optionLen); - CoapMsg::Result getOption(CoapMsg::Option optionCode, uint16_t index, uint8_t*& optionValue, uint16_t& optionLen); - uint16_t getOptionCount(CoapMsg::Option optionCode); - uint16_t getOptionLen(CoapMsg::Option optionCode, uint16_t index); - uint8_t* getOptionValue(CoapMsg::Option optionCode, uint16_t index); - - CoapMsg::Result setPayload(const uint8_t* payload, uint16_t payloadLen); - uint8_t* getPayload(); - uint16_t getPayloadLen(); - - uint8_t* getMsgBytes(); - uint16_t getMsgLen(); - - bool isValid(); - - uint16_t getBlock1Size(); - uint32_t getBlock1Num(); - bool getBlock1More(); - - uint16_t getBlock2Size(); - uint32_t getBlock2Num(); - bool getBlock2More(); - - void convertToReset(); - void convertToEmptyAck(); - - protected: - uint8_t* m_buffer; - uint16_t m_bufferLen; - uint16_t m_msgLen; - - enum BuildState { - BUILD_BEGIN, - BUILD_HAVE_TOKEN, - BUILD_HAVE_OPTIONS, - BUILD_HAVE_PAYLOAD - }; - CoapMsg::BuildState m_buildState; - uint16_t m_lastOptionCode; - - protected: - CoapMsg::Result validateOption(CoapMsg::Option optionCode, const uint8_t* optionValue, uint16_t optionLen); - CoapMsg::Result validateOptionValue(uint16_t minLen, uint16_t maxLen, const uint8_t* optionValue, uint16_t optionLen); - uint8_t* decodeOption(uint8_t* buffer, uint16_t* optionDelta, uint16_t* optionLen); - uint16_t getBlockSize(CoapMsg::Option optionCode); - uint32_t getBlockNum(CoapMsg::Option optionCode); - bool getBlockMore(CoapMsg::Option optionCode); -}; - - -#endif //TEMBOOCOAP_H_ diff --git a/include/Temboo/utility/CoapRRLayer.h b/include/Temboo/utility/CoapRRLayer.h @@ -1,82 +0,0 @@ -/* - ############################################################################### - # - # Temboo CoAP Edge Device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef COAPRRLAYER_H_ -#define COAPRRLAYER_H_ - -#include "CoapMessageLayer.h" -#include "CoapMsg.h" - -/** - * CoapRRLayer (Request/Response layer) is a middle layer of the CoAP stack. It is responsible for - * sending requests and receiving responses to those requests. Note that it does not handle - * ACKs or RESETs. Those are handled at the CoapMessageLayer. - * - * This class is intended to implement the CoAP Client Request/Response Layer FSM as described - * by Kovatsch et al. in https://tools.ietf.org/html/draft-kovatsch-lwig-coap-01 - * - * Note that this design only implements the client functionality as our application does not - * serve anything. - */ - -class CoapRRLayer { - - public: - enum Result { - NO_ERROR = 0, - RESPONSE_RECEIVED, - ACK_RECEIVED, - CON_RECEIVED, - ERROR_IMPROPER_STATE, - ERROR_SENDING_MSG, - ERROR_RECEIVING_RESPONSE, - RST_RECEIVED - }; - - enum State { - STATE_IDLE, - STATE_WAITING - }; - - CoapRRLayer(CoapMessageLayer& messageLayer, uint8_t* rxBuffer, uint16_t rxBufferLen); - - Result reliableSend(CoapMsg& msg, char* token, IPAddress addr, uint16_t port); - Result send(CoapMsg& msg, char* token, IPAddress addr, uint16_t port); - Result loop(); - Result getLastResult() {return m_lastResult;} - void setState(State state) {m_state = state;} - int16_t getRxByteCount() {return m_rxByteCount;} - - protected: - - CoapMessageLayer& m_messageLayer; - State m_state; - Result m_lastResult; - char* m_token; - uint8_t* m_rxBuffer; - int16_t m_rxByteCount; - uint16_t m_rxBufferLen; - - bool rxTokenMatches(CoapMsg& msg); -}; - -#endif diff --git a/include/Temboo/utility/DataFormatter.h b/include/Temboo/utility/DataFormatter.h @@ -1,63 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef DATAFORMATTER_H_ -#define DATAFORMATTER_H_ -#include "TembooGlobal.h" -#include "ChoreoInputSet.h" -#include "ChoreoOutputSet.h" -#include "ChoreoPreset.h" -#include "ChoreoInputFormatter.h" -#include "ChoreoOutputFormatter.h" -#include "ChoreoPresetFormatter.h" - - -class DataFormatter { - - public: - DataFormatter(const ChoreoInputSet* inputSet, const ChoreoOutputSet* outputSet, const ChoreoPreset* preset); - bool hasNext(); - char next(); - void reset(); - - private: - const ChoreoInputSet* m_inputSet; - const ChoreoOutputSet* m_outputSet; - const ChoreoPreset* m_preset; - - ChoreoInputFormatter m_inputFormatter; - ChoreoOutputFormatter m_outputFormatter; - ChoreoPresetFormatter m_presetFormatter; - - enum State { - DATA_START, - FORMATTING_INPUTS, - FORMATTING_OUTPUTS, - FORMATTING_PRESET, - FORMATTING_EMPTY, - DATA_END - }; - - State m_nextState; - -}; -#endif diff --git a/include/Temboo/utility/FP.h b/include/Temboo/utility/FP.h @@ -1,208 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2014 - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Sam Grove - initial API and implementation and/or initial documentation - * Ian Craggs - added attached and detached member functions - * Sam Grove - removed need for FP.cpp - *******************************************************************************/ - -#ifndef FP_H -#define FP_H - -/** Example using the FP Class with global functions - * @code - * #include "mbed.h" - * #include "FP.h" - * - * FP<void,bool>fp; - * DigitalOut myled(LED1); - * - * void handler(bool value) - * { - * myled = value; - * return; - * } - * - * int main() - * { - * fp.attach(&handler); - * - * while(1) - * { - * fp(1); - * wait(0.2); - * fp(0); - * wait(0.2); - * } - * } - * @endcode - */ - -/** Example using the FP Class with different class member functions - * @code - * #include "mbed.h" - * #include "FP.h" - * - * FP<void,bool>fp; - * DigitalOut myled(LED4); - * - * class Wrapper - * { - * public: - * Wrapper(){} - * - * void handler(bool value) - * { - * myled = value; - * return; - * } - * }; - * - * int main() - * { - * Wrapper wrapped; - * fp.attach(&wrapped, &Wrapper::handler); - * - * while(1) - * { - * fp(1); - * wait(0.2); - * fp(0); - * wait(0.2); - * } - * } - * @endcode - */ - -/** Example using the FP Class with member FP and member function -* @code -* #include "mbed.h" -* #include "FP.h" -* -* DigitalOut myled(LED2); -* -* class Wrapper -* { -* public: -* Wrapper() -* { -* fp.attach(this, &Wrapper::handler); -* } -* -* void handler(bool value) -* { -* myled = value; -* return; -* } -* -* FP<void,bool>fp; -* }; -* -* int main() -* { -* Wrapper wrapped; -* -* while(1) -* { -* wrapped.fp(1); -* wait(0.2); -* wrapped.fp(0); -* wait(0.2); -* } -* } -* @endcode -*/ - -/** - * @class FP - * @brief API for managing Function Pointers - */ -template<class retT, class argT> -class FP -{ -public: - /** Create the FP object - only one callback can be attached to the object, that is - * a member function or a global function, not both at the same time - */ - FP() - { - obj_callback = 0; - c_callback = 0; - } - - /** Add a callback function to the object - * @param item - Address of the initialized object - * @param member - Address of the member function (dont forget the scope that the function is defined in) - */ - template<class T> - void attach(T *item, retT (T::*method)(argT)) - { - obj_callback = (FPtrDummy *)(item); - method_callback = (retT (FPtrDummy::*)(argT))(method); - return; - } - - /** Add a callback function to the object - * @param function - The address of a globally defined function - */ - void attach(retT (*function)(argT)) - { - c_callback = function; - } - - /** Invoke the function attached to the class - * @param arg - An argument that is passed into the function handler that is called - * @return The return from the function hanlder called by this class - */ - retT operator()(argT arg) const - { - if( 0 != c_callback ) { - return obj_callback ? (obj_callback->*method_callback)(arg) : (*c_callback)(arg); - } - return (retT)0; - } - - /** Determine if an callback is currently hooked - * @return 1 if a method is hooked, 0 otherwise - */ - bool attached() - { - return obj_callback || c_callback; - } - - /** Release a function from the callback hook - */ - void detach() - { - obj_callback = 0; - c_callback = 0; - } - -private: - - // empty type used for casting - class FPtrDummy; - - FPtrDummy *obj_callback; - - /** - * @union Funciton - * @brief Member or global callback function - */ - union { - retT (*c_callback)(argT); /*!< Footprint for a global function */ - retT (FPtrDummy::*method_callback)(argT); /*!< Footprint for a member function */ - }; -}; - -#endif diff --git a/include/Temboo/utility/MQTTClient.h b/include/Temboo/utility/MQTTClient.h @@ -1,954 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014, 2015 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - * Ian Craggs - fix for bug 458512 - QoS 2 messages - * Ian Craggs - fix for bug 460389 - send loop uses wrong length - * Ian Craggs - fix for bug 464169 - clearing subscriptions - * Ian Craggs - fix for bug 464551 - enums and ints can be different size - *******************************************************************************/ - -#if !defined(MQTTCLIENT_H) -#define MQTTCLIENT_H - -#include "FP.h" -#include "MQTTPacket.h" -#include "stdio.h" -#include "MQTTLogging.h" - -#if !defined(MQTTCLIENT_QOS1) - #define MQTTCLIENT_QOS1 1 -#endif -#if !defined(MQTTCLIENT_QOS2) - #define MQTTCLIENT_QOS2 0 -#endif - -namespace MQTT -{ - - -enum QoS { QOS0, QOS1, QOS2 }; - -// all failure return codes must be negative -enum returnCode { BUFFER_OVERFLOW = -2, FAILURE = -1, SUCCESS = 0 }; - - -struct Message -{ - enum QoS qos; - bool retained; - bool dup; - unsigned short id; - void *payload; - size_t payloadlen; -}; - - -struct MessageData -{ - MessageData(MQTTString &aTopicName, struct Message &aMessage) : message(aMessage), topicName(aTopicName) - { } - - struct Message &message; - MQTTString &topicName; -}; - - -class PacketId -{ -public: - PacketId() - { - next = 0; - } - - int getNext() - { - next = (next == MAX_PACKET_ID) ? 1 : next + 1; - return next; - } - -private: - static const int MAX_PACKET_ID = 65535; - int next; -}; - - -/** - * @class Client - * @brief blocking, non-threaded MQTT client API - * - * This version of the API blocks on all method calls, until they are complete. This means that only one - * MQTT request can be in process at any one time. - * @param Network a network class which supports send, receive - * @param Timer a timer class with the methods: - */ -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE = 100, int MAX_MESSAGE_HANDLERS = 5> -class Client -{ - -public: - - typedef void (*messageHandler)(MessageData&); - - /** Construct the client - * @param network - pointer to an instance of the Network class - must be connected to the endpoint - * before calling MQTT connect - * @param limits an instance of the Limit class - to alter limits as required - */ - Client(Network& network, unsigned int command_timeout_ms = 30000); - - /** Set the default message handling callback - used for any message which does not match a subscription message handler - * @param mh - pointer to the callback function - */ - void setDefaultMessageHandler(messageHandler mh) - { - defaultMessageHandler.attach(mh); - } - - /** MQTT Connect - send an MQTT connect packet down the network and wait for a Connack - * The nework object must be connected to the network endpoint before calling this - * Default connect options are used - * @return success code - - */ - int connect(); - - /** MQTT Connect - send an MQTT connect packet down the network and wait for a Connack - * The nework object must be connected to the network endpoint before calling this - * @param options - connect options - * @return success code - - */ - int connect(MQTTPacket_connectData& options); - - /** MQTT Publish - send an MQTT publish packet and wait for all acks to complete for all QoSs - * @param topic - the topic to publish to - * @param message - the message to send - * @return success code - - */ - int publish(const char* topicName, Message& message); - - /** MQTT Publish - send an MQTT publish packet and wait for all acks to complete for all QoSs - * @param topic - the topic to publish to - * @param payload - the data to send - * @param payloadlen - the length of the data - * @param qos - the QoS to send the publish at - * @param retained - whether the message should be retained - * @return success code - - */ - int publish(const char* topicName, void* payload, size_t payloadlen, enum QoS qos = QOS0, bool retained = false); - - /** MQTT Publish - send an MQTT publish packet and wait for all acks to complete for all QoSs - * @param topic - the topic to publish to - * @param payload - the data to send - * @param payloadlen - the length of the data - * @param id - the packet id used - returned - * @param qos - the QoS to send the publish at - * @param retained - whether the message should be retained - * @return success code - - */ - int publish(const char* topicName, void* payload, size_t payloadlen, unsigned short& id, enum QoS qos = QOS1, bool retained = false); - - /** MQTT Subscribe - send an MQTT subscribe packet and wait for the suback - * @param topicFilter - a topic pattern which can include wildcards - * @param qos - the MQTT QoS to subscribe at - * @param mh - the callback function to be invoked when a message is received for this subscription - * @return success code - - */ - int subscribe(const char* topicFilter, enum QoS qos, messageHandler mh); - - /** MQTT Unsubscribe - send an MQTT unsubscribe packet and wait for the unsuback - * @param topicFilter - a topic pattern which can include wildcards - * @return success code - - */ - int unsubscribe(const char* topicFilter); - - /** MQTT Disconnect - send an MQTT disconnect packet, and clean up any state - * @return success code - - */ - int disconnect(); - - /** A call to this API must be made within the keepAlive interval to keep the MQTT connection alive - * yield can be called if no other MQTT operation is needed. This will also allow messages to be - * received. - * @param timeout_ms the time to wait, in milliseconds - * @return success code - on failure, this means the client has disconnected - */ - int yield(unsigned long timeout_ms = 1000L); - - /** Is the client connected? - * @return flag - is the client connected or not? - */ - bool isConnected() - { - return isconnected; - } - -private: - - void cleanSession(); - int cycle(Timer& timer); - int waitfor(int packet_type, Timer& timer); - int keepalive(); - int publish(int len, Timer& timer, enum QoS qos); - - int decodePacket(int* value, int timeout); - int readPacket(Timer& timer); - int sendPacket(int length, Timer& timer); - int deliverMessage(MQTTString& topicName, Message& message); - bool isTopicMatched(char* topicFilter, MQTTString& topicName); - - Network& ipstack; - unsigned long command_timeout_ms; - - unsigned char sendbuf[MAX_MQTT_PACKET_SIZE]; - unsigned char readbuf[MAX_MQTT_PACKET_SIZE]; - - Timer last_sent, last_received; - unsigned int keepAliveInterval; - bool ping_outstanding; - bool cleansession; - - PacketId packetid; - - struct MessageHandlers - { - const char* topicFilter; - FP<void, MessageData&> fp; - } messageHandlers[MAX_MESSAGE_HANDLERS]; // Message handlers are indexed by subscription topic - - FP<void, MessageData&> defaultMessageHandler; - - bool isconnected; - -#if MQTTCLIENT_QOS1 || MQTTCLIENT_QOS2 - unsigned char pubbuf[MAX_MQTT_PACKET_SIZE]; // store the last publish for sending on reconnect - int inflightLen; - unsigned short inflightMsgid; - enum QoS inflightQoS; -#endif - -#if MQTTCLIENT_QOS2 - bool pubrel; - #if !defined(MAX_INCOMING_QOS2_MESSAGES) - #define MAX_INCOMING_QOS2_MESSAGES 10 - #endif - unsigned short incomingQoS2messages[MAX_INCOMING_QOS2_MESSAGES]; - bool isQoS2msgidFree(unsigned short id); - bool useQoS2msgid(unsigned short id); - void freeQoS2msgid(unsigned short id); -#endif - -}; - -} - - -template<class Network, class Timer, int a, int MAX_MESSAGE_HANDLERS> -void MQTT::Client<Network, Timer, a, MAX_MESSAGE_HANDLERS>::cleanSession() -{ - ping_outstanding = false; - for (int i = 0; i < MAX_MESSAGE_HANDLERS; ++i) - messageHandlers[i].topicFilter = 0; - isconnected = false; - -#if MQTTCLIENT_QOS1 || MQTTCLIENT_QOS2 - inflightMsgid = 0; - inflightQoS = QOS0; -#endif - -#if MQTTCLIENT_QOS2 - pubrel = false; - for (int i = 0; i < MAX_INCOMING_QOS2_MESSAGES; ++i) - incomingQoS2messages[i] = 0; -#endif -} - - -template<class Network, class Timer, int a, int MAX_MESSAGE_HANDLERS> -MQTT::Client<Network, Timer, a, MAX_MESSAGE_HANDLERS>::Client(Network& network, unsigned int command_timeout_ms) : ipstack(network), packetid() -{ - last_sent = Timer(); - last_received = Timer(); - this->command_timeout_ms = command_timeout_ms; - cleanSession(); -} - - -#if MQTTCLIENT_QOS2 -template<class Network, class Timer, int a, int b> -bool MQTT::Client<Network, Timer, a, b>::isQoS2msgidFree(unsigned short id) -{ - for (int i = 0; i < MAX_INCOMING_QOS2_MESSAGES; ++i) - { - if (incomingQoS2messages[i] == id) - return false; - } - return true; -} - - -template<class Network, class Timer, int a, int b> -bool MQTT::Client<Network, Timer, a, b>::useQoS2msgid(unsigned short id) -{ - for (int i = 0; i < MAX_INCOMING_QOS2_MESSAGES; ++i) - { - if (incomingQoS2messages[i] == 0) - { - incomingQoS2messages[i] = id; - return true; - } - } - return false; -} - - -template<class Network, class Timer, int a, int b> -void MQTT::Client<Network, Timer, a, b>::freeQoS2msgid(unsigned short id) -{ - for (int i = 0; i < MAX_INCOMING_QOS2_MESSAGES; ++i) - { - if (incomingQoS2messages[i] == id) - { - incomingQoS2messages[i] = 0; - return; - } - } -} -#endif - - -template<class Network, class Timer, int a, int b> -int MQTT::Client<Network, Timer, a, b>::sendPacket(int length, Timer& timer) -{ - int rc = FAILURE, - sent = 0; - - while (sent < length && !timer.expired()) - { - rc = ipstack.write(&sendbuf[sent], length - sent, timer.left_ms()); - if (rc < 0) // there was an error writing the data - break; - sent += rc; - } - if (sent == length) - { - if (this->keepAliveInterval > 0) - last_sent.countdown(this->keepAliveInterval); // record the fact that we have successfully sent the packet - rc = SUCCESS; - } - else - rc = FAILURE; - -#if defined(MQTT_DEBUG) - char printbuf[150]; - DEBUG("Rc %d from sending packet %s\n", rc, MQTTFormat_toServerString(printbuf, sizeof(printbuf), sendbuf, length)); -#endif - return rc; -} - - -template<class Network, class Timer, int a, int b> -int MQTT::Client<Network, Timer, a, b>::decodePacket(int* value, int timeout) -{ - unsigned char c; - int multiplier = 1; - int len = 0; - const int MAX_NO_OF_REMAINING_LENGTH_BYTES = 4; - - *value = 0; - do - { - int rc = MQTTPACKET_READ_ERROR; - - if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) - { - rc = MQTTPACKET_READ_ERROR; /* bad data */ - goto exit; - } - rc = ipstack.read(&c, 1, timeout); - if (rc != 1) - goto exit; - *value += (c & 127) * multiplier; - multiplier *= 128; - } while ((c & 128) != 0); -exit: - return len; -} - - -/** - * If any read fails in this method, then we should disconnect from the network, as on reconnect - * the packets can be retried. - * @param timeout the max time to wait for the packet read to complete, in milliseconds - * @return the MQTT packet type, or -1 if none - */ -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::readPacket(Timer& timer) -{ - int rc = FAILURE; - MQTTHeader header = {0}; - int len = 0; - int rem_len = 0; - - /* 1. read the header byte. This has the packet type in it */ - if (ipstack.read(readbuf, 1, timer.left_ms()) != 1) - goto exit; - - len = 1; - /* 2. read the remaining length. This is variable in itself */ - decodePacket(&rem_len, timer.left_ms()); - len += MQTTPacket_encode(readbuf + 1, rem_len); /* put the original remaining length into the buffer */ - - if (rem_len > (MAX_MQTT_PACKET_SIZE - len)) - { - rc = BUFFER_OVERFLOW; - } - - /* 3. read the rest of the buffer using a callback to supply the rest of the data */ - if (rc == BUFFER_OVERFLOW) { - if (rem_len > 0 && (ipstack.read(readbuf + len, MAX_MQTT_PACKET_SIZE - len, timer.left_ms()) != (MAX_MQTT_PACKET_SIZE - len))) - goto exit; - readbuf[MAX_MQTT_PACKET_SIZE-1] = '\0'; - rem_len = rem_len - MAX_MQTT_PACKET_SIZE - len; - while(rem_len--) { - unsigned char c; - ipstack.read(&c, 1, timer.left_ms() ); - } - } - else { - if (rem_len > 0 && (ipstack.read(readbuf + len, rem_len, timer.left_ms()) != rem_len)) - goto exit; - header.byte = readbuf[0]; - rc = header.bits.type; - } - - if (this->keepAliveInterval > 0) - last_received.countdown(this->keepAliveInterval); // record the fact that we have successfully received a packet -exit: -#if defined(MQTT_DEBUG) - if (rc >= 0) - { - char printbuf[50]; - DEBUG("Rc %d from receiving packet %s\n", rc, MQTTFormat_toClientString(printbuf, sizeof(printbuf), readbuf, len)); - } -#endif - return rc; -} - - -// assume topic filter and name is in correct format -// # can only be at end -// + and # can only be next to separator -template<class Network, class Timer, int a, int b> -bool MQTT::Client<Network, Timer, a, b>::isTopicMatched(char* topicFilter, MQTTString& topicName) -{ - char* curf = topicFilter; - char* curn = topicName.lenstring.data; - char* curn_end = curn + topicName.lenstring.len; - - while (*curf && curn < curn_end) - { - if (*curn == '/' && *curf != '/') - break; - if (*curf != '+' && *curf != '#' && *curf != *curn) - break; - if (*curf == '+') - { // skip until we meet the next separator, or end of string - char* nextpos = curn + 1; - while (nextpos < curn_end && *nextpos != '/') - nextpos = ++curn + 1; - } - else if (*curf == '#') - curn = curn_end - 1; // skip until end of string - curf++; - curn++; - }; - - return (curn == curn_end) && (*curf == '\0'); -} - - - -template<class Network, class Timer, int a, int MAX_MESSAGE_HANDLERS> -int MQTT::Client<Network, Timer, a, MAX_MESSAGE_HANDLERS>::deliverMessage(MQTTString& topicName, Message& message) -{ - int rc = FAILURE; - - // we have to find the right message handler - indexed by topic - for (int i = 0; i < MAX_MESSAGE_HANDLERS; ++i) - { - if (messageHandlers[i].topicFilter != 0 && (MQTTPacket_equals(&topicName, (char*)messageHandlers[i].topicFilter) || - isTopicMatched((char*)messageHandlers[i].topicFilter, topicName))) - { - if (messageHandlers[i].fp.attached()) - { - MessageData md(topicName, message); - messageHandlers[i].fp(md); - rc = SUCCESS; - } - } - } - - if (rc == FAILURE && defaultMessageHandler.attached()) - { - MessageData md(topicName, message); - defaultMessageHandler(md); - rc = SUCCESS; - } - - return rc; -} - - - -template<class Network, class Timer, int a, int b> -int MQTT::Client<Network, Timer, a, b>::yield(unsigned long timeout_ms) -{ - int rc = SUCCESS; - Timer timer = Timer(); - - timer.countdown_ms(timeout_ms); - while (!timer.expired()) - { - if (cycle(timer) < 0) - { - rc = FAILURE; - break; - } - } - - return rc; -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::cycle(Timer& timer) -{ - /* get one piece of work off the wire and one pass through */ - - // read the socket, see what work is due - int packet_type = readPacket(timer); - int rc = SUCCESS; - if (packet_type == BUFFER_OVERFLOW) { - MQTTHeader header = {0}; - header.byte = readbuf[0]; - packet_type = header.bits.type; - } - - int len = 0; - switch (packet_type) - { - case FAILURE: - case BUFFER_OVERFLOW: - rc = packet_type; - break; - case CONNACK: - case PUBACK: - case SUBACK: - break; - case PUBLISH: - { - MQTTString topicName = MQTTString_initializer; - Message msg; - int intQoS; - if (MQTTDeserialize_publish((unsigned char*)&msg.dup, &intQoS, (unsigned char*)&msg.retained, (unsigned short*)&msg.id, &topicName, - (unsigned char**)&msg.payload, (int*)&msg.payloadlen, readbuf, MAX_MQTT_PACKET_SIZE) != 1) - goto exit; - msg.qos = (enum QoS)intQoS; -#if MQTTCLIENT_QOS2 - if (msg.qos != QOS2) -#endif - deliverMessage(topicName, msg); -#if MQTTCLIENT_QOS2 - else if (isQoS2msgidFree(msg.id)) - { - if (useQoS2msgid(msg.id)) - deliverMessage(topicName, msg); - else - WARN("Maximum number of incoming QoS2 messages exceeded"); - } -#endif -#if MQTTCLIENT_QOS1 || MQTTCLIENT_QOS2 - if (msg.qos != QOS0) - { - if (msg.qos == QOS1) - len = MQTTSerialize_ack(sendbuf, MAX_MQTT_PACKET_SIZE, PUBACK, 0, msg.id); - else if (msg.qos == QOS2) - len = MQTTSerialize_ack(sendbuf, MAX_MQTT_PACKET_SIZE, PUBREC, 0, msg.id); - if (len <= 0) - rc = FAILURE; - else - rc = sendPacket(len, timer); - if (rc == FAILURE) - goto exit; // there was a problem - } - break; -#endif - } -#if MQTTCLIENT_QOS2 - case PUBREC: - case PUBREL: - unsigned short mypacketid; - unsigned char dup, type; - if (MQTTDeserialize_ack(&type, &dup, &mypacketid, readbuf, MAX_MQTT_PACKET_SIZE) != 1) - rc = FAILURE; - else if ((len = MQTTSerialize_ack(sendbuf, MAX_MQTT_PACKET_SIZE, - (packet_type == PUBREC) ? PUBREL : PUBCOMP, 0, mypacketid)) <= 0) - rc = FAILURE; - else if ((rc = sendPacket(len, timer)) != SUCCESS) // send the PUBREL packet - rc = FAILURE; // there was a problem - if (rc == FAILURE) - goto exit; // there was a problem - if (packet_type == PUBREL) - freeQoS2msgid(mypacketid); - break; - - case PUBCOMP: - break; -#endif - case PINGRESP: - ping_outstanding = false; - break; - } - keepalive(); -exit: - if (rc == SUCCESS) - rc = packet_type; - return rc; -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::keepalive() -{ - int rc = FAILURE; - - if (keepAliveInterval == 0) - { - rc = SUCCESS; - goto exit; - } - - if (last_sent.expired() || last_received.expired()) - { - if (!ping_outstanding) - { - Timer timer = Timer(1000); - int len = MQTTSerialize_pingreq(sendbuf, MAX_MQTT_PACKET_SIZE); - if (len > 0 && (rc = sendPacket(len, timer)) == SUCCESS) // send the ping packet - ping_outstanding = true; - } - } - -exit: - return rc; -} - - -// only used in single-threaded mode where one command at a time is in process -template<class Network, class Timer, int a, int b> -int MQTT::Client<Network, Timer, a, b>::waitfor(int packet_type, Timer& timer) -{ - int rc = FAILURE; - - do - { - if (timer.expired()) - break; // we timed out - } - while ((rc = cycle(timer)) != packet_type); - - return rc; -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::connect(MQTTPacket_connectData& options) -{ - Timer connect_timer = Timer(command_timeout_ms); - int rc = FAILURE; - int len = 0; - - if (isconnected) // don't send connect packet again if we are already connected - goto exit; - - this->keepAliveInterval = options.keepAliveInterval; - this->cleansession = options.cleansession; - if ((len = MQTTSerialize_connect(sendbuf, MAX_MQTT_PACKET_SIZE, &options)) <= 0) - goto exit; - if ((rc = sendPacket(len, connect_timer)) != SUCCESS) // send the connect packet - goto exit; // there was a problem - - if (this->keepAliveInterval > 0) - last_received.countdown(this->keepAliveInterval); - // this will be a blocking call, wait for the connack - if (waitfor(CONNACK, connect_timer) == CONNACK) - { - unsigned char connack_rc = 255; - bool sessionPresent = false; - if (MQTTDeserialize_connack((unsigned char*)&sessionPresent, &connack_rc, readbuf, MAX_MQTT_PACKET_SIZE) == 1) - rc = connack_rc; - else - rc = FAILURE; - } - else - rc = FAILURE; - -#if MQTTCLIENT_QOS2 - // resend any inflight publish - if (inflightMsgid > 0 && inflightQoS == QOS2 && pubrel) - { - if ((len = MQTTSerialize_ack(sendbuf, MAX_MQTT_PACKET_SIZE, PUBREL, 0, inflightMsgid)) <= 0) - rc = FAILURE; - else - rc = publish(len, connect_timer, inflightQoS); - } - else -#endif -#if MQTTCLIENT_QOS1 || MQTTCLIENT_QOS2 - if (inflightMsgid > 0) - { - memcpy(sendbuf, pubbuf, MAX_MQTT_PACKET_SIZE); - rc = publish(inflightLen, connect_timer, inflightQoS); - } -#endif - -exit: - if (rc == SUCCESS) - isconnected = true; - return rc; -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::connect() -{ - MQTTPacket_connectData default_options = MQTTPacket_connectData_initializer; - return connect(default_options); -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int MAX_MESSAGE_HANDLERS> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, MAX_MESSAGE_HANDLERS>::subscribe(const char* topicFilter, enum QoS qos, messageHandler messageHandler) -{ - int rc = FAILURE; - Timer timer = Timer(command_timeout_ms); - int len = 0; - MQTTString topic = {(char*)topicFilter, {0, 0}}; - - if (!isconnected) - goto exit; - - len = MQTTSerialize_subscribe(sendbuf, MAX_MQTT_PACKET_SIZE, 0, packetid.getNext(), 1, &topic, (int*)&qos); - if (len <= 0) - goto exit; - if ((rc = sendPacket(len, timer)) != SUCCESS) // send the subscribe packet - goto exit; // there was a problem - - if (waitfor(SUBACK, timer) == SUBACK) // wait for suback - { - int count = 0, grantedQoS = -1; - unsigned short mypacketid; - if (MQTTDeserialize_suback(&mypacketid, 1, &count, &grantedQoS, readbuf, MAX_MQTT_PACKET_SIZE) == 1) - rc = grantedQoS; // 0, 1, 2 or 0x80 - if (rc != 0x80) - { - for (int i = 0; i < MAX_MESSAGE_HANDLERS; ++i) - { - if (messageHandlers[i].topicFilter == 0) - { - messageHandlers[i].topicFilter = topicFilter; - messageHandlers[i].fp.attach(messageHandler); - rc = 0; - break; - } - } - } - } - else - rc = FAILURE; - -exit: - if (rc != SUCCESS) - cleanSession(); - return rc; -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int MAX_MESSAGE_HANDLERS> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, MAX_MESSAGE_HANDLERS>::unsubscribe(const char* topicFilter) -{ - int rc = FAILURE; - Timer timer = Timer(command_timeout_ms); - MQTTString topic = {(char*)topicFilter, {0, 0}}; - int len = 0; - - if (!isconnected) - goto exit; - - if ((len = MQTTSerialize_unsubscribe(sendbuf, MAX_MQTT_PACKET_SIZE, 0, packetid.getNext(), 1, &topic)) <= 0) - goto exit; - if ((rc = sendPacket(len, timer)) != SUCCESS) // send the unsubscribe packet - goto exit; // there was a problem - - if (waitfor(UNSUBACK, timer) == UNSUBACK) - { - unsigned short mypacketid; // should be the same as the packetid above - if (MQTTDeserialize_unsuback(&mypacketid, readbuf, MAX_MQTT_PACKET_SIZE) == 1) - { - rc = 0; - - // remove the subscription message handler associated with this topic, if there is one - for (int i = 0; i < MAX_MESSAGE_HANDLERS; ++i) - { - if (strcmp(messageHandlers[i].topicFilter, topicFilter) == 0) - { - messageHandlers[i].topicFilter = 0; - break; - } - } - } - } - else - rc = FAILURE; - -exit: - if (rc != SUCCESS) - cleanSession(); - return rc; -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::publish(int len, Timer& timer, enum QoS qos) -{ - int rc; - - if ((rc = sendPacket(len, timer)) != SUCCESS) // send the publish packet - goto exit; // there was a problem - -#if MQTTCLIENT_QOS1 - if (qos == QOS1) - { - if (waitfor(PUBACK, timer) == PUBACK) - { - unsigned short mypacketid; - unsigned char dup, type; - if (MQTTDeserialize_ack(&type, &dup, &mypacketid, readbuf, MAX_MQTT_PACKET_SIZE) != 1) - rc = FAILURE; - else if (inflightMsgid == mypacketid) - inflightMsgid = 0; - } - else - rc = FAILURE; - } -#elif MQTTCLIENT_QOS2 - else if (qos == QOS2) - { - if (waitfor(PUBCOMP, timer) == PUBCOMP) - { - unsigned short mypacketid; - unsigned char dup, type; - if (MQTTDeserialize_ack(&type, &dup, &mypacketid, readbuf, MAX_MQTT_PACKET_SIZE) != 1) - rc = FAILURE; - else if (inflightMsgid == mypacketid) - inflightMsgid = 0; - } - else - rc = FAILURE; - } -#endif - -exit: - if (rc != SUCCESS) - cleanSession(); - return rc; -} - - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::publish(const char* topicName, void* payload, size_t payloadlen, unsigned short& id, enum QoS qos, bool retained) -{ - int rc = FAILURE; - Timer timer = Timer(command_timeout_ms); - MQTTString topicString = MQTTString_initializer; - int len = 0; - - if (!isconnected) - goto exit; - - topicString.cstring = (char*)topicName; - -#if MQTTCLIENT_QOS1 || MQTTCLIENT_QOS2 - if (qos == QOS1 || qos == QOS2) - id = packetid.getNext(); -#endif - - len = MQTTSerialize_publish(sendbuf, MAX_MQTT_PACKET_SIZE, 0, qos, retained, id, - topicString, (unsigned char*)payload, payloadlen); - if (len <= 0) - goto exit; - -#if MQTTCLIENT_QOS1 || MQTTCLIENT_QOS2 - if (!cleansession) - { - memcpy(pubbuf, sendbuf, len); - inflightMsgid = id; - inflightLen = len; - inflightQoS = qos; -#if MQTTCLIENT_QOS2 - pubrel = false; -#endif - } -#endif - - rc = publish(len, timer, qos); -exit: - return rc; -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::publish(const char* topicName, void* payload, size_t payloadlen, enum QoS qos, bool retained) -{ - unsigned short id = 0; // dummy - not used for anything - return publish(topicName, payload, payloadlen, id, qos, retained); -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::publish(const char* topicName, Message& message) -{ - return publish(topicName, message.payload, message.payloadlen, message.qos, message.retained); -} - - -template<class Network, class Timer, int MAX_MQTT_PACKET_SIZE, int b> -int MQTT::Client<Network, Timer, MAX_MQTT_PACKET_SIZE, b>::disconnect() -{ - int rc = FAILURE; - Timer timer = Timer(command_timeout_ms); // we might wait for incomplete incoming publishes to complete - int len = MQTTSerialize_disconnect(sendbuf, MAX_MQTT_PACKET_SIZE); - if (len > 0) - rc = sendPacket(len, timer); // send the disconnect packet - - if (cleansession) - cleanSession(); - else - isconnected = false; - return rc; -} - - -#endif diff --git a/include/Temboo/utility/MQTTConnect.h b/include/Temboo/utility/MQTTConnect.h @@ -1,136 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - * Xiang Rong - 442039 Add makefile to Embedded C client - *******************************************************************************/ - -#ifndef MQTTCONNECT_H_ -#define MQTTCONNECT_H_ - -#if !defined(DLLImport) - #define DLLImport -#endif -#if !defined(DLLExport) - #define DLLExport -#endif - - -typedef union -{ - unsigned char all; /**< all connect flags */ -#if defined(REVERSED) - struct - { - unsigned int username : 1; /**< 3.1 user name */ - unsigned int password : 1; /**< 3.1 password */ - unsigned int willRetain : 1; /**< will retain setting */ - unsigned int willQoS : 2; /**< will QoS value */ - unsigned int will : 1; /**< will flag */ - unsigned int cleansession : 1; /**< clean session flag */ - unsigned int : 1; /**< unused */ - } bits; -#else - struct - { - unsigned int : 1; /**< unused */ - unsigned int cleansession : 1; /**< cleansession flag */ - unsigned int will : 1; /**< will flag */ - unsigned int willQoS : 2; /**< will QoS value */ - unsigned int willRetain : 1; /**< will retain setting */ - unsigned int password : 1; /**< 3.1 password */ - unsigned int username : 1; /**< 3.1 user name */ - } bits; -#endif -} MQTTConnectFlags; /**< connect flags byte */ - - - -/** - * Defines the MQTT "Last Will and Testament" (LWT) settings for - * the connect packet. - */ -typedef struct -{ - /** The eyecatcher for this structure. must be MQTW. */ - char struct_id[4]; - /** The version number of this structure. Must be 0 */ - int struct_version; - /** The LWT topic to which the LWT message will be published. */ - MQTTString topicName; - /** The LWT payload. */ - MQTTString message; - /** - * The retained flag for the LWT message (see MQTTAsync_message.retained). - */ - unsigned char retained; - /** - * The quality of service setting for the LWT message (see - * MQTTAsync_message.qos and @ref qos). - */ - char qos; -} MQTTPacket_willOptions; - - -#define MQTTPacket_willOptions_initializer { {'M', 'Q', 'T', 'W'}, 0, {NULL, {0, NULL}}, {NULL, {0, NULL}}, 0, 0 } - - -typedef struct -{ - /** The eyecatcher for this structure. must be MQTC. */ - char struct_id[4]; - /** The version number of this structure. Must be 0 */ - int struct_version; - /** Version of MQTT to be used. 3 = 3.1 4 = 3.1.1 - */ - unsigned char MQTTVersion; - MQTTString clientID; - unsigned short keepAliveInterval; - unsigned char cleansession; - unsigned char willFlag; - MQTTPacket_willOptions will; - MQTTString username; - MQTTString password; -} MQTTPacket_connectData; - -typedef union -{ - unsigned char all; /**< all connack flags */ -#if defined(REVERSED) - struct - { - unsigned int sessionpresent : 1; /**< session present flag */ - unsigned int : 7; /**< unused */ - } bits; -#else - struct - { - unsigned int : 7; /**< unused */ - unsigned int sessionpresent : 1; /**< session present flag */ - } bits; -#endif -} MQTTConnackFlags; /**< connack flags byte */ - -#define MQTTPacket_connectData_initializer { {'M', 'Q', 'T', 'C'}, 0, 4, {NULL, {0, NULL}}, 60, 1, 0, \ - MQTTPacket_willOptions_initializer, {NULL, {0, NULL}}, {NULL, {0, NULL}} } - -DLLExport int MQTTSerialize_connect(unsigned char* buf, int buflen, MQTTPacket_connectData* options); -DLLExport int MQTTDeserialize_connect(MQTTPacket_connectData* data, unsigned char* buf, int len); - -DLLExport int MQTTSerialize_connack(unsigned char* buf, int buflen, unsigned char connack_rc, unsigned char sessionPresent); -DLLExport int MQTTDeserialize_connack(unsigned char* sessionPresent, unsigned char* connack_rc, unsigned char* buf, int buflen); - -DLLExport int MQTTSerialize_disconnect(unsigned char* buf, int buflen); -DLLExport int MQTTSerialize_pingreq(unsigned char* buf, int buflen); - -#endif /* MQTTCONNECT_H_ */ diff --git a/include/Temboo/utility/MQTTFormat.h b/include/Temboo/utility/MQTTFormat.h @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - *******************************************************************************/ - -#if !defined(MQTTFORMAT_H) -#define MQTTFORMAT_H - -#include "StackTrace.h" -#include "MQTTPacket.h" - -const char* MQTTPacket_getName(unsigned short packetid); -int MQTTStringFormat_connect(char* strbuf, int strbuflen, MQTTPacket_connectData* data); -int MQTTStringFormat_connack(char* strbuf, int strbuflen, unsigned char connack_rc, unsigned char sessionPresent); -int MQTTStringFormat_publish(char* strbuf, int strbuflen, unsigned char dup, int qos, unsigned char retained, - unsigned short packetid, MQTTString topicName, unsigned char* payload, int payloadlen); -int MQTTStringFormat_ack(char* strbuf, int strbuflen, unsigned char packettype, unsigned char dup, unsigned short packetid); -int MQTTStringFormat_subscribe(char* strbuf, int strbuflen, unsigned char dup, unsigned short packetid, int count, - MQTTString topicFilters[], int requestedQoSs[]); -int MQTTStringFormat_suback(char* strbuf, int strbuflen, unsigned short packetid, int count, int* grantedQoSs); -int MQTTStringFormat_unsubscribe(char* strbuf, int strbuflen, unsigned char dup, unsigned short packetid, - int count, MQTTString topicFilters[]); -char* MQTTFormat_toClientString(char* strbuf, int strbuflen, unsigned char* buf, int buflen); -char* MQTTFormat_toServerString(char* strbuf, int strbuflen, unsigned char* buf, int buflen); - -#endif diff --git a/include/Temboo/utility/MQTTLogging.h b/include/Temboo/utility/MQTTLogging.h @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - *******************************************************************************/ - -/******************************************************************************* - * Modified for Arduino environment by Temboo - * Joe Planisky - replaced fancy fprintf stuff with Serial.print(ln) - *******************************************************************************/ - -#if !defined(MQTT_LOGGING_H) -#define MQTT_LOGGING_H - -#if !defined(DEBUG) -#define DEBUG(msg) {Serial.print("DEBUG: "); Serial.println(msg);} -#endif - -#if !defined(LOG) -#define LOG(msg) {Serial.print("LOG: "); Serial.println(msg);} -#endif - -#if !defined(WARN) -#define WARN(msg) {Serial.print("WARN: "); Serial.println(msg);} -#endif - -#if !defined(ERROR) -#define ERROR() {Serial.print("ERROR: "); Serial.println(msg);} -#endif - -#endif diff --git a/include/Temboo/utility/MQTTPacket.h b/include/Temboo/utility/MQTTPacket.h @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - * Xiang Rong - 442039 Add makefile to Embedded C client - *******************************************************************************/ - -#ifndef MQTTPACKET_H_ -#define MQTTPACKET_H_ - -#if defined(__cplusplus) /* If this is a C++ compiler, use C linkage */ -extern "C" { -#endif - -#if defined(WIN32_DLL) || defined(WIN64_DLL) - #define DLLImport __declspec(dllimport) - #define DLLExport __declspec(dllexport) -#elif defined(LINUX_SO) - #define DLLImport extern - #define DLLExport __attribute__ ((visibility ("default"))) -#else - #define DLLImport - #define DLLExport -#endif - -enum errors -{ - MQTTPACKET_BUFFER_TOO_SHORT = -2, - MQTTPACKET_READ_ERROR = -1, - MQTTPACKET_READ_COMPLETE -}; - -enum msgTypes -{ - CONNECT = 1, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, - PUBCOMP, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, - PINGREQ, PINGRESP, DISCONNECT -}; - -/** - * Bitfields for the MQTT header byte. - */ -typedef union -{ - unsigned char byte; /**< the whole byte */ -#if defined(REVERSED) - struct - { - unsigned int type : 4; /**< message type nibble */ - unsigned int dup : 1; /**< DUP flag bit */ - unsigned int qos : 2; /**< QoS value, 0, 1 or 2 */ - unsigned int retain : 1; /**< retained flag bit */ - } bits; -#else - struct - { - unsigned int retain : 1; /**< retained flag bit */ - unsigned int qos : 2; /**< QoS value, 0, 1 or 2 */ - unsigned int dup : 1; /**< DUP flag bit */ - unsigned int type : 4; /**< message type nibble */ - } bits; -#endif -} MQTTHeader; - -typedef struct -{ - int len; - char* data; -} MQTTLenString; - -typedef struct -{ - char* cstring; - MQTTLenString lenstring; -} MQTTString; - -#define MQTTString_initializer {NULL, {0, NULL}} - -int MQTTstrlen(MQTTString mqttstring); - -#include "MQTTConnect.h" -#include "MQTTPublish.h" -#include "MQTTSubscribe.h" -#include "MQTTUnsubscribe.h" -#include "MQTTFormat.h" - -int MQTTSerialize_ack(unsigned char* buf, int buflen, unsigned char type, unsigned char dup, unsigned short packetid); -int MQTTDeserialize_ack(unsigned char* packettype, unsigned char* dup, unsigned short* packetid, unsigned char* buf, int buflen); - -int MQTTPacket_len(int rem_len); -int MQTTPacket_equals(MQTTString* a, char* b); - -int MQTTPacket_encode(unsigned char* buf, int length); -int MQTTPacket_decode(int (*getcharfn)(unsigned char*, int), int* value); -int MQTTPacket_decodeBuf(unsigned char* buf, int* value); - -int readInt(unsigned char** pptr); -char readChar(unsigned char** pptr); -void writeChar(unsigned char** pptr, char c); -void writeInt(unsigned char** pptr, int anInt); -int readMQTTLenString(MQTTString* mqttstring, unsigned char** pptr, unsigned char* enddata); -void writeCString(unsigned char** pptr, const char* string); -void writeMQTTString(unsigned char** pptr, MQTTString mqttstring); - -DLLExport int MQTTPacket_read(unsigned char* buf, int buflen, int (*getfn)(unsigned char*, int)); - -typedef struct { - int (*getfn)(void *, unsigned char*, int); /* must return -1 for error, 0 for call again, or the number of bytes read */ - void *sck; /* pointer to whatever the system may use to identify the transport */ - int multiplier; - int rem_len; - int len; - char state; -}MQTTTransport; - -int MQTTPacket_readnb(unsigned char* buf, int buflen, MQTTTransport *trp); - -#ifdef __cplusplus /* If this is a C++ compiler, use C linkage */ -} -#endif - - -#endif /* MQTTPACKET_H_ */ diff --git a/include/Temboo/utility/MQTTPublish.h b/include/Temboo/utility/MQTTPublish.h @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - * Xiang Rong - 442039 Add makefile to Embedded C client - *******************************************************************************/ - -#ifndef MQTTPUBLISH_H_ -#define MQTTPUBLISH_H_ - -#if !defined(DLLImport) - #define DLLImport -#endif -#if !defined(DLLExport) - #define DLLExport -#endif - -DLLExport int MQTTSerialize_publish(unsigned char* buf, int buflen, unsigned char dup, int qos, unsigned char retained, unsigned short packetid, - MQTTString topicName, unsigned char* payload, int payloadlen); - -DLLExport int MQTTDeserialize_publish(unsigned char* dup, int* qos, unsigned char* retained, unsigned short* packetid, MQTTString* topicName, - unsigned char** payload, int* payloadlen, unsigned char* buf, int len); - -DLLExport int MQTTSerialize_puback(unsigned char* buf, int buflen, unsigned short packetid); -DLLExport int MQTTSerialize_pubrel(unsigned char* buf, int buflen, unsigned char dup, unsigned short packetid); -DLLExport int MQTTSerialize_pubcomp(unsigned char* buf, int buflen, unsigned short packetid); - -#endif /* MQTTPUBLISH_H_ */ diff --git a/include/Temboo/utility/MQTTSubscribe.h b/include/Temboo/utility/MQTTSubscribe.h @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - * Xiang Rong - 442039 Add makefile to Embedded C client - *******************************************************************************/ - -#ifndef MQTTSUBSCRIBE_H_ -#define MQTTSUBSCRIBE_H_ - -#if !defined(DLLImport) - #define DLLImport -#endif -#if !defined(DLLExport) - #define DLLExport -#endif - -DLLExport int MQTTSerialize_subscribe(unsigned char* buf, int buflen, unsigned char dup, unsigned short packetid, - int count, MQTTString topicFilters[], int requestedQoSs[]); - -DLLExport int MQTTDeserialize_subscribe(unsigned char* dup, unsigned short* packetid, - int maxcount, int* count, MQTTString topicFilters[], int requestedQoSs[], unsigned char* buf, int len); - -DLLExport int MQTTSerialize_suback(unsigned char* buf, int buflen, unsigned short packetid, int count, int* grantedQoSs); - -DLLExport int MQTTDeserialize_suback(unsigned short* packetid, int maxcount, int* count, int grantedQoSs[], unsigned char* buf, int len); - - -#endif /* MQTTSUBSCRIBE_H_ */ diff --git a/include/Temboo/utility/MQTTUnsubscribe.h b/include/Temboo/utility/MQTTUnsubscribe.h @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - * Xiang Rong - 442039 Add makefile to Embedded C client - *******************************************************************************/ - -#ifndef MQTTUNSUBSCRIBE_H_ -#define MQTTUNSUBSCRIBE_H_ - -#if !defined(DLLImport) - #define DLLImport -#endif -#if !defined(DLLExport) - #define DLLExport -#endif - -DLLExport int MQTTSerialize_unsubscribe(unsigned char* buf, int buflen, unsigned char dup, unsigned short packetid, - int count, MQTTString topicFilters[]); - -DLLExport int MQTTDeserialize_unsubscribe(unsigned char* dup, unsigned short* packetid, int max_count, int* count, MQTTString topicFilters[], - unsigned char* buf, int len); - -DLLExport int MQTTSerialize_unsuback(unsigned char* buf, int buflen, unsigned short packetid); - -DLLExport int MQTTDeserialize_unsuback(unsigned short* packetid, unsigned char* buf, int len); - -#endif /* MQTTUNSUBSCRIBE_H_ */ diff --git a/include/Temboo/utility/StackTrace.h b/include/Temboo/utility/StackTrace.h @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - * Ian Craggs - fix for bug #434081 - *******************************************************************************/ - -#ifndef STACKTRACE_H_ -#define STACKTRACE_H_ - -#include <stdio.h> -#define NOSTACKTRACE 1 - -#if defined(NOSTACKTRACE) -#define FUNC_ENTRY -#define FUNC_ENTRY_NOLOG -#define FUNC_ENTRY_MED -#define FUNC_ENTRY_MAX -#define FUNC_EXIT -#define FUNC_EXIT_NOLOG -#define FUNC_EXIT_MED -#define FUNC_EXIT_MAX -#define FUNC_EXIT_RC(x) -#define FUNC_EXIT_MED_RC(x) -#define FUNC_EXIT_MAX_RC(x) - -#else - -#if defined(WIN32) -#define inline __inline -#define FUNC_ENTRY StackTrace_entry(__FUNCTION__, __LINE__, TRACE_MINIMUM) -#define FUNC_ENTRY_NOLOG StackTrace_entry(__FUNCTION__, __LINE__, -1) -#define FUNC_ENTRY_MED StackTrace_entry(__FUNCTION__, __LINE__, TRACE_MEDIUM) -#define FUNC_ENTRY_MAX StackTrace_entry(__FUNCTION__, __LINE__, TRACE_MAXIMUM) -#define FUNC_EXIT StackTrace_exit(__FUNCTION__, __LINE__, NULL, TRACE_MINIMUM) -#define FUNC_EXIT_NOLOG StackTrace_exit(__FUNCTION__, __LINE__, -1) -#define FUNC_EXIT_MED StackTrace_exit(__FUNCTION__, __LINE__, NULL, TRACE_MEDIUM) -#define FUNC_EXIT_MAX StackTrace_exit(__FUNCTION__, __LINE__, NULL, TRACE_MAXIMUM) -#define FUNC_EXIT_RC(x) StackTrace_exit(__FUNCTION__, __LINE__, &x, TRACE_MINIMUM) -#define FUNC_EXIT_MED_RC(x) StackTrace_exit(__FUNCTION__, __LINE__, &x, TRACE_MEDIUM) -#define FUNC_EXIT_MAX_RC(x) StackTrace_exit(__FUNCTION__, __LINE__, &x, TRACE_MAXIMUM) -#else -#define FUNC_ENTRY StackTrace_entry(__func__, __LINE__, TRACE_MINIMUM) -#define FUNC_ENTRY_NOLOG StackTrace_entry(__func__, __LINE__, -1) -#define FUNC_ENTRY_MED StackTrace_entry(__func__, __LINE__, TRACE_MEDIUM) -#define FUNC_ENTRY_MAX StackTrace_entry(__func__, __LINE__, TRACE_MAXIMUM) -#define FUNC_EXIT StackTrace_exit(__func__, __LINE__, NULL, TRACE_MINIMUM) -#define FUNC_EXIT_NOLOG StackTrace_exit(__func__, __LINE__, NULL, -1) -#define FUNC_EXIT_MED StackTrace_exit(__func__, __LINE__, NULL, TRACE_MEDIUM) -#define FUNC_EXIT_MAX StackTrace_exit(__func__, __LINE__, NULL, TRACE_MAXIMUM) -#define FUNC_EXIT_RC(x) StackTrace_exit(__func__, __LINE__, &x, TRACE_MINIMUM) -#define FUNC_EXIT_MED_RC(x) StackTrace_exit(__func__, __LINE__, &x, TRACE_MEDIUM) -#define FUNC_EXIT_MAX_RC(x) StackTrace_exit(__func__, __LINE__, &x, TRACE_MAXIMUM) - -void StackTrace_entry(const char* name, int line, int trace); -void StackTrace_exit(const char* name, int line, void* return_value, int trace); - -void StackTrace_printStack(FILE* dest); -char* StackTrace_get(unsigned long); - -#endif - -#endif - - - - -#endif /* STACKTRACE_H_ */ diff --git a/include/Temboo/utility/TembooCoAPIPStack.h b/include/Temboo/utility/TembooCoAPIPStack.h @@ -1,101 +0,0 @@ -/* - ############################################################################### - # - # Temboo CoAP Edge Device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef TEMBOOCOAPIPSTACK_H_ -#define TEMBOOCOAPIPSTACK_H_ - -#include <string.h> -#include <Udp.h> -#include "TembooGlobal.h" - -class TembooCoAPIPStack -{ -public: - enum Error { - SUCCESS = 0, - ERROR_RESOLVING, - ERROR_WRITING, - ERROR_SENDING, - ERROR_RECEIVING - - }; - - - TembooCoAPIPStack(UDP& udp) : m_udp(udp) {} - - - int sendDatagram(IPAddress address, uint16_t port, uint8_t* data, size_t len) { - if (0 == m_udp.beginPacket(address, port)) { - TEMBOO_TRACE("ERROR: "); - TEMBOO_TRACELN("UDP begin"); - return ERROR_RESOLVING; - } - - uint16_t c = m_udp.write(data, len); - if (len != c) { - TEMBOO_TRACE("ERROR: "); - TEMBOO_TRACELN("UDP write"); - Serial.println(len); - Serial.println(c); - Serial.println((char*)data); - - return ERROR_WRITING; - } - - if (0 == m_udp.endPacket()) { - TEMBOO_TRACE("ERROR: "); - TEMBOO_TRACELN("UDP send"); - return ERROR_SENDING; - } - - return SUCCESS; - } - - int recvDatagram(uint8_t* buffer, size_t maxLen, int32_t& count) { - memset(buffer, 0, maxLen); - count = 0; - if (m_udp.parsePacket() > 0) { - count = m_udp.read(buffer, maxLen); - if (count < 0) { - TEMBOO_TRACE("ERROR: "); - TEMBOO_TRACELN("UDP read"); - return ERROR_RECEIVING; - } - } - return SUCCESS; - } - - IPAddress getRemoteAddress() { - return m_udp.remoteIP(); - } - - uint16_t getRemotePort() { - return m_udp.remotePort(); - } - - -protected: - UDP& m_udp; -}; - -#endif - diff --git a/include/Temboo/utility/TembooCoAPSession.h b/include/Temboo/utility/TembooCoAPSession.h @@ -1,111 +0,0 @@ -/* - ############################################################################### - # - # Temboo CoAP Edge Device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef TEMBOOCOAPSESSIONCLASS_H_ -#define TEMBOOCOAPSESSIONCLASS_H_ - -#include <stdint.h> -#include <Arduino.h> -#include "TembooCoAPEdgeDevice.h" -#include "TembooGlobal.h" - -#ifndef TEMBOO_SEND_QUEUE_SIZE -#define TEMBOO_SEND_QUEUE_SIZE (1000) -#endif - -class ChoreoInputSet; -class ChoreoOutputSet; -class ChoreoPreset; -class DataFormatter; - -class TembooCoAPSession { - public: - - //TembooSession constructor - //client: REQUIRED TembooCoAPClient client object. - TembooCoAPSession(TembooCoAPClient& client); - - //executeChoreo sends a choreo execution request to the Temboo system. - // Does not wait for a response (that's a job for whoever owns the Client.) - //accountName: the name of the user's account at Temboo. - //appKeyName: the name of an application key in the user's account to use - // for this execution (analogous to a user name). - //appKeyValue: the value of the application key named in appKeyName. - // Used to authenticate the user (analogous to a password) - //path: The full path to the choreo to be executed (relative to the root of the - // user's account.) - //inputSet: the set of inputs needed by the choreo. - // May be an empty ChoreoInputSet. - //outputSet: the set of output filters to be applied to the choreo results. - // May be an empty ChoreoOutputSet - //preset: the ChoreoPreset to be used with the choreo execution. - // May be an empty ChoreoPreset. - int executeChoreo( - uint16_t requestId, - const char* accountName, - const char* appKeyName, - const char* appKeyValue, - const char* path, - const ChoreoInputSet& inputSet, - const ChoreoOutputSet& outputSet, - const ChoreoPreset& preset); - - // setTime sets the current time in Unix timestamp format. Needed for execution request authentication. - // NOTE: This method is usually called by TembooChoreo.run() with the current time returned by - // an error response from the Temboo system, thus automatically setting the time. However, it - // MAY be called from user code if the particular board has a way of determining the current - // time in the proper format. - // currentTime: the number of seconds since 1970-01-01 00:00:00 UTC. - static void setTime(unsigned long currentTime); - - //getTime returns the current time in Unix timestamp format (seconds since 1970-01-01 00:00:00 UTC). - // Only valid after setTime has been called. - static unsigned long getTime(); - - enum Error { - SUCCESS = 0, - FAILURE - }; - - private: - TembooCoAPClient& m_client; - static unsigned long s_timeOffset; - - // calculate the authentication code value of the formatted request body - // using the salted application key value as the key. - // Returns the number of characters processed (i.e. the length of the request body) - uint16_t getAuth(DataFormatter& fmt, const char* appKeyValue, const char* salt, char* hexAuth) const; - - - // queue an entire nul-terminated char array - // from RAM one byte at a time. - // returns true on success, false on failure - bool qsend(const char*); - - // queue a single character to be sent. - // returns true on success, false on failure - bool qsend(char); - -}; - -#endif - diff --git a/include/Temboo/utility/TembooGlobal.h b/include/Temboo/utility/TembooGlobal.h @@ -1,53 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef TEMBOOGLOBAL_H_ -#define TEMBOOGLOBAL_H_ - -#include <Arduino.h> - -//#define TEMBOO_VERBOSE - -#ifdef TEMBOO_VERBOSE - #define TEMBOO_TRACE(x) Serial.print(x) - #define TEMBOO_TRACE_BYTES(x,c) Serial.write((const uint8_t*)x,c) - #define TEMBOO_TRACELN(x) Serial.println(x) -#else - #define TEMBOO_TRACE(x) - #define TEMBOO_TRACE_BYTES(x,c) - #define TEMBOO_TRACELN(x) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -char* uint16toa(uint16_t value, char* dest); -char* uint32toa(uint32_t value, char* dest); - -#ifdef __cplusplus -} -#endif - - -#endif - diff --git a/include/Temboo/utility/TembooMQTTIPStack.h b/include/Temboo/utility/TembooMQTTIPStack.h @@ -1,96 +0,0 @@ -/* - ############################################################################### - # - # Temboo MQTT edge device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef TEMBOOBASEIPSTACK_H_ -#define TEMBOOBASEIPSTACK_H_ - -#include <Client.h> - -static const int WRITE_CHUNK_SIZE = 64; - -class TembooMQTTIPStack -{ -public: - TembooMQTTIPStack(Client& client) : m_client(client) { - } - - int connect(const char* hostname, int port) { - return m_client.connect(hostname, port); - } - - bool isConnected() { - return m_client.connected(); - } - - int disconnect() { - m_client.stop(); - return 0; - } - - int read(unsigned char* buffer, int len, int timeoutMillis) { - - m_client.setTimeout(timeoutMillis); - size_t count = m_client.readBytes((char*)buffer, len); - - // Not sure this is a totally good idea. - // (Stream defaults to 1000 mS timeouts.) - m_client.setTimeout(1000); - return count; - } - - int write(unsigned char* buffer, int len, int timeout) { - - // It's possible for write to get called with a 0 timeout, - // in which case we want to make at least one attempt to send - // the data. - timeout = timeout == 0 ? 1 : timeout; - m_client.setTimeout(timeout); - - // Arduino's WiFiClient::write can accept only a limited - // number of characters on each call, so we must make sure - // we pass less than this limit. Note that this isn't necessary - // for Arduino's EthernetClient. However, instead of trying to - // differentiate between clients, we do it for both. - // It SHOULDN'T impact performance in any significant way, but - // if you're using a client that doesn't have this limitation and - // the idea bothers you, feel free to eliminate the min() call or - // else set WRITE_CHUNK_SIZE to a large number. - - // Note that the caller (in this case, MQTT::Client::sendPacket) - // is responsible for calling this method repeatedly until all - // bytes have been written. - - size_t count = m_client.write(buffer, min(len, WRITE_CHUNK_SIZE)); - - // Not sure this is a totally good idea. - // (Stream defaults to 1000 mS timeouts.) - m_client.setTimeout(1000); - return count; - } - - -protected: - Client& m_client; -}; - -#endif - diff --git a/include/Temboo/utility/TembooMQTTSession.h b/include/Temboo/utility/TembooMQTTSession.h @@ -1,108 +0,0 @@ -/* - ############################################################################### - # - # Temboo MQTT edge device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef TEMBOOMQTTSESSIONCLASS_H_ -#define TEMBOOMQTTSESSIONCLASS_H_ - -#include <stdint.h> -#include <Arduino.h> -#include "TembooMQTTEdgeDevice.h" -#include "TembooGlobal.h" - -#ifndef TEMBOO_SEND_QUEUE_SIZE -#define TEMBOO_SEND_QUEUE_SIZE (1000) -#endif - -class ChoreoInputSet; -class ChoreoOutputSet; -class ChoreoPreset; -class DataFormatter; - -class TembooMQTTSession { - public: - - //TembooMQTTSession constructor - //client: REQUIRED TembooMQTTClient client object. - TembooMQTTSession(TembooMQTTClient& client); - - //executeChoreo sends a choreo execution request to the Temboo system. - // Does not wait for a response (that's a job for whoever owns the Client.) - //accountName: the name of the user's account at Temboo. - //appKeyName: the name of an application key in the user's account to use - // for this execution (analogous to a user name). - //appKeyValue: the value of the application key named in appKeyName. - // Used to authenticate the user (analogous to a password) - //path: The full path to the choreo to be executed (relative to the root of the - // user's account.) - //inputSet: the set of inputs needed by the choreo. - // May be an empty ChoreoInputSet. - //outputSet: the set of output filters to be applied to the choreo results. - // May be an empty ChoreoOutputSet - //preset: the ChoreoPreset to be used with the choreo execution. - // May be an empty ChoreoPreset. - int executeChoreo( - uint16_t requestId, - const char* accountName, - const char* appKeyName, - const char* appKeyValue, - const char* path, - const ChoreoInputSet& inputSet, - const ChoreoOutputSet& outputSet, - const ChoreoPreset& preset); - - // setTime sets the current time in Unix timestamp format. Needed for execution request authentication. - // NOTE: This method is usually called by TembooChoreo.run() with the current time returned by - // an error response from the Temboo system, thus automatically setting the time. However, it - // MAY be called from user code if the particular board has a way of determining the current - // time in the proper format. - // currentTime: the number of seconds since 1970-01-01 00:00:00 UTC. - static void setTime(unsigned long currentTime); - - //getTime returns the current time in Unix timestamp format (seconds since 1970-01-01 00:00:00 UTC). - // Only valid after setTime has been called. - static unsigned long getTime(); - - private: - TembooMQTTClient& m_client; - size_t m_sendQueueDepth; - char m_sendQueue[TEMBOO_SEND_QUEUE_SIZE]; - static unsigned long s_timeOffset; - - // calculate the authentication code value of the formatted request body - // using the salted application key value as the key. - // Returns the number of characters processed (i.e. the length of the request body) - uint16_t getAuth(DataFormatter& fmt, const char* appKeyValue, const char* salt, char* hexAuth) const; - - - // queue an entire nul-terminated char array - // from RAM one byte at a time. - // returns true on success, false on failure - bool qsend(const char*); - - // queue a single character to be sent. - // returns true on success, false on failure - bool qsend(char); - -}; - -#endif - diff --git a/include/Temboo/utility/TembooSession.h b/include/Temboo/utility/TembooSession.h @@ -1,134 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef TEMBOOSESSIONCLASS_H_ -#define TEMBOOSESSIONCLASS_H_ - -#include <stdint.h> -#include <Arduino.h> -#include <IPAddress.h> -#include <Client.h> -#include "TembooGlobal.h" - -#ifndef TEMBOO_SEND_QUEUE_SIZE - -// Some network interfaces (i.e. ethernet or WiFi shields) can only accept -// a limited amount of data. If you try to send more than the limit, the excess -// is just lost. However, sending one character at a time is very inefficient. -// To deal with this situation, we queue up TEMBOO_SEND_QUEUE_SIZE bytes to send -// to the network device at one time. This is a compromise between RAM usage -// and performance. -#define TEMBOO_SEND_QUEUE_SIZE (32) -#endif - -class ChoreoInputSet; -class ChoreoOutputSet; -class ChoreoPreset; -class DataFormatter; - -class TembooSession { - public: - - //TembooSession constructor - //client: REQUIRED TCP/IP client object. Usually either an EthernetClient or a WiFiClient - //IPAddress: OPTIONAL IP address of the server to connect to. Usually only used for testing. - //port: OPTIONAL port number to use with the IPAddress. Usually only used for testing. - TembooSession(Client& client, IPAddress serverAddr=INADDR_NONE, uint16_t port=80); - - //executeChoreo sends a choreo execution request to the Temboo system. - // Does not wait for a response (that's a job for whoever owns the Client.) - //accountName: the name of the user's account at Temboo. - //appKeyName: the name of an application key in the user's account to use - // for this execution (analogous to a user name). - //appKeyValue: the value of the application key named in appKeyName. - // Used to authenticate the user (analogous to a password) - //path: The full path to the choreo to be executed (relative to the root of the - // user's account.) - //inputSet: the set of inputs needed by the choreo. - // May be an empty ChoreoInputSet. - //outputSet: the set of output filters to be applied to the choreo results. - // May be an empty ChoreoOutputSet - //preset: the ChoreoPreset to be used with the choreo execution. - // May be an empty ChoreoPreset. - int executeChoreo(const char* accountName, - const char* appKeyName, - const char* appKeyValue, - const char* path, - const ChoreoInputSet& inputSet, - const ChoreoOutputSet& outputSet, - const ChoreoPreset& preset); - - // setTime sets the current time in Unix timestamp format. Needed for execution request authentication. - // NOTE: This method is usually called by TembooChoreo.run() with the current time returned by - // an error response from the Temboo system, thus automatically setting the time. However, it - // MAY be called from user code if the particular board has a way of determining the current - // time in the proper format. - // currentTime: the number of seconds since 1970-01-01 00:00:00 UTC. - static void setTime(unsigned long currentTime); - - //getTime returns the current time in Unix timestamp format (seconds since 1970-01-01 00:00:00 UTC). - // Only valid after setTime has been called. - static unsigned long getTime(); - - private: - static unsigned long s_timeOffset; - - IPAddress m_addr; - uint16_t m_port; - - Client& m_client; - char m_sendQueue[TEMBOO_SEND_QUEUE_SIZE]; - size_t m_sendQueueDepth; - - // calculate the authentication code value of the formatted request body - // using the salted application key value as the key. - // Returns the number of characters processed (i.e. the length of the request body) - uint16_t getAuth(DataFormatter& fmt, const char* appKeyValue, const char* salt, char* hexAuth) const; - - - // queue an entire nul-terminated char array - // from RAM followed by a newline. - void qsendln(const char* str); - - // queue an entire nul-terminated char array - // from flash memory (PROGMEM) one byte at a time, - // followed by a newline. - void qsendlnProgmem(const char* str); - - // queue an entire nul-terminated char array - // from RAM one byte at a time. - void qsend(const char*); - - // queue an entire nul-terminated char array - // from flash memory (PROGMEM) one byte at a time. - void qsendProgmem(const char*); - - // queue a single character to be sent when the queue is full. - void qsend(char); - - // send the current contents of the send queue to the client. - void qflush(); - -}; - -#endif - diff --git a/include/Temboo/utility/TembooTags.h b/include/Temboo/utility/TembooTags.h @@ -1,37 +0,0 @@ -/* -############################################################################### -# -# Temboo CoAP Edge Device library for Arduino -# -# Copyright (C) 2014, 2015 Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef TEMBOOTAGS_H_ -#define TEMBOOTAGS_H_ - -#define TAG_REQUEST_ID ('R') -#define TAG_ACCOUNT_NAME ('N') -#define TAG_APP_KEY_NAME ('K') -#define TAG_TIME ('T') -#define TAG_AUTH ('A') -#define TAG_CHOREO_ID ('C') -#define TAG_DATA ('X') -#define TAG_END_REQUEST ('!') -#define TAG_ELEMENT_SEPARATOR ('|') -#define TAG_VALUE_SEPARATOR (':') - -#endif //TEMBOOTAGS_H_ diff --git a/include/Temboo/utility/TembooTimer.h b/include/Temboo/utility/TembooTimer.h @@ -1,62 +0,0 @@ -/* - ############################################################################### - # - # Temboo CoAP Edge Device library - # - # Copyright (C) 2015, Temboo Inc. - # - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - # - # http://www.apache.org/licenses/LICENSE-2.0 - # - # Unless required by applicable law or agreed to in writing, - # software distributed under the License is distributed on an - # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - # either express or implied. See the License for the specific - # language governing permissions and limitations under the License. - # - ############################################################################### - */ - -#ifndef TEMBOOTIMER_H_ -#define TEMBOOTIMER_H_ - -class TembooTimer { - public: - TembooTimer() { - this->m_startTimeMillis = 0; - this->m_durationMillis = 0; - } - - TembooTimer(uint32_t m_durationMillis) { - this->start(m_durationMillis); - } - - bool expired() { - return leftMillis() == 0; - } - - void start(uint32_t m_durationMillis) { - this->m_startTimeMillis = getMillis(); - this->m_durationMillis = m_durationMillis; - } - - uint32_t leftMillis() { - uint32_t elapsedMillis = getMillis() - this->m_startTimeMillis; - return elapsedMillis < this->m_durationMillis ? (this->m_durationMillis - elapsedMillis) : 0; - } - - protected: - uint32_t getMillis() { - return millis(); - } - - uint32_t m_startTimeMillis; - uint32_t m_durationMillis; - -}; - - -#endif /* TEMBOOTIMER_H_ */ diff --git a/include/Temboo/utility/TembooWebSocketRequestHandles.h b/include/Temboo/utility/TembooWebSocketRequestHandles.h @@ -1,66 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2016, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef __TembooWebSocketRequestHandles__ -#define __TembooWebSocketRequestHandles__ - -#include <Arduino.h> - -#if defined(__cplusplus) -extern "C" { -#endif - -typedef enum { - WS_GET_REQUEST = 0, - WS_SET_REQUEST, - WS_DATA_REQUEST, - WS_MESSAGE_REQUEST, - WS_RR_REQUEST, - WS_SESSION_ID_REQUEST, - WS_REQUEST_ERROR, - WS_UPDATE_CONNECTED, - WS_UPDATE_DISCONNECTED, - WS_NO_MESSAGE, - WS_INTERVAL_REQUEST -} WSMessageRequest; - -typedef struct TembooPinTable { - uint8_t pin; - uint32_t (*pinRead)(uint32_t pin); - void (*pinWrite)(uint32_t pin, int val); - int currentPinValue; - int defaultValue; -} TembooPinTable; - -void addWebSocketPinData(int pin, int pinVal, bool requestResponse); -void updateIntervalTime(int intervalTime); - -// Send frame -WSMessageRequest handleResponse(uint8_t* request, TembooPinTable* pinTable, int pinTableDepth, bool connectionStatus); -void logTembooDebug(const char *c); -#if defined(__cplusplus) -} -#endif - - - -#endif /* defined(__TembooWebSocketRequestHandles__) */ diff --git a/include/Temboo/utility/tmbhmac.h b/include/Temboo/utility/tmbhmac.h @@ -1,57 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef TMBHMAC_H_ -#define TMBHMAC_H_ -#include "tmbmd5.h" -#include "TembooGlobal.h" - -#define HMAC_HASH_SIZE_BYTES (MD5_HASH_SIZE_BYTES) -#define HMAC_BLOCK_SIZE_BYTES (MD5_BLOCK_SIZE_BYTES) - -#define HMAC_HEX_SIZE_BYTES (HMAC_HASH_SIZE_BYTES * 2) - -class HMAC -{ - public: - HMAC(); - HMAC(const uint8_t* key, uint32_t keyLength); - void init(const uint8_t* key, uint32_t keyLength); - void process(const uint8_t* msg, uint32_t msgLength); - void finish(uint8_t* dest); - void finishHex(char* dest); - enum { - HMAC_OK = 0, - HMAC_ERROR, - HMAC_FAIL_TESTVECTOR - }; - - private: - MD5 m_md5; - const uint8_t* m_key; - uint32_t m_keyLength; - - void constructKeyPad(uint8_t* dest, const uint8_t* key, uint32_t keyLength, uint8_t padByte); - void toHex(uint8_t* hmac, char* dest); -}; -#endif - diff --git a/include/Temboo/utility/tmbmd5.h b/include/Temboo/utility/tmbmd5.h @@ -1,72 +0,0 @@ -/* -############################################################################### -# -# Temboo Arduino library -# -# Copyright 2015, Temboo Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -# either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -# -############################################################################### -*/ - -#ifndef TMBMD5_H_ -#define TMBMD5_H_ - -#include <stdint.h> -#include "TembooGlobal.h" - -#define MD5_HASH_SIZE_BITS (128) -#define MD5_HASH_SIZE_BYTES (MD5_HASH_SIZE_BITS/8) - -#define MD5_BLOCK_SIZE_BITS (512) -#define MD5_BLOCK_SIZE_BYTES (MD5_BLOCK_SIZE_BITS/8) - - -#define ROL(x, y) ( (((uint32_t)(x)<<(uint32_t)((y)&31)) | (((uint32_t)(x)&0xFFFFFFFFUL)>>(uint32_t)(32-((y)&31)))) & 0xFFFFFFFFUL) -class MD5 { - -public: - MD5(); - void init(); - int process(const uint8_t* in, uint32_t inlen); - int finish(uint8_t* hash); - enum { - MD5_OK = 0, - MD5_ERROR, - MD5_INVALID_ARG, - MD5_FAIL_TESTVECTOR - }; - -private: - uint64_t m_msgLengthBits; - uint32_t m_state[4]; - uint32_t m_bufLength; - uint8_t m_buf[64]; - - int compress(const uint8_t* buf); - - inline uint32_t F_(uint32_t x, uint32_t y, uint32_t z) { return (z ^ (x & (y ^ z))); } - inline uint32_t G_(uint32_t x, uint32_t y, uint32_t z) { return (y ^ (z & (y ^ x))); } - inline uint32_t H_(uint32_t x, uint32_t y, uint32_t z) { return (x^y^z); } - inline uint32_t I_(uint32_t x, uint32_t y, uint32_t z) { return (y^(x|(~z))); } - - - inline void FF(uint32_t* a, uint32_t b, uint32_t c, uint32_t d, uint32_t M, uint32_t s, uint32_t t) { *a = (*a + F_(b,c,d) + M + t); *a = ROL(*a, s) + b; } - inline void GG(uint32_t* a, uint32_t b, uint32_t c, uint32_t d, uint32_t M, uint32_t s, uint32_t t) { *a = (*a + G_(b,c,d) + M + t); *a = ROL(*a, s) + b; } - inline void HH(uint32_t* a, uint32_t b, uint32_t c, uint32_t d, uint32_t M, uint32_t s, uint32_t t) { *a = (*a + H_(b,c,d) + M + t); *a = ROL(*a, s) + b; } - inline void II(uint32_t* a, uint32_t b, uint32_t c, uint32_t d, uint32_t M, uint32_t s, uint32_t t) { *a = (*a + I_(b,c,d) + M + t); *a = ROL(*a, s) + b; } - -}; - -#endif diff --git a/lib/Bridge/Bridge.cpp b/lib/Bridge/Bridge.cpp @@ -1,281 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "Bridge.h" - -BridgeClass::BridgeClass(Stream &_stream) : - index(0), stream(_stream), started(false), max_retries(0) { - // Empty -} - -void BridgeClass::begin() { - if (started) - return; - started = true; - - // Wait for U-boot to finish startup - do { - dropAll(); - delay(1000); - } while (stream.available() > 0); - - while (true) { - // Bridge interrupt: - // - Ask the bridge to close itself - uint8_t quit_cmd[] = {'X', 'X', 'X', 'X', 'X'}; - max_retries = 1; - transfer(quit_cmd, 5); - - // Bridge startup: - // - If the bridge is not running starts it safely - stream.print(CTRL_C); - delay(250); - stream.print(F("\n")); - delay(250); - stream.print(F("\n")); - delay(500); - // Wait for OpenWRT message - // "Press enter to activate console" - stream.print(F("run-bridge\n")); - delay(500); - dropAll(); - - // Reset the brigde to check if it is running - uint8_t cmd[] = {'X', 'X', '1', '0', '0'}; - uint8_t res[4]; - max_retries = 50; - uint16_t l = transfer(cmd, 5, res, 4); - if (l == TRANSFER_TIMEOUT) { - // Bridge didn't start... - // Maybe the board is starting-up? - - // Wait and retry - delay(1000); - continue; - } - if (res[0] != 0) - while (true); - - // Detect bridge version - if (l == 4) { - bridgeVersion = (res[1]-'0')*100 + (res[2]-'0')*10 + (res[3]-'0'); - } else { - // Bridge v1.0.0 didn't send any version info - bridgeVersion = 100; - } - - max_retries = 50; - return; - } -} - -void BridgeClass::put(const char *key, const char *value) { - // TODO: do it in a more efficient way - String cmd = "D"; - uint8_t res[1]; - cmd += key; - cmd += "\xFE"; - cmd += value; - transfer((uint8_t*)cmd.c_str(), cmd.length(), res, 1); -} - -unsigned int BridgeClass::get(const char *key, uint8_t *value, unsigned int maxlen) { - uint8_t cmd[] = {'d'}; - unsigned int l = transfer(cmd, 1, (uint8_t *)key, strlen(key), value, maxlen); - if (l < maxlen) - value[l] = 0; // Zero-terminate string - return l; -} - -#if defined(ARDUINO_ARCH_AVR) -// AVR use an optimized implementation of CRC -#include <util/crc16.h> -#else -// Generic implementation for non-AVR architectures -uint16_t _crc_ccitt_update(uint16_t crc, uint8_t data) -{ - data ^= crc & 0xff; - data ^= data << 4; - return ((((uint16_t)data << 8) | ((crc >> 8) & 0xff)) ^ - (uint8_t)(data >> 4) ^ - ((uint16_t)data << 3)); -} -#endif - -void BridgeClass::crcUpdate(uint8_t c) { - CRC = _crc_ccitt_update(CRC, c); -} - -void BridgeClass::crcReset() { - CRC = 0xFFFF; -} - -void BridgeClass::crcWrite() { - stream.write((char)(CRC >> 8)); - stream.write((char)(CRC & 0xFF)); -} - -bool BridgeClass::crcCheck(uint16_t _CRC) { - return CRC == _CRC; -} - -uint16_t BridgeClass::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) -{ - uint16_t len = len1 + len2 + len3; - uint8_t retries = 0; - for ( ; retries < max_retries; retries++, delay(100), dropAll() /* Delay for retransmission */) { - // Send packet - crcReset(); - stream.write((char)0xFF); // Start of packet (0xFF) - crcUpdate(0xFF); - stream.write((char)index); // Message index - crcUpdate(index); - stream.write((char)((len >> 8) & 0xFF)); // Message length (hi) - crcUpdate((len >> 8) & 0xFF); - stream.write((char)(len & 0xFF)); // Message length (lo) - crcUpdate(len & 0xFF); - for (uint16_t i = 0; i < len1; i++) { // Payload - stream.write((char)buff1[i]); - crcUpdate(buff1[i]); - } - for (uint16_t i = 0; i < len2; i++) { // Payload - stream.write((char)buff2[i]); - crcUpdate(buff2[i]); - } - for (uint16_t i = 0; i < len3; i++) { // Payload - stream.write((char)buff3[i]); - crcUpdate(buff3[i]); - } - crcWrite(); // CRC - - // Wait for ACK in 100ms - if (timedRead(100) != 0xFF) - continue; - crcReset(); - crcUpdate(0xFF); - - // Check packet index - if (timedRead(5) != index) - continue; - crcUpdate(index); - - // Recv len - int lh = timedRead(10); - if (lh < 0) - continue; - crcUpdate(lh); - int ll = timedRead(10); - if (ll < 0) - continue; - crcUpdate(ll); - uint16_t l = lh; - l <<= 8; - l += ll; - - // Recv data - for (uint16_t i = 0; i < l; i++) { - // Cut received data if rxbuffer is too small - if (i >= rxlen) - break; - int c = timedRead(5); - if (c < 0) - continue; - rxbuff[i] = c; - crcUpdate(c); - } - - // Check CRC - int crc_hi = timedRead(5); - if (crc_hi < 0) - continue; - int crc_lo = timedRead(5); - if (crc_lo < 0) - continue; - if (!crcCheck((crc_hi << 8) + crc_lo)) - continue; - - // Increase index - index++; - - // Return bytes received - if (l > rxlen) - return rxlen; - return l; - } - - // Max retries exceeded - return TRANSFER_TIMEOUT; -} - -int BridgeClass::timedRead(unsigned int timeout) { - int c; - unsigned long _startMillis = millis(); - do { - c = stream.read(); - if (c >= 0) return c; - } while (millis() - _startMillis < timeout); - return -1; // -1 indicates timeout -} - -void BridgeClass::dropAll() { - while (stream.available() > 0) { - stream.read(); - } -} - -#if defined(ARDUINO_ARCH_SAM) -#include <Reset.h> -#endif - -#if defined(ARDUINO_ARCH_SAM) -void checkForRemoteSketchUpdate(uint8_t pin) { - // The host force pin LOW to signal that a new sketch is coming - pinMode(pin, INPUT_PULLUP); - delay(50); - if (digitalRead(pin) == LOW) { - initiateReset(1); - while (true) - ; // Wait for reset to SAM-BA - } - - // Restore in standard state - pinMode(pin, INPUT); -} -#else -void checkForRemoteSketchUpdate(uint8_t /* pin */) { - // Empty, bootloader is enough. -} -#endif - -// Bridge instance -#if defined(SERIAL_PORT_LINUXBRIDGE) -SerialBridgeClass Bridge(SERIAL_PORT_LINUXBRIDGE); -#elif defined(SERIAL_PORT_HARDWARE) -SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE); -#elif defined(SERIAL_PORT_HARDWARE_OPEN) -SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE_OPEN); -#elif defined(__AVR_ATmega32U4__) // Legacy fallback -// Leonardo variants (where HardwareSerial is Serial1) -SerialBridgeClass Bridge(Serial1); -#else -SerialBridgeClass Bridge(Serial); -#endif - diff --git a/lib/Bridge/BridgeClient.cpp b/lib/Bridge/BridgeClient.cpp @@ -1,207 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include <BridgeClient.h> - -BridgeClient::BridgeClient(uint8_t _h, BridgeClass &_b) : - bridge(_b), handle(_h), opened(true), buffered(0) { -} - -BridgeClient::BridgeClient(BridgeClass &_b) : - bridge(_b), handle(0), opened(false), buffered(0) { -} - -BridgeClient::~BridgeClient() { -} - -BridgeClient& BridgeClient::operator=(const BridgeClient &_x) { - opened = _x.opened; - handle = _x.handle; - return *this; -} - -void BridgeClient::stop() { - if (opened) { - uint8_t cmd[] = {'j', handle}; - bridge.transfer(cmd, 2); - } - opened = false; - buffered = 0; - readPos = 0; -} - -void BridgeClient::doBuffer() { - // If there are already char in buffer exit - if (buffered > 0) - return; - - // Try to buffer up to 32 characters - readPos = 0; - uint8_t cmd[] = {'K', handle, sizeof(buffer)}; - buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); -} - -int BridgeClient::available() { - // Look if there is new data available - doBuffer(); - return buffered; -} - -int BridgeClient::read() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else { - buffered--; - return buffer[readPos++]; - } -} - -int BridgeClient::read(uint8_t *buff, size_t size) { - size_t readed = 0; - do { - if (buffered == 0) { - doBuffer(); - if (buffered == 0) - return readed; - } - buff[readed++] = buffer[readPos++]; - buffered--; - } while (readed < size); - return readed; -} - -int BridgeClient::peek() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else - return buffer[readPos]; -} - -size_t BridgeClient::write(uint8_t c) { - if (!opened) - return 0; - uint8_t cmd[] = {'l', handle, c}; - bridge.transfer(cmd, 3); - return 1; -} - -size_t BridgeClient::write(const uint8_t *buf, size_t size) { - if (!opened) - return 0; - uint8_t cmd[] = {'l', handle}; - bridge.transfer(cmd, 2, buf, size, NULL, 0); - return size; -} - -void BridgeClient::flush() { -} - -uint8_t BridgeClient::connected() { - if (!opened) - return false; - // Client is "connected" if it has unread bytes - if (available()) - return true; - - uint8_t cmd[] = {'L', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, res, 1); - return (res[0] == 1); -} - -int BridgeClient::connect(IPAddress ip, uint16_t port) { - String address; - address.reserve(18); - address += ip[0]; - address += '.'; - address += ip[1]; - address += '.'; - address += ip[2]; - address += '.'; - address += ip[3]; - return connect(address.c_str(), port); -} - -int BridgeClient::connect(const char *host, uint16_t port) { - uint8_t tmp[] = { - 'C', - static_cast<uint8_t>(port >> 8), - static_cast<uint8_t>(port) - }; - uint8_t res[1]; - int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); - if (l == 0) - return 0; - handle = res[0]; - - // wait for connection - uint8_t tmp2[] = { 'c', handle }; - uint8_t res2[1]; - while (true) { - bridge.transfer(tmp2, 2, res2, 1); - if (res2[0] == 0) - break; - delay(1); - } - opened = true; - - // check for successful connection - if (connected()) - return 1; - - stop(); - handle = 0; - return 0; -} - -int BridgeClient::connectSSL(const char *host, uint16_t port) { - if (bridge.getBridgeVersion() < 161) - return -1; - - uint8_t tmp[] = { - 'Z', - static_cast<uint8_t>(port >> 8), - static_cast<uint8_t>(port) - }; - uint8_t res[1]; - int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); - if (l == 0) - return 0; - handle = res[0]; - - // wait for connection - uint8_t tmp2[] = { 'c', handle }; - uint8_t res2[1]; - while (true) { - bridge.transfer(tmp2, 2, res2, 1); - if (res2[0] == 0) - break; - delay(1); - } - opened = true; - - // check for successful connection - if (connected()) - return 1; - - stop(); - handle = 0; - return 0; -}- \ No newline at end of file diff --git a/lib/Bridge/BridgeSSLClient.cpp b/lib/Bridge/BridgeSSLClient.cpp @@ -1,36 +0,0 @@ -/* - Copyright (c) 2016 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include <BridgeSSLClient.h> - -BridgeSSLClient::BridgeSSLClient(uint8_t _h, BridgeClass &_b) : - BridgeClient(_h, _b) -{ -} - -BridgeSSLClient::BridgeSSLClient(BridgeClass &_b): - BridgeClient(_b) -{ -} - -BridgeSSLClient::~BridgeSSLClient() { -} - -int BridgeSSLClient::connect(const char *host, uint16_t port) { - return BridgeClient::connectSSL(host, port); -}- \ No newline at end of file diff --git a/lib/Bridge/BridgeServer.cpp b/lib/Bridge/BridgeServer.cpp @@ -1,54 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include <BridgeServer.h> -#include <BridgeClient.h> - -BridgeServer::BridgeServer(uint16_t _p, BridgeClass &_b) : - bridge(_b), port(_p), listening(false), useLocalhost(false) { -} - -void BridgeServer::begin() { - uint8_t tmp[] = { - 'N', - static_cast<uint8_t>(port >> 8), - static_cast<uint8_t>(port) - }; - uint8_t res[1]; - String address = F("127.0.0.1"); - if (!useLocalhost) - address = F("0.0.0.0"); - bridge.transfer(tmp, 3, (const uint8_t *)address.c_str(), address.length(), res, 1); - listening = (res[0] == 1); -} - -BridgeClient BridgeServer::accept() { - uint8_t cmd[] = {'k'}; - uint8_t res[1]; - unsigned int l = bridge.transfer(cmd, 1, res, 1); - if (l == 0) - return BridgeClient(); - return BridgeClient(res[0]); -} - -size_t BridgeServer::write(uint8_t c) { - uint8_t cmd[] = { 'b', c }; - bridge.transfer(cmd, 2); - return 1; -} - diff --git a/lib/Bridge/BridgeUdp.cpp b/lib/Bridge/BridgeUdp.cpp @@ -1,198 +0,0 @@ -/* - Copyright (c) 2015 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "BridgeUdp.h" - -BridgeUDP::BridgeUDP(BridgeClass &_b) : - bridge(_b), opened(false), avail(0), buffered(0), readPos(0) { -} - -/* Start BridgeUDP socket, listening at local port PORT */ -uint8_t BridgeUDP::begin(uint16_t port) { - if (opened) - return 0; - uint8_t cmd[] = {'e', (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; - uint8_t res[2]; - bridge.transfer(cmd, 3, res, 2); - if (res[1] == 1) // Error... - return 0; - handle = res[0]; - opened = true; - return 1; -} - -/* Release any resources being used by this BridgeUDP instance */ -void BridgeUDP::stop() -{ - if (!opened) - return; - uint8_t cmd[] = {'q', handle}; - bridge.transfer(cmd, 2); - opened = false; -} - -int BridgeUDP::beginPacket(const char *host, uint16_t port) -{ - if (!opened) - return 0; - uint8_t cmd[] = {'E', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; - uint8_t res[1]; - bridge.transfer(cmd, 4, (const uint8_t *)host, strlen(host), res, 1); - return res[0]; // 1=Success, 0=Error -} - -int BridgeUDP::beginBroadcastPacket(uint16_t port) -{ - if (!opened) - return 0; - uint8_t cmd[] = {'v', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; - uint8_t res[1]; - bridge.transfer(cmd, 4, res, 1); - return res[0]; // 1=Success, 0=Error -} - -int BridgeUDP::beginPacket(IPAddress ip, uint16_t port) -{ - if (!opened) - return 0; - String address; - address.reserve(18); - address += ip[0]; - address += '.'; - address += ip[1]; - address += '.'; - address += ip[2]; - address += '.'; - address += ip[3]; - return beginPacket(address.c_str(), port); -} - -int BridgeUDP::endPacket() -{ - if (!opened) - return 0; - uint8_t cmd[] = {'H', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, res, 1); - return res[0]; // 1=Success, 0=Error -} - -size_t BridgeUDP::write(const uint8_t *buffer, size_t size) -{ - if (!opened) - return 0; - uint8_t cmd[] = {'h', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, buffer, size, res, 1); - return res[0]; // 1=Success, 0=Error -} - -int BridgeUDP::parsePacket() -{ - if (!opened) - return 0; - buffered = 0; - readPos = 0; - uint8_t cmd[] = {'Q', handle}; - uint8_t res[3]; - bridge.transfer(cmd, 2, res, 3); - if (res[0] == 0) { - // There aren't any packets available - return 0; - } - avail = (res[1] << 8) + res[2]; - return 1; -} - -void BridgeUDP::doBuffer() { - // If there are already char in buffer exit - if (buffered > 0) - return; - if (avail == 0) - return; - - // Try to buffer up to 32 characters - readPos = 0; - uint8_t cmd[] = {'u', handle, sizeof(buffer)}; - buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); -} - -int BridgeUDP::read() -{ - if (!opened) - return -1; - doBuffer(); - if (buffered == 0) { - return -1; // no chars available - } - buffered--; - avail--; - return buffer[readPos++]; -} - -int BridgeUDP::read(unsigned char* buff, size_t size) -{ - if (!opened) - return -1; - size_t readed = 0; - do { - if (buffered == 0) { - doBuffer(); - if (buffered == 0) - return readed; - } - buff[readed++] = buffer[readPos++]; - buffered--; - avail--; - } while (readed < size); - return readed; -} - -int BridgeUDP::peek() -{ - if (!opened) - return -1; - doBuffer(); - if (buffered == 0) - return -1; // no chars available - return buffer[readPos]; -} - -IPAddress BridgeUDP::remoteIP() -{ - if (!opened) - return -1; - uint8_t cmd[] = {'T', handle}; - uint8_t res[7]; - bridge.transfer(cmd, 2, res, 7); - if (res[0] == 0) - return IPAddress(0,0,0,0); - return IPAddress(res[1], res[2], res[3], res[4]); -} - -uint16_t BridgeUDP::remotePort() -{ - if (!opened) - return -1; - uint8_t cmd[] = {'T', handle}; - uint8_t res[7]; - bridge.transfer(cmd, 2, res, 7); - if (res[0] == 0) - return 0; - return (res[5] << 8) + res[6]; -} diff --git a/lib/Bridge/Console.cpp b/lib/Bridge/Console.cpp @@ -1,150 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include <Console.h> - -// Default constructor uses global Bridge instance -ConsoleClass::ConsoleClass() : - bridge(Bridge), inBuffered(0), inReadPos(0), inBuffer(NULL), - autoFlush(true) -{ - // Empty -} - -// Constructor with a user provided BridgeClass instance -ConsoleClass::ConsoleClass(BridgeClass &_b) : - bridge(_b), inBuffered(0), inReadPos(0), inBuffer(NULL), - autoFlush(true) -{ - // Empty -} - -ConsoleClass::~ConsoleClass() { - end(); -} - -size_t ConsoleClass::write(uint8_t c) { - if (autoFlush) { - uint8_t tmp[] = { 'P', c }; - bridge.transfer(tmp, 2); - } else { - outBuffer[outBuffered++] = c; - if (outBuffered == outBufferSize) - flush(); - } - return 1; -} - -size_t ConsoleClass::write(const uint8_t *buff, size_t size) { - if (autoFlush) { - uint8_t tmp[] = { 'P' }; - bridge.transfer(tmp, 1, buff, size, NULL, 0); - } else { - size_t sent = size; - while (sent > 0) { - outBuffer[outBuffered++] = *buff++; - sent--; - if (outBuffered == outBufferSize) - flush(); - } - } - return size; -} - -void ConsoleClass::flush() { - if (autoFlush) - return; - - bridge.transfer(outBuffer, outBuffered); - outBuffered = 1; -} - -void ConsoleClass::noBuffer() { - if (autoFlush) - return; - delete[] outBuffer; - autoFlush = true; -} - -void ConsoleClass::buffer(uint8_t size) { - noBuffer(); - if (size == 0) - return; - outBuffer = new uint8_t[size + 1]; - outBuffer[0] = 'P'; // WRITE tag - outBufferSize = size + 1; - outBuffered = 1; - autoFlush = false; -} - -bool ConsoleClass::connected() { - uint8_t tmp = 'a'; - bridge.transfer(&tmp, 1, &tmp, 1); - return tmp == 1; -} - -int ConsoleClass::available() { - // Look if there is new data available - doBuffer(); - return inBuffered; -} - -int ConsoleClass::read() { - doBuffer(); - if (inBuffered == 0) - return -1; // no chars available - else { - inBuffered--; - return inBuffer[inReadPos++]; - } -} - -int ConsoleClass::peek() { - doBuffer(); - if (inBuffered == 0) - return -1; // no chars available - else - return inBuffer[inReadPos]; -} - -void ConsoleClass::doBuffer() { - // If there are already char in buffer exit - if (inBuffered > 0) - return; - - // Try to buffer up to 32 characters - inReadPos = 0; - uint8_t tmp[] = { 'p', BUFFER_SIZE }; - inBuffered = bridge.transfer(tmp, 2, inBuffer, BUFFER_SIZE); -} - -void ConsoleClass::begin() { - bridge.begin(); - end(); - inBuffer = new uint8_t[BUFFER_SIZE]; -} - -void ConsoleClass::end() { - noBuffer(); - if (inBuffer) { - delete[] inBuffer; - inBuffer = NULL; - } -} - -ConsoleClass Console; diff --git a/lib/Bridge/FileIO.cpp b/lib/Bridge/FileIO.cpp @@ -1,283 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include <FileIO.h> - -namespace BridgeLib { - -File::File(BridgeClass &b) : bridge(b), mode(255) { - // Empty -} - -File::File(const char *_filename, uint8_t _mode, BridgeClass &b) : bridge(b), mode(_mode) { - filename = _filename; - uint8_t modes[] = {'r', 'w', 'a'}; - uint8_t cmd[] = {'F', modes[mode]}; - uint8_t res[2]; - dirPosition = 1; - bridge.transfer(cmd, 2, (uint8_t*)filename.c_str(), filename.length(), res, 2); - if (res[0] != 0) { // res[0] contains error code - mode = 255; // In case of error keep the file closed - return; - } - handle = res[1]; - buffered = 0; -} - -File::operator bool() { - return (mode != 255); -} - -File::~File() { - close(); -} - -size_t File::write(uint8_t c) { - return write(&c, 1); -} - -size_t File::write(const uint8_t *buf, size_t size) { - if (mode == 255) - return -1; - uint8_t cmd[] = {'g', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, buf, size, res, 1); - if (res[0] != 0) // res[0] contains error code - return -res[0]; - return size; -} - -int File::read() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else { - buffered--; - return buffer[readPos++]; - } -} - -int File::peek() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else - return buffer[readPos]; -} - -boolean File::seek(uint32_t position) { - uint8_t cmd[] = { - 's', - handle, - static_cast<uint8_t>(position >> 24), - static_cast<uint8_t>(position >> 16), - static_cast<uint8_t>(position >> 8), - static_cast<uint8_t>(position) - }; - uint8_t res[1]; - bridge.transfer(cmd, 6, res, 1); - if (res[0] == 0) { - // If seek succeed then flush buffers - buffered = 0; - return true; - } - return false; -} - -uint32_t File::position() { - uint8_t cmd[] = {'S', handle}; - uint8_t res[5]; - bridge.transfer(cmd, 2, res, 5); - //err = res[0]; // res[0] contains error code - uint32_t pos; - pos = static_cast<uint32_t>(res[1]) << 24; - pos += static_cast<uint32_t>(res[2]) << 16; - pos += static_cast<uint32_t>(res[3]) << 8; - pos += static_cast<uint32_t>(res[4]); - return pos - buffered; -} - -void File::doBuffer() { - // If there are already char in buffer exit - if (buffered > 0) - return; - - // Try to buffer up to BUFFER_SIZE characters - readPos = 0; - uint8_t cmd[] = {'G', handle, BUFFER_SIZE - 1}; - uint16_t readed = bridge.transfer(cmd, 3, buffer, BUFFER_SIZE); - //err = buff[0]; // First byte is error code - if (readed == BridgeClass::TRANSFER_TIMEOUT || readed == 0) { - // transfer failed to retrieve any data - buffered = 0; - } else { - // transfer retrieved at least one byte of data so skip the error code character - readPos++; - buffered = readed - 1; - } -} - -int File::available() { - // Look if there is new data available - doBuffer(); - return buffered; -} - -void File::flush() { -} - -int File::read(void *buff, uint16_t nbyte) { - uint16_t n = 0; - uint8_t *p = reinterpret_cast<uint8_t *>(buff); - while (n < nbyte) { - if (buffered == 0) { - doBuffer(); - if (buffered == 0) - break; - } - *p++ = buffer[readPos++]; - buffered--; - n++; - } - return n; -} - -uint32_t File::size() { - if (bridge.getBridgeVersion() < 101) - return 0; - uint8_t cmd[] = {'t', handle}; - uint8_t buff[5]; - bridge.transfer(cmd, 2, buff, 5); - //err = res[0]; // First byte is error code - uint32_t res; - res = ((uint32_t)buff[1]) << 24; - res |= ((uint32_t)buff[2]) << 16; - res |= ((uint32_t)buff[3]) << 8; - res |= ((uint32_t)buff[4]); - return res; -} - -void File::close() { - if (mode == 255) - return; - uint8_t cmd[] = {'f', handle}; - uint8_t ret[1]; - bridge.transfer(cmd, 2, ret, 1); - mode = 255; -} - -const char *File::name() { - return filename.c_str(); -} - - -boolean File::isDirectory() { - uint8_t res[1]; - uint8_t cmd[] = {'i'}; - if (mode != 255) - return 0; - - bridge.transfer(cmd, 1, (uint8_t *)filename.c_str(), filename.length(), res, 1); - return res[0]; -} - - -File File::openNextFile(uint8_t mode) { - Process awk; - char tmp; - String command; - String filepath; - if (dirPosition == 0xFFFF) return File(); - - command = "ls "; - command += filename; - command += " | awk 'NR=="; - command += dirPosition; - command += "'"; - - awk.runShellCommand(command); - - while (awk.running()); - - command = ""; - - while (awk.available()) { - tmp = awk.read(); - if (tmp != '\n') command += tmp; - } - if (command.length() == 0) - return File(); - dirPosition++; - filepath = filename + "/" + command; - return File(filepath.c_str(), mode); - -} - -void File::rewindDirectory(void) { - dirPosition = 1; -} - - - - - - -boolean FileSystemClass::begin() { - return true; -} - -File FileSystemClass::open(const char *filename, uint8_t mode) { - return File(filename, mode); -} - -boolean FileSystemClass::exists(const char *filepath) { - Process ls; - ls.begin("ls"); - ls.addParameter(filepath); - int res = ls.run(); - return (res == 0); -} - -boolean FileSystemClass::mkdir(const char *filepath) { - Process mk; - mk.begin("mkdir"); - mk.addParameter("-p"); - mk.addParameter(filepath); - int res = mk.run(); - return (res == 0); -} - -boolean FileSystemClass::remove(const char *filepath) { - Process rm; - rm.begin("rm"); - rm.addParameter(filepath); - int res = rm.run(); - return (res == 0); -} - -boolean FileSystemClass::rmdir(const char *filepath) { - Process rm; - rm.begin("rmdir"); - rm.addParameter(filepath); - int res = rm.run(); - return (res == 0); -} - -FileSystemClass FileSystem; - -} diff --git a/lib/Bridge/HttpClient.cpp b/lib/Bridge/HttpClient.cpp @@ -1,204 +0,0 @@ -/* - Copyright (c) 2013-2014 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "HttpClient.h" - -HttpClient::HttpClient() : - insecure(false) { - // Empty -} - -unsigned int HttpClient::get(String &url) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addHeader(); - addParameter(url); - return run(); -} - -unsigned int HttpClient::get(const char *url) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addHeader(); - addParameter(url); - return run(); -} - -void HttpClient::getAsynchronously(String &url) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addHeader(); - addParameter(url); - runAsynchronously(); -} - -void HttpClient::getAsynchronously(const char *url) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addHeader(); - addParameter(url); - runAsynchronously(); -} - -unsigned int HttpClient::post(String &url, String &data) { - return post(url.c_str(), data.c_str()); -} - -unsigned int HttpClient::post(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("POST"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - return run(); -} - -void HttpClient::postAsynchronously(String &url, String &data) { - postAsynchronously(url.c_str(), data.c_str()); -} - -void HttpClient::postAsynchronously(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("POST"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - runAsynchronously(); -} - -unsigned int HttpClient::patch(String &url, String &data) { - return patch(url.c_str(), data.c_str()); -} - -unsigned int HttpClient::patch(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("PATCH"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - return run(); -} - -void HttpClient::patchAsynchronously(String &url, String &data) { - patchAsynchronously(url.c_str(), data.c_str()); -} - -void HttpClient::patchAsynchronously(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("PATCH"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - runAsynchronously(); -} - -unsigned int HttpClient::put(String &url, String &data) { - return put(url.c_str(), data.c_str()); -} - -unsigned int HttpClient::put(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("PUT"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - return run(); -} - -void HttpClient::putAsynchronously(String &url, String &data) { - putAsynchronously(url.c_str(), data.c_str()); -} - -void HttpClient::putAsynchronously(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("PUT"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - runAsynchronously(); -} - -boolean HttpClient::ready() { - return !running(); -} - -unsigned int HttpClient::getResult() { - return exitValue(); -} - -void HttpClient::noCheckSSL() { - insecure = true; -} - -void HttpClient::checkSSL() { - insecure = false; -} - -void HttpClient::setHeader(String &header) { - this->header = header; -} - -void HttpClient::setHeader(const char * header) { - this->header = String(header); -} - -void HttpClient::addHeader() { - if (header.length() > 0) { - addParameter("--header"); - addParameter(header); - } -} - diff --git a/lib/Bridge/Mailbox.cpp b/lib/Bridge/Mailbox.cpp @@ -1,56 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include <Mailbox.h> - -unsigned int MailboxClass::readMessage(uint8_t *buff, unsigned int size) { - uint8_t tmp[] = { 'm' }; - return bridge.transfer(tmp, 1, buff, size); -} - -void MailboxClass::readMessage(String &str, unsigned int maxLength) { - uint8_t tmp[] = { 'm' }; - // XXX: Is there a better way to create the string? - uint8_t buff[maxLength + 1]; - int l = bridge.transfer(tmp, 1, buff, maxLength); - buff[l] = 0; - str = (const char *)buff; -} - -void MailboxClass::writeMessage(const uint8_t *buff, unsigned int size) { - uint8_t cmd[] = {'M'}; - bridge.transfer(cmd, 1, buff, size, NULL, 0); -} - -void MailboxClass::writeMessage(const String& str) { - writeMessage((uint8_t*) str.c_str(), str.length()); -} - -void MailboxClass::writeJSON(const String& str) { - uint8_t cmd[] = {'J'}; - bridge.transfer(cmd, 1, (uint8_t*) str.c_str(), str.length(), NULL, 0); -} - -unsigned int MailboxClass::messageAvailable() { - uint8_t tmp[] = {'n'}; - uint8_t res[2]; - bridge.transfer(tmp, 1, res, 2); - return (res[0] << 8) + res[1]; -} - -MailboxClass Mailbox(Bridge); diff --git a/lib/Bridge/Process.cpp b/lib/Bridge/Process.cpp @@ -1,142 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include <Process.h> - -Process::~Process() { - close(); -} - -size_t Process::write(uint8_t c) { - uint8_t cmd[] = {'I', handle, c}; - bridge.transfer(cmd, 3); - return 1; -} - -void Process::flush() { -} - -int Process::available() { - // Look if there is new data available - doBuffer(); - return buffered; -} - -int Process::read() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else { - buffered--; - return buffer[readPos++]; - } -} - -int Process::peek() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else - return buffer[readPos]; -} - -void Process::doBuffer() { - // If there are already char in buffer exit - if (buffered > 0) - return; - - // Try to buffer up to 32 characters - readPos = 0; - uint8_t cmd[] = {'O', handle, sizeof(buffer)}; - buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); -} - -void Process::begin(const String &command) { - close(); - cmdline = new String(command); -} - -void Process::addParameter(const String &param) { - *cmdline += "\xFE"; - *cmdline += param; -} - -void Process::runAsynchronously() { - uint8_t cmd[] = {'R'}; - uint8_t res[2]; - bridge.transfer(cmd, 1, (uint8_t*)cmdline->c_str(), cmdline->length(), res, 2); - handle = res[1]; - - delete cmdline; - cmdline = NULL; - - if (res[0] == 0) // res[0] contains error code - started = true; -} - -boolean Process::running() { - uint8_t cmd[] = {'r', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, res, 1); - return (res[0] == 1); -} - -unsigned int Process::exitValue() { - uint8_t cmd[] = {'W', handle}; - uint8_t res[2]; - bridge.transfer(cmd, 2, res, 2); - return (res[0] << 8) + res[1]; -} - -unsigned int Process::run() { - runAsynchronously(); - while (running()) - delay(100); - return exitValue(); -} - -void Process::close() { - if (started) { - uint8_t cmd[] = {'w', handle}; - bridge.transfer(cmd, 2); - } - started = false; -} - -unsigned int Process::runShellCommand(const String &command) { - runShellCommandAsynchronously(command); - while (running()) - delay(100); - return exitValue(); -} - -void Process::runShellCommandAsynchronously(const String &command) { - begin("/bin/ash"); - addParameter("-c"); - addParameter(command); - runAsynchronously(); -} - -// This method is currently unused -//static unsigned int __commandOutputAvailable(uint8_t handle) { -// uint8_t cmd[] = {'o', handle}; -// uint8_t res[1]; -// Bridge.transfer(cmd, 2, res, 1); -// return res[0]; -//} - diff --git a/lib/Esplora/Esplora.cpp b/lib/Esplora/Esplora.cpp @@ -1,184 +0,0 @@ -/* - Esplora.cpp - Arduino Esplora board library - Written by Enrico Gueli - Copyright (c) 2012 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - - -#include "Esplora.h" - -_Esplora Esplora; - -/* - * The following constants tell, for each accelerometer - * axis, which values are returned when the axis measures - * zero acceleration. - */ -const int ACCEL_ZERO_X = 320; -const int ACCEL_ZERO_Y = 330; -const int ACCEL_ZERO_Z = 310; - -const byte MUX_ADDR_PINS[] = { A0, A1, A2, A3 }; -const byte MUX_COM_PIN = A4; - -const int JOYSTICK_DEAD_ZONE = 100; - -const byte RED_PIN = 5; -const byte BLUE_PIN = 9; -const byte GREEN_PIN = 10; - -const byte BUZZER_PIN = 6; - -// non-multiplexer Esplora pins: -// Accelerometer: x-A5, y-A11, z-A6 -// External outputs: D3, D11 -// Buzzer: D6 -// RGB Led: red-D5, green-D10, blue-D9 -// Led 13: D13 - -const byte ACCEL_X_PIN = A5; -const byte ACCEL_Y_PIN = A11; -const byte ACCEL_Z_PIN = A6; - -const byte LED_PIN = 13; - -_Esplora::_Esplora() { - for (byte p=0; p<4; p++) { - pinMode(MUX_ADDR_PINS[p], OUTPUT); - } - pinMode(RED_PIN, OUTPUT); - pinMode(GREEN_PIN, OUTPUT); - pinMode(BLUE_PIN, OUTPUT); -} - -unsigned int _Esplora::readChannel(byte channel) { - digitalWrite(MUX_ADDR_PINS[0], (channel & 1) ? HIGH : LOW); - digitalWrite(MUX_ADDR_PINS[1], (channel & 2) ? HIGH : LOW); - digitalWrite(MUX_ADDR_PINS[2], (channel & 4) ? HIGH : LOW); - digitalWrite(MUX_ADDR_PINS[3], (channel & 8) ? HIGH : LOW); - // workaround to cope with lack of pullup resistor on joystick switch - if (channel == CH_JOYSTICK_SW) { - pinMode(MUX_COM_PIN, INPUT_PULLUP); - unsigned int joystickSwitchState = (digitalRead(MUX_COM_PIN) == HIGH) ? 1023 : 0; - digitalWrite(MUX_COM_PIN, LOW); - return joystickSwitchState; - } - else - return analogRead(MUX_COM_PIN); -} - -boolean _Esplora::joyLowHalf(byte joyCh) { - return (readChannel(joyCh) < 512 - JOYSTICK_DEAD_ZONE) - ? LOW : HIGH; -} - -boolean _Esplora::joyHighHalf(byte joyCh) { - return (readChannel(joyCh) > 512 + JOYSTICK_DEAD_ZONE) - ? LOW : HIGH; -} - -boolean _Esplora::readButton(byte ch) { - if (ch >= SWITCH_1 && ch <= SWITCH_4) { - ch--; - } - - switch(ch) { - case JOYSTICK_RIGHT: - return joyLowHalf(CH_JOYSTICK_X); - case JOYSTICK_LEFT: - return joyHighHalf(CH_JOYSTICK_X); - case JOYSTICK_UP: - return joyLowHalf(CH_JOYSTICK_Y); - case JOYSTICK_DOWN: - return joyHighHalf(CH_JOYSTICK_Y); - } - - unsigned int val = readChannel(ch); - return (val > 512) ? HIGH : LOW; -} - -boolean _Esplora::readJoystickButton() { - if (readChannel(CH_JOYSTICK_SW) == 1023) { - return HIGH; - } else if (readChannel(CH_JOYSTICK_SW) == 0) { - return LOW; - } -} - - -void _Esplora::writeRGB(byte r, byte g, byte b) { - writeRed(r); - writeGreen(g); - writeBlue(b); -} - -#define RGB_FUNC(name, pin, lastVar) \ -void _Esplora::write##name(byte val) { \ - if (val == lastVar) \ - return; \ - analogWrite(pin, val); \ - lastVar = val; \ - delay(5); \ -} \ -\ -byte _Esplora::read##name() { \ - return lastVar; \ -} - -RGB_FUNC(Red, RED_PIN, lastRed) -RGB_FUNC(Green, GREEN_PIN, lastGreen) -RGB_FUNC(Blue, BLUE_PIN, lastBlue) - -void _Esplora::tone(unsigned int freq) { - if (freq > 0) - ::tone(BUZZER_PIN, freq); - else - ::noTone(BUZZER_PIN); -} - -void _Esplora::tone(unsigned int freq, unsigned long duration) { - if (freq > 0) - ::tone(BUZZER_PIN, freq, duration); - else - ::noTone(BUZZER_PIN); -} - -void _Esplora::noTone() { - ::noTone(BUZZER_PIN); -} - -int _Esplora::readTemperature(const byte scale) { - long rawT = readChannel(CH_TEMPERATURE); - if (scale == DEGREES_C) { - return (int)((rawT * 500 / 1024) - 50); - } - else if (scale == DEGREES_F) { - return (int)((rawT * 450 / 512 ) - 58); - } - else { - return readTemperature(DEGREES_C); - } -} - -int _Esplora::readAccelerometer(const byte axis) { - switch (axis) { - case X_AXIS: return analogRead(ACCEL_X_PIN) - ACCEL_ZERO_X; - case Y_AXIS: return analogRead(ACCEL_Y_PIN) - ACCEL_ZERO_Y; - case Z_AXIS: return analogRead(ACCEL_Z_PIN) - ACCEL_ZERO_Z; - default: return 0; - } -} diff --git a/lib/HID/HID.cpp b/lib/HID/HID.cpp @@ -1,162 +0,0 @@ -/* - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - Permission to use, copy, modify, and/or distribute this software for - any purpose with or without fee is hereby granted, provided that the - above copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL - WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR - BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES - OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, - WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, - ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS - SOFTWARE. - */ - -#include "HID.h" - -#if defined(USBCON) - -HID_& HID() -{ - static HID_ obj; - return obj; -} - -int HID_::getInterface(uint8_t* interfaceCount) -{ - *interfaceCount += 1; // uses 1 - HIDDescriptor hidInterface = { - D_INTERFACE(pluggedInterface, 1, USB_DEVICE_CLASS_HUMAN_INTERFACE, HID_SUBCLASS_NONE, HID_PROTOCOL_NONE), - D_HIDREPORT(descriptorSize), - D_ENDPOINT(USB_ENDPOINT_IN(pluggedEndpoint), USB_ENDPOINT_TYPE_INTERRUPT, USB_EP_SIZE, 0x01) - }; - return USB_SendControl(0, &hidInterface, sizeof(hidInterface)); -} - -int HID_::getDescriptor(USBSetup& setup) -{ - // Check if this is a HID Class Descriptor request - if (setup.bmRequestType != REQUEST_DEVICETOHOST_STANDARD_INTERFACE) { return 0; } - if (setup.wValueH != HID_REPORT_DESCRIPTOR_TYPE) { return 0; } - - // In a HID Class Descriptor wIndex cointains the interface number - if (setup.wIndex != pluggedInterface) { return 0; } - - int total = 0; - HIDSubDescriptor* node; - for (node = rootNode; node; node = node->next) { - int res = USB_SendControl(TRANSFER_PGM, node->data, node->length); - if (res == -1) - return -1; - total += res; - } - - // Reset the protocol on reenumeration. Normally the host should not assume the state of the protocol - // due to the USB specs, but Windows and Linux just assumes its in report mode. - protocol = HID_REPORT_PROTOCOL; - - return total; -} - -uint8_t HID_::getShortName(char *name) -{ - name[0] = 'H'; - name[1] = 'I'; - name[2] = 'D'; - name[3] = 'A' + (descriptorSize & 0x0F); - name[4] = 'A' + ((descriptorSize >> 4) & 0x0F); - return 5; -} - -void HID_::AppendDescriptor(HIDSubDescriptor *node) -{ - if (!rootNode) { - rootNode = node; - } else { - HIDSubDescriptor *current = rootNode; - while (current->next) { - current = current->next; - } - current->next = node; - } - descriptorSize += node->length; -} - -int HID_::SendReport(uint8_t id, const void* data, int len) -{ - auto ret = USB_Send(pluggedEndpoint, &id, 1); - if (ret < 0) return ret; - auto ret2 = USB_Send(pluggedEndpoint | TRANSFER_RELEASE, data, len); - if (ret2 < 0) return ret2; - return ret + ret2; -} - -bool HID_::setup(USBSetup& setup) -{ - if (pluggedInterface != setup.wIndex) { - return false; - } - - uint8_t request = setup.bRequest; - uint8_t requestType = setup.bmRequestType; - - if (requestType == REQUEST_DEVICETOHOST_CLASS_INTERFACE) - { - if (request == HID_GET_REPORT) { - // TODO: HID_GetReport(); - return true; - } - if (request == HID_GET_PROTOCOL) { - // TODO: Send8(protocol); - return true; - } - if (request == HID_GET_IDLE) { - // TODO: Send8(idle); - } - } - - if (requestType == REQUEST_HOSTTODEVICE_CLASS_INTERFACE) - { - if (request == HID_SET_PROTOCOL) { - // The USB Host tells us if we are in boot or report mode. - // This only works with a real boot compatible device. - protocol = setup.wValueL; - return true; - } - if (request == HID_SET_IDLE) { - idle = setup.wValueL; - return true; - } - if (request == HID_SET_REPORT) - { - //uint8_t reportID = setup.wValueL; - //uint16_t length = setup.wLength; - //uint8_t data[length]; - // Make sure to not read more data than USB_EP_SIZE. - // You can read multiple times through a loop. - // The first byte (may!) contain the reportID on a multreport. - //USB_RecvControl(data, length); - } - } - - return false; -} - -HID_::HID_(void) : PluggableUSBModule(1, 1, epType), - rootNode(NULL), descriptorSize(0), - protocol(HID_REPORT_PROTOCOL), idle(1) -{ - epType[0] = EP_TYPE_INTERRUPT_IN; - PluggableUSB().plug(this); -} - -int HID_::begin(void) -{ - return 0; -} - -#endif /* if defined(USBCON) */ diff --git a/lib/Keyboard/Keyboard.cpp b/lib/Keyboard/Keyboard.cpp @@ -1,322 +0,0 @@ -/* - Keyboard.cpp - - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "Keyboard.h" - -#if defined(_USING_HID) - -//================================================================================ -//================================================================================ -// Keyboard - -static const uint8_t _hidReportDescriptor[] PROGMEM = { - - // Keyboard - 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47 - 0x09, 0x06, // USAGE (Keyboard) - 0xa1, 0x01, // COLLECTION (Application) - 0x85, 0x02, // REPORT_ID (2) - 0x05, 0x07, // USAGE_PAGE (Keyboard) - - 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl) - 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x25, 0x01, // LOGICAL_MAXIMUM (1) - 0x75, 0x01, // REPORT_SIZE (1) - - 0x95, 0x08, // REPORT_COUNT (8) - 0x81, 0x02, // INPUT (Data,Var,Abs) - 0x95, 0x01, // REPORT_COUNT (1) - 0x75, 0x08, // REPORT_SIZE (8) - 0x81, 0x03, // INPUT (Cnst,Var,Abs) - - 0x95, 0x06, // REPORT_COUNT (6) - 0x75, 0x08, // REPORT_SIZE (8) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x25, 0x65, // LOGICAL_MAXIMUM (101) - 0x05, 0x07, // USAGE_PAGE (Keyboard) - - 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated)) - 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application) - 0x81, 0x00, // INPUT (Data,Ary,Abs) - 0xc0, // END_COLLECTION -}; - -Keyboard_::Keyboard_(void) -{ - static HIDSubDescriptor node(_hidReportDescriptor, sizeof(_hidReportDescriptor)); - HID().AppendDescriptor(&node); -} - -void Keyboard_::begin(void) -{ -} - -void Keyboard_::end(void) -{ -} - -void Keyboard_::sendReport(KeyReport* keys) -{ - HID().SendReport(2,keys,sizeof(KeyReport)); -} - -extern -const uint8_t _asciimap[128] PROGMEM; - -#define SHIFT 0x80 -const uint8_t _asciimap[128] = -{ - 0x00, // NUL - 0x00, // SOH - 0x00, // STX - 0x00, // ETX - 0x00, // EOT - 0x00, // ENQ - 0x00, // ACK - 0x00, // BEL - 0x2a, // BS Backspace - 0x2b, // TAB Tab - 0x28, // LF Enter - 0x00, // VT - 0x00, // FF - 0x00, // CR - 0x00, // SO - 0x00, // SI - 0x00, // DEL - 0x00, // DC1 - 0x00, // DC2 - 0x00, // DC3 - 0x00, // DC4 - 0x00, // NAK - 0x00, // SYN - 0x00, // ETB - 0x00, // CAN - 0x00, // EM - 0x00, // SUB - 0x00, // ESC - 0x00, // FS - 0x00, // GS - 0x00, // RS - 0x00, // US - - 0x2c, // ' ' - 0x1e|SHIFT, // ! - 0x34|SHIFT, // " - 0x20|SHIFT, // # - 0x21|SHIFT, // $ - 0x22|SHIFT, // % - 0x24|SHIFT, // & - 0x34, // ' - 0x26|SHIFT, // ( - 0x27|SHIFT, // ) - 0x25|SHIFT, // * - 0x2e|SHIFT, // + - 0x36, // , - 0x2d, // - - 0x37, // . - 0x38, // / - 0x27, // 0 - 0x1e, // 1 - 0x1f, // 2 - 0x20, // 3 - 0x21, // 4 - 0x22, // 5 - 0x23, // 6 - 0x24, // 7 - 0x25, // 8 - 0x26, // 9 - 0x33|SHIFT, // : - 0x33, // ; - 0x36|SHIFT, // < - 0x2e, // = - 0x37|SHIFT, // > - 0x38|SHIFT, // ? - 0x1f|SHIFT, // @ - 0x04|SHIFT, // A - 0x05|SHIFT, // B - 0x06|SHIFT, // C - 0x07|SHIFT, // D - 0x08|SHIFT, // E - 0x09|SHIFT, // F - 0x0a|SHIFT, // G - 0x0b|SHIFT, // H - 0x0c|SHIFT, // I - 0x0d|SHIFT, // J - 0x0e|SHIFT, // K - 0x0f|SHIFT, // L - 0x10|SHIFT, // M - 0x11|SHIFT, // N - 0x12|SHIFT, // O - 0x13|SHIFT, // P - 0x14|SHIFT, // Q - 0x15|SHIFT, // R - 0x16|SHIFT, // S - 0x17|SHIFT, // T - 0x18|SHIFT, // U - 0x19|SHIFT, // V - 0x1a|SHIFT, // W - 0x1b|SHIFT, // X - 0x1c|SHIFT, // Y - 0x1d|SHIFT, // Z - 0x2f, // [ - 0x31, // bslash - 0x30, // ] - 0x23|SHIFT, // ^ - 0x2d|SHIFT, // _ - 0x35, // ` - 0x04, // a - 0x05, // b - 0x06, // c - 0x07, // d - 0x08, // e - 0x09, // f - 0x0a, // g - 0x0b, // h - 0x0c, // i - 0x0d, // j - 0x0e, // k - 0x0f, // l - 0x10, // m - 0x11, // n - 0x12, // o - 0x13, // p - 0x14, // q - 0x15, // r - 0x16, // s - 0x17, // t - 0x18, // u - 0x19, // v - 0x1a, // w - 0x1b, // x - 0x1c, // y - 0x1d, // z - 0x2f|SHIFT, // { - 0x31|SHIFT, // | - 0x30|SHIFT, // } - 0x35|SHIFT, // ~ - 0 // DEL -}; - - -uint8_t USBPutChar(uint8_t c); - -// press() adds the specified key (printing, non-printing, or modifier) -// to the persistent key report and sends the report. Because of the way -// USB HID works, the host acts like the key remains pressed until we -// call release(), releaseAll(), or otherwise clear the report and resend. -size_t Keyboard_::press(uint8_t k) -{ - uint8_t i; - if (k >= 136) { // it's a non-printing key (not a modifier) - k = k - 136; - } else if (k >= 128) { // it's a modifier key - _keyReport.modifiers |= (1<<(k-128)); - k = 0; - } else { // it's a printing key - k = pgm_read_byte(_asciimap + k); - if (!k) { - setWriteError(); - return 0; - } - if (k & 0x80) { // it's a capital letter or other character reached with shift - _keyReport.modifiers |= 0x02; // the left shift modifier - k &= 0x7F; - } - } - - // Add k to the key report only if it's not already present - // and if there is an empty slot. - if (_keyReport.keys[0] != k && _keyReport.keys[1] != k && - _keyReport.keys[2] != k && _keyReport.keys[3] != k && - _keyReport.keys[4] != k && _keyReport.keys[5] != k) { - - for (i=0; i<6; i++) { - if (_keyReport.keys[i] == 0x00) { - _keyReport.keys[i] = k; - break; - } - } - if (i == 6) { - setWriteError(); - return 0; - } - } - sendReport(&_keyReport); - return 1; -} - -// release() takes the specified key out of the persistent key report and -// sends the report. This tells the OS the key is no longer pressed and that -// it shouldn't be repeated any more. -size_t Keyboard_::release(uint8_t k) -{ - uint8_t i; - if (k >= 136) { // it's a non-printing key (not a modifier) - k = k - 136; - } else if (k >= 128) { // it's a modifier key - _keyReport.modifiers &= ~(1<<(k-128)); - k = 0; - } else { // it's a printing key - k = pgm_read_byte(_asciimap + k); - if (!k) { - return 0; - } - if (k & 0x80) { // it's a capital letter or other character reached with shift - _keyReport.modifiers &= ~(0x02); // the left shift modifier - k &= 0x7F; - } - } - - // Test the key report to see if k is present. Clear it if it exists. - // Check all positions in case the key is present more than once (which it shouldn't be) - for (i=0; i<6; i++) { - if (0 != k && _keyReport.keys[i] == k) { - _keyReport.keys[i] = 0x00; - } - } - - sendReport(&_keyReport); - return 1; -} - -void Keyboard_::releaseAll(void) -{ - _keyReport.keys[0] = 0; - _keyReport.keys[1] = 0; - _keyReport.keys[2] = 0; - _keyReport.keys[3] = 0; - _keyReport.keys[4] = 0; - _keyReport.keys[5] = 0; - _keyReport.modifiers = 0; - sendReport(&_keyReport); -} - -size_t Keyboard_::write(uint8_t c) -{ - uint8_t p = press(c); // Keydown - release(c); // Keyup - return p; // just return the result of press() since release() almost always returns 1 -} - -Keyboard_ Keyboard; - -#endif diff --git a/lib/Mouse/Mouse.cpp b/lib/Mouse/Mouse.cpp @@ -1,123 +0,0 @@ -/* - Mouse.cpp - - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "Mouse.h" - -#if defined(_USING_HID) - -static const uint8_t _hidReportDescriptor[] PROGMEM = { - - // Mouse - 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 54 - 0x09, 0x02, // USAGE (Mouse) - 0xa1, 0x01, // COLLECTION (Application) - 0x09, 0x01, // USAGE (Pointer) - 0xa1, 0x00, // COLLECTION (Physical) - 0x85, 0x01, // REPORT_ID (1) - 0x05, 0x09, // USAGE_PAGE (Button) - 0x19, 0x01, // USAGE_MINIMUM (Button 1) - 0x29, 0x03, // USAGE_MAXIMUM (Button 3) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x25, 0x01, // LOGICAL_MAXIMUM (1) - 0x95, 0x03, // REPORT_COUNT (3) - 0x75, 0x01, // REPORT_SIZE (1) - 0x81, 0x02, // INPUT (Data,Var,Abs) - 0x95, 0x01, // REPORT_COUNT (1) - 0x75, 0x05, // REPORT_SIZE (5) - 0x81, 0x03, // INPUT (Cnst,Var,Abs) - 0x05, 0x01, // USAGE_PAGE (Generic Desktop) - 0x09, 0x30, // USAGE (X) - 0x09, 0x31, // USAGE (Y) - 0x09, 0x38, // USAGE (Wheel) - 0x15, 0x81, // LOGICAL_MINIMUM (-127) - 0x25, 0x7f, // LOGICAL_MAXIMUM (127) - 0x75, 0x08, // REPORT_SIZE (8) - 0x95, 0x03, // REPORT_COUNT (3) - 0x81, 0x06, // INPUT (Data,Var,Rel) - 0xc0, // END_COLLECTION - 0xc0, // END_COLLECTION -}; - -//================================================================================ -//================================================================================ -// Mouse - -Mouse_::Mouse_(void) : _buttons(0) -{ - static HIDSubDescriptor node(_hidReportDescriptor, sizeof(_hidReportDescriptor)); - HID().AppendDescriptor(&node); -} - -void Mouse_::begin(void) -{ -} - -void Mouse_::end(void) -{ -} - -void Mouse_::click(uint8_t b) -{ - _buttons = b; - move(0,0,0); - _buttons = 0; - move(0,0,0); -} - -void Mouse_::move(signed char x, signed char y, signed char wheel) -{ - uint8_t m[4]; - m[0] = _buttons; - m[1] = x; - m[2] = y; - m[3] = wheel; - HID().SendReport(1,m,4); -} - -void Mouse_::buttons(uint8_t b) -{ - if (b != _buttons) - { - _buttons = b; - move(0,0,0); - } -} - -void Mouse_::press(uint8_t b) -{ - buttons(_buttons | b); -} - -void Mouse_::release(uint8_t b) -{ - buttons(_buttons & ~b); -} - -bool Mouse_::isPressed(uint8_t b) -{ - if ((b & _buttons) > 0) - return true; - return false; -} - -Mouse_ Mouse; - -#endif diff --git a/lib/RobotIRremote/IRremote.cpp b/lib/RobotIRremote/IRremote.cpp @@ -1,777 +0,0 @@ -/* - * IRremote - * Version 0.11 August, 2009 - * Copyright 2009 Ken Shirriff - * For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html - * - * Modified by Paul Stoffregen <paul@pjrc.com> to support other boards and timers - * Modified by Mitra Ardron <mitra@mitra.biz> - * Added Sanyo and Mitsubishi controllers - * Modified Sony to spot the repeat codes that some Sony's send - * - * Interrupt code based on NECIRrcv by Joe Knapp - * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 - * Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ - * - * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) - */ -