From aa4bda8dd6df6ceb74d9eccaf8536c8d98ad36dc Mon Sep 17 00:00:00 2001 From: kevinbuck-temboo Date: Mon, 31 Oct 2016 16:23:01 -0400 Subject: [PATCH 1/2] release1.1.8 --- .../CloudControlsConfig.ino | 4 +- .../ArduinoYun/SendAnEmail/SendAnEmail.ino | 6 +- .../SendDataToGoogleSpreadsheet.ino | 72 +-- keywords.txt | 18 +- library.properties | 4 +- src/Temboo.h | 1 + src/TembooMonitoring.cpp | 169 ++--- src/TembooMonitoring.h | 25 +- src/TembooYunShield.h | 1 + src/utility/TembooDS18B20.cpp | 100 +++ src/utility/TembooDS18B20.h | 42 ++ src/utility/TembooGPIO.c | 113 ++++ src/utility/TembooGPIO.h | 55 ++ src/utility/TembooOneWire.cpp | 580 ++++++++++++++++++ src/utility/TembooOneWire.h | 371 +++++++++++ src/utility/TembooWebSocketRequestHandles.c | 153 ++++- src/utility/TembooWebSocketRequestHandles.h | 24 +- 17 files changed, 1527 insertions(+), 211 deletions(-) create mode 100644 src/utility/TembooDS18B20.cpp create mode 100644 src/utility/TembooDS18B20.h create mode 100644 src/utility/TembooGPIO.c create mode 100644 src/utility/TembooGPIO.h create mode 100644 src/utility/TembooOneWire.cpp create mode 100644 src/utility/TembooOneWire.h diff --git a/examples/ArduinoYun/CloudControlsConfig/CloudControlsConfig.ino b/examples/ArduinoYun/CloudControlsConfig/CloudControlsConfig.ino index 562cb85..2e96df2 100644 --- a/examples/ArduinoYun/CloudControlsConfig/CloudControlsConfig.ino +++ b/examples/ArduinoYun/CloudControlsConfig/CloudControlsConfig.ino @@ -28,7 +28,7 @@ void setup() { Serial.println(); // upgrade the Temboo package Serial.print("Updating Temboo..."); - p.runShellCommand("opkg install http://downloads.arduino.cc/openwrtyun/1/packages/temboo_1.3.1-1_ar71xx.ipk"); + p.runShellCommand("opkg install http://downloads.arduino.cc/openwrtyun/1/packages/temboo_1.4.0-1_ar71xx.ipk"); returnCode = p.exitValue(); if (returnCode == 0) { Serial.println("Success!"); @@ -88,7 +88,7 @@ void setup() { } return; } - + Serial.println(); Serial.println("Update Complete - your Yun is ready for Cloud Controls!"); } diff --git a/examples/ArduinoYun/SendAnEmail/SendAnEmail.ino b/examples/ArduinoYun/SendAnEmail/SendAnEmail.ino index bb4172a..bb6b09b 100644 --- a/examples/ArduinoYun/SendAnEmail/SendAnEmail.ino +++ b/examples/ArduinoYun/SendAnEmail/SendAnEmail.ino @@ -3,7 +3,7 @@ Demonstrates sending an email via a Google Gmail account using Temboo from an Arduino Yún. - Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino + Check out the latest Arduino & Temboo examples and tutorials at http://www.temboo.com/arduino A Temboo account and application key are necessary to run all Temboo examples. If you don't already have one, you can register for a free Temboo account at @@ -34,13 +34,13 @@ 9. Copy and paste this password into the code below, updating the GMAIL_APP_PASSWORD variable - 10. Upload the sketch to your Arduino Yún and open Arduino's serial monitor + 10. Upload the sketch to your Arduino Yún and open the serial monitor NOTE: You can test this Choreo and find the latest instructions on our website: https://temboo.com/library/Library/Google/Gmail/SendEmail You can also find an in-depth version of this example here: - https://temboo.com/hardware/ti/send-an-email + https://temboo.com/arduino/yun/send-an-email This example assumes basic familiarity with Arduino sketches, and that your Yún is connected to the Internet. diff --git a/examples/ArduinoYun/SendDataToGoogleSpreadsheet/SendDataToGoogleSpreadsheet.ino b/examples/ArduinoYun/SendDataToGoogleSpreadsheet/SendDataToGoogleSpreadsheet.ino index d8c80b7..664095a 100644 --- a/examples/ArduinoYun/SendDataToGoogleSpreadsheet/SendDataToGoogleSpreadsheet.ino +++ b/examples/ArduinoYun/SendDataToGoogleSpreadsheet/SendDataToGoogleSpreadsheet.ino @@ -3,7 +3,7 @@ Demonstrates appending a row of data to a Google spreadsheet using Temboo from an Arduino Yún. - Check out the latest Arduino & Temboo examples and support docs at http://www.temboo.com/arduino + Check out the latest Arduino & Temboo examples and tutorials at http://www.temboo.com/arduino A Temboo account and application key are necessary to run all Temboo examples. If you don't already have one, you can register for a free Temboo account at @@ -12,8 +12,11 @@ Instructions: 1. Create a Temboo account: http://www.temboo.com + 2. Retrieve your Temboo application details: http://www.temboo.com/account/applications + 3. Replace the values in the TembooAccount.h tab with your Temboo application details + 4. You'll also need a Google Spreadsheet that includes a title in the first row of each column that data will be written to. This example assumes there are two columns. The first column is the time (in milliseconds) that the row was appended, and the second @@ -29,7 +32,7 @@ https://temboo.com/library/Library/Google/OAuth/ - For the scope field, you need to use: https://spreadsheets.google.com/feeds/ + For the scope field, you need to use: https://www.googleapis.com/auth/spreadsheets Here's a video outlines how Temboo helps with the OAuth process: @@ -37,12 +40,12 @@ And here's a more in-depth version of this example on our website: - https://temboo.com/hardware/ti/update-google-spreadsheet - - 6. Next, upload the sketch to your Arduino Yún and open Arduino's serial monitor + https://temboo.com/arduino/yun/update-google-spreadsheet + 6. Next, upload the sketch to your Arduino Yún and open the serial monitor + Note: you can test this Choreo and find the latest instructions on our website: - https://temboo.com/library/Library/Google/Spreadsheets/AppendRow/ + https://temboo.com/library/Library/Google/Sheets/AppendValues/ Looking for another API to use with your Arduino Yún? We've got over 100 in our Library! @@ -61,20 +64,20 @@ // Note that for additional security and reusability, you could // use #define statements to specify these values in a .h file. -// the clientID found in Google's Developer Console under APIs & Auth > Credentials +// the clientID found in Google's Developer Console under API Manager > Credentials const String CLIENT_ID = "your-client-id"; -// the clientSecret found in Google's Developer Console under APIs & Auth > Credentials +// the clientSecret found in Google's Developer Console under API Manager > Credentials const String CLIENT_SECRET = "your-client-secret"; // returned after running FinalizeOAuth const String REFRESH_TOKEN = "your-oauth-refresh-token"; -// the title of the spreadsheet you want to send data to -// (Note that this must actually be the title of a Google spreadsheet -// that exists in your Google Drive/Docs account, and is configured -// as described above.) -const String SPREADSHEET_TITLE = "your-spreadsheet-title"; +// The ID of the spreadsheet you want to send data to +// which can be found in the URL when viewing your spreadsheet at Google. For example, +// the ID in the URL below is: "1tvFW2n-xFFJCE1q5j0HTetOsDhhgw7_998_K4sFtk" +// Sample URL: https://docs.google.com/spreadsheets/d/1tvFW2n-xFFJCE1q5j0HTetOsDhhgw7_998_K4sFtk/edit +const String SPREADSHEET_ID = "your-spreadsheet-id"; const unsigned long RUN_INTERVAL_MILLIS = 60000; // how often to run the Choreo (in milliseconds) @@ -114,47 +117,44 @@ void loop() Serial.println("Appending value to spreadsheet..."); // we need a Process object to send a Choreo request to Temboo - TembooChoreo AppendRowChoreo; + TembooChoreo AppendValuesChoreo; // invoke the Temboo client // NOTE that the client must be reinvoked and repopulated with // appropriate arguments each time its run() method is called. - AppendRowChoreo.begin(); + AppendValuesChoreo.begin(); // set Temboo account credentials - AppendRowChoreo.setAccountName(TEMBOO_ACCOUNT); - AppendRowChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); - AppendRowChoreo.setAppKey(TEMBOO_APP_KEY); + AppendValuesChoreo.setAccountName(TEMBOO_ACCOUNT); + AppendValuesChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); + AppendValuesChoreo.setAppKey(TEMBOO_APP_KEY); - // identify the Temboo Library choreo to run (Google > Spreadsheets > AppendRow) - AppendRowChoreo.setChoreo("/Library/Google/Spreadsheets/AppendRow"); + // identify the Temboo Library choreo to run (Google > Sheets > AppendValues) + AppendValuesChoreo.setChoreo("/Library/Google/Sheets/AppendValues"); // set the required Choreo inputs - // see https://www.temboo.com/library/Library/Google/Spreadsheets/AppendRow/ + // see https://www.temboo.com/library/Library/Google/Sheets/AppendValues/ // for complete details about the inputs for this Choreo // your Google application client ID - AppendRowChoreo.addInput("ClientID", CLIENT_ID); - // your Google application client secert - AppendRowChoreo.addInput("ClientSecret", CLIENT_SECRET); + AppendValuesChoreo.addInput("ClientID", CLIENT_ID); + // your Google application client secret + AppendValuesChoreo.addInput("ClientSecret", CLIENT_SECRET); // your Google OAuth refresh token - AppendRowChoreo.addInput("RefreshToken", REFRESH_TOKEN); + AppendValuesChoreo.addInput("RefreshToken", REFRESH_TOKEN); - // the title of the spreadsheet you want to append to - // NOTE: substitute your own value, retaining the "SpreadsheetTitle:" prefix. - AppendRowChoreo.addInput("SpreadsheetTitle", SPREADSHEET_TITLE); + // the ID of the spreadsheet you want to append to + AppendValuesChoreo.addInput("SpreadsheetID", SPREADSHEET_ID); // convert the time and sensor values to a comma separated string - String rowData(now); - rowData += ","; - rowData += sensorValue; + String rowData = "[[\"" + String(now) + "\", \"" + String(sensorValue) + "\"]]"; // add the RowData input item - AppendRowChoreo.addInput("RowData", rowData); + AppendValuesChoreo.addInput("Values", rowData); // run the Choreo and wait for the results // The return code (returnCode) will indicate success or failure - unsigned int returnCode = AppendRowChoreo.run(); + unsigned int returnCode = AppendValuesChoreo.run(); // return code of zero (0) means success if (returnCode == 0) { @@ -163,13 +163,13 @@ void loop() } else { // return code of anything other than zero means failure // read and display any error messages - while (AppendRowChoreo.available()) { - char c = AppendRowChoreo.read(); + while (AppendValuesChoreo.available()) { + char c = AppendValuesChoreo.read(); Serial.print(c); } } - AppendRowChoreo.close(); + AppendValuesChoreo.close(); } } diff --git a/keywords.txt b/keywords.txt index d6bff6a..fb185d3 100644 --- a/keywords.txt +++ b/keywords.txt @@ -7,18 +7,21 @@ ####################################### Temboo KEYWORD1 -TembooMQTTEdgeDevice KEYWORD1 -TembooCoAPEdgeDevice KEYWORD1 -TembooYunShield KEYWORD1 +TembooMQTTEdgeDevice KEYWORD1 +TembooCoAPEdgeDevice KEYWORD1 +TembooYunShield KEYWORD1 ####################################### # Datatypes (KEYWORD2) ####################################### TembooChoreo KEYWORD2 -TembooCoAPChoreo KEYWORD2 -TembooMQTTChoreo KEYWORD2 -TembooYunShieldChoreo KEYWORD2 +TembooCoAPChoreo KEYWORD2 +TembooMQTTChoreo KEYWORD2 +TembooYunShieldChoreo KEYWORD2 +TembooDS18B20Config KEYWORD2 +TembooGPIOConfig KEYWORD2 +TembooSensor KEYWORD2 ####################################### # Methods and Functions (KEYWORD2) @@ -40,3 +43,6 @@ setDeviceType KEYWORD2 setSettingsFileToWrite KEYWORD2 setSettingsFileToRead KEYWORD2 setGatewayAddress KEYWORD2 +tembooDS18B20Init KEYWORD2 +tembooDigitalGPIOInit KEYWORD2 +tembooAnalogGPIOInit KEYWORD2 diff --git a/library.properties b/library.properties index 0377a8c..c7e9617 100644 --- a/library.properties +++ b/library.properties @@ -6,5 +6,5 @@ paragraph=Use this library to connect your Arduino or Genuino board to Temboo, m category=Communication url=http://www.temboo.com/arduino architectures=* -version=1.1.7 -core-dependencies=arduino (>=1.5.0) +version=1.1.8 +core-dependencies=arduino (>=1.5.0) \ No newline at end of file diff --git a/src/Temboo.h b/src/Temboo.h index 930a036..e74d69a 100644 --- a/src/Temboo.h +++ b/src/Temboo.h @@ -51,6 +51,7 @@ class TembooChoreo : public Process { 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& conversion, const String& calibrationValue) {addParameter("-b" + sensorName + ":" + String(sensorValue) + ":" + conversion + ":" + calibrationValue);} 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);} diff --git a/src/TembooMonitoring.cpp b/src/TembooMonitoring.cpp index 247d2a9..f703daf 100644 --- a/src/TembooMonitoring.cpp +++ b/src/TembooMonitoring.cpp @@ -23,6 +23,9 @@ #include #include +#ifdef ARDUINO_ARCH_SAMD +#include "avr/dtostrf.h" +#endif #include "utility/TembooGlobal.h" #include "TembooMonitoring.h" @@ -47,42 +50,41 @@ void updateIntervalTime(int intervalTime) { Mailbox.writeMessage(msg, messageSize); } -static void tembooDigitalWrite(uint32_t pin, int val) { - digitalWrite(pin, val); -} - -uint32_t tembooDigitalRead(uint32_t pin) { - return digitalRead(pin); -} - -static void tembooAnalogWrite(uint32_t pin, int val) { - analogWrite(pin, val); -} - -uint32_t tembooAnalogRead(uint32_t pin) { - return analogRead(pin); -} - -TembooMessaging::TembooMessaging(TembooPinTable* pinTable, int pinTableSize) { +TembooMessaging::TembooMessaging(TembooSensor** sensorTable, int sensorTableSize) { m_accountName = NULL; m_appKey = NULL; m_appKeyName = NULL; m_deviceID = NULL; m_connectionStatus = false; - m_pinTable = pinTable; - m_pinTableSize = pinTableSize; - m_pinTableDepth = 0; + m_sensorTable = sensorTable; + m_sensorTableSize = sensorTableSize; + m_sensorTableDepth = 0; m_connectionAttemptTime = millis(); m_lastPingTime = millis(); - // init array + // init sensor array int i = 0; - for (i = 0; i < m_pinTableSize; i++) { - m_pinTable[i].pin = -1; - m_pinTable[i].pinRead = NULL; - m_pinTable[i].pinWrite = NULL; + for (i = 0; i < m_sensorTableSize; i++) { + m_sensorTable[i] = NULL; } } +int TembooMessaging::addTembooSensor(TembooSensor* sensor) { + int i = 0; + for (; i < m_sensorTableSize; i++) { + if (m_sensorTable[i] == sensor) { + logTembooDebug("Sensor already added"); + return -1; + } + if (m_sensorTable[i] == NULL) { + m_sensorTable[i] = sensor; + m_sensorTableDepth++; + return 0; + } + } + logTembooDebug("Sensor table full, sensor not added"); + return -1; +} + void TembooMessaging::startMessaging() { if (!running()) { TEMBOO_TRACELN("starting messanger"); @@ -92,75 +94,11 @@ void TembooMessaging::startMessaging() { } } -void TembooMessaging::setPinsToDefaultState() { - int i = 0; - for (; i < m_pinTableDepth; i++) { - if (m_pinTable[i].pinWrite != NULL) { - m_pinTable[i].pinWrite(m_pinTable[i].pin, m_pinTable[i].defaultValue); - m_pinTable[i].currentPinValue = m_pinTable[i].defaultValue; - } - } -} - -void TembooMessaging::addPinConfig(int pin, const char* type, int mode, int defaultValue) { - // check if there is room to add new pin information - if (m_pinTableDepth == m_pinTableSize) { - return; - } - bool success = true; - // check if pin has already been added, if it has - // edit the config/mode, else, add to config +void TembooMessaging::setSensorsToDefaultState() { int i = 0; - for (; i < m_pinTableDepth; i++) { - if (m_pinTable[i].pin == pin) { - break; - } - } - if (mode == INPUT) { - if (!strcasecmp(type, "analog")) { - pinMode(pin, INPUT); - m_pinTable[i].pinRead = tembooAnalogRead; - m_pinTable[i].pinWrite = NULL; - m_pinTable[i].pin = pin; - m_pinTable[i].currentPinValue = tembooAnalogRead(pin); - m_pinTable[i].defaultValue = defaultValue; - } else if (!strcasecmp(type, "digital")) { - pinMode(pin, INPUT); - m_pinTable[i].pinRead = tembooDigitalRead; - m_pinTable[i].pinWrite = NULL; - m_pinTable[i].pin = pin; - m_pinTable[i].currentPinValue = tembooDigitalRead(pin); - m_pinTable[i].defaultValue = defaultValue; - } else { - success = false; - } - } else if (mode == OUTPUT) { - if (!strcasecmp(type, "analog")) { - pinMode(pin, OUTPUT); - m_pinTable[i].pinRead = NULL; - m_pinTable[i].pinWrite = tembooAnalogWrite; - m_pinTable[i].pin = pin; - m_pinTable[i].currentPinValue = defaultValue; - m_pinTable[i].defaultValue = defaultValue; - tembooAnalogWrite(pin, defaultValue); - } else if (!strcasecmp(type, "digital")) { - pinMode(pin, OUTPUT); - m_pinTable[i].pinRead = NULL; - m_pinTable[i].pinWrite = tembooDigitalWrite; - m_pinTable[i].pin = pin; - m_pinTable[i].currentPinValue = defaultValue; - m_pinTable[i].defaultValue = defaultValue; - tembooDigitalWrite(pin, defaultValue); - } else { - success = false; - } - } else { - success = false; - } - if (success) { - if (i >= m_pinTableDepth) { - // if we needed to add a new pin, increment depth - m_pinTableDepth++; + for (; i < m_sensorTableDepth; i++) { + if (m_sensorTable[i]->write != NULL) { + m_sensorTable[i]->write(m_sensorTable[i]->sensorConfig, m_sensorTable[i]->defaultValue); } } } @@ -198,40 +136,36 @@ void TembooMessaging::setDeviceID(const char* deviceID) { m_deviceID = deviceID; } -void TembooMessaging::initiateConnection() { +int TembooMessaging::initiateConnection() { unsigned long now = millis(); if (now - m_connectionAttemptTime < INITIATE_TIMEOUT_MS) { poll(); - return; + return TEMBOO_MONITORING_ERROR_NOT_CONNECTION_TIME; } if (m_accountName == NULL || *m_accountName == '\0') { - logTembooDebug("Account name invalid or not set"); - return; + return TEMBOO_MONITORING_ERROR_ACCOUNT_MISSING; } if (m_appKeyName == NULL || *m_appKeyName == '\0') { - logTembooDebug("Appkey name invalid or not set"); - return; + + return TEMBOO_MONITORING_ERROR_APPKEY_NAME_MISSING; } if (m_deviceID == NULL || *m_deviceID == '\0') { - logTembooDebug("DeviceID invalid or not set"); - return; + return TEMBOO_MONITORING_ERROR_DEVICEID_MISSING; } if (m_appKey == NULL || *m_appKey == '\0') { - logTembooDebug("Appkey invalid or not set"); - return; + return TEMBOO_MONITORING_ERROR_APPKEY_MISSING; } startMessaging(); int messageSize = strlen(m_accountName) + strlen(m_appKey) + strlen(m_appKeyName) + strlen(m_deviceID) + 11; uint8_t msg[messageSize]; if (messageSize < MAX_MAILBOX_MESSAGE_SIZE) { - Console.println("Attempting to connect to Temboo"); messageSize = snprintf((char*)msg, messageSize, "MI|N%s|K%s|B%s|A%s", m_accountName, m_appKeyName, m_deviceID, m_appKey); Mailbox.writeMessage(msg, messageSize); m_connectionAttemptTime = now; } else { - logTembooDebug("Initiation request too large"); - return; + return TEMBOO_MONITORING_ERROR_REQUEST_TOO_LARGE; } + return TEMBOO_MONITORING_ERROR_OK; } WSMessageRequest TembooMessaging::poll() { @@ -247,12 +181,12 @@ WSMessageRequest TembooMessaging::poll() { uint8_t msg[MAX_MAILBOX_MESSAGE_SIZE] = {0}; int recvLen = Mailbox.readMessage(msg, MAX_MAILBOX_MESSAGE_SIZE); if (recvLen > 0) { - rc = handleResponse(msg, m_pinTable, m_pinTableDepth, m_connectionStatus); + rc = handleResponse(msg, m_sensorTable, m_sensorTableDepth, m_connectionStatus); if (rc == WS_UPDATE_CONNECTED) { - logTembooDebug("Connected to Temboo"); + //logTembooDebug("Connected to Temboo"); m_connectionStatus = true; } else if (rc == WS_UPDATE_DISCONNECTED) { - logTembooDebug("Disconnected from Temboo"); + //logTembooDebug("Disconnected from Temboo"); m_connectionStatus = false; } else if (rc == WS_REQUEST_ERROR) { // disconnect @@ -267,13 +201,12 @@ WSMessageRequest TembooMessaging::poll() { void TembooMessaging::updatePinValue(int pinNum, int pinVal) { // save the data to the strcuture and then send to Temboo int i = 0; - for (; i < m_pinTableDepth; i++) { - if (m_pinTable[i].pin == pinNum) { - m_pinTable[i].currentPinValue = pinVal; + for (; i < m_sensorTableDepth; i++) { + if (m_sensorTable[i]->getSensorPin(m_sensorTable[i]->sensorConfig) == pinNum) { // if pin has pinWrite as NULL, it is an input // pin and needs to be stored. If not NULL, // pin is an actuator and should not be stored - if(m_pinTable[i].pinWrite == NULL){ + if(m_sensorTable[i]->write == NULL){ sendData(pinNum, pinVal, false); } else { sendData(pinNum, pinVal, true); @@ -281,18 +214,18 @@ void TembooMessaging::updatePinValue(int pinNum, int pinVal) { return; } } - logTembooDebug("Pin not found, unable to update"); + logTembooDebug("Unable to update pin"); } int TembooMessaging::retrievePinValue(int pinNum) { // search through pin structure and return the pin value int i = 0; - for (; i < m_pinTableDepth; i++) { - if (m_pinTable[i].pin == pinNum) { - return m_pinTable[i].currentPinValue; + for (; i < m_sensorTableDepth; i++) { + if (m_sensorTable[i]->getSensorPin(m_sensorTable[i]->sensorConfig) == pinNum) { + return m_sensorTable[i]->read(m_sensorTable[i]->sensorConfig); } } - logTembooDebug("Pin not found, unable to obtain value"); + logTembooDebug("Unable to obtain pin value"); return 0; } diff --git a/src/TembooMonitoring.h b/src/TembooMonitoring.h index 1cdc461..962cac2 100644 --- a/src/TembooMonitoring.h +++ b/src/TembooMonitoring.h @@ -28,10 +28,20 @@ #include "utility/TembooWebSocketRequestHandles.h" +#define TEMBOO_MONITORING_ERROR_OK (0) +#define TEMBOO_MONITORING_ERROR_ACCOUNT_MISSING (201) +#define TEMBOO_MONITORING_ERROR_CHOREO_MISSING (203) +#define TEMBOO_MONITORING_ERROR_APPKEY_NAME_MISSING (205) +#define TEMBOO_MONITORING_ERROR_APPKEY_MISSING (207) +#define TEMBOO_MONITORING_ERROR_DEVICEID_MISSING (209) + +#define TEMBOO_MONITORING_ERROR_REQUEST_TOO_LARGE (251) +#define TEMBOO_MONITORING_ERROR_NOT_CONNECTION_TIME (253) + class TembooMessaging : public Process { public: - TembooMessaging(TembooPinTable* pinTable, int pinTableSize); + TembooMessaging(TembooSensor** sensors, int pinTableSize); void begin(); void setAccountName(const String& accountName); @@ -46,9 +56,7 @@ class TembooMessaging : public Process { void setDeviceID(const String& appKey); void setDeviceID(const char* appKey); - void addPinConfig(int pin, const char* type, int mode, int defaultValue); - - void initiateConnection(); + int initiateConnection(); WSMessageRequest poll(); @@ -56,7 +64,8 @@ class TembooMessaging : public Process { void sendData(int pin, float pinVal); void updatePinValue(int pinNum, int pinVal); int retrievePinValue(int pinNum); - void setPinsToDefaultState(); + int addTembooSensor(TembooSensor* sensor); + void setSensorsToDefaultState(); bool isConnected(); @@ -66,10 +75,10 @@ class TembooMessaging : public Process { const char* m_appKeyName; const char* m_deviceID; bool m_connectionStatus; - int m_pinTableSize; - int m_pinTableDepth; + int m_sensorTableSize; + int m_sensorTableDepth; long int m_connectionAttemptTime; - TembooPinTable* m_pinTable; + TembooSensor** m_sensorTable; unsigned long m_lastPingTime; void startMessaging(); diff --git a/src/TembooYunShield.h b/src/TembooYunShield.h index ff00dbe..b56d50d 100644 --- a/src/TembooYunShield.h +++ b/src/TembooYunShield.h @@ -51,6 +51,7 @@ class TembooYunShieldChoreo : public Process { 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 addSensorInput(const String& sensorName, long sensorValue, const String& conversion, const String& calibrationValue) {addParameter("-b" + sensorName + ":" + String(sensorValue) + ":" + conversion + ":" + calibrationValue);} void setDeviceName(const String& deviceName) {addParameter("-d" + deviceName);} void setDeviceType(const String& deviceType) {addParameter("-t" + deviceType);} }; diff --git a/src/utility/TembooDS18B20.cpp b/src/utility/TembooDS18B20.cpp new file mode 100644 index 0000000..236c927 --- /dev/null +++ b/src/utility/TembooDS18B20.cpp @@ -0,0 +1,100 @@ +/* +############################################################################### +# +# 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. +# +############################################################################### +*/ + +#include "TembooOneWire.h" +#include "TembooDS18B20.h" + +TembooOneWire* g_wire; + +int tembooDS18B20Read(void* sensorConfig) { + + uint8_t scratchPad[9]; + TembooDS18B20Config* config = (TembooDS18B20Config*) sensorConfig; + + g_wire->reset(); + g_wire->select(config->channel); + // tells device to convert temperature to scratchpad to read + g_wire->write(0x44, config->parasite); + // delay 750ms for conversion to occur, but wait for 1 second just in case + delay(config->conversionDelayMillis); + + // begin reading data + g_wire->reset(); + // select the device we're requesting data from + g_wire->select(config->channel); + // send message to device requesting data + g_wire->write(0xBE); + + for(int i = 0; i < 9; i++) { + scratchPad[i] = g_wire->read(); + } + int16_t temp = (((int16_t)scratchPad[1]) << 8) + (int16_t)scratchPad[0]; + + return temp; +} + +void tembooDS18B20Begin(__attribute__((unused)) void* sensorConfig) { + // all of the initializtion is done in init + return; +} + +uint8_t* tembooDS18B20GetSensorChannel(void* sensorConfig) { + TembooDS18B20Config* config = (TembooDS18B20Config*) sensorConfig; + return config->channel; +} + +int tembooDS18B20GetSensorPin(void* sensorConfig) { + TembooDS18B20Config* config = (TembooDS18B20Config*) sensorConfig; + return config->pin; +} + +void tembooDS18B20Init(TembooDS18B20Config* sensorConfig, TembooSensor* tembooSensor, int pin, int defaultValue) { + sensorConfig->pin = pin; + sensorConfig->conversionDelayMillis = 1000; + + // create OneWire object + if (NULL == g_wire) { + g_wire = new TembooOneWire(pin); + } + // reset search before searching for device + g_wire->reset_search(); + // find device connected to the wire + g_wire->search(sensorConfig->channel); + + if (g_wire->crc8(sensorConfig->channel, 7) != sensorConfig->channel[7]) { + // invalid address + } + // begin to check if sensor is in parasite mode + g_wire->reset(); + g_wire->select(sensorConfig->channel); + g_wire->write(0xB4); + sensorConfig->parasite = g_wire->read_bit() == 0; + g_wire->reset(); + + tembooSensor->sensorConfig = sensorConfig; + tembooSensor->read = tembooDS18B20Read; + tembooSensor->begin = tembooDS18B20Begin; + tembooSensor->write = NULL; + tembooSensor->getSensorPin = tembooDS18B20GetSensorPin; + tembooSensor->getSensorChannel = tembooDS18B20GetSensorChannel; + tembooSensor->defaultValue = defaultValue; +} \ No newline at end of file diff --git a/src/utility/TembooDS18B20.h b/src/utility/TembooDS18B20.h new file mode 100644 index 0000000..6e955b8 --- /dev/null +++ b/src/utility/TembooDS18B20.h @@ -0,0 +1,42 @@ +/* +############################################################################### +# +# 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 __TEMBOODS18B20__ +#define __TEMBOODS18B20__ + +#include "TembooWebSocketRequestHandles.h" + +typedef struct TembooDS18B20Config{ + uint8_t channel[8]; + int pin; + uint16_t conversionDelayMillis; + bool parasite; +} TembooDS18B20Config; + +void tembooDS18B20Init(TembooDS18B20Config* sensorConfig, TembooSensor* tembooSensor, int pin, int defaultValue); +void tembooDS18B20Begin(void* sensorConfig); +uint8_t* tembooDS18B20GetSensorChannel(void* sensorConfig); +int tembooDS18B20GetSensorPin(void* sensorConfig); +int tembooDS18B20Read(void* sensorConfig); + + +#endif /* defined(__TEMBOODS18B20__) */ \ No newline at end of file diff --git a/src/utility/TembooGPIO.c b/src/utility/TembooGPIO.c new file mode 100644 index 0000000..48906f6 --- /dev/null +++ b/src/utility/TembooGPIO.c @@ -0,0 +1,113 @@ +/* +############################################################################### +# +# 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. +# +############################################################################### +*/ + +#include "TembooGPIO.h" + +int tembooDigitalRead(void* sensorConfig) { + TembooGPIOConfig* config = (TembooGPIOConfig*) sensorConfig; + if (config->mode == OUTPUT) { + return config->currentValue; + } + return digitalRead(config->pin); + +} + +void tembooDigitalWrite(void* sensorConfig, int val) { + TembooGPIOConfig* config = (TembooGPIOConfig*) sensorConfig; + digitalWrite(config->pin, val); + config->currentValue = val; +} + +int tembooAnalogRead(void* sensorConfig) { + TembooGPIOConfig* config = (TembooGPIOConfig*) sensorConfig; + if (config->mode == OUTPUT) { + return config->currentValue; + } + return analogRead(config->pin); +} + +void tembooAnalogWrite(void* sensorConfig, int val) { + TembooGPIOConfig* config = (TembooGPIOConfig*) sensorConfig; + analogWrite(config->pin, val); + config->currentValue = val; +} + +void tembooGPIOBegin(__attribute__((unused)) void* sensorConfig) { + // all of the initializtion is done in init + return; +} + +uint8_t* tembooGPIOGetSensorChannel(void* sensorConfig) { + TembooGPIOConfig* config = (TembooGPIOConfig*) sensorConfig; + return config->channel; +} + +int tembooGPIOGetSensorPin(void* sensorConfig) { + TembooGPIOConfig* config = (TembooGPIOConfig*) sensorConfig; + return config->pin; +} + +void tembooDigitalGPIOInit(TembooGPIOConfig* sensorConfig, TembooSensor* tembooSensor, int pin, int defaultValue, int mode) { + sensorConfig->pin = pin; + sensorConfig->channel = NULL; + sensorConfig->mode = mode; + pinMode(pin, mode); + if (mode == OUTPUT) { + // this will set the current value + tembooDigitalWrite(sensorConfig, defaultValue); + tembooSensor->write = tembooDigitalWrite; + } else { + // probably don't need to do this, but best go on and set it + // TODO: remove /comment after review + sensorConfig->currentValue = tembooDigitalRead(sensorConfig); + tembooSensor->write = NULL; + } + tembooSensor->sensorConfig = sensorConfig; + tembooSensor->read = tembooDigitalRead; + tembooSensor->begin = tembooGPIOBegin; + tembooSensor->getSensorPin = tembooGPIOGetSensorPin; + tembooSensor->getSensorChannel = tembooGPIOGetSensorChannel; + tembooSensor->defaultValue = defaultValue; +} + +void tembooAnalogGPIOInit(TembooGPIOConfig* sensorConfig, TembooSensor* tembooSensor, int pin, int defaultValue, int mode) { + sensorConfig->pin = pin; + sensorConfig->channel = NULL; + sensorConfig->mode = mode; + pinMode(pin, mode); + if (mode == OUTPUT) { + // this will set the current value + tembooAnalogWrite(sensorConfig, defaultValue); + tembooSensor->write = tembooAnalogWrite; + } else { + // probably don't need to do this, but best go on and set it + // TODO: remove /comment after review + sensorConfig->currentValue = tembooAnalogRead(sensorConfig); + tembooSensor->write = NULL; + } + tembooSensor->sensorConfig = sensorConfig; + tembooSensor->read = tembooAnalogRead; + tembooSensor->begin = tembooGPIOBegin; + tembooSensor->getSensorPin = tembooGPIOGetSensorPin; + tembooSensor->getSensorChannel = tembooGPIOGetSensorChannel; + tembooSensor->defaultValue = defaultValue; +} diff --git a/src/utility/TembooGPIO.h b/src/utility/TembooGPIO.h new file mode 100644 index 0000000..2381b2b --- /dev/null +++ b/src/utility/TembooGPIO.h @@ -0,0 +1,55 @@ +/* +############################################################################### +# +# 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 __TEMBOOGPIO__ +#define __TEMBOOGPIO__ + +#include "TembooWebSocketRequestHandles.h" + +#if defined(__cplusplus) +extern "C" { +#endif + +typedef struct TembooGPIOConfig{ + uint8_t* channel; + int pin; + int currentValue; + int mode; +} TembooGPIOConfig; + +void tembooGPIOBegin(void* sensorConfig); +uint8_t* tembooGPIOGetSensorChannel(void* sensorConfig); +int tembooGPIOGetSensorPin(void* sensorConfig); + +void tembooDigitalGPIOInit(TembooGPIOConfig* sensorConfig, TembooSensor* tembooSensor, int pin, int defaultValue, int mode); +int tembooDigitalRead(void* sensorConfig); +void tembooDigitalWrite(void* sensorConfig, int val); + +void tembooAnalogGPIOInit(TembooGPIOConfig* sensorConfig, TembooSensor* tembooSensor, int pin, int defaultValue, int mode); +int tembooAnalogRead(void* sensorConfig); +void tembooAnalogWrite(void* sensorConfig, int val); + +#if defined(__cplusplus) +} +#endif + +#endif /* defined(__TEMBOOGPIO__) */ \ No newline at end of file diff --git a/src/utility/TembooOneWire.cpp b/src/utility/TembooOneWire.cpp new file mode 100644 index 0000000..1756b71 --- /dev/null +++ b/src/utility/TembooOneWire.cpp @@ -0,0 +1,580 @@ +/* +Copyright (c) 2007, Jim Studt (original old version - many contributors since) + +The latest version of this library may be found at: + http://www.pjrc.com/teensy/td_libs_OneWire.html + +OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since +January 2010. At the time, it was in need of many bug fixes, but had +been abandoned the original author (Jim Studt). None of the known +contributors were interested in maintaining OneWire. Paul typically +works on OneWire every 6 to 12 months. Patches usually wait that +long. If anyone is interested in more actively maintaining OneWire, +please contact Paul. + +Temboo Version: + Class renamed to resolve a distribution issue. + +Version 2.3: + Unknonw chip fallback mode, Roger Clark + Teensy-LC compatibility, Paul Stoffregen + Search bug fix, Love Nystrom + +Version 2.2: + Teensy 3.0 compatibility, Paul Stoffregen, paul@pjrc.com + Arduino Due compatibility, http://arduino.cc/forum/index.php?topic=141030 + Fix DS18B20 example negative temperature + Fix DS18B20 example's low res modes, Ken Butcher + Improve reset timing, Mark Tillotson + Add const qualifiers, Bertrik Sikken + Add initial value input to crc16, Bertrik Sikken + Add target_search() function, Scott Roberts + +Version 2.1: + Arduino 1.0 compatibility, Paul Stoffregen + Improve temperature example, Paul Stoffregen + DS250x_PROM example, Guillermo Lovato + PIC32 (chipKit) compatibility, Jason Dangel, dangel.jason AT gmail.com + Improvements from Glenn Trewitt: + - crc16() now works + - check_crc16() does all of calculation/checking work. + - Added read_bytes() and write_bytes(), to reduce tedious loops. + - Added ds2408 example. + Delete very old, out-of-date readme file (info is here) + +Version 2.0: Modifications by Paul Stoffregen, January 2010: +http://www.pjrc.com/teensy/td_libs_OneWire.html + Search fix from Robin James + http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27 + Use direct optimized I/O in all cases + Disable interrupts during timing critical sections + (this solves many random communication errors) + Disable interrupts during read-modify-write I/O + Reduce RAM consumption by eliminating unnecessary + variables and trimming many to 8 bits + Optimize both crc8 - table version moved to flash + +Modified to work with larger numbers of devices - avoids loop. +Tested in Arduino 11 alpha with 12 sensors. +26 Sept 2008 -- Robin James +http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27 + +Updated to work with arduino-0008 and to include skip() as of +2007/07/06. --RJL20 + +Modified to calculate the 8-bit CRC directly, avoiding the need for +the 256-byte lookup table to be loaded in RAM. Tested in arduino-0010 +-- Tom Pollard, Jan 23, 2008 + +Jim Studt's original library was modified by Josh Larios. + +Tom Pollard, pollard@alum.mit.edu, contributed around May 20, 2008 + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Much of the code was inspired by Derek Yerger's code, though I don't +think much of that remains. In any event that was.. + (copyleft) 2006 by Derek Yerger - Free to distribute freely. + +The CRC code was excerpted and inspired by the Dallas Semiconductor +sample code bearing this copyright. +//--------------------------------------------------------------------------- +// Copyright (C) 2000 Dallas Semiconductor Corporation, All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES +// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// +// Except as contained in this notice, the name of Dallas Semiconductor +// shall not be used except as stated in the Dallas Semiconductor +// Branding Policy. +//-------------------------------------------------------------------------- +*/ + +#include "TembooOneWire.h" + + +TembooOneWire::TembooOneWire(uint8_t pin) +{ + pinMode(pin, INPUT); + bitmask = PIN_TO_BITMASK(pin); + baseReg = PIN_TO_BASEREG(pin); +#if ONEWIRE_SEARCH + reset_search(); +#endif +} + + +// Perform the onewire reset function. We will wait up to 250uS for +// the bus to come high, if it doesn't then it is broken or shorted +// and we return a 0; +// +// Returns 1 if a device asserted a presence pulse, 0 otherwise. +// +uint8_t TembooOneWire::reset(void) +{ + IO_REG_TYPE mask = bitmask; + volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg; + uint8_t r; + uint8_t retries = 125; + + noInterrupts(); + DIRECT_MODE_INPUT(reg, mask); + interrupts(); + // wait until the wire is high... just in case + do { + if (--retries == 0) return 0; + delayMicroseconds(2); + } while ( !DIRECT_READ(reg, mask)); + + noInterrupts(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + interrupts(); + delayMicroseconds(480); + noInterrupts(); + DIRECT_MODE_INPUT(reg, mask); // allow it to float + delayMicroseconds(70); + r = !DIRECT_READ(reg, mask); + interrupts(); + delayMicroseconds(410); + return r; +} + +// +// Write a bit. Port and bit is used to cut lookup time and provide +// more certain timing. +// +void TembooOneWire::write_bit(uint8_t v) +{ + IO_REG_TYPE mask=bitmask; + volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg; + + if (v & 1) { + noInterrupts(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + delayMicroseconds(10); + DIRECT_WRITE_HIGH(reg, mask); // drive output high + interrupts(); + delayMicroseconds(55); + } else { + noInterrupts(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + delayMicroseconds(65); + DIRECT_WRITE_HIGH(reg, mask); // drive output high + interrupts(); + delayMicroseconds(5); + } +} + +// +// Read a bit. Port and bit is used to cut lookup time and provide +// more certain timing. +// +uint8_t TembooOneWire::read_bit(void) +{ + IO_REG_TYPE mask=bitmask; + volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg; + uint8_t r; + + noInterrupts(); + DIRECT_MODE_OUTPUT(reg, mask); + DIRECT_WRITE_LOW(reg, mask); + delayMicroseconds(3); + DIRECT_MODE_INPUT(reg, mask); // let pin float, pull up will raise + delayMicroseconds(10); + r = DIRECT_READ(reg, mask); + interrupts(); + delayMicroseconds(53); + return r; +} + +// +// Write a byte. The writing code uses the active drivers to raise the +// pin high, if you need power after the write (e.g. DS18S20 in +// parasite power mode) then set 'power' to 1, otherwise the pin will +// go tri-state at the end of the write to avoid heating in a short or +// other mishap. +// +void TembooOneWire::write(uint8_t v, uint8_t power /* = 0 */) { + uint8_t bitMask; + + for (bitMask = 0x01; bitMask; bitMask <<= 1) { + TembooOneWire::write_bit( (bitMask & v)?1:0); + } + if ( !power) { + noInterrupts(); + DIRECT_MODE_INPUT(baseReg, bitmask); + DIRECT_WRITE_LOW(baseReg, bitmask); + interrupts(); + } +} + +void TembooOneWire::write_bytes(const uint8_t *buf, uint16_t count, bool power /* = 0 */) { + for (uint16_t i = 0 ; i < count ; i++) + write(buf[i]); + if (!power) { + noInterrupts(); + DIRECT_MODE_INPUT(baseReg, bitmask); + DIRECT_WRITE_LOW(baseReg, bitmask); + interrupts(); + } +} + +// +// Read a byte +// +uint8_t TembooOneWire::read() { + uint8_t bitMask; + uint8_t r = 0; + + for (bitMask = 0x01; bitMask; bitMask <<= 1) { + if ( TembooOneWire::read_bit()) r |= bitMask; + } + return r; +} + +void TembooOneWire::read_bytes(uint8_t *buf, uint16_t count) { + for (uint16_t i = 0 ; i < count ; i++) + buf[i] = read(); +} + +// +// Do a ROM select +// +void TembooOneWire::select(const uint8_t rom[8]) +{ + uint8_t i; + + write(0x55); // Choose ROM + + for (i = 0; i < 8; i++) write(rom[i]); +} + +// +// Do a ROM skip +// +void TembooOneWire::skip() +{ + write(0xCC); // Skip ROM +} + +void TembooOneWire::depower() +{ + noInterrupts(); + DIRECT_MODE_INPUT(baseReg, bitmask); + interrupts(); +} + +#if ONEWIRE_SEARCH + +// +// You need to use this function to start a search again from the beginning. +// You do not need to do it for the first search, though you could. +// +void TembooOneWire::reset_search() +{ + // reset the search state + LastDiscrepancy = 0; + LastDeviceFlag = FALSE; + LastFamilyDiscrepancy = 0; + for(int i = 7; ; i--) { + ROM_NO[i] = 0; + if ( i == 0) break; + } +} + +// Setup the search to find the device type 'family_code' on the next call +// to search(*newAddr) if it is present. +// +void TembooOneWire::target_search(uint8_t family_code) +{ + // set the search state to find SearchFamily type devices + ROM_NO[0] = family_code; + for (uint8_t i = 1; i < 8; i++) + ROM_NO[i] = 0; + LastDiscrepancy = 64; + LastFamilyDiscrepancy = 0; + LastDeviceFlag = FALSE; +} + +// +// Perform a search. If this function returns a '1' then it has +// enumerated the next device and you may retrieve the ROM from the +// OneWire::address variable. If there are no devices, no further +// devices, or something horrible happens in the middle of the +// enumeration then a 0 is returned. If a new device is found then +// its address is copied to newAddr. Use OneWire::reset_search() to +// start over. +// +// --- Replaced by the one from the Dallas Semiconductor web site --- +//-------------------------------------------------------------------------- +// Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing +// search state. +// Return TRUE : device found, ROM number in ROM_NO buffer +// FALSE : device not found, end of search +// +uint8_t TembooOneWire::search(uint8_t *newAddr, bool search_mode /* = true */) +{ + uint8_t id_bit_number; + uint8_t last_zero, rom_byte_number, search_result; + uint8_t id_bit, cmp_id_bit; + + unsigned char rom_byte_mask, search_direction; + + // initialize for search + id_bit_number = 1; + last_zero = 0; + rom_byte_number = 0; + rom_byte_mask = 1; + search_result = 0; + + // if the last call was not the last one + if (!LastDeviceFlag) + { + // 1-Wire reset + if (!reset()) + { + // reset the search + LastDiscrepancy = 0; + LastDeviceFlag = FALSE; + LastFamilyDiscrepancy = 0; + return FALSE; + } + + // issue the search command + if (search_mode == true) { + write(0xF0); // NORMAL SEARCH + } else { + write(0xEC); // CONDITIONAL SEARCH + } + + // loop to do the search + do + { + // read a bit and its complement + id_bit = read_bit(); + cmp_id_bit = read_bit(); + + // check for no devices on 1-wire + if ((id_bit == 1) && (cmp_id_bit == 1)) + break; + else + { + // all devices coupled have 0 or 1 + if (id_bit != cmp_id_bit) + search_direction = id_bit; // bit write value for search + else + { + // if this discrepancy if before the Last Discrepancy + // on a previous next then pick the same as last time + if (id_bit_number < LastDiscrepancy) + search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0); + else + // if equal to last pick 1, if not then pick 0 + search_direction = (id_bit_number == LastDiscrepancy); + + // if 0 was picked then record its position in LastZero + if (search_direction == 0) + { + last_zero = id_bit_number; + + // check for Last discrepancy in family + if (last_zero < 9) + LastFamilyDiscrepancy = last_zero; + } + } + + // set or clear the bit in the ROM byte rom_byte_number + // with mask rom_byte_mask + if (search_direction == 1) + ROM_NO[rom_byte_number] |= rom_byte_mask; + else + ROM_NO[rom_byte_number] &= ~rom_byte_mask; + + // serial number search direction write bit + write_bit(search_direction); + + // increment the byte counter id_bit_number + // and shift the mask rom_byte_mask + id_bit_number++; + rom_byte_mask <<= 1; + + // if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask + if (rom_byte_mask == 0) + { + rom_byte_number++; + rom_byte_mask = 1; + } + } + } + while(rom_byte_number < 8); // loop until through all ROM bytes 0-7 + + // if the search was successful then + if (!(id_bit_number < 65)) + { + // search successful so set LastDiscrepancy,LastDeviceFlag,search_result + LastDiscrepancy = last_zero; + + // check for last device + if (LastDiscrepancy == 0) + LastDeviceFlag = TRUE; + + search_result = TRUE; + } + } + + // if no device found then reset counters so next 'search' will be like a first + if (!search_result || !ROM_NO[0]) + { + LastDiscrepancy = 0; + LastDeviceFlag = FALSE; + LastFamilyDiscrepancy = 0; + search_result = FALSE; + } else { + for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i]; + } + return search_result; + } + +#endif + +#if ONEWIRE_CRC +// The 1-Wire CRC scheme is described in Maxim Application Note 27: +// "Understanding and Using Cyclic Redundancy Checks with Maxim iButton Products" +// + +#if ONEWIRE_CRC8_TABLE +// This table comes from Dallas sample code where it is freely reusable, +// though Copyright (C) 2000 Dallas Semiconductor Corporation +static const uint8_t PROGMEM dscrc_table[] = { + 0, 94,188,226, 97, 63,221,131,194,156,126, 32,163,253, 31, 65, + 157,195, 33,127,252,162, 64, 30, 95, 1,227,189, 62, 96,130,220, + 35,125,159,193, 66, 28,254,160,225,191, 93, 3,128,222, 60, 98, + 190,224, 2, 92,223,129, 99, 61,124, 34,192,158, 29, 67,161,255, + 70, 24,250,164, 39,121,155,197,132,218, 56,102,229,187, 89, 7, + 219,133,103, 57,186,228, 6, 88, 25, 71,165,251,120, 38,196,154, + 101, 59,217,135, 4, 90,184,230,167,249, 27, 69,198,152,122, 36, + 248,166, 68, 26,153,199, 37,123, 58,100,134,216, 91, 5,231,185, + 140,210, 48,110,237,179, 81, 15, 78, 16,242,172, 47,113,147,205, + 17, 79,173,243,112, 46,204,146,211,141,111, 49,178,236, 14, 80, + 175,241, 19, 77,206,144,114, 44,109, 51,209,143, 12, 82,176,238, + 50,108,142,208, 83, 13,239,177,240,174, 76, 18,145,207, 45,115, + 202,148,118, 40,171,245, 23, 73, 8, 86,180,234,105, 55,213,139, + 87, 9,235,181, 54,104,138,212,149,203, 41,119,244,170, 72, 22, + 233,183, 85, 11,136,214, 52,106, 43,117,151,201, 74, 20,246,168, + 116, 42,200,150, 21, 75,169,247,182,232, 10, 84,215,137,107, 53}; + +// +// Compute a Dallas Semiconductor 8 bit CRC. These show up in the ROM +// and the registers. (note: this might better be done without to +// table, it would probably be smaller and certainly fast enough +// compared to all those delayMicrosecond() calls. But I got +// confused, so I use this table from the examples.) +// +uint8_t TembooOneWire::crc8(const uint8_t *addr, uint8_t len) +{ + uint8_t crc = 0; + + while (len--) { + crc = pgm_read_byte(dscrc_table + (crc ^ *addr++)); + } + return crc; +} +#else +// +// Compute a Dallas Semiconductor 8 bit CRC directly. +// this is much slower, but much smaller, than the lookup table. +// +uint8_t TembooOneWire::crc8(const uint8_t *addr, uint8_t len) +{ + uint8_t crc = 0; + + while (len--) { +#if defined(__AVR__) + crc = _crc_ibutton_update(crc, *addr++); +#else + uint8_t inbyte = *addr++; + for (uint8_t i = 8; i; i--) { + uint8_t mix = (crc ^ inbyte) & 0x01; + crc >>= 1; + if (mix) crc ^= 0x8C; + inbyte >>= 1; + } +#endif + } + return crc; +} +#endif + +#if ONEWIRE_CRC16 +bool TembooOneWire::check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc) +{ + crc = ~crc16(input, len, crc); + return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1]; +} + +uint16_t TembooOneWire::crc16(const uint8_t* input, uint16_t len, uint16_t crc) +{ +#if defined(__AVR__) + for (uint16_t i = 0 ; i < len ; i++) { + crc = _crc16_update(crc, input[i]); + } +#else + static const uint8_t oddparity[16] = + { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; + + for (uint16_t i = 0 ; i < len ; i++) { + // Even though we're just copying a byte from the input, + // we'll be doing 16-bit computation with it. + uint16_t cdata = input[i]; + cdata = (cdata ^ crc) & 0xff; + crc >>= 8; + + if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4]) + crc ^= 0xC001; + + cdata <<= 6; + crc ^= cdata; + cdata <<= 1; + crc ^= cdata; + } +#endif + return crc; +} +#endif + +#endif diff --git a/src/utility/TembooOneWire.h b/src/utility/TembooOneWire.h new file mode 100644 index 0000000..930f075 --- /dev/null +++ b/src/utility/TembooOneWire.h @@ -0,0 +1,371 @@ +#ifndef TembooOneWire_h +#define TembooOneWire_h + +#include + +#if defined(__AVR__) +#include +#endif + +#if ARDUINO >= 100 +#include "Arduino.h" // for delayMicroseconds, digitalPinToBitMask, etc +#else +#include "WProgram.h" // for delayMicroseconds +#include "pins_arduino.h" // for digitalPinToBitMask, etc +#endif + +// You can exclude certain features from OneWire. In theory, this +// might save some space. In practice, the compiler automatically +// removes unused code (technically, the linker, using -fdata-sections +// and -ffunction-sections when compiling, and Wl,--gc-sections +// when linking), so most of these will not result in any code size +// reduction. Well, unless you try to use the missing features +// and redesign your program to not need them! ONEWIRE_CRC8_TABLE +// is the exception, because it selects a fast but large algorithm +// or a small but slow algorithm. + +// you can exclude onewire_search by defining that to 0 +#ifndef ONEWIRE_SEARCH +#define ONEWIRE_SEARCH 1 +#endif + +// You can exclude CRC checks altogether by defining this to 0 +#ifndef ONEWIRE_CRC +#define ONEWIRE_CRC 1 +#endif + +// Select the table-lookup method of computing the 8-bit CRC +// by setting this to 1. The lookup table enlarges code size by +// about 250 bytes. It does NOT consume RAM (but did in very +// old versions of OneWire). If you disable this, a slower +// but very compact algorithm is used. +#ifndef ONEWIRE_CRC8_TABLE +#define ONEWIRE_CRC8_TABLE 1 +#endif + +// You can allow 16-bit CRC checks by defining this to 1 +// (Note that ONEWIRE_CRC must also be 1.) +#ifndef ONEWIRE_CRC16 +#define ONEWIRE_CRC16 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif +#ifndef TRUE +#define TRUE 1 +#endif + +// Platform specific I/O definitions + +#if defined(__AVR__) +#define PIN_TO_BASEREG(pin) (portInputRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint8_t +#define IO_REG_ASM asm("r30") +#define DIRECT_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+1)) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+2)) &= ~(mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+2)) |= (mask)) + +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) +#define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) +#define PIN_TO_BITMASK(pin) (1) +#define IO_REG_TYPE uint8_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (*((base)+512)) +#define DIRECT_MODE_INPUT(base, mask) (*((base)+640) = 0) +#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+640) = 1) +#define DIRECT_WRITE_LOW(base, mask) (*((base)+256) = 1) +#define DIRECT_WRITE_HIGH(base, mask) (*((base)+128) = 1) + +#elif defined(__MKL26Z64__) +#define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint8_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) ((*((base)+16) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) (*((base)+20) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+20) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) (*((base)+8) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) (*((base)+4) = (mask)) + +#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) +// Arduino 1.5.1 may have a bug in delayMicroseconds() on Arduino Due. +// http://arduino.cc/forum/index.php/topic,141030.msg1076268.html#msg1076268 +// If you have trouble with OneWire on Arduino Due, please check the +// status of delayMicroseconds() before reporting a bug in OneWire! +#define PIN_TO_BASEREG(pin) (&(digitalPinToPort(pin)->PIO_PER)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (((*((base)+15)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+5)) = (mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+4)) = (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+13)) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+12)) = (mask)) +#ifndef PROGMEM +#define PROGMEM +#endif +#ifndef pgm_read_byte +#define pgm_read_byte(addr) (*(const uint8_t *)(addr)) +#endif + +#elif defined(__PIC32MX__) +#define PIN_TO_BASEREG(pin) (portModeRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (((*(base+4)) & (mask)) ? 1 : 0) //PORTX + 0x10 +#define DIRECT_MODE_INPUT(base, mask) ((*(base+2)) = (mask)) //TRISXSET + 0x08 +#define DIRECT_MODE_OUTPUT(base, mask) ((*(base+1)) = (mask)) //TRISXCLR + 0x04 +#define DIRECT_WRITE_LOW(base, mask) ((*(base+8+1)) = (mask)) //LATXCLR + 0x24 +#define DIRECT_WRITE_HIGH(base, mask) ((*(base+8+2)) = (mask)) //LATXSET + 0x28 + +#elif defined(ARDUINO_ARCH_ESP8266) +#define PIN_TO_BASEREG(pin) ((volatile uint32_t*) GPO) +#define PIN_TO_BITMASK(pin) (1 << pin) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) ((GPI & (mask)) ? 1 : 0) //GPIO_IN_ADDRESS +#define DIRECT_MODE_INPUT(base, mask) (GPE &= ~(mask)) //GPIO_ENABLE_W1TC_ADDRESS +#define DIRECT_MODE_OUTPUT(base, mask) (GPE |= (mask)) //GPIO_ENABLE_W1TS_ADDRESS +#define DIRECT_WRITE_LOW(base, mask) (GPOC = (mask)) //GPIO_OUT_W1TC_ADDRESS +#define DIRECT_WRITE_HIGH(base, mask) (GPOS = (mask)) //GPIO_OUT_W1TS_ADDRESS + +#elif defined(__SAMD21G18A__) +#define PIN_TO_BASEREG(pin) portModeRegister(digitalPinToPort(pin)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (((*((base)+8)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) = (mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+2)) = (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+5)) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+6)) = (mask)) + +#elif defined(RBL_NRF51822) +#define PIN_TO_BASEREG(pin) (0) +#define PIN_TO_BITMASK(pin) (pin) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, pin) nrf_gpio_pin_read(pin) +#define DIRECT_WRITE_LOW(base, pin) nrf_gpio_pin_clear(pin) +#define DIRECT_WRITE_HIGH(base, pin) nrf_gpio_pin_set(pin) +#define DIRECT_MODE_INPUT(base, pin) nrf_gpio_cfg_input(pin, NRF_GPIO_PIN_NOPULL) +#define DIRECT_MODE_OUTPUT(base, pin) nrf_gpio_cfg_output(pin) + +#elif defined(__arc__) /* Arduino101/Genuino101 specifics */ + +#include "scss_registers.h" +#include "portable.h" +#include "avr/pgmspace.h" + +#define GPIO_ID(pin) (g_APinDescription[pin].ulGPIOId) +#define GPIO_TYPE(pin) (g_APinDescription[pin].ulGPIOType) +#define GPIO_BASE(pin) (g_APinDescription[pin].ulGPIOBase) +#define DIR_OFFSET_SS 0x01 +#define DIR_OFFSET_SOC 0x04 +#define EXT_PORT_OFFSET_SS 0x0A +#define EXT_PORT_OFFSET_SOC 0x50 + +/* GPIO registers base address */ +#define PIN_TO_BASEREG(pin) ((volatile uint32_t *)g_APinDescription[pin].ulGPIOBase) +#define PIN_TO_BITMASK(pin) pin +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM + +static inline __attribute__((always_inline)) +IO_REG_TYPE directRead(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + IO_REG_TYPE ret; + if (SS_GPIO == GPIO_TYPE(pin)) { + ret = READ_ARC_REG(((IO_REG_TYPE)base + EXT_PORT_OFFSET_SS)); + } else { + ret = MMIO_REG_VAL_FROM_BASE((IO_REG_TYPE)base, EXT_PORT_OFFSET_SOC); + } + return ((ret >> GPIO_ID(pin)) & 0x01); +} + +static inline __attribute__((always_inline)) +void directModeInput(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG((((IO_REG_TYPE)base) + DIR_OFFSET_SS)) & ~(0x01 << GPIO_ID(pin)), + ((IO_REG_TYPE)(base) + DIR_OFFSET_SS)); + } else { + MMIO_REG_VAL_FROM_BASE((IO_REG_TYPE)base, DIR_OFFSET_SOC) &= ~(0x01 << GPIO_ID(pin)); + } +} + +static inline __attribute__((always_inline)) +void directModeOutput(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG(((IO_REG_TYPE)(base) + DIR_OFFSET_SS)) | (0x01 << GPIO_ID(pin)), + ((IO_REG_TYPE)(base) + DIR_OFFSET_SS)); + } else { + MMIO_REG_VAL_FROM_BASE((IO_REG_TYPE)base, DIR_OFFSET_SOC) |= (0x01 << GPIO_ID(pin)); + } +} + +static inline __attribute__((always_inline)) +void directWriteLow(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG(base) & ~(0x01 << GPIO_ID(pin)), base); + } else { + MMIO_REG_VAL(base) &= ~(0x01 << GPIO_ID(pin)); + } +} + +static inline __attribute__((always_inline)) +void directWriteHigh(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG(base) | (0x01 << GPIO_ID(pin)), base); + } else { + MMIO_REG_VAL(base) |= (0x01 << GPIO_ID(pin)); + } +} + +#define DIRECT_READ(base, pin) directRead(base, pin) +#define DIRECT_MODE_INPUT(base, pin) directModeInput(base, pin) +#define DIRECT_MODE_OUTPUT(base, pin) directModeOutput(base, pin) +#define DIRECT_WRITE_LOW(base, pin) directWriteLow(base, pin) +#define DIRECT_WRITE_HIGH(base, pin) directWriteHigh(base, pin) + +#else +#define PIN_TO_BASEREG(pin) (0) +#define PIN_TO_BITMASK(pin) (pin) +#define IO_REG_TYPE unsigned int +#define IO_REG_ASM +#define DIRECT_READ(base, pin) digitalRead(pin) +#define DIRECT_WRITE_LOW(base, pin) digitalWrite(pin, LOW) +#define DIRECT_WRITE_HIGH(base, pin) digitalWrite(pin, HIGH) +#define DIRECT_MODE_INPUT(base, pin) pinMode(pin,INPUT) +#define DIRECT_MODE_OUTPUT(base, pin) pinMode(pin,OUTPUT) +#warning "OneWire. Fallback mode. Using API calls for pinMode,digitalRead and digitalWrite. Operation of this library is not guaranteed on this architecture." + +#endif + + +class TembooOneWire +{ + private: + IO_REG_TYPE bitmask; + volatile IO_REG_TYPE *baseReg; + +#if ONEWIRE_SEARCH + // global search state + unsigned char ROM_NO[8]; + uint8_t LastDiscrepancy; + uint8_t LastFamilyDiscrepancy; + uint8_t LastDeviceFlag; +#endif + + public: + TembooOneWire( uint8_t pin); + + // Perform a 1-Wire reset cycle. Returns 1 if a device responds + // with a presence pulse. Returns 0 if there is no device or the + // bus is shorted or otherwise held low for more than 250uS + uint8_t reset(void); + + // Issue a 1-Wire rom select command, you do the reset first. + void select(const uint8_t rom[8]); + + // Issue a 1-Wire rom skip command, to address all on bus. + void skip(void); + + // Write a byte. If 'power' is one then the wire is held high at + // the end for parasitically powered devices. You are responsible + // for eventually depowering it by calling depower() or doing + // another read or write. + void write(uint8_t v, uint8_t power = 0); + + void write_bytes(const uint8_t *buf, uint16_t count, bool power = 0); + + // Read a byte. + uint8_t read(void); + + void read_bytes(uint8_t *buf, uint16_t count); + + // Write a bit. The bus is always left powered at the end, see + // note in write() about that. + void write_bit(uint8_t v); + + // Read a bit. + uint8_t read_bit(void); + + // Stop forcing power onto the bus. You only need to do this if + // you used the 'power' flag to write() or used a write_bit() call + // and aren't about to do another read or write. You would rather + // not leave this powered if you don't have to, just in case + // someone shorts your bus. + void depower(void); + +#if ONEWIRE_SEARCH + // Clear the search state so that if will start from the beginning again. + void reset_search(); + + // Setup the search to find the device type 'family_code' on the next call + // to search(*newAddr) if it is present. + void target_search(uint8_t family_code); + + // Look for the next device. Returns 1 if a new address has been + // returned. A zero might mean that the bus is shorted, there are + // no devices, or you have already retrieved all of them. It + // might be a good idea to check the CRC to make sure you didn't + // get garbage. The order is deterministic. You will always get + // the same devices in the same order. + uint8_t search(uint8_t *newAddr, bool search_mode = true); +#endif + +#if ONEWIRE_CRC + // Compute a Dallas Semiconductor 8 bit CRC, these are used in the + // ROM and scratchpad registers. + static uint8_t crc8(const uint8_t *addr, uint8_t len); + +#if ONEWIRE_CRC16 + // Compute the 1-Wire CRC16 and compare it against the received CRC. + // Example usage (reading a DS2408): + // // Put everything in a buffer so we can compute the CRC easily. + // uint8_t buf[13]; + // buf[0] = 0xF0; // Read PIO Registers + // buf[1] = 0x88; // LSB address + // buf[2] = 0x00; // MSB address + // WriteBytes(net, buf, 3); // Write 3 cmd bytes + // ReadBytes(net, buf+3, 10); // Read 6 data bytes, 2 0xFF, 2 CRC16 + // if (!CheckCRC16(buf, 11, &buf[11])) { + // // Handle error. + // } + // + // @param input - Array of bytes to checksum. + // @param len - How many bytes to use. + // @param inverted_crc - The two CRC16 bytes in the received data. + // This should just point into the received data, + // *not* at a 16-bit integer. + // @param crc - The crc starting value (optional) + // @return True, iff the CRC matches. + static bool check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc = 0); + + // Compute a Dallas Semiconductor 16 bit CRC. This is required to check + // the integrity of data received from many 1-Wire devices. Note that the + // CRC computed here is *not* what you'll get from the 1-Wire network, + // for two reasons: + // 1) The CRC is transmitted bitwise inverted. + // 2) Depending on the endian-ness of your processor, the binary + // representation of the two-byte return value may have a different + // byte order than the two bytes you get from 1-Wire. + // @param input - Array of bytes to checksum. + // @param len - How many bytes to use. + // @param crc - The crc starting value (optional) + // @return The CRC16, as defined by Dallas Semiconductor. + static uint16_t crc16(const uint8_t* input, uint16_t len, uint16_t crc = 0); +#endif +#endif +}; + +#endif \ No newline at end of file diff --git a/src/utility/TembooWebSocketRequestHandles.c b/src/utility/TembooWebSocketRequestHandles.c index 113c6c9..d14c8f9 100644 --- a/src/utility/TembooWebSocketRequestHandles.c +++ b/src/utility/TembooWebSocketRequestHandles.c @@ -27,15 +27,15 @@ static WSMessageRequest handleMessageRequest(char** saveptr); static WSMessageRequest handleIntervalRequest(char** saveptr); -static WSMessageRequest handleSetRequest(char** saveptr, TembooPinTable* pinTable, int pinTableDepth); -static WSMessageRequest handleGetRequest(char** saveptr, TembooPinTable* pinTable, int pinTableDepth); +static WSMessageRequest handleSetRequest(char** saveptr, TembooSensor** sensorTable, int sensorTableDepth); +static WSMessageRequest handleGetRequest(char** saveptr, TembooSensor** sensorTable, int sensorTableDepth); static WSMessageRequest handleMonitoringUpdateRequest(char**saveptr); static const uint16_t WS_MAX_PAYLOAD_SIZE = 126; -WSMessageRequest handleGetRequest(char** saveptr, TembooPinTable* pinTable, int pinTableDepth) { +WSMessageRequest handleGetRequest(char** saveptr, TembooSensor** sensorTable, int sensorTableDepth) { char* textField = strtok_r(NULL, "|", &(*saveptr)); int pinNum = -1; int pinVal = -1; @@ -43,11 +43,31 @@ WSMessageRequest handleGetRequest(char** saveptr, TembooPinTable* pinTable, int // strlen should catch the + sign while (textField != NULL && strlen(textField) >= 2) { if (*textField == 'P') { - if (isdigit(textField[1]) && strlen(&textField[1]) < 4) { - pinNum = atoi(&textField[1]); + // if pinNum is already set, then an extra pin number + // has been added to the request incorrectly + if (pinNum != -1) { + logTembooDebug("Invalid Get request\n"); + return WS_REQUEST_ERROR; + } + size_t i = 0; + // make sure the pin value is made of digits + while (i < strlen(&textField[1])) { + if (isdigit(textField[1 + i++]) == 0) { + logTembooDebug(("Invalid pin number\n")); + return WS_REQUEST_ERROR; + } + } + pinNum = atoi(&textField[1]); + // make sure pin number is valid, set to -1 if error + if (pinNum > MAX_PIN_NUMBER) { + logTembooDebug(("Invalid pin number\n")); + pinNum = -1; } } else if (*textField == '+') { break; + } else { + logTembooDebug("Invalid message key\n"); + return WS_REQUEST_ERROR; } textField = strtok_r(NULL, "|", &(*saveptr)); } @@ -55,15 +75,9 @@ WSMessageRequest handleGetRequest(char** saveptr, TembooPinTable* pinTable, int if (pinNum >= 0) { //obtain the data and send to Temboo int i = 0; - for (i = 0; i < pinTableDepth; i++) { - if (pinTable[i].pin == pinNum) { - if (pinTable[i].pinRead != NULL) { - // input pin - pinVal = pinTable[i].pinRead(pinNum); - } else { - // output pin/actuator, use saved value - pinVal = pinTable[i].currentPinValue; - } + for (i = 0; i < sensorTableDepth; i++) { + if (sensorTable[i]->getSensorPin(sensorTable[i]->sensorConfig) == pinNum) { + pinVal = sensorTable[i]->read(sensorTable[i]->sensorConfig); rc = WS_GET_REQUEST; break; } @@ -76,7 +90,7 @@ WSMessageRequest handleGetRequest(char** saveptr, TembooPinTable* pinTable, int return rc; } -WSMessageRequest handleSetRequest(char** saveptr, TembooPinTable* pinTable, int pinTableDepth) { +WSMessageRequest handleSetRequest(char** saveptr, TembooSensor** sensorTable, int sensorTableDepth) { int pinNum = -1; int pinVal = -1; bool pinValSet = false; @@ -84,28 +98,65 @@ WSMessageRequest handleSetRequest(char** saveptr, TembooPinTable* pinTable, int char* textField = strtok_r(NULL, "|", &(*saveptr)); while (textField != NULL && strlen(textField) >= 2) { if (*textField == 'P') { - if (isdigit(textField[1]) && strlen(&textField[1]) < 4) { - pinNum = atoi(&textField[1]); + // if pinNum is already set, then an extra pin number + // has been added to the request incorrectly + if (pinNum != -1) { + logTembooDebug("Invalid Set request\n"); + return WS_REQUEST_ERROR; + } + size_t i = 0; + // make sure the pin value is made of digits + while (i < strlen(&textField[1])) { + if (isdigit(textField[1 + i++]) == 0) { + logTembooDebug(("Invalid pin number\n")); + return WS_REQUEST_ERROR; + } + } + pinNum = atoi(&textField[1]); + // make sure pin number is valid, set to -1 if error + if (pinNum > MAX_PIN_NUMBER) { + logTembooDebug(("Invalid pin number\n")); + return WS_REQUEST_ERROR; } } else if (*textField == 'V') { - if (isdigit(textField[1]) && strlen(&textField[1]) < 7) { - pinVal = atoi(&textField[1]); + // if pinVal is already set, then an extra pin value + // has been added to the request incorrectly + if (pinValSet) { + logTembooDebug("Invalid Set request\n"); + return WS_REQUEST_ERROR; + } + size_t i = 0; + // make sure the pin value is made of digits + while (i < strlen(&textField[1])) { + if (isdigit(textField[1 + i++]) == 0) { + logTembooDebug(("Invalid pin value\n")); + return WS_REQUEST_ERROR; + } + } + pinVal = atoi(&textField[1]); + // make sure pin value is valid, pinValSet will remain false + if (pinVal > MAX_PIN_VALUE) { + logTembooDebug(("Invalid pin value\n")); + return WS_REQUEST_ERROR; + } else { pinValSet = true; } } else if (*textField == '+') { break; + } else { + logTembooDebug("Invalid message key\n"); + return WS_REQUEST_ERROR; } textField = strtok_r(NULL, "|", &(*saveptr)); } if (pinNum >= 0 && pinValSet) { - int i = 0; - for (; i < pinTableDepth; i++) { - if (pinTable[i].pin == pinNum) { - if (pinTable[i].pinWrite != NULL) { - pinTable[i].currentPinValue = pinVal; - pinTable[i].pinWrite(pinNum, pinVal); + int i = 0; + for (; i < sensorTableDepth; i++) { + if (sensorTable[i]->getSensorPin(sensorTable[i]->sensorConfig) == pinNum) { + if (sensorTable[i]->write != NULL) { + sensorTable[i]->write(sensorTable[i]->sensorConfig, pinVal); rc = WS_SET_REQUEST; } break; @@ -119,8 +170,52 @@ WSMessageRequest handleSetRequest(char** saveptr, TembooPinTable* pinTable, int return rc; } +// Parse out the error message while ignoring escaped characters. +// This functions acts like strstr where it will move saveptr +// to the index past the delimeter ('|' in this case), add '\0' +// where the delimeter is, and return the pointer of the error message +char* getErrorMessage(char** saveptr) { + if (saveptr == NULL || *saveptr == NULL) { + return NULL; + } + char* tok = *saveptr; + size_t len = strlen(*saveptr); + (*saveptr)++; + if (**saveptr == '\0') { + return NULL; + } + while (**saveptr != '\0') { + // check for delimiter + if (**saveptr == '\\') { + // check if we're escaping a special character + switch (*(*saveptr+1)) { + case '+': + case '|': + case '\\': + // shift string over 1 and increment + memmove(*saveptr,*saveptr+1, --len); + (*saveptr)++; + break; + default: + break; + } + } else if (**saveptr == '|') { + // end of message + **saveptr = '\0'; + (*saveptr)++; + return tok; + } else { + // increment pointer and decrement str length + (*saveptr)++; + len--; + } + } + // return string when if the end of the text is found + return tok; +} + WSMessageRequest handleMessageRequest(char** saveptr) { - char* textField = strtok_r(NULL, "|", &(*saveptr)); + char* textField = getErrorMessage(&(*saveptr)); WSMessageRequest rc = WS_REQUEST_ERROR; if (textField != NULL && strlen(textField) >= 2) { if (*textField == 'T') { @@ -162,7 +257,7 @@ WSMessageRequest handleIntervalRequest(char** saveptr) { return rc; } -WSMessageRequest handleResponse(uint8_t* request, TembooPinTable* pinTable, int pinTableDepth, bool connectionStatus) { +WSMessageRequest handleResponse(uint8_t* request, TembooSensor** sensorTable, int sensorTableDepth, bool connectionStatus) { // parse response to find request type char* saveptr = NULL; char* requestField = strtok_r((char*)request, "|", &saveptr); @@ -175,13 +270,13 @@ WSMessageRequest handleResponse(uint8_t* request, TembooPinTable* pinTable, int case 'G': // send pin data to Temboo if (connectionStatus) { - rc = handleGetRequest(&saveptr, pinTable, pinTableDepth); + rc = handleGetRequest(&saveptr, sensorTable, sensorTableDepth); } break; case 'S': // change state of a pin if (connectionStatus) { - rc = handleSetRequest(&saveptr, pinTable, pinTableDepth); + rc = handleSetRequest(&saveptr, sensorTable, sensorTableDepth); } break; case 'E': diff --git a/src/utility/TembooWebSocketRequestHandles.h b/src/utility/TembooWebSocketRequestHandles.h index 0223f5f..c7d2ff9 100644 --- a/src/utility/TembooWebSocketRequestHandles.h +++ b/src/utility/TembooWebSocketRequestHandles.h @@ -29,6 +29,14 @@ extern "C" { #endif +#ifndef MAX_PIN_NUMBER +#define MAX_PIN_NUMBER 256 +#endif + +#ifndef MAX_PIN_VALUE +#define MAX_PIN_VALUE 255 +#endif + typedef enum { WS_GET_REQUEST = 0, WS_SET_REQUEST, @@ -43,19 +51,21 @@ typedef enum { 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; +typedef struct TembooSensor{ + void* sensorConfig; + int (*read)(void* sensorConfig); + void (*write)(void* sensorConfig, int val); + void (*begin)(void* sensorConfig); + int (*getSensorPin)(void*sensorConfig); + uint8_t* (*getSensorChannel)(void*sensorConfig); int defaultValue; -} TembooPinTable; +} TembooSensor; 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); +WSMessageRequest handleResponse(uint8_t* request, TembooSensor** sensors, int sensorTableDepth, bool connectionStatus); void logTembooDebug(const char *c); #if defined(__cplusplus) } From 35c816e1dbb67246986cc5efd2cd3e903632d996 Mon Sep 17 00:00:00 2001 From: kevinbuck-temboo Date: Mon, 31 Oct 2016 16:54:04 -0400 Subject: [PATCH 2/2] update handler --- src/utility/TembooWebSocketRequestHandles.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/utility/TembooWebSocketRequestHandles.c b/src/utility/TembooWebSocketRequestHandles.c index d14c8f9..3e570f6 100644 --- a/src/utility/TembooWebSocketRequestHandles.c +++ b/src/utility/TembooWebSocketRequestHandles.c @@ -197,6 +197,9 @@ char* getErrorMessage(char** saveptr) { (*saveptr)++; break; default: + // increment pointer and decrement str length + (*saveptr)++; + len--; break; } } else if (**saveptr == '|') {