Release version 5.13.0
This commit is contained in:
Theo Arends 2018-04-30 17:10:21 +02:00
parent f4dec9df40
commit 6f5800173c
181 changed files with 25419 additions and 2796 deletions

10
.gitignore vendored
View File

@ -1,6 +1,14 @@
.pioenvs
## OS specific ########
.DS_Store
.fuse_hidden*
## Project files ######.pioenvs
.piolibdeps
.clang_complete
.gcc-flags.json
.vscode
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
sonoff/user_config_override.h
.pioenvs

130
README.md
View File

@ -1,6 +1,6 @@
## Sonoff-Tasmota
Alternative firmware for _ESP8266 based devices_ like [iTead](https://www.itead.cc/) _**Sonoff**_ with **web**, **timers**, 'Over The Air' (**OTA**) firmware updates and **sensors support**, allowing control under **Serial**, **HTTP** and **MQTT**, so as to be used on **Smart Home Systems**. Written for Arduino IDE and PlatformIO.
Alternative firmware for _ESP8266 based devices_ like [iTead](https://www.itead.cc/) _**Sonoff**_ with **web**, **timers**, 'Over The Air' (**OTA**) firmware updates and **sensors support**, allowing control under **Serial**, **HTTP**, **MQTT** and **KNX**, so as to be used on **Smart Home Systems**. Written for Arduino IDE and PlatformIO.
[![GitHub version](https://img.shields.io/github/release/arendst/Sonoff-Tasmota.svg)](https://github.com/arendst/Sonoff-Tasmota/releases/latest)
[![GitHub download](https://img.shields.io/github/downloads/arendst/Sonoff-Tasmota/total.svg)](https://github.com/arendst/Sonoff-Tasmota/releases/latest)
@ -10,6 +10,8 @@ If you like **Sonoff-Tasmota**, give it a star, or fork it and contribute!
[![GitHub stars](https://img.shields.io/github/stars/arendst/Sonoff-Tasmota.svg?style=social&label=Star)](https://github.com/arendst/Sonoff-Tasmota/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/arendst/Sonoff-Tasmota.svg?style=social&label=Fork)](https://github.com/arendst/Sonoff-Tasmota/network)
See [sonoff/_releasenotes.ino](https://github.com/arendst/Sonoff-Tasmota/blob/master/sonoff/_releasenotes.ino) for change information.
### Quick install
Download one of the released binaries from https://github.com/arendst/Sonoff-Tasmota/releases and flash it to your hardware as documented in the wiki.
@ -39,9 +41,10 @@ The following devices are supported:
- [iTead Sonoff SV](https://www.itead.cc/smart-home/sonoff-sv.html)<img src="https://github.com/arendst/arendst.github.io/blob/master/media/sonoff_th.jpg" width="250" align="right" />
- [iTead Sonoff TH10/TH16 with temperature sensor](https://www.itead.cc/smart-home/sonoff-th.html)
- [iTead Sonoff Dual (R2)](https://www.itead.cc/smart-home/sonoff-dual.html)
- [iTead Sonoff Pow](https://www.itead.cc/smart-home/sonoff-pow.html)
- [iTead Sonoff 4CH](https://www.itead.cc/smart-home/sonoff-4ch.html)
- [iTead Sonoff 4CH Pro](https://www.itead.cc/smart-home/sonoff-4ch-pro.html)
- [iTead Sonoff Pow with Energy Monitoring](https://www.itead.cc/smart-home/sonoff-pow.html)
- [iTead Sonoff Pow R2 with Energy Monitoring](https://www.itead.cc/sonoff-pow-r2.html)
- [iTead Sonoff 4CH (R2)](https://www.itead.cc/smart-home/sonoff-4ch.html)
- [iTead Sonoff 4CH Pro (R2)](https://www.itead.cc/smart-home/sonoff-4ch-pro.html)
- [iTead S20 Smart Socket](https://www.itead.cc/smart-socket.html)
- [Sonoff S22 Smart Socket](https://github.com/arendst/Sonoff-Tasmota/issues/627)
- [iTead Sonoff S31 Smart Socket with Energy Monitoring](https://www.itead.cc/sonoff-s31.html)
@ -49,7 +52,7 @@ The following devices are supported:
- [iTead Sonoff Touch](https://www.itead.cc/sonoff-touch.html)
- [iTead Sonoff T1](https://www.itead.cc/sonoff-t1.html)
- [iTead Sonoff SC](https://www.itead.cc/sonoff-sc.html)
- [iTead Sonoff Led](https://www.itead.cc/sonoff-led.html)<img src="https://github.com/arendst/arendst.github.io/blob/master/media/sonoff4ch.jpg" height="250" align="right" />
- [iTead Sonoff Led](https://www.itead.cc/sonoff-led.html)<img src="https://github.com/arendst/arendst.github.io/blob/master/media/sonoff4chpror2.jpg" height="250" align="right" />
- [iTead Sonoff BN-SZ01 Ceiling Led](https://www.itead.cc/bn-sz01.html)
- [iTead Sonoff B1](https://www.itead.cc/sonoff-b1.html)
- [iTead Sonoff RF Bridge 433](https://www.itead.cc/sonoff-rf-bridge-433.html)
@ -63,17 +66,126 @@ The following devices are supported:
- AriLux AL-LC01, AL-LC06 and AL-LC11 PWM LED controller
- [Supla device - Espablo-inCan mod. for electrical Installation box](https://forum.supla.org/viewtopic.php?f=33&t=2188)
- [Luani HVIO board](https://luani.de/projekte/esp8266-hvio/)
- Wemos D1 mini and NodeMcu
- Wemos D1 mini, NodeMcu and Ledunia
### Firmware release information
Different firmware images are released based on Features and Sensors selection guided by code and memory usage.
- The Minimal version allows intermediate OTA uploads to support larger versions and does NOT change any persistent parameter.
- The Classic version allows single OTA uploads as did the previous Sonoff-Tasmota versions.
#### Available Features and Sensors
| Feature or Sensor | sonoff | classic | minimal | knx | allsensors |
|--------------------------------|--------|---------|---------|-----|------------|
| MY_LANGUAGE en-GB | x | x | x | x | x |
| MQTT_LIBRARY_TYPE PUBSUBCLIENT | x | x | x | x | x |
| USE_DOMOTICZ | x | x | - | x | x |
| USE_HOME_ASSISTANT | x | x | - | x | x |
| USE_MQTT_TLS | - | - | - | - | - |
| USE_KNX | - | - | - | x | - |
| USE_WEBSERVER | x | x | x | x | x |
| USE_EMULATION | x | x | - | - | x |
| USE_DISCOVERY | x | x | - | x | x |
| WEBSERVER_ADVERTISE | x | x | - | x | x |
| MQTT_HOST_DISCOVERY | x | x | - | x | x |
| USE_TIMERS | x | - | - | x | x |
| USE_TIMERS_WEB | x | - | - | x | x |
| USE_SUNRISE | x | - | - | x | x |
| USE_RULES | x | - | - | x | x |
| | | | | | |
| USE_ADC_VCC | x | x | x | x | x |
| USE_DS18B20 | x | x | - | x | - |
| USE_DS18x20 | - | - | - | - | x |
| USE_DS18x20_LEGACY | - | - | - | - | - |
| USE_I2C | x | x | - | x | x |
| USE_SHT | x | x | - | x | x |
| USE_SHT3X | x | x | - | x | x |
| USE_HTU | x | x | - | x | x |
| USE_BMP | x | x | - | x | x |
| USE_BME680 | - | - | - | - | x |
| USE_SGP30 | x | - | - | x | x |
| USE_BH1750 | x | x | - | x | x |
| USE_VEML6070 | - | - | - | - | x |
| USE_TSL2561 | - | - | - | - | x |
| USE_ADS1115 | - | - | - | - | x |
| USE_ADS1115_I2CDEV | - | - | - | - | - |
| USE_INA219 | - | - | - | - | x |
| USE_MGS | - | - | - | - | x |
| USE_SPI | - | - | - | - | - |
| USE_MHZ19 | x | x | - | x | x |
| USE_SENSEAIR | x | x | - | x | x |
| USE_PMS5003 | x | x | - | x | x |
| USE_NOVA_SDS | x | - | - | x | x |
| USE_PZEM004T | x | x | - | x | x |
| USE_SERIAL_BRIDGE | x | - | - | x | x |
| USE_IR_REMOTE | x | x | - | x | x |
| USE_IR_HVAC | - | - | - | - | x |
| USE_IR_RECEIVE | x | - | - | x | x |
| USE_WS2812 | x | x | - | x | x |
| USE_WS2812_DMA | - | - | - | - | - |
| USE_ARILUX_RF | x | x | - | x | x |
| USE_SR04 | x | - | - | x | x |
#### Typical file size
| ESP/Arduino library version | sonoff | classic | minimal | knx | allsensors |
|--------------------------------|--------|---------|---------|------|------------|
| ESP/Arduino lib v2.3.0 | 526k | 488k | 427k | 535k | 549k |
| ESP/Arduino lib v2.4.0 | 531k | 496k | 435k | 540k | 552k |
| ESP/Arduino lib v2.4.1 | 534k | 499k | 437k | 543k | 555k |
### Contribute
You can contribute to Sonoff-Tasmota by
- providing Pull Requests (Features, Proof of Concepts, Language files or Fixes)
- testing new released features and report issues
- donating to acquire hardware for testing and implementating or out of gratitude
- donating to acquire hardware for testing and implementing or out of gratitude
[![donate](https://img.shields.io/badge/donate-PayPal-blue.svg)](https://paypal.me/tasmota)
### Credits
#### Libraries used
Libraries used with Sonoff-Tasmota are:
- [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)
- [Adafruit BME680](https://github.com/adafruit/Adafruit_BME680)
- [Adafruit Sensor](https://github.com/adafruit/Adafruit_Sensor)
- [Adafruit SGP30](https://github.com/adafruit/Adafruit_SGP30)
- [ArduinoJson](https://arduinojson.org/)
- [Esp8266MqttClient](https://github.com/tuanpmt/ESP8266MQTTClient)
- [esp-knx-ip](https://github.com/envy/esp-knx-ip)
- [esp-mqtt-arduino](https://github.com/i-n-g-o/esp-mqtt-arduino)
- [I2Cdevlib](https://github.com/jrowberg/i2cdevlib)
- [IRremoteEsp8266](https://github.com/markszabo/IRremoteESP8266)
- [JobaTsl2561](https://github.com/joba-1/Joba_Tsl2561)
- [MultiChannelGasSensor](http://wiki.seeedstudio.com/Grove-Multichannel_Gas_Sensor/)
- [NeoPixelBus](https://github.com/Makuna/NeoPixelBus)
- [OneWire](https://github.com/PaulStoffregen/OneWire)
- [PubSubClient](https://github.com/knolleary/pubsubclient)
#### People inspiring me
People helping to keep the show on the road:
- David Lang providing initial issue resolution and code optimizations
- Heiko Krupp for his IRSend, HTU21, SI70xx and Wemo/Hue emulation drivers
- Wiktor Schmidt for Travis CI implementation
- Thom Dietrich for PlatformIO optimizations
- Marinus van den Broek for his EspEasy groundwork
- Pete Ba for more user friendly energy monitor calibration
- Lobradov providing compile optimization tips
- Flexiti for his initial timer implementation
- reloxx13 for his [SonWeb](https://github.com/reloxx13/SonWEB) management tool
- Joachim Banzhaf for his TSL2561 library and driver
- Gijs Noorlander for his MHZ19 and SenseAir drivers
- Emontnemery for his HomeAssistant Discovery concept and many code tuning tips
- Aidan Mountford for his HSB support
- Daniel Ztolnai for his Serial Bridge implementation
- Gerhard Mutz for his SGP30 and Sunrise/Sunset driver
- Nuno Ferreira for his HC-SR04 driver
- Adrian Scillato for his (security)fixes and implementing and maintaining KNX
- Raymond Mouthaan for managing Wemos Wiki information
- Norbert Richter, Frogmore42 and Jason2866 for providing many issue answers
- Many more providing Tips, Pocs or PRs
### License
This program is licensed under GPL-3.0
This program is licensed under GPL-3.0

View File

@ -0,0 +1,4 @@
*~
Doxyfile*
doxygen_sqlite3.db
html

View File

@ -0,0 +1,27 @@
language: c
sudo: false
# Blacklist
branches:
except:
- gh-pages
env:
global:
- PRETTYNAME="Adafruit SGP30 Arduino Library"
# Optional, will default to "$TRAVIS_BUILD_DIR/Doxyfile"
# - DOXYFILE: $TRAVIS_BUILD_DIR/Doxyfile
before_install:
- source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/install.sh)
#install:
# - arduino --install-library "Adafruit ILI9341","Adafruit GFX Library"
script:
- build_main_platforms
# Generate and deploy documentation
after_success:
- source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/library_check.sh)
- source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/doxy_gen_and_deploy.sh)

View File

@ -0,0 +1,243 @@
/*!
* @file Adafruit_SGP30.cpp
*
* @mainpage Adafruit SGP30 gas sensor driver
*
* @section intro_sec Introduction
*
* This is the documentation for Adafruit's SGP30 driver for the
* Arduino platform. It is designed specifically to work with the
* Adafruit SGP30 breakout: http://www.adafruit.com/products/3709
*
* These sensors use I2C to communicate, 2 pins (SCL+SDA) are required
* to interface with the breakout.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
*
* @section author Author
* Written by Ladyada for Adafruit Industries.
*
* @section license License
* BSD license, all text here must be included in any redistribution.
*
*/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "Adafruit_SGP30.h"
//#define I2C_DEBUG
/**************************************************************************/
/*!
@brief Instantiates a new SGP30 class
*/
/**************************************************************************/
Adafruit_SGP30::Adafruit_SGP30() {
}
/**************************************************************************/
/*!
@brief Setups the hardware and detects a valid SGP30. Initializes I2C
then reads the serialnumber and checks that we are talking to an SGP30
@param theWire Optional pointer to I2C interface, otherwise use Wire
@returns True if SGP30 found on I2C, False if something went wrong!
*/
/**************************************************************************/
boolean Adafruit_SGP30::begin(TwoWire *theWire) {
_i2caddr = SGP30_I2CADDR_DEFAULT;
if (theWire == NULL) {
_i2c = &Wire;
} else {
_i2c = theWire;
}
_i2c->begin();
uint8_t command[2];
command[0] = 0x36;
command[1] = 0x82;
if (! readWordFromCommand(command, 2, 10, serialnumber, 3))
return false;
uint16_t featureset;
command[0] = 0x20;
command[1] = 0x2F;
if (! readWordFromCommand(command, 2, 10, &featureset, 1))
return false;
//Serial.print("Featureset 0x"); Serial.println(featureset, HEX);
if (featureset != SGP30_FEATURESET)
return false;
if (! IAQinit())
return false;
return true;
}
/**************************************************************************/
/*!
@brief Commands the sensor to begin the IAQ algorithm. Must be called after startup.
@returns True if command completed successfully, false if something went wrong!
*/
/**************************************************************************/
boolean Adafruit_SGP30::IAQinit(void) {
uint8_t command[2];
command[0] = 0x20;
command[1] = 0x03;
return readWordFromCommand(command, 2, 10);
}
/**************************************************************************/
/*!
@brief Commands the sensor to take a single eCO2/VOC measurement. Places results in {@link TVOC} and {@link eCO2}
@returns True if command completed successfully, false if something went wrong!
*/
/**************************************************************************/
boolean Adafruit_SGP30::IAQmeasure(void) {
uint8_t command[2];
command[0] = 0x20;
command[1] = 0x08;
uint16_t reply[2];
if (! readWordFromCommand(command, 2, 12, reply, 2))
return false;
TVOC = reply[1];
eCO2 = reply[0];
return true;
}
/**************************************************************************/
/*!
@brief Request baseline calibration values for both CO2 and TVOC IAQ calculations. Places results in parameter memory locaitons.
@param eco2_base A pointer to a uint16_t which we will save the calibration value to
@param tvoc_base A pointer to a uint16_t which we will save the calibration value to
@returns True if command completed successfully, false if something went wrong!
*/
/**************************************************************************/
boolean Adafruit_SGP30::getIAQBaseline(uint16_t *eco2_base, uint16_t *tvoc_base) {
uint8_t command[2];
command[0] = 0x20;
command[1] = 0x15;
uint16_t reply[2];
if (! readWordFromCommand(command, 2, 10, reply, 2))
return false;
*eco2_base = reply[0];
*tvoc_base = reply[1];
return true;
}
/**************************************************************************/
/*!
@brief Assign baseline calibration values for both CO2 and TVOC IAQ calculations.
@param eco2_base A uint16_t which we will save the calibration value from
@param tvoc_base A uint16_t which we will save the calibration value from
@returns True if command completed successfully, false if something went wrong!
*/
/**************************************************************************/
boolean Adafruit_SGP30::setIAQBaseline(uint16_t eco2_base, uint16_t tvoc_base) {
uint8_t command[8];
command[0] = 0x20;
command[1] = 0x1e;
command[2] = tvoc_base >> 8;
command[3] = tvoc_base & 0xFF;
command[4] = generateCRC(command+2, 2);
command[5] = eco2_base >> 8;
command[6] = eco2_base & 0xFF;
command[7] = generateCRC(command+5, 2);
return readWordFromCommand(command, 8, 10);
}
/**************************************************************************/
/*!
@brief I2C low level interfacing
*/
/**************************************************************************/
boolean Adafruit_SGP30::readWordFromCommand(uint8_t command[], uint8_t commandLength, uint16_t delayms, uint16_t *readdata, uint8_t readlen)
{
uint8_t data;
_i2c->beginTransmission(_i2caddr);
#ifdef I2C_DEBUG
Serial.print("\t\t-> ");
#endif
for (uint8_t i=0; i<commandLength; i++) {
_i2c->write(command[i]);
#ifdef I2C_DEBUG
Serial.print("0x"); Serial.print(command[i], HEX); Serial.print(", ");
#endif
}
#ifdef I2C_DEBUG
Serial.println();
#endif
_i2c->endTransmission();
delay(delayms);
if (readlen == 0)
return true;
uint8_t replylen = readlen * (SGP30_WORD_LEN +1);
if (_i2c->requestFrom(_i2caddr, replylen) != replylen)
return false;
uint8_t replybuffer[replylen];
#ifdef I2C_DEBUG
Serial.print("\t\t<- ");
#endif
for (uint8_t i=0; i<replylen; i++) {
replybuffer[i] = _i2c->read();
#ifdef I2C_DEBUG
Serial.print("0x"); Serial.print(replybuffer[i], HEX); Serial.print(", ");
#endif
}
#ifdef I2C_DEBUG
Serial.println();
#endif
for (uint8_t i=0; i<readlen; i++) {
uint8_t crc = generateCRC(replybuffer+i*3, 2);
#ifdef I2C_DEBUG
Serial.print("\t\tCRC calced: 0x"); Serial.print(crc, HEX);
Serial.print(" vs. 0x"); Serial.println(replybuffer[i * 3 + 2], HEX);
#endif
if (crc != replybuffer[i * 3 + 2])
return false;
// success! store it
readdata[i] = replybuffer[i*3];
readdata[i] <<= 8;
readdata[i] |= replybuffer[i*3 + 1];
#ifdef I2C_DEBUG
Serial.print("\t\tRead: 0x"); Serial.println(readdata[i], HEX);
#endif
}
return true;
}
uint8_t Adafruit_SGP30::generateCRC(uint8_t *data, uint8_t datalen) {
// calculates 8-Bit checksum with given polynomial
uint8_t crc = SGP30_CRC8_INIT;
for (uint8_t i=0; i<datalen; i++) {
crc ^= data[i];
for (uint8_t b=0; b<8; b++) {
if (crc & 0x80)
crc = (crc << 1) ^ SGP30_CRC8_POLYNOMIAL;
else
crc <<= 1;
}
}
return crc;
}

View File

@ -0,0 +1,68 @@
/*!
* @file Adafruit_SGP30.h
*
* This is the documentation for Adafruit's SGP30 driver for the
* Arduino platform. It is designed specifically to work with the
* Adafruit SGP30 breakout: http://www.adafruit.com/products/3709
*
* These sensors use I2C to communicate, 2 pins (SCL+SDA) are required
* to interface with the breakout.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* Written by Ladyada for Adafruit Industries.
*
* BSD license, all text here must be included in any redistribution.
*
*/
#include "Arduino.h"
#include <Wire.h>
// the i2c address
#define SGP30_I2CADDR_DEFAULT 0x58 ///< SGP30 has only one I2C address
// commands and constants
#define SGP30_FEATURESET 0x0020 ///< The required set for this library
#define SGP30_CRC8_POLYNOMIAL 0x31 ///< Seed for SGP30's CRC polynomial
#define SGP30_CRC8_INIT 0xFF ///< Init value for CRC
#define SGP30_WORD_LEN 2 ///< 2 bytes per word
/**************************************************************************/
/*! Class that stores state and functions for interacting with SGP30 Gas Sensor */
/**************************************************************************/
class Adafruit_SGP30 {
public:
Adafruit_SGP30();
boolean begin(TwoWire *theWire = NULL);
boolean IAQinit(void);
boolean IAQmeasure(void);
boolean getIAQBaseline(uint16_t *eco2_base, uint16_t *tvoc_base);
boolean setIAQBaseline(uint16_t eco2_base, uint16_t tvoc_base);
/**
* The last measurement of the IAQ-calculated Total Volatile Organic Compounds in ppb. This value is set when you call {@link IAQmeasure()}
*/
uint16_t TVOC;
/**
* The last measurement of the IAQ-calculated equivalent CO2 in ppm. This value is set when you call {@link IAQmeasure()}
*/
uint16_t eCO2;
/**
* The 48-bit serial number, this value is set when you call {@link begin()}
*/
uint16_t serialnumber[3];
private:
TwoWire *_i2c;
uint8_t _i2caddr;
void write(uint8_t address, uint8_t *data, uint8_t n);
void read(uint8_t address, uint8_t *data, uint8_t n);
boolean readWordFromCommand(uint8_t command[], uint8_t commandLength, uint16_t delay, uint16_t *readdata = NULL, uint8_t readlen = 0);
uint8_t generateCRC(uint8_t data[], uint8_t datalen);
};

View File

@ -0,0 +1,18 @@
Adafruit_SGP30
================
This is the Adafruit SGP30 Gas / Air Quality I2C sensor library
Tested and works great with the Aadafruit SGP30 Breakout Board
* http://www.adafruit.com/products/3709
This chip uses I2C to communicate, 2 pins are required to interface
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 for Adafruit Industries.
BSD license, check license.txt for more information
All text above must be included in any redistribution

View File

@ -0,0 +1,45 @@
#include <Wire.h>
#include "Adafruit_SGP30.h"
Adafruit_SGP30 sgp;
void setup() {
Serial.begin(9600);
Serial.println("SGP30 test");
if (! sgp.begin()){
Serial.println("Sensor not found :(");
while (1);
}
Serial.print("Found SGP30 serial #");
Serial.print(sgp.serialnumber[0], HEX);
Serial.print(sgp.serialnumber[1], HEX);
Serial.println(sgp.serialnumber[2], HEX);
// If you have a baseline measurement from before you can assign it to start, to 'self-calibrate'
//sgp.setIAQBaseline(0x8E68, 0x8F41); // Will vary for each sensor!
}
int counter = 0;
void loop() {
if (! sgp.IAQmeasure()) {
Serial.println("Measurement failed");
return;
}
Serial.print("TVOC "); Serial.print(sgp.TVOC); Serial.print(" ppb\t");
Serial.print("eCO2 "); Serial.print(sgp.eCO2); Serial.println(" ppm");
delay(1000);
counter++;
if (counter == 30) {
counter = 0;
uint16_t TVOC_base, eCO2_base;
if (! sgp.getIAQBaseline(&eCO2_base, &TVOC_base)) {
Serial.println("Failed to get baseline readings");
return;
}
Serial.print("****Baseline values: eCO2: 0x"); Serial.print(eCO2_base, HEX);
Serial.print(" & TVOC: 0x"); Serial.println(TVOC_base, HEX);
}
}

View File

@ -0,0 +1,9 @@
name=Adafruit SGP30 Sensor
version=1.0.2
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=This is an Arduino library for the Adafruit SGP30 Gas / Air Quality Sensor
paragraph=This is an Arduino library for the Adafruit SGP30 Gas / Air Quality Sensor
category=Sensors
url=https://github.com/adafruit/Adafruit_SGP30
architectures=*

View File

@ -0,0 +1,26 @@
Software License Agreement (BSD License)
Copyright (c) 2012, Adafruit Industries
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 holders 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 ''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 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.

674
lib/Joba_Tsl2561/COPYING Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

20
lib/Joba_Tsl2561/README Normal file
View File

@ -0,0 +1,20 @@
This is a library for the TSL2561 digital luminosity sensors from Ams (Taos).
Design goals:
* It is modularized so you can use only what you need if space/ram is constrained.
* It does not swallow error codes so you can react on them.
* It doesn't use floats as they are overkill for most IoT stuff.
Datasheet used:
http://ams.com/eng/Products/Light-Sensors/Ambient-Light-Sensors/TSL2561/TSL2560-TSL2561-Datasheet
http://ams.com/eng/content/download/250094/975485/file/TSL2560-61_DS000110_2-00.pdf
http://ams.com/eng/content/view/download/145438
http://ams.com/eng/content/view/download/181895
To use the library, just place the folder in your projects lib folder.
For usage, see the examples folder.
The library has 3 classes:
Tsl2561 All register access as described in the datasheet, except for interrupts
Tsl2561Util Convenience functions like lux calculation or automatic gain
Tsl2561Int TODO, Interrupt related stuff (not needed if int pin unconnected)

View File

@ -0,0 +1,65 @@
/*
Autogain tests for Tsl2561Util namespace.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 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 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561Util.h>
Tsl2561 Tsl(Wire);
uint8_t id;
void setup() {
Serial.begin(115200);
Wire.begin();
while( !Tsl.begin() )
; // wait until chip detected or wdt reset
Serial.println("\nStarting Tsl2561Util autogain loop");
Tsl.on();
Tsl.id(id);
}
void loop() {
uint16_t scaledFull = ~0, scaledIr = ~0;
uint32_t full = ~0, ir = ~0, milliLux = ~0;
bool gain = false;
Tsl2561::exposure_t exposure = Tsl2561::EXP_OFF;
if( Tsl2561Util::autoGain(Tsl, gain, exposure, scaledFull, scaledIr) ) {
if( Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr) ) {
if( Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id)) ) {
Serial.printf("Tsl2561 addr: 0x%02x, id: 0x%02x, sfull: %5u, sir: %5u, full: %5u, ir: %5u, gain: %d, exp: %d, lux: %5u.%03u\n",
Tsl.address(), id, scaledFull, scaledIr, full, ir, gain, exposure, milliLux/1000, milliLux%1000);
}
else {
Serial.printf("Tsl2561Util::milliLux(full=%u, ir=%u) error\n", full, ir);
}
}
else {
Serial.printf("Tsl2561Util::normalizedLuminosity(gain=%u, exposure=%u, sfull=%u, sir=%u, full=%u, ir=%u) error\n",
gain, exposure, scaledFull, scaledIr, full, ir);
}
}
else {
Serial.printf("Tsl2561Util::autoGain(gain=%u, exposure=%u, sfull=%u, sir=%u) error\n",
gain, exposure, scaledFull, scaledIr);
}
delay(1000);
}

View File

@ -0,0 +1,56 @@
/*
Simple tests for Tsl2561 class. No error checking is done.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 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 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561.h>
Tsl2561 Tsl(Wire);
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nStarting Tsl2561 simple loop");
}
void loop() {
Tsl.begin();
if( Tsl.available() ) {
Tsl.on();
Tsl.setSensitivity(true, Tsl2561::EXP_14);
delay(16);
uint8_t id;
uint16_t full, ir;
Tsl.id(id);
Tsl.fullLuminosity(full);
Tsl.irLuminosity(ir);
Serial.printf("Tsl2561 at 0x%02x(id=0x%02x) luminosity is %5u (full) and %5u (ir)\n", Tsl.address(), id, full, ir);
Tsl.off();
}
else {
Serial.println("No Tsl2561 found. Check wiring.");
}
delay(5000);
}

View File

@ -0,0 +1,163 @@
/*
Tests for the Tsl2561 class.
It shows how to use every available method.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 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 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561.h>
Tsl2561 Tsl(Wire);
void showError( Tsl2561 &tsl ) {
Tsl2561::status_t status = tsl.status();
Serial.printf("Error was %u: ", status);
switch( status ) {
case Tsl2561::ERR_OK: Serial.println("None"); break;
case Tsl2561::ERR_RW: Serial.println("Read/Write"); break;
case Tsl2561::ERR_BUSY: Serial.println("Busy"); break;
case Tsl2561::ERR_GONE: Serial.println("Gone"); break;
case Tsl2561::ERR_GENERAL: Serial.println("General"); break;
default: Serial.println("Unknown"); break;
}
}
void testSensitivity( Tsl2561 &tsl, bool newGain, Tsl2561::exposure_t newExp ) {
if( tsl.on() ) {
uint32_t start = millis();
Serial.printf("Chip powered on at %u\n", start);
bool chipGain;
Tsl2561::exposure_t chipExp;
bool change = true;
if( tsl.getSensitivity(chipGain, chipExp) ) {
if( chipGain == newGain && chipExp == newExp ) {
change = false;
}
}
else {
Serial.print("getSensitivity failed. ");
showError(tsl);
}
bool check = true;
if( change ) {
if( tsl.setSensitivity(newGain, newExp) ) {
Serial.printf("New gain = %d, exposure = 0x%02x\n", newGain, newExp);
}
else {
check = false;
Serial.print("setSensitivity failed. ");
showError(tsl);
}
}
if( check ) {
uint16_t ir, full = 0;
while( !full && millis() - start < 1000 ) {
if( !tsl.fullLuminosity(full) ) {
Serial.print("Check full luminosity failed. ");
showError(tsl);
}
if( full ) {
if( !tsl.irLuminosity(ir) ) {
Serial.print("Check ir luminosity failed. ");
showError(tsl);
}
}
else {
delay(10);
}
}
if( !full ) {
Serial.println("No luminosity reading after 1s. Too dark?");
}
else {
Serial.printf("Got luminosity after %d ms. Full spectrum is %d and IR only is %d\n", millis() - start, full, ir);
}
}
if( !tsl.off() ) {
Serial.print("Power off failed. ");
showError(tsl);
}
}
else {
Serial.print("Power on failed. ");
showError(tsl);
}
}
bool testPackage( Tsl2561 &tsl ) {
uint8_t id;
if( tsl.id(id) ) {
Serial.printf("Chip has type %02x and revision %x\n", Tsl2561::type(id), Tsl2561::revision(id) );
if( Tsl2561::packageT_FN_CL(id) ) {
Serial.println("Chip is a T, FN or CL type package");
}
else if( Tsl2561::packageCS(id) ) {
Serial.println("Chip is a CS type package");
}
else {
Serial.println("Chip is an unknown package");
}
return true;
}
else {
Serial.print("Get Chip ID failed. ");
showError(tsl);
}
return false;
}
void test( Tsl2561 &tsl ) {
bool ok = tsl.available();
Serial.printf("\nTesting Tsl2561 at address %02x: %sfound\n", tsl.address(), ok ? "" : "NOT ");
if( ok ) {
if( testPackage(tsl) ) {
testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_402);
testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_402);
testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_101);
testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_101);
testSensitivity(tsl, Tsl2561::GAIN_OFF, Tsl2561::EXP_14);
testSensitivity(tsl, Tsl2561::GAIN_ON, Tsl2561::EXP_14);
}
}
else {
showError(tsl);
}
}
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nStarting Tsl2561 testing loop");
}
void loop() {
Tsl.begin(Tsl2561::ADDR_GND);
test(Tsl);
Tsl.begin(Tsl2561::ADDR_FLOAT);
test(Tsl);
Tsl.begin(Tsl2561::ADDR_VDD);
test(Tsl);
Serial.println("\nNext test in 5s\n");
delay(5000);
}

View File

@ -0,0 +1,87 @@
/*
Simple tests for Tsl2561Util namespace.
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 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 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Tsl2561Util.h>
Tsl2561::address_t addr[] = { Tsl2561::ADDR_GND, Tsl2561::ADDR_FLOAT, Tsl2561::ADDR_VDD };
Tsl2561 Tsl(Wire);
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nStarting Tsl2561Util loop");
}
void loop() {
bool found = false;
for( uint8_t i = 0; i < sizeof(addr)/sizeof(addr[0]); i++ ) {
if( Tsl.begin(addr[i]) ) {
found = true;
Serial.println();
uint16_t scaledFull = 0, scaledIr;
uint32_t full, ir, milliLux;
uint8_t id;
bool gain;
Tsl2561::exposure_t exposure;
for( uint8_t g=0; g<2; g++ ) {
gain = g;
for( uint8_t e=0; e<3; e++ ) {
exposure = (Tsl2561::exposure_t)e;
Tsl.on();
Tsl.setSensitivity(gain, exposure);
Tsl2561Util::waitNext(exposure);
Tsl.id(id);
Tsl.getSensitivity(gain, exposure);
Tsl.fullLuminosity(scaledFull);
Tsl.irLuminosity(scaledIr);
Serial.printf("Tsl2561 addr: 0x%02x, id: 0x%02x, sfull: %5u, sir: %5u, gain: %d, exp: %d", addr[i], id, scaledFull, scaledIr, gain, exposure);
if( Tsl2561Util::normalizedLuminosity(gain, exposure, full = scaledFull, ir = scaledIr) ) {
if( Tsl2561Util::milliLux(full, ir, milliLux, Tsl2561::packageCS(id)) ) {
Serial.printf(", full: %5u, ir: %5u, lux: %5u.%03u\n", full, ir, milliLux/1000, milliLux%1000);
}
else {
Serial.printf(", full: %5u, ir: %5u: Tsl2561Util::milliLux() error\n", full, ir);
}
}
else {
Serial.printf(", full: %5u, ir: %5u: Tsl2561Util::normalizedLuminosity() error\n", full, ir);
}
Tsl.off();
}
}
}
}
if( !found ) {
Serial.println("No Tsl2561 found. Check wiring.");
}
delay(5000);
}

View File

@ -0,0 +1,13 @@
{
"name": "Joba_Tsl2561",
"version": "2.0.1",
"keywords": "twowire, i2c, bus, sensor, luminosity, illuminance, lux",
"description": "Arduino Library for ams (taos) luminance chip Tsl2561 with autogain",
"repository":
{
"type": "git",
"url": "https://github.com/joba-1/Joba_Tsl2561.git"
},
"frameworks": "arduino",
"platforms": "*"
}

View File

@ -0,0 +1,9 @@
name=Joba Tsl2561 Library
version=2.0.1
author=joba-1
maintainer=joba-1 <joban123.psn@gmail.com>
sentence=IoT library for using the Tsl2561 luminosity sensor
paragraph=Luminosity measurement in lux with autogain
category=Sensors
url=https://github.com/joba-1/Joba_Tsl2561
architectures=*

View File

@ -0,0 +1,134 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 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 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Tsl2561.h"
Tsl2561::Tsl2561( TwoWire &wire ) : _addr(ADDR_NONE), _wire(wire), _status(ERR_OK) {
}
bool Tsl2561::available() {
_wire.beginTransmission(_addr);
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
bool Tsl2561::begin( address_t addr ) {
_addr = addr;
return available();
}
bool Tsl2561::begin() {
static address_t addr[] = { ADDR_GND, ADDR_FLOAT, ADDR_VDD };
for( uint8_t i=0; i<sizeof(addr)/sizeof(addr[0]); i++ ) {
if( begin(addr[i]) ) {
return true;
}
}
_addr = ADDR_NONE;
return false;
}
bool Tsl2561::readByte( register_t reg, uint8_t &val ) {
_wire.beginTransmission(_addr);
_wire.write(reg | CONTROL_CMD);
if( _wire.endTransmission(false) == ERR_OK ) {
if( _wire.requestFrom(_addr, 1) ) {
val = static_cast<uint8_t>(_wire.read());
}
}
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
bool Tsl2561::readWord( register_t reg, uint16_t &val ) {
_wire.beginTransmission(_addr);
_wire.write(reg | CONTROL_CMD);
if( _wire.endTransmission(false) == ERR_OK ) {
if( _wire.requestFrom(_addr, 2) ) {
val = (uint16_t)_wire.read() & 0xff;
val |= ((uint16_t)_wire.read() & 0xff) << 8;
}
}
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
bool Tsl2561::writeByte( register_t reg, uint8_t val ) {
_wire.beginTransmission(_addr);
_wire.write(reg | CONTROL_CMD);
_wire.write(val);
return (_status = static_cast<status_t>(_wire.endTransmission())) == ERR_OK;
}
Tsl2561::status_t Tsl2561::status() const {
return _status;
}
Tsl2561::address_t Tsl2561::address() const {
return _addr;
}
bool Tsl2561::id( uint8_t &id ) {
return readByte(REG_ID, id);
}
uint8_t Tsl2561::type( uint8_t id ) {
return id & PKG_ID;
}
uint8_t Tsl2561::revision( uint8_t id ) {
return id & PKG_REV;
}
bool Tsl2561::packageCS( uint8_t id ) {
return type(id) == PKG_CS;
}
bool Tsl2561::packageT_FN_CL( uint8_t id ) {
return type(id) == PKG_T_FN_CL;
}
bool Tsl2561::on() {
return writeByte(REG_CONTROL, POWER_ON);
}
bool Tsl2561::off() {
return writeByte(REG_CONTROL, POWER_OFF);
}
bool Tsl2561::setSensitivity( bool gain, exposure_t exposure ) {
return writeByte(REG_TIMING, (gain ? GAIN_ON : GAIN_OFF) | exposure);
}
bool Tsl2561::getSensitivity( bool &gain, exposure_t &exposure )
{
uint8_t val;
if( readByte(REG_TIMING, val) ) {
gain = val & GAIN_ON;
exposure = static_cast<exposure_t>(val & EXP_ON);
}
return _status == ERR_OK;
}
bool Tsl2561::fullLuminosity( uint16_t &luminosity ) {
return readWord(REG_DATA0LOW, luminosity);
}
bool Tsl2561::irLuminosity( uint16_t &luminosity ) {
return readWord(REG_DATA1LOW, luminosity);
}

View File

@ -0,0 +1,133 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 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 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Tsl2561_H
#define Tsl2561_H
#include <Arduino.h>
#include <Wire.h>
class Tsl2561 {
public:
typedef enum {
ADDR_NONE = 0b0000000,
ADDR_GND = 0b0101001,
ADDR_FLOAT = 0b0111001,
ADDR_VDD = 0b1001001
} address_t;
typedef enum {
REG_CONTROL, // Control of basic functions
REG_TIMING, // Integration time/gain control
REG_THRESHLOWLOW, // Low byte of low interrupt threshold
REG_THRESHLOWHIGH, // High byte of low interrupt threshold
REG_THRESHHIGHLOW, // Low byte of high interrupt threshold
REG_THRESHHIGHHIGH, // High byte of high interrupt threshold
REG_INTERRUPT, // Interrupt control
REG_RESERVED1,
REG_CRC, // Factory test - not a user register
REG_RESERVED2,
REG_ID, // Part number/Rev ID
REG_RESERVED3,
REG_DATA0LOW, // Low byte of ADC channel 0
REG_DATA0HIGH, // High byte of ADC channel 0
REG_DATA1LOW, // Low byte of ADC channel 1
REG_DATA1HIGH // High byte of ADC channel 1
} register_t;
enum {
CONTROL_CMD = 0b10000000,
CONTROL_CLEAR = 0b01000000,
CONTROL_WORD = 0b00100000, // SPI only?
CONTROL_BLOCK = 0b00010000, // SPI only?
CONTROL_ADDRESS = 0b00001111
};
enum {
POWER_OFF,
POWER_ON = 0b11,
};
enum {
GAIN_OFF,
GAIN_ON = 0b00010000
};
typedef enum {
EXP_ON = 0b00001011,
EXP_OFF = 0b00000011,
EXP_14 = 0b00000000,
EXP_101 = 0b00000001,
EXP_402 = 0b00000010
} exposure_t;
enum {
PKG_ID = 0b11110000,
PKG_REV = 0b00001111,
PKG_CS = 0b00010000,
PKG_T_FN_CL = 0b01010000
};
typedef enum {
ERR_OK = 0,
ERR_GENERAL = 1,
ERR_GONE = 2,
ERR_RW = 3,
ERR_BUSY = 4
} status_t;
Tsl2561( TwoWire &wire );
bool begin( address_t addr );
bool begin();
bool available();
status_t status() const;
address_t address() const;
bool id( uint8_t &id );
static uint8_t type( uint8_t id );
static uint8_t revision( uint8_t id );
static bool packageCS( uint8_t id );
static bool packageT_FN_CL( uint8_t id );
bool on();
bool off();
bool setSensitivity( bool gain, exposure_t exposure );
bool getSensitivity( bool &gain, exposure_t &exposure );
bool fullLuminosity( uint16_t &luminosity );
bool irLuminosity( uint16_t &luminosity );
protected:
bool readByte( register_t reg, uint8_t &val );
bool readWord( register_t reg, uint16_t &val );
bool writeByte( register_t reg, uint8_t val );
private:
Tsl2561();
Tsl2561( Tsl2561 & );
address_t _addr;
TwoWire &_wire;
status_t _status;
};
#endif

View File

@ -0,0 +1,193 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 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 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Tsl2561Util.h"
namespace Tsl2561Util {
// Tsl2561Util::normalizedLuminosity returncode false can mean:
// - saturation: full and/or ir have value ~0 (aka -1)
// - manual exposure time: full and ir are corrected only for gain
// If true, full and ir have values as if exposure was 402 and gain 16.
bool normalizedLuminosity( bool gain, Tsl2561::exposure_t exposure, uint32_t &full, uint32_t &ir ) {
uint16_t scaledFull = (uint16_t)full;
uint16_t scaledIr = (uint16_t)ir;
if( scaledFull ) {
if( ! gain ) {
full <<= 4;
ir <<= 4;
}
switch( exposure ) {
case Tsl2561::EXP_14:
full = (scaledFull >= 5047/4*3) ? ~0 : ((full + 5) * 322) / 11;
ir = (scaledIr >= 5047/4*3) ? ~0 : ((ir + 5) * 322) / 11;
break;
case Tsl2561::EXP_101:
full = (scaledFull >= 37177/4*3) ? ~0 : ((full + 40) * 322) / 81;
ir = (scaledIr >= 37177/4*3) ? ~0 : ((ir + 40) * 322) / 81;
break;
case Tsl2561::EXP_402:
if( scaledFull >= 65535/4*3 ) full = ~0;
if( scaledIr >= 65535/4*3 ) ir = ~0;
break;
default:
return false;
}
return full != ~0U && ir != ~0U;
}
return false;
}
// Return upper saturation limit upto which chip returns accurate data
uint16_t getLimit( Tsl2561::exposure_t exposure ) {
switch( exposure ) {
case Tsl2561::EXP_14: return 5047/4*3;
case Tsl2561::EXP_101: return 37177/4*3;
default: return 65535/4*3;
}
}
// Wait for one measurement interval plus some empirically tested extra millis
void waitNext( Tsl2561::exposure_t exposure ) {
switch( exposure ) {
case Tsl2561::EXP_14: delay(16); break;
case Tsl2561::EXP_101: delay(103); break;
default: delay(408); break;
}
}
// Wait for next sample, read luminosity and adjust sensitivity, if needed and possible
bool autoGain( Tsl2561 &tsl, bool &gain, Tsl2561::exposure_t &exposure, uint16_t &full, uint16_t &ir ) {
static const struct {
bool gain;
Tsl2561::exposure_t exposure;
} sensitivity[] = {
{ false, Tsl2561::EXP_14, }, // min
{ false, Tsl2561::EXP_101 },
{ true, Tsl2561::EXP_14 },
{ false, Tsl2561::EXP_402 },
{ true, Tsl2561::EXP_101 },
{ true, Tsl2561::EXP_402 } // max
};
// get current sensitivity
if( !tsl.getSensitivity(gain, exposure) ) {
return false;
}
// find index of current sensitivity
uint8_t curr = 0;
while( curr < sizeof(sensitivity)/sizeof(sensitivity[0]) ) {
if( sensitivity[curr].gain == gain && sensitivity[curr].exposure == exposure ) {
break;
}
curr++;
}
if( curr == sizeof(sensitivity)/sizeof(sensitivity[0]) ) {
return false; // should not happen...
}
// in a loop wait for next sample, get values and adjust sensitivity if needed
while( true ) {
waitNext(exposure);
if( !tsl.fullLuminosity(full) || !tsl.irLuminosity(ir) ) {
return false;
}
uint16_t limit = getLimit(exposure);
if( full >= 1000 && full <= limit ) {
return true; // new value within limits
}
if( (full < 1000 && ++curr < sizeof(sensitivity)/sizeof(sensitivity[0]))
|| (full > limit && curr-- > 0) ) {
if( !tsl.setSensitivity(sensitivity[curr].gain, sensitivity[curr].exposure) ) {
return false;
}
gain = sensitivity[curr].gain;
exposure = sensitivity[curr].exposure;
}
else {
return true; // saturated, but best we can do
}
}
}
// Measurement is up to 20% too high for temperatures above 25°C. Compensate for that.
bool compensateTemperature( int16_t centiCelsius, uint32_t &full, uint32_t &ir ) {
// assume linear gradient 0% at 25°C to +20% at 70°C
if( centiCelsius >= -3000 && centiCelsius <= 7000 ) {
full -= (full * (centiCelsius - 2500) * 20) / (100 * (7000 - 2500));
ir -= (ir * (centiCelsius - 2500) * 20) / (100 * (7000 - 2500));
return true;
}
return false;
}
// Calculate lux from raw luminosity values
bool milliLux( uint32_t full, uint32_t ir, uint32_t &mLux, bool csType ) {
if( !full ) {
mLux = 0;
return true;
}
uint32_t milliRatio = ir * 1000 / full;
if( csType ) {
if( milliRatio < 130 ) { mLux = 1000 * full - 840 * ir; }
else if ( milliRatio < 260 ) { mLux = 1080 * full - 1380 * ir; }
else if ( milliRatio < 390 ) { mLux = 1160 * full - 1690 * ir; }
else if ( milliRatio < 520 ) { mLux = 1260 * full - 1940 * ir; }
else if ( milliRatio < 650 ) { mLux = 730 * full - 930 * ir; }
else if ( milliRatio < 800 ) { mLux = 500 * full - 575 * ir; }
else if ( milliRatio < 1300 ) { mLux = 110 * full - 85 * ir; }
else {
mLux = 0;
return false;
}
mLux /= 400 * 16 / 200; // 32 = counts/lux (cpl)
}
else {
if( milliRatio < 125 ) { mLux = 1000 * full - 895 * ir; }
else if ( milliRatio < 250 ) { mLux = 1070 * full - 1045 * ir; }
else if ( milliRatio < 375 ) { mLux = 1150 * full - 1790 * ir; }
else if ( milliRatio < 500 ) { mLux = 1260 * full - 2050 * ir; }
else if ( milliRatio < 610 ) { mLux = 740 * full - 1020 * ir; }
else if ( milliRatio < 800 ) { mLux = 420 * full - 500 * ir; }
else if ( milliRatio < 1300 ) { mLux = 48 * full - 37 * ir; }
else {
mLux = 0;
return false;
}
mLux /= 400 * 16 / 193; // 33 = counts/lux (cpl)
}
return true;
}
} // namespace Tsl2561Util

View File

@ -0,0 +1,48 @@
/*
Copyright: Joachim Banzhaf, 2018
This file is part of the Joba_Tsl2561 Library.
Joba_Tsl2561 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 3 of the License, or
(at your option) any later version.
Joba_Tsl2561 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 Joba_Tsl2561. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef Tsl2561Util_H
#define Tsl2561Util_H
#include <Tsl2561.h>
namespace Tsl2561Util {
// delay until next sample is available
void waitNext( Tsl2561::exposure_t exposure );
// get saturation limit for given exposure time
uint16_t getLimit( Tsl2561::exposure_t exposure );
// in a loop wait for a sample, get it, check if within thresholds,
// until luminosity is either valid or at upper or lower saturation limit
bool autoGain( Tsl2561 &tsl, bool &gain, Tsl2561::exposure_t &exposure, uint16_t &full, uint16_t &ir );
// adjust luminosity as if measured with maximum exposure time and maximum gain
bool normalizedLuminosity( bool gain, Tsl2561::exposure_t exposure, uint32_t &full, uint32_t &ir );
// adjust luminosity according to sensor temperature (max +/-20% from 25°C)
bool compensateTemperature( int16_t centiCelsius, uint32_t &full, uint32_t &ir );
// calculate lux from normalized (and optionally temperature adjusted) luminosity
bool milliLux( uint32_t full, uint32_t ir, uint32_t &milliLux, bool csType = false );
};
#endif

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Seeed Technology Inc.
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.

View File

@ -0,0 +1,45 @@
# Mutichannel_Gas_Sensor
This Arduino library is used for driving "Xadow - Mutichannel Gas Sensor" and "Grove - Mutichanel Gas Sensor"
## Usage:
mutichannelGasSensor.begin(0x04);
mutichannelGasSensor.powerOn();
then read the concentration of the specific gas you want to measure:
mutichannelGasSensor.measure_NH3();
mutichannelGasSensor.measure_CO();
mutichannelGasSensor.measure_NO2();
mutichannelGasSensor.measure_C3H8();
mutichannelGasSensor.measure_C4H10();
mutichannelGasSensor.measure_CH4();
mutichannelGasSensor.measure_H2();
mutichannelGasSensor.measure_C2H5OH();
For details please move to [wiki page](http://www.seeedstudio.com/wiki/Grove_-_Multichannel_Gas_Sensor).
----
This software is written by Jacky Zhang (![](http://www.seeedstudio.com/wiki/images/8/8f/Email_addr_of_jacky_zhang.png)) from [Seeed Technology Inc.](http://www.seeed.cc) and is licensed under [The MIT License](http://opensource.org/licenses/mit-license.php). Check License.txt/LICENSE for the details of MIT license.<br>
Contributing to this software is warmly welcomed. You can do this basically by<br>
[forking](https://help.github.com/articles/fork-a-repo), committing modifications and then [pulling requests](https://help.github.com/articles/using-pull-requests) (follow the links above<br>
for operating guide). Adding change log and your contact into file header is encouraged.<br>
Thanks for your contribution.
Seeed is a hardware innovation platform for makers to grow inspirations into differentiating products. By working closely with technology providers of all scale, Seeed provides accessible technologies with quality, speed and supply chain knowledge. When prototypes are ready to iterate, Seeed helps productize 1 to 1,000 pcs using in-house engineering, supply chain management and agile manufacture forces. Seeed also team up with incubators, Chinese tech ecosystem, investors and distribution channels to portal Maker startups beyond.
[![Analytics](https://ga-beacon.appspot.com/UA-46589105-3/Mutichannel_Gas_Sensor)](https://github.com/igrigorik/ga-beacon)

View File

@ -0,0 +1,20 @@
// Get firmware version of Grove Multichannel Gas Sensor
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR);
unsigned char version = gas.getVersion();
Serial.print("Version = ");
Serial.println(version);
}
void loop()
{
// nothing to do
}

View File

@ -0,0 +1,25 @@
// change i2c address
// Loovee
// 2016-11-10
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR_OLD 0x04 // default to 0x04
#define SENSOR_ADDR_NEW 0x19 // change i2c address to 0x19
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR_OLD); //
gas.change_i2c_address(SENSOR_ADDR_NEW);
Serial.print("I2C ADDRESS SET TO 0X");;
Serial.println(SENSOR_ADDR_NEW, HEX);
}
void loop()
{
}
// END FILE

View File

@ -0,0 +1,57 @@
// get RAW data from the sensor
// Loovee
// 2016-11-10
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR); //
}
void loop()
{
float R0_NH3, R0_CO, R0_NO2;
float Rs_NH3, Rs_CO, Rs_NO2;
float ratio_NH3, ratio_CO, ratio_NO2;
R0_NH3 = gas.getR0(0);
R0_CO = gas.getR0(1);
R0_NO2 = gas.getR0(2);
Rs_NH3 = gas.getRs(0);
Rs_CO = gas.getRs(1);
Rs_NO2 = gas.getRs(2);
ratio_NH3 = Rs_NH3/R0_NH3;
ratio_CO = Rs_CO/R0_CO;
ratio_NO2 = Rs_NH3/R0_NO2;
Serial.println("R0:");
Serial.print(R0_NH3);
Serial.print('\t');
Serial.print(R0_CO);
Serial.print('\t');
Serial.println(R0_NO2);
Serial.println("Rs:");
Serial.print(Rs_NH3);
Serial.print('\t');
Serial.print(Rs_CO);
Serial.print('\t');
Serial.println(Rs_NO2);
Serial.println("ratio:");
Serial.print(ratio_NH3);
Serial.print('\t');
Serial.print(ratio_CO);
Serial.print('\t');
Serial.println(ratio_NO2);
Serial.println("------------------------");
delay(1000);
}

View File

@ -0,0 +1,81 @@
/*
This is a demo to test gas library
This code is running on Xadow-mainboard, and the I2C slave is Xadow-gas
There is a ATmega168PA on Xadow-gas, it get sensors output and feed back to master.
the data is raw ADC value, algorithm should be realized on master.
please feel free to write email to me if there is any question
Jacky Zhang, Embedded Software Engineer
qi.zhang@seeed.cc
17,mar,2015
*/
#include <Wire.h>
#include "MutichannelGasSensor.h"
void setup()
{
Serial.begin(115200); // start serial for output
Serial.println("power on!");
gas.begin(0x04);//the default I2C address of the slave is 0x04
gas.powerOn();
Serial.print("Firmware Version = ");
Serial.println(gas.getVersion());
}
void loop()
{
float c;
c = gas.measure_NH3();
Serial.print("The concentration of NH3 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CO();
Serial.print("The concentration of CO is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_NO2();
Serial.print("The concentration of NO2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C3H8();
Serial.print("The concentration of C3H8 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C4H10();
Serial.print("The concentration of C4H10 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CH4();
Serial.print("The concentration of CH4 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_H2();
Serial.print("The concentration of H2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C2H5OH();
Serial.print("The concentration of C2H5OH is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
delay(1000);
Serial.println("...");
}

View File

@ -0,0 +1,89 @@
/*
This is a demo to test gas library
This code is running on Xadow-mainboard, and the I2C slave is Xadow-gas
There is a ATmega168PA on Xadow-gas, it get sensors output and feed back to master.
the data is raw ADC value, algorithm should be realized on master.
please feel free to write email to me if there is any question
Jacky Zhang, Embedded Software Engineer
qi.zhang@seeed.cc
17,mar,2015
*/
#include "xadow.h"
#include <Wire.h>
#include "MutichannelGasSensor.h"
void setup()
{
Xadow.init();
Serial.begin(9600); // start serial for output
Serial.println("power on!");
gas.begin(0x04);//the default I2C address of the slave is 0x04
//gas.changeI2cAddr(0x10);
//gas.doCalibrate();
gas.powerOn();
}
void loop()
{
float c;
c = gas.measure_NH3();
Serial.print("The concentration of NH3 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CO();
Serial.print("The concentration of CO is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_NO2();
Serial.print("The concentration of NO2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C3H8();
Serial.print("The concentration of C3H8 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C4H10();
Serial.print("The concentration of C4H10 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_CH4();
Serial.print("The concentration of CH4 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_H2();
Serial.print("The concentration of H2 is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
c = gas.measure_C2H5OH();
Serial.print("The concentration of C2H5OH is ");
if(c>=0) Serial.print(c);
else Serial.print("invalid");
Serial.println(" ppm");
Xadow.greenLed(LEDON);
delay(500);
Xadow.greenLed(LEDOFF);
delay(500);
Serial.println("...");
}

View File

@ -0,0 +1,513 @@
// Atmega chip programmer
// Author: Nick Gammon
// Date: 22nd May 2012
// Version: 1.17
// Version 1.1: Reset foundSig to -1 each time around the loop.
// Version 1.2: Put hex bootloader data into separate files
// Version 1.3: Added verify, and MD5 sums
// Version 1.4: Added signatures for ATmeag8U2/16U2/32U2 (7 May 2012)
// Version 1.5: Added signature for ATmega1284P (8 May 2012)
// Version 1.6: Allow sketches to read bootloader area (lockbyte: 0x2F)
// Version 1.7: Added choice of bootloaders for the Atmega328P (8 MHz or 16 MHz)
// Version 1.8: Output an 8 MHz clock on pin 9
// Version 1.9: Added support for Atmega1284P, and fixed some bugs
// Version 1.10: Corrected flash size for Atmega1284P.
// Version 1.11: Added support for Atmega1280. Removed MD5SUM stuff to make room.
// Version 1.12: Added signatures for ATtiny2313A, ATtiny4313, ATtiny13
// Version 1.13: Added signature for Atmega8A
// Version 1.14: Added bootloader for Atmega8
// Version 1.15: Removed extraneous 0xFF from some files
// Version 1.16: Added signature for Atmega328
// Version 1.17: Allowed for running on the Leonardo, Micro, etc.
/*
Copyright 2012 Nick Gammon.
PERMISSION TO DISTRIBUTE
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.
LIMITATION OF LIABILITY
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.
*/
#include <SPI.h>
#include <avr/pgmspace.h>
const unsigned long BAUD_RATE = 115200;
const byte CLOCKOUT = 9;
const byte RESET = 10; // --> goes to reset on the target board
#if ARDUINO < 100
const byte SCK = 13; // SPI clock
#endif
// number of items in an array
#define NUMITEMS(arg) ((unsigned int) (sizeof (arg) / sizeof (arg [0])))
// programming commands to send via SPI to the chip
enum {
progamEnable = 0xAC,
// writes are preceded by progamEnable
chipErase = 0x80,
writeLockByte = 0xE0,
writeLowFuseByte = 0xA0,
writeHighFuseByte = 0xA8,
writeExtendedFuseByte = 0xA4,
pollReady = 0xF0,
programAcknowledge = 0x53,
readSignatureByte = 0x30,
readCalibrationByte = 0x38,
readLowFuseByte = 0x50, readLowFuseByteArg2 = 0x00,
readExtendedFuseByte = 0x50, readExtendedFuseByteArg2 = 0x08,
readHighFuseByte = 0x58, readHighFuseByteArg2 = 0x08,
readLockByte = 0x58, readLockByteArg2 = 0x00,
readProgramMemory = 0x20,
writeProgramMemory = 0x4C,
loadExtendedAddressByte = 0x4D,
loadProgramMemory = 0x40,
}; // end of enum
// structure to hold signature and other relevant data about each chip
typedef struct {
byte sig [3];
char * desc;
unsigned long flashSize;
unsigned int baseBootSize;
const byte * bootloader;
unsigned long loaderStart; // bytes
unsigned int loaderLength; // bytes
unsigned long pageSize; // bytes
byte lowFuse, highFuse, extFuse, lockByte;
} signatureType;
const unsigned long kb = 1024;
// hex bootloader data
#include "bootloader_atmega168.h"
// see Atmega328 datasheet page 298
signatureType signatures [] =
{
// signature description flash size bootloader size
// Attiny84 family
{ { 0x1E, 0x91, 0x0B }, "ATtiny24", 2 * kb, 0 },
{ { 0x1E, 0x92, 0x07 }, "ATtiny44", 4 * kb, 0 },
{ { 0x1E, 0x93, 0x0C }, "ATtiny84", 8 * kb, 0 },
// Attiny85 family
{ { 0x1E, 0x91, 0x08 }, "ATtiny25", 2 * kb, 0 },
{ { 0x1E, 0x92, 0x06 }, "ATtiny45", 4 * kb, 0 },
{ { 0x1E, 0x93, 0x0B }, "ATtiny85", 8 * kb, 0 },
// Atmega328 family
{ { 0x1E, 0x92, 0x0A }, "ATmega48PA", 4 * kb, 0 },
{ { 0x1E, 0x93, 0x0F }, "ATmega88PA", 8 * kb, 256 },
{ { 0x1E, 0x94, 0x0B }, "ATmega168PA", 16 * kb, 256,
atmega168_optiboot, // loader image
//0x3E00, // start address
0x0,
sizeof atmega168_optiboot,
128, // page size (for committing)
0xC6, // fuse low byte: external full-swing crystal
0xde, // fuse high byte: SPI enable, brown-out detection at 2.7V
0xf8, // fuse extended byte: boot into bootloader, 512 byte bootloader
0xcf }, // lock bits: SPM is not allowed to write to the Boot Loader section.
}; // end of signatures
// if signature found in above table, this is its index
int foundSig = -1;
byte lastAddressMSB = 0;
// execute one programming instruction ... b1 is command, b2, b3, b4 are arguments
// processor may return a result on the 4th transfer, this is returned.
byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0)
{
SPI.transfer (b1);
SPI.transfer (b2);
SPI.transfer (b3);
return SPI.transfer (b4);
} // end of program
// read a byte from flash memory
byte readFlash (unsigned long addr)
{
byte high = (addr & 1) ? 0x08 : 0; // set if high byte wanted
addr >>= 1; // turn into word address
// set the extended (most significant) address byte if necessary
byte MSB = (addr >> 16) & 0xFF;
if (MSB != lastAddressMSB)
{
program (loadExtendedAddressByte, 0, MSB);
lastAddressMSB = MSB;
} // end if different MSB
return program (readProgramMemory | high, highByte (addr), lowByte (addr));
} // end of readFlash
// write a byte to the flash memory buffer (ready for committing)
byte writeFlash (unsigned long addr, const byte data)
{
byte high = (addr & 1) ? 0x08 : 0; // set if high byte wanted
addr >>= 1; // turn into word address
program (loadProgramMemory | high, 0, lowByte (addr), data);
} // end of writeFlash
// show a byte in hex with leading zero and optional newline
void showHex (const byte b, const boolean newline = false, const boolean show0x = true)
{
if (show0x)
Serial.print (F("0x"));
// try to avoid using sprintf
char buf [4] = { ((b >> 4) & 0x0F) | '0', (b & 0x0F) | '0', ' ' , 0 };
if (buf [0] > '9')
buf [0] += 7;
if (buf [1] > '9')
buf [1] += 7;
Serial.print (buf);
if (newline)
Serial.println ();
} // end of showHex
// convert a boolean to Yes/No
void showYesNo (const boolean b, const boolean newline = false)
{
if (b)
Serial.print (F("Yes"));
else
Serial.print (F("No"));
if (newline)
Serial.println ();
} // end of showYesNo
// poll the target device until it is ready to be programmed
void pollUntilReady ()
{
while ((program (pollReady) & 1) == 1)
{} // wait till ready
} // end of pollUntilReady
// commit page
void commitPage (unsigned long addr)
{
//Serial.print (F("Committing page starting at 0x"));
//Serial.println (addr, HEX);
addr >>= 1; // turn into word address
// set the extended (most significant) address byte if necessary
byte MSB = (addr >> 16) & 0xFF;
if (MSB != lastAddressMSB)
{
program (loadExtendedAddressByte, 0, MSB);
lastAddressMSB = MSB;
} // end if different MSB
program (writeProgramMemory, highByte (addr), lowByte (addr));
pollUntilReady ();
} // end of commitPage
// write specified value to specified fuse/lock byte
void writeFuse (const byte newValue, const byte instruction)
{
if (newValue == 0)
return; // ignore
program (progamEnable, instruction, 0, newValue);
pollUntilReady ();
} // end of writeFuse
void getFuseBytes ()
{
Serial.print (F("LFuse = "));
showHex (program (readLowFuseByte, readLowFuseByteArg2), true);
Serial.print (F("HFuse = "));
showHex (program (readHighFuseByte, readHighFuseByteArg2), true);
Serial.print (F("EFuse = "));
showHex (program (readExtendedFuseByte, readExtendedFuseByteArg2), true);
Serial.print (F("Lock byte = "));
showHex (program (readLockByte, readLockByteArg2), true);
Serial.print ("Clock calibration = ");
showHex (program (readCalibrationByte), true);
} // end of getFuseBytes
// burn the bootloader to the target device
void writeBootloader ()
{
if (signatures [foundSig].bootloader == 0)
{
Serial.println (F("No bootloader support for this device."));
return;
} // end if
int i;
byte lFuse = program (readLowFuseByte, readLowFuseByteArg2);
byte newlFuse = signatures [foundSig].lowFuse;
byte newhFuse = signatures [foundSig].highFuse;
byte newextFuse = signatures [foundSig].extFuse;
byte newlockByte = signatures [foundSig].lockByte;
unsigned long addr = signatures [foundSig].loaderStart;
unsigned int len = signatures [foundSig].loaderLength;
unsigned long pagesize = signatures [foundSig].pageSize;
unsigned long pagemask = ~(pagesize - 1);
const byte * bootloader = signatures [foundSig].bootloader;
Serial.print (F("Bootloader address = 0x"));
Serial.println (addr, HEX);
Serial.print (F("Bootloader length = "));
Serial.print (len);
Serial.println (F(" bytes."));
byte subcommand = 'U';
// Atmega328P or Atmega328
if (signatures [foundSig].sig [0] == 0x1E &&
signatures [foundSig].sig [1] == 0x95 &&
(signatures [foundSig].sig [2] == 0x0F || signatures [foundSig].sig [2] == 0x14)
)
{
Serial.println (F("Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ..."));
do
{
subcommand = toupper (Serial.read ());
} while (subcommand != 'L' && subcommand != 'U');
if (subcommand == 'L') // use internal 8 MHz clock
{
Serial.println (F("Using Lilypad 8 MHz loader."));
bootloader = atmega168_optiboot;
newlFuse = 0xE2; // internal 8 MHz oscillator
newhFuse = 0xDA; // 2048 byte bootloader, SPI enabled
addr = 0x7800;
len = sizeof atmega168_optiboot;
} // end of using the 8 MHz clock
else
Serial.println (F("Using Uno Optiboot 16 MHz loader."));
} // end of being Atmega328P
unsigned long oldPage = addr & pagemask;
Serial.println (F("Type 'V' to verify, or 'G' to program the chip with the bootloader ..."));
char command;
do
{
command = toupper (Serial.read ());
} while (command != 'G' && command != 'V');
if (command == 'G')
{
Serial.println (F("Erasing chip ..."));
program (progamEnable, chipErase); // erase it
pollUntilReady ();
Serial.println (F("Writing bootloader ..."));
for (i = 0; i < len; i += 2)
{
unsigned long thisPage = (addr + i) & pagemask;
// page changed? commit old one
if (thisPage != oldPage)
{
commitPage (oldPage);
oldPage = thisPage;
}
unsigned char c1 = pgm_read_byte(bootloader + i);
unsigned char c2 = pgm_read_byte(bootloader + i+1);
writeFlash (addr + i, c1);
writeFlash (addr + i + 1, c2);
} // end while doing each word
Serial.println();
// commit final page
commitPage (oldPage);
Serial.println ("Written.");
} // end if programming
Serial.println (F("Verifying ..."));
// count errors
unsigned int errors = 0;
// check each byte
for (i = 0; i < signatures [foundSig].loaderLength; i++)
{
//if(i==0)Serial.print(" ");
byte found = readFlash (addr + i);
byte expected = pgm_read_byte(bootloader + i);
if (found != expected)
{
if (errors <= 100)
{
Serial.print (F("Verification error at address "));
Serial.print (addr + i, HEX);
Serial.print (F(". Got: "));
showHex (found);
Serial.print (F(" Expected: "));
showHex (expected, true);
} // end of haven't shown 100 errors yet
errors++;
} // end if error
} // end of for
Serial.println("\r\n");
if (errors == 0)
Serial.println (F("No errors found."));
else
{
Serial.print (errors, DEC);
Serial.println (F(" verification error(s)."));
if (errors > 100)
Serial.println (F("First 100 shown."));
return; // don't change fuses if errors
} // end if
if (command == 'G')
{
Serial.println (F("Writing fuses ..."));
writeFuse (newlFuse, writeLowFuseByte);
writeFuse (newhFuse, writeHighFuseByte);
writeFuse (newextFuse, writeExtendedFuseByte);
writeFuse (newlockByte, writeLockByte);
// confirm them
getFuseBytes ();
} // end if programming
Serial.println (F("Done."));
} // end of writeBootloader
void startProgramming ()
{
byte confirm;
pinMode (RESET, OUTPUT);
pinMode (SCK, OUTPUT);
// we are in sync if we get back programAcknowledge on the third byte
do
{
delay (100);
// ensure SCK low
digitalWrite (SCK, LOW);
// then pulse reset, see page 309 of datasheet
digitalWrite (RESET, HIGH);
delay (1); // pulse for at least 2 clock cycles
digitalWrite (RESET, LOW);
delay (25); // wait at least 20 mS
SPI.transfer (progamEnable);
SPI.transfer (programAcknowledge);
confirm = SPI.transfer (0);
SPI.transfer (0);
} while (confirm != programAcknowledge);
Serial.println (F("Entered programming mode OK."));
} // end of startProgramming
void getSignature ()
{
foundSig = -1;
lastAddressMSB = 0;
byte sig [3];
Serial.print (F("Signature = "));
for (byte i = 0; i < 3; i++)
{
sig [i] = program (readSignatureByte, 0, i);
showHex (sig [i]);
} // end for each signature byte
Serial.println ();
for (int j = 0; j < NUMITEMS (signatures); j++)
{
if (memcmp (sig, signatures [j].sig, sizeof sig) == 0)
{
foundSig = j;
Serial.print (F("Processor = "));
Serial.println (signatures [j].desc);
Serial.print (F("Flash memory size = "));
Serial.print (signatures [j].flashSize, DEC);
Serial.println (F(" bytes."));
return;
} // end of signature found
} // end of for each signature
Serial.println (F("Unrecogized signature."));
} // end of getSignature
void setup ()
{
Serial.begin (BAUD_RATE);
while (!Serial) ; // for Leonardo, Micro etc.
Serial.println ();
Serial.println (F("Atmega chip programmer."));
Serial.println (F("Written by Nick Gammon."));
digitalWrite (RESET, HIGH); // ensure SS stays high for now
SPI.begin ();
// slow down SPI for benefit of slower processors like the Attiny
SPI.setClockDivider (SPI_CLOCK_DIV64);
pinMode (CLOCKOUT, OUTPUT);
// set up Timer 1
TCCR1A = _BV (COM1A0); // toggle OC1A on Compare Match
TCCR1B = _BV(WGM12) | _BV(CS10); // CTC, no prescaling
OCR1A = 0; // output every cycle
} // end of setup
void loop ()
{
startProgramming ();
getSignature ();
getFuseBytes ();
// if we found a signature try to write a bootloader
if (foundSig != -1)
writeBootloader ();
// release reset
digitalWrite (RESET, HIGH);
Serial.println (F("Type 'C' when ready to continue with another chip ..."));
while (toupper (Serial.read ()) != 'C')
{}
} // end of loop

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 2 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.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -0,0 +1,35 @@
// Calibration code for Grove - Multichannel Gas Sensor
// Note that it need 10 minutes pre-heat before calibration
// This code is writen by Loovee@2016-5-18
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
#define PRE_HEAT_TIME 0 // pre-heat time, 10-30 minutes is recommended
void setup()
{
Serial.begin(115200);
gas.begin(SENSOR_ADDR); //
Serial.println("power on, and pre-heat");
for(int i=60*PRE_HEAT_TIME; i>=0; i--)
{
Serial.print(i/60);
Serial.print(":");
Serial.println(i%60);
delay(1000);
}
Serial.println("Begin to calibrate...");
gas.doCalibrate();
Serial.println("Calibration ok");
gas.display_eeprom();
}
void loop()
{
}

View File

@ -0,0 +1,36 @@
// factory setting
// Loovee
// 2016-11-10
#include <Wire.h>
#include "MutichannelGasSensor.h"
#define SENSOR_ADDR 0X04 // default to 0x04
void setup()
{
Serial.begin(115200);
Serial.println("Please input something to continue");
while(!Serial.available());
gas.begin(SENSOR_ADDR); //
Serial.println("FACTORY SETTING OK");
float R0_NH3, R0_CO, R0_NO2;
R0_NH3 = gas.getR0(0);
R0_CO = gas.getR0(1);
R0_NO2 = gas.getR0(2);
Serial.print("R0_NH3 = ");
Serial.println(R0_NH3);
Serial.print("R0_CO = ");
Serial.println(R0_CO);
Serial.print("R0_NO2 = ");
Serial.println(R0_NO2);
}
void loop()
{
}

View File

@ -0,0 +1,272 @@
/*firmware of multichannel gas sensor v2.0*3
write by loovee
2016-11-6
Factory adc value of 3 channels:
NH3 = 860
CO = 950
NO2 = 155
Default address is 0x04
*/
#include <Wire.h>
#include <EEPROM.h>
#define DEFAULT_I2C_ADDR 0x04
#define DBG 1
// EEPROM ADDRESS
#define ADDR_IS_SET 0 // if this is the first time to run, if 1126, set
#define ADDR_FACTORY_ADC_NH3 2
#define ADDR_FACTORY_ADC_CO 4
#define ADDR_FACTORY_ADC_NO2 6
#define ADDR_USER_ADC_HN3 8
#define ADDR_USER_ADC_CO 10
#define ADDR_USER_ADC_NO2 12
#define ADDR_IF_CALI 14 // IF USER HAD CALI
#define ADDR_I2C_ADDRESS 20
// I2C COMMAND
#define CMD_ADC_RES0 1 // NH3
#define CMD_ADC_RES1 2 // CO
#define CMD_ADC_RES2 3 // NO2
#define CMD_ADC_RESALL 4 // ALL CHANNEL
#define CMD_CHANGE_I2C 5 // CHANGE I2C
#define CMD_READ_EEPROM 6 // READ EEPROM VALUE, RETURN UNSIGNED INT
#define CMD_SET_R0_ADC 7 // SET R0 ADC VALUE
#define CMD_GET_R0_ADC 8 // GET R0 ADC VALUE
#define CMD_GET_R0_ADC_FACTORY 9 // GET FACTORY R0 ADC VALUE
#define CMD_CONTROL_LED 10
#define CMD_CONTROL_PWR 11
// EEPROM READ AND WRITE - UNSIGNED INT
void eeprom_write(int addr, unsigned int value)
{
EEPROM.write(addr, value>>8);
EEPROM.write(addr+1, value&0xff);
}
unsigned int eeprom_read(int addr)
{
unsigned int r = EEPROM.read(addr);
r <<= 8;
r+= EEPROM.read(addr+1);
return r;
}
const int pin_pwr = 8;
const int pin_led = 9;
const int pin_NH3 = A0; // RES0
const int pin_CO = A1; // RES1
const int pin_NO2 = A2; // RES2
unsigned char i2c_address = 0;
#define LED_ON() digitalWrite(pin_led, LOW)
#define LED_OFF() digitalWrite(pin_led, HIGH)
void factory_init()
{
#if DBG
Serial.print("FACTORY: ");
#endif
if(1126 != eeprom_read(ADDR_IS_SET)) // IF FACTORY SET
{
#if DBG
Serial.println("YES");
#endif
eeprom_write(ADDR_IS_SET, 1126);
eeprom_write(ADDR_FACTORY_ADC_NH3, 860);
eeprom_write(ADDR_FACTORY_ADC_CO, 950);
eeprom_write(ADDR_FACTORY_ADC_NO2, 155);
eeprom_write(ADDR_USER_ADC_HN3, 860);
eeprom_write(ADDR_USER_ADC_CO, 950);
eeprom_write(ADDR_USER_ADC_NO2, 155);
eeprom_write(ADDR_IF_CALI, 0);
eeprom_write(ADDR_I2C_ADDRESS, DEFAULT_I2C_ADDR);
}
#if DBG
else Serial.println("NO");
#endif
}
int getAnalog(int pin)
{
long sum = 0;
for(int i=0; i<64; i++)
{
sum += analogRead(pin);
}
return sum>>6;
}
unsigned int ADC_RES0 = 0;
unsigned int ADC_RES1 = 0;
unsigned int ADC_RES2 = 0;
unsigned char raw_adc[6];
void updateValue()
{
static unsigned long timer_s = millis();
if(millis()-timer_s < 1000)return;
timer_s = millis();
ADC_RES0 = getAnalog(pin_NH3);
ADC_RES1 = getAnalog(pin_CO);
ADC_RES2 = getAnalog(pin_NO2);
raw_adc[0] = ADC_RES0>>8;
raw_adc[1] = ADC_RES0;
raw_adc[2] = ADC_RES1>>8;
raw_adc[3] = ADC_RES1;
raw_adc[4] = ADC_RES2>>8;
raw_adc[5] = ADC_RES2;
}
void setup()
{
#if DBG
Serial.begin(115200);
#endif
pinMode(pin_pwr, OUTPUT);
digitalWrite(pin_pwr, HIGH);
pinMode(pin_led, OUTPUT);
factory_init();
i2c_address = eeprom_read(ADDR_I2C_ADDRESS);
#if DBG
Serial.print("i2d address = 0x");
Serial.println(i2c_address, HEX);
#endif
for(int i=0; i<5; i++)
{
digitalWrite(pin_led, LOW);
delay(100);
digitalWrite(pin_led, HIGH);
delay(100);
}
Wire.begin(i2c_address); // join i2c bus with address
Wire.onReceive(receiveCallback); // register receive callback
Wire.onRequest(requestCallback); // register request callback
}
void loop()
{
updateValue();
}
unsigned char recvCmd = 0;
unsigned char recvDta = 0;
unsigned char recvDtaStr[10];
void receiveCallback(int dtaCount)
{
if(dtaCount == 1)
{
recvCmd = Wire.read();
}
else if(dtaCount == 2) // set i2c address
{
recvCmd = Wire.read();
recvDta = Wire.read();
if(CMD_CHANGE_I2C == recvCmd)
{
i2c_address = recvDta;
eeprom_write(ADDR_I2C_ADDRESS, i2c_address);
Wire.begin(i2c_address);
}
else if(CMD_CONTROL_LED == recvCmd)
{
if(0 == recvDta)LED_OFF();
else if(1 == recvDta)LED_ON();
}
else if(CMD_CONTROL_PWR == recvCmd)
{
if(0 == recvDta)digitalWrite(pin_pwr, LOW);
else if(1 == recvDta)digitalWrite(pin_pwr, HIGH);
}
}
else if(dtaCount == 7) // set ADC value
{
recvCmd = Wire.read();
unsigned int dta[3];
for(int i=0; i<3; i++)
{
dta[i] = Wire.read();
dta[i] <<= 8;
dta[i] += Wire.read();
}
if(recvCmd == CMD_SET_R0_ADC)
{
eeprom_write(ADDR_USER_ADC_HN3, dta[0]);
eeprom_write(ADDR_USER_ADC_CO, dta[1]);
eeprom_write(ADDR_USER_ADC_NO2, dta[2]);
}
}
}
unsigned char rcDta[10];
void requestCallback()
{
switch(recvCmd)
{
case CMD_ADC_RES0: // NH3
Wire.write(&raw_adc[0], 2); // HIGH FIRST
break;
case CMD_ADC_RES1: // CO
Wire.write(&raw_adc[2], 2); // HIGH FIRST
break;
case CMD_ADC_RES2: // NO2
Wire.write(&raw_adc[4], 2); // HIGH FIRST
break;
case CMD_ADC_RESALL:
Wire.write(raw_adc, 6);
break;
case CMD_READ_EEPROM:
rcDta[0] = EEPROM.read(recvDta);
rcDta[1] = EEPROM.read(recvDta+1);
Wire.write(rcDta, 2);
break;
case CMD_GET_R0_ADC:
rcDta[0] = EEPROM.read(ADDR_USER_ADC_HN3);
rcDta[1] = EEPROM.read(ADDR_USER_ADC_HN3+1);
rcDta[2] = EEPROM.read(ADDR_USER_ADC_CO);
rcDta[3] = EEPROM.read(ADDR_USER_ADC_CO+1);
rcDta[4] = EEPROM.read(ADDR_USER_ADC_NO2);
rcDta[5] = EEPROM.read(ADDR_USER_ADC_NO2+1);
Wire.write(rcDta, 6);
break;
case CMD_GET_R0_ADC_FACTORY:
rcDta[0] = EEPROM.read(ADDR_FACTORY_ADC_NH3);
rcDta[1] = EEPROM.read(ADDR_FACTORY_ADC_NH3+1);
rcDta[2] = EEPROM.read(ADDR_FACTORY_ADC_CO);
rcDta[3] = EEPROM.read(ADDR_FACTORY_ADC_CO+1);
rcDta[4] = EEPROM.read(ADDR_FACTORY_ADC_NO2);
rcDta[5] = EEPROM.read(ADDR_FACTORY_ADC_NO2+1);
Wire.write(rcDta, 6);
break;
default:;
}
}
// END FILE

View File

@ -0,0 +1,14 @@
{
"name": "Mutichannel_Gas_Sensor",
"keywords": "Gas Sensor",
"description": "Grove - Multichannel Gas Sensor",
"homepage": "http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/",
"repository":
{
"type": "git",
"url": "https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git"
},
"version": "0.0.1",
"frameworks": "arduino",
"platforms": "*"
}

View File

@ -0,0 +1,9 @@
name=Grove - Multichannel Gas Sensor
version=0.0.1
author=WEMOS.CC <support@wemos.cc>
maintainer=WEMOS.CC
sentence=Library for the <a href="http://wiki.seeed.cc/Grove-Multichannel_Gas_Sensor/"> Grove - Multichannel Gas Sensor</a>.
paragraph=Library for the Grove - Multichannel Gas Sensor.
category=Device Control
url=https://github.com/Seeed-Studio/Mutichannel_Gas_Sensor.git
architectures=*

View File

@ -0,0 +1,729 @@
/*
MutichannelGasSensor.cpp
2015 Copyright (c) Seeed Technology Inc. All right reserved.
Author: Jacky Zhang
2015-3-17
http://www.seeed.cc/
modi by Jack, 2015-8
The MIT License (MIT)
Copyright (c) 2015 Seeed Technology Inc.
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.
*/
#include <math.h>
#include <Wire.h>
#include <Arduino.h>
#include "MutichannelGasSensor.h"
/*********************************************************************************************************
** Function name: begin
** Descriptions: initialize I2C
*********************************************************************************************************/
void MutichannelGasSensor::begin(int address)
{
__version = 1; // version 1/2
r0_inited = false;
Wire.begin();
i2cAddress = address;
__send_error = false;
__version = getVersion();
}
bool MutichannelGasSensor::isError()
{
return __send_error;
}
unsigned char MutichannelGasSensor::getVersion()
{
if(get_addr_dta(CMD_READ_EEPROM, ADDR_IS_SET) == 1126) // get version
{
__version = 2;
return __version;
}
if (!__send_error) {
__version = 1;
}
else {
__version = -1;
}
return __version;
}
void MutichannelGasSensor::begin()
{
begin(DEFAULT_I2C_ADDR);
}
/*********************************************************************************************************
** Function name: sendI2C
** Descriptions: send one byte to I2C Wire
*********************************************************************************************************/
void MutichannelGasSensor::sendI2C(unsigned char dta)
{
__send_error = false;
Wire.beginTransmission(i2cAddress); // transmit to device #4
Wire.write(dta); // sends one byte
if (Wire.endTransmission()) { // stop transmitting
__send_error = true;
}
}
unsigned int MutichannelGasSensor::get_addr_dta(unsigned char addr_reg)
{
int trys = 0;
START:
__send_error = false;
Wire.beginTransmission(i2cAddress);
Wire.write(addr_reg);
if (Wire.endTransmission()) { // stop transmitting
trys++;
__send_error = true;
if (trys > 3) {
return 0;
}
}
Wire.requestFrom(i2cAddress, (uint8_t)2);
unsigned int dta = 0;
unsigned char raw[10];
int cnt = 0;
while(Wire.available())
{
raw[cnt++] = Wire.read();
}
if(cnt == 0)goto START;
dta = raw[0];
dta <<= 8;
dta += raw[1];
switch(addr_reg)
{
case CH_VALUE_NH3:
if(dta > 0)
{
adcValueR0_NH3_Buf = dta;
}
else
{
dta = adcValueR0_NH3_Buf;
}
break;
case CH_VALUE_CO:
if(dta > 0)
{
adcValueR0_CO_Buf = dta;
}
else
{
dta = adcValueR0_CO_Buf;
}
break;
case CH_VALUE_NO2:
if(dta > 0)
{
adcValueR0_NO2_Buf = dta;
}
else
{
dta = adcValueR0_NO2_Buf;
}
break;
default:;
}
return dta;
}
unsigned int MutichannelGasSensor::get_addr_dta(unsigned char addr_reg, unsigned char __dta)
{
int trys = 0;
START:
__send_error = false;
Wire.beginTransmission(i2cAddress);
Wire.write(addr_reg);
Wire.write(__dta);
if (Wire.endTransmission()) { // stop transmitting
trys++;
__send_error = true;
if (trys > 3) {
return 0;
}
}
Wire.requestFrom(i2cAddress, (uint8_t)2);
unsigned int dta = 0;
unsigned char raw[10];
int cnt = 0;
while(Wire.available())
{
raw[cnt++] = Wire.read();
}
if(cnt == 0)goto START;
dta = raw[0];
dta <<= 8;
dta += raw[1];
return dta;
}
void MutichannelGasSensor::write_i2c(unsigned char addr, unsigned char *dta, unsigned char dta_len)
{
__send_error = false;
Wire.beginTransmission(addr);
for(int i=0; i<dta_len; i++)
{
Wire.write(dta[i]);
}
if (Wire.endTransmission()) {
__send_error = true;
}
}
/*********************************************************************************************************
** Function name: readData
** Descriptions: read 4 bytes from I2C slave
*********************************************************************************************************/
int16_t MutichannelGasSensor::readData(uint8_t cmd)
{
uint16_t timeout = 0;
uint8_t buffer[4];
uint8_t checksum = 0;
int16_t rtnData = 0;
//send command
sendI2C(cmd);
//wait for a while
delay(2);
//get response
Wire.requestFrom(i2cAddress, (uint8_t)4); // request 4 bytes from slave device
while(Wire.available() == 0)
{
if(timeout++ > 100)
return -2;//time out
delay(2);
}
if(Wire.available() != 4)
return -3;//rtnData length wrong
buffer[0] = Wire.read();
buffer[1] = Wire.read();
buffer[2] = Wire.read();
buffer[3] = Wire.read();
checksum = (uint8_t)(buffer[0] + buffer[1] + buffer[2]);
if(checksum != buffer[3])
return -4;//checksum wrong
rtnData = ((buffer[1] << 8) + buffer[2]);
return rtnData;//successful
}
/*********************************************************************************************************
** Function name: readR0
** Descriptions: read R0 stored in slave MCU
*********************************************************************************************************/
int16_t MutichannelGasSensor::readR0(void)
{
int16_t rtnData = 0;
rtnData = readData(0x11);
if(rtnData > 0)
res0[0] = rtnData;
else
return rtnData; //unsuccessful
rtnData = readData(0x12);
if(rtnData > 0)
res0[1] = rtnData;
else
return rtnData; //unsuccessful
rtnData = readData(0x13);
if(rtnData > 0)
res0[2] = rtnData;
else
return rtnData; //unsuccessful
return 1;//successful
}
/*********************************************************************************************************
** Function name: readR
** Descriptions: read resistance value of each channel from slave MCU
*********************************************************************************************************/
int16_t MutichannelGasSensor::readR(void)
{
int16_t rtnData = 0;
rtnData = readData(0x01);
if(rtnData >= 0)
res[0] = rtnData;
else
return rtnData;//unsuccessful
rtnData = readData(0x02);
if(rtnData >= 0)
res[1] = rtnData;
else
return rtnData;//unsuccessful
rtnData = readData(0x03);
if(rtnData >= 0)
res[2] = rtnData;
else
return rtnData;//unsuccessful
return 0;//successful
}
/*********************************************************************************************************
** Function name: readR
** Descriptions: calculate gas concentration of each channel from slave MCU
** Parameters:
gas - gas type
** Returns:
float value - concentration of the gas
*********************************************************************************************************/
float MutichannelGasSensor::calcGas(int gas)
{
float ratio0, ratio1, ratio2;
if(1 == __version)
{
if(!r0_inited)
{
if(readR0() >= 0) r0_inited = true;
else return -1.0f;
}
if(readR() < 0)
return -2.0f;
ratio0 = (float)res[0] / res0[0];
ratio1 = (float)res[1] / res0[1];
ratio2 = (float)res[2] / res0[2];
}
else if(2 == __version)
{
// how to calc ratio/123
ledOn();
int A0_0 = get_addr_dta(6, ADDR_USER_ADC_HN3);
int A0_1 = get_addr_dta(6, ADDR_USER_ADC_CO);
int A0_2 = get_addr_dta(6, ADDR_USER_ADC_NO2);
int An_0 = get_addr_dta(CH_VALUE_NH3);
int An_1 = get_addr_dta(CH_VALUE_CO);
int An_2 = get_addr_dta(CH_VALUE_NO2);
ratio0 = (float)An_0/(float)A0_0*(1023.0-A0_0)/(1023.0-An_0);
ratio1 = (float)An_1/(float)A0_1*(1023.0-A0_1)/(1023.0-An_1);
ratio2 = (float)An_2/(float)A0_2*(1023.0-A0_2)/(1023.0-An_2);
}
float c = 0;
switch(gas)
{
case CO:
{
c = pow(ratio1, -1.179)*4.385; //mod by jack
break;
}
case NO2:
{
c = pow(ratio2, 1.007)/6.855; //mod by jack
break;
}
case NH3:
{
c = pow(ratio0, -1.67)/1.47; //modi by jack
break;
}
case C3H8: //add by jack
{
c = pow(ratio0, -2.518)*570.164;
break;
}
case C4H10: //add by jack
{
c = pow(ratio0, -2.138)*398.107;
break;
}
case GAS_CH4: //add by jack
{
c = pow(ratio1, -4.363)*630.957;
break;
}
case H2: //add by jack
{
c = pow(ratio1, -1.8)*0.73;
break;
}
case C2H5OH: //add by jack
{
c = pow(ratio1, -1.552)*1.622;
break;
}
default:
break;
}
if(2==__version)ledOff();
return isnan(c)?-3:c;
}
/*********************************************************************************************************
** Function name: changeI2cAddr
** Descriptions: change I2C address of the slave MCU, and this address will be stored in EEPROM of slave MCU
*********************************************************************************************************/
void MutichannelGasSensor::changeI2cAddr(uint8_t newAddr)
{
Wire.beginTransmission(i2cAddress); // transmit to device
Wire.write(0x23); // sends one byte
Wire.write(newAddr); // sends one byte
if (Wire.endTransmission()){ // stop transmitting
__send_error = true;
} else {
i2cAddress = newAddr;
}
}
/*********************************************************************************************************
** Function name: doCalibrate
** Descriptions: tell slave to do a calibration, it will take about 8s
after the calibration, must reread the R0 values
*********************************************************************************************************/
void MutichannelGasSensor::doCalibrate(void)
{
if(1 == __version)
{
START:
sendI2C(0x22);
if(readR0() > 0)
{
for(int i=0; i<3; i++)
{
Serial.print(res0[i]);
Serial.print('\t');
}
}
else
{
delay(5000);
Serial.println("continue...");
for(int i=0; i<3; i++)
{
Serial.print(res0[i]);
Serial.print('\t');
}
Serial.println();
goto START;
}
}
else if(2 == __version)
{
unsigned int i, a0, a1, a2;
while(1)
{
a0 = get_addr_dta(CH_VALUE_NH3);
a1 = get_addr_dta(CH_VALUE_CO);
a2 = get_addr_dta(CH_VALUE_NO2);
Serial.print(a0);
Serial.print('\t');
Serial.print(a1);
Serial.print('\t');
Serial.print(a2);
Serial.println('\t');
ledOn();
int cnt = 0;
for(i=0; i<20; i++)
{
if((a0 - get_addr_dta(CH_VALUE_NH3)) > 2 || (get_addr_dta(CH_VALUE_NH3) - a0) > 2)cnt++;
if((a1 - get_addr_dta(CH_VALUE_CO)) > 2 || (get_addr_dta(CH_VALUE_CO) - a1) > 2)cnt++;
if((a2 - get_addr_dta(CH_VALUE_NO2)) > 2 || (get_addr_dta(CH_VALUE_NO2) - a2) > 2)cnt++;
if(cnt>5)
{
break;
}
delay(1000);
}
ledOff();
if(cnt <= 5)break;
delay(200);
}
Serial.print("write user adc value: ");
Serial.print(a0);Serial.print('\t');
Serial.print(a1);Serial.print('\t');
Serial.print(a2);Serial.println('\t');
unsigned char tmp[7];
tmp[0] = 7;
tmp[1] = a0>>8;
tmp[2] = a0&0xff;
tmp[3] = a1>>8;
tmp[4] = a1&0xff;
tmp[5] = a2>>8;
tmp[6] = a2&0xff;
write_i2c(i2cAddress, tmp, 7);
}
}
/*********************************************************************************************************
** Function name: powerOn
** Descriptions: power on sensor heater
*********************************************************************************************************/
void MutichannelGasSensor::powerOn(void)
{
if(__version == 1)
sendI2C(0x21);
else if(__version == 2)
{
dta_test[0] = 11;
dta_test[1] = 1;
write_i2c(i2cAddress, dta_test, 2);
}
}
/*********************************************************************************************************
** Function name: powerOff
** Descriptions: power off sensor heater
*********************************************************************************************************/
void MutichannelGasSensor::powerOff(void)
{
if(__version == 1)
sendI2C(0x20);
else if(__version == 2)
{
dta_test[0] = 11;
dta_test[1] = 0;
write_i2c(i2cAddress, dta_test, 2);
}
}
void MutichannelGasSensor::display_eeprom()
{
if(__version == 1)
{
Serial.println("ERROR: display_eeprom() is NOT support by V1 firmware.");
return ;
}
Serial.print("ADDR_IS_SET = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_IS_SET));
Serial.print("ADDR_FACTORY_ADC_NH3 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NH3));
Serial.print("ADDR_FACTORY_ADC_CO = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_CO));
Serial.print("ADDR_FACTORY_ADC_NO2 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NO2));
Serial.print("ADDR_USER_ADC_HN3 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_HN3));
Serial.print("ADDR_USER_ADC_CO = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_CO));
Serial.print("ADDR_USER_ADC_NO2 = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_NO2));
Serial.print("ADDR_I2C_ADDRESS = "); Serial.println(get_addr_dta(CMD_READ_EEPROM, ADDR_I2C_ADDRESS));
}
float MutichannelGasSensor::getR0(unsigned char ch) // 0:CH3, 1:CO, 2:NO2
{
if(__version == 1)
{
Serial.println("ERROR: getR0() is NOT support by V1 firmware.");
return -1;
}
int a = 0;
switch(ch)
{
case 0: // CH3
a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_HN3);
Serial.print("a_ch3 = ");
Serial.println(a);
break;
case 1: // CO
a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_CO);
Serial.print("a_co = ");
Serial.println(a);
break;
case 2: // NO2
a = get_addr_dta(CMD_READ_EEPROM, ADDR_USER_ADC_NO2);
Serial.print("a_no2 = ");
Serial.println(a);
break;
default:;
}
float r = 56.0*(float)a/(1023.0-(float)a);
return r;
}
float MutichannelGasSensor::getRs(unsigned char ch) // 0:CH3, 1:CO, 2:NO2
{
if(__version == 1)
{
Serial.println("ERROR: getRs() is NOT support by V1 firmware.");
return -1;
}
int a = 0;
switch(ch)
{
case 0: // NH3
a = get_addr_dta(1);
break;
case 1: // CO
a = get_addr_dta(2);
break;
case 2: // NO2
a = get_addr_dta(3);
break;
default:;
}
float r = 56.0*(float)a/(1023.0-(float)a);
return r;
}
// 1. change i2c address to 0x04
// 2. change adc value of R0 to default
void MutichannelGasSensor::factory_setting()
{
unsigned char tmp[7];
unsigned char error;
unsigned char address = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
// change i2c to 0x04
Serial.print("I2C address is: 0x");
Serial.println(address, HEX);
Serial.println("Change I2C address to 0x04");
dta_test[0] = CMD_CHANGE_I2C;
dta_test[1] = 0x04;
write_i2c(address, dta_test, 2);
i2cAddress = 0x04;
delay(100);
getVersion();
break;
}
}
unsigned int a0 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NH3);
unsigned int a1 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_CO);
unsigned int a2 = get_addr_dta(CMD_READ_EEPROM, ADDR_FACTORY_ADC_NO2);
tmp[0] = 7;
tmp[1] = a0>>8;
tmp[2] = a0&0xff;
tmp[3] = a1>>8;
tmp[4] = a1&0xff;
tmp[5] = a2>>8;
tmp[6] = a2&0xff;
delay(100);
write_i2c(i2cAddress, tmp, 7);
delay(100);
}
void MutichannelGasSensor::change_i2c_address(unsigned char addr)
{
dta_test[0] = CMD_CHANGE_I2C;
dta_test[1] = addr;
write_i2c(i2cAddress, dta_test, 2);
Serial.print("FUNCTION: CHANGE I2C ADDRESS: 0X");
Serial.print(i2cAddress, HEX);
Serial.print(" > 0x");
Serial.println(addr, HEX);
i2cAddress = addr;
}
void MutichannelGasSensor::ledOn()
{
dta_test[0] = CMD_CONTROL_LED;
dta_test[1] = 1;
write_i2c(i2cAddress, dta_test, 2);
}
void MutichannelGasSensor::ledOff()
{
dta_test[0] = CMD_CONTROL_LED;
dta_test[1] = 0;
write_i2c(i2cAddress, dta_test, 2);
}
MutichannelGasSensor gas;
/*********************************************************************************************************
END FILE
*********************************************************************************************************/

View File

@ -0,0 +1,140 @@
/*
MutichannelGasSensor.h
2015 Copyright (c) Seeed Technology Inc. All right reserved.
Author: Jacky Zhang
2015-3-17
http://www.seeed.cc/
modi by Jack, 2015-8
V2 by Loovee
2016-11-11
The MIT License (MIT)
Copyright (c) 2015 Seeed Technology Inc.
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.
*/
#ifndef __MUTICHANNELGASSENSOR_H__
#define __MUTICHANNELGASSENSOR_H__
#define DEFAULT_I2C_ADDR 0x04
#define ADDR_IS_SET 0 // if this is the first time to run, if 1126, set
#define ADDR_FACTORY_ADC_NH3 2
#define ADDR_FACTORY_ADC_CO 4
#define ADDR_FACTORY_ADC_NO2 6
#define ADDR_USER_ADC_HN3 8
#define ADDR_USER_ADC_CO 10
#define ADDR_USER_ADC_NO2 12
#define ADDR_IF_CALI 14 // IF USER HAD CALI
#define ADDR_I2C_ADDRESS 20
#define CH_VALUE_NH3 1
#define CH_VALUE_CO 2
#define CH_VALUE_NO2 3
#define CMD_ADC_RES0 1 // NH3
#define CMD_ADC_RES1 2 // CO
#define CMD_ADC_RES2 3 // NO2
#define CMD_ADC_RESALL 4 // ALL CHANNEL
#define CMD_CHANGE_I2C 5 // CHANGE I2C
#define CMD_READ_EEPROM 6 // READ EEPROM VALUE, RETURN UNSIGNED INT
#define CMD_SET_R0_ADC 7 // SET R0 ADC VALUE
#define CMD_GET_R0_ADC 8 // GET R0 ADC VALUE
#define CMD_GET_R0_ADC_FACTORY 9 // GET FACTORY R0 ADC VALUE
#define CMD_CONTROL_LED 10
#define CMD_CONTROL_PWR 11
enum{CO, NO2, NH3, C3H8, C4H10, GAS_CH4, H2, C2H5OH};
class MutichannelGasSensor{
private:
int __version;
int __send_error;
unsigned char dta_test[20];
unsigned int readChAdcValue(int ch);
unsigned int adcValueR0_NH3_Buf;
unsigned int adcValueR0_CO_Buf;
unsigned int adcValueR0_NO2_Buf;
public:
uint8_t i2cAddress; //I2C address of this MCU
uint16_t res0[3]; //sensors res0
uint16_t res[3]; //sensors res
bool r0_inited;
inline unsigned int get_addr_dta(unsigned char addr_reg);
inline unsigned int get_addr_dta(unsigned char addr_reg, unsigned char __dta);
inline void write_i2c(unsigned char addr, unsigned char *dta, unsigned char dta_len);
void sendI2C(unsigned char dta);
int16_t readData(uint8_t cmd);
int16_t readR0(void);
int16_t readR(void);
float calcGas(int gas);
public:
void begin(int address);
void begin();
void changeI2cAddr(uint8_t newAddr);
void powerOn(void);
void powerOff(void);
void doCalibrate(void);
//get gas concentration, unit: ppm
float measure_CO(){return calcGas(CO);}
float measure_NO2(){return calcGas(NO2);}
float measure_NH3(){return calcGas(NH3);}
float measure_C3H8(){return calcGas(C3H8);}
float measure_C4H10(){return calcGas(C4H10);}
float measure_CH4(){return calcGas(GAS_CH4);}
float measure_H2(){return calcGas(H2);}
float measure_C2H5OH(){return calcGas(C2H5OH);}
float getR0(unsigned char ch); // 0:CH3, 1:CO, 2:NO2
float getRs(unsigned char ch); // 0:CH3, 1:CO, 2:NO2
public:
bool isError();
void ledOn();
void ledOff();
void display_eeprom();
void factory_setting();
void change_i2c_address(unsigned char addr);
unsigned char getVersion();
};
extern MutichannelGasSensor gas;
#endif
/*********************************************************************************************************
END FILE
*********************************************************************************************************/

View File

@ -1,7 +0,0 @@
This is an Arduino library for the TSL2561 digital luminosity (light) sensors.
Pick one up at http://www.adafruit.com/products/439
To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder TSL2561. Check that the TSL2561 folder contains TSL2561.cpp and TSL2561.h
Place the TSL2561 library folder your <arduinosketchfolder>/libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE.

View File

@ -1,301 +0,0 @@
/**************************************************************************/
/*!
@file tsl2561.c
@author K. Townsend (microBuilder.eu / adafruit.com)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2010, microBuilder SARL, Adafruit Industries
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 holders 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 ''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 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.
*/
/**************************************************************************/
#if defined ( ESP8266 )
#include <pgmspace.h>
#else
#include <avr/pgmspace.h>
#include <util/delay.h>
#endif
#include <stdlib.h>
#include "TSL2561.h"
TSL2561::TSL2561(uint8_t addr) {
_addr = addr;
_initialized = false;
_integration = TSL2561_INTEGRATIONTIME_13MS;
_gain = TSL2561_GAIN_16X;
// we cant do wire initialization till later, because we havent loaded Wire yet
}
boolean TSL2561::begin(void) {
Wire.begin();
// Initialise I2C
Wire.beginTransmission(_addr);
#if ARDUINO >= 100
Wire.write(TSL2561_REGISTER_ID);
#else
Wire.send(TSL2561_REGISTER_ID);
#endif
Wire.endTransmission();
Wire.requestFrom(_addr, 1);
#if ARDUINO >= 100
int x = Wire.read();
#else
int x = Wire.receive();
#endif
//Serial.print("0x"); Serial.println(x, HEX);
if (x & 0x0A ) {
//Serial.println("Found TSL2561");
} else {
return false;
}
_initialized = true;
// Set default integration time and gain
setTiming(_integration);
setGain(_gain);
// Note: by default, the device is in power down mode on bootup
disable();
return true;
}
void TSL2561::enable(void)
{
if (!_initialized) begin();
// Enable the device by setting the control bit to 0x03
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWERON);
}
void TSL2561::disable(void)
{
if (!_initialized) begin();
// Disable the device by setting the control bit to 0x03
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWEROFF);
}
void TSL2561::setGain(tsl2561Gain_t gain) {
if (!_initialized) begin();
enable();
_gain = gain;
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, _integration | _gain);
disable();
}
void TSL2561::setTiming(tsl2561IntegrationTime_t integration)
{
if (!_initialized) begin();
enable();
_integration = integration;
write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, _integration | _gain);
disable();
}
uint32_t TSL2561::calculateLux(uint16_t ch0, uint16_t ch1)
{
unsigned long chScale;
unsigned long channel1;
unsigned long channel0;
switch (_integration)
{
case TSL2561_INTEGRATIONTIME_13MS:
chScale = TSL2561_LUX_CHSCALE_TINT0;
break;
case TSL2561_INTEGRATIONTIME_101MS:
chScale = TSL2561_LUX_CHSCALE_TINT1;
break;
default: // No scaling ... integration time = 402ms
chScale = (1 << TSL2561_LUX_CHSCALE);
break;
}
// Scale for gain (1x or 16x)
if (!_gain) chScale = chScale << 4;
// scale the channel values
channel0 = (ch0 * chScale) >> TSL2561_LUX_CHSCALE;
channel1 = (ch1 * chScale) >> TSL2561_LUX_CHSCALE;
// find the ratio of the channel values (Channel1/Channel0)
unsigned long ratio1 = 0;
if (channel0 != 0) ratio1 = (channel1 << (TSL2561_LUX_RATIOSCALE+1)) / channel0;
// round the ratio value
unsigned long ratio = (ratio1 + 1) >> 1;
unsigned int b, m;
#ifdef TSL2561_PACKAGE_CS
if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1C))
{b=TSL2561_LUX_B1C; m=TSL2561_LUX_M1C;}
else if (ratio <= TSL2561_LUX_K2C)
{b=TSL2561_LUX_B2C; m=TSL2561_LUX_M2C;}
else if (ratio <= TSL2561_LUX_K3C)
{b=TSL2561_LUX_B3C; m=TSL2561_LUX_M3C;}
else if (ratio <= TSL2561_LUX_K4C)
{b=TSL2561_LUX_B4C; m=TSL2561_LUX_M4C;}
else if (ratio <= TSL2561_LUX_K5C)
{b=TSL2561_LUX_B5C; m=TSL2561_LUX_M5C;}
else if (ratio <= TSL2561_LUX_K6C)
{b=TSL2561_LUX_B6C; m=TSL2561_LUX_M6C;}
else if (ratio <= TSL2561_LUX_K7C)
{b=TSL2561_LUX_B7C; m=TSL2561_LUX_M7C;}
else if (ratio > TSL2561_LUX_K8C)
{b=TSL2561_LUX_B8C; m=TSL2561_LUX_M8C;}
#else
if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1T))
{b=TSL2561_LUX_B1T; m=TSL2561_LUX_M1T;}
else if (ratio <= TSL2561_LUX_K2T)
{b=TSL2561_LUX_B2T; m=TSL2561_LUX_M2T;}
else if (ratio <= TSL2561_LUX_K3T)
{b=TSL2561_LUX_B3T; m=TSL2561_LUX_M3T;}
else if (ratio <= TSL2561_LUX_K4T)
{b=TSL2561_LUX_B4T; m=TSL2561_LUX_M4T;}
else if (ratio <= TSL2561_LUX_K5T)
{b=TSL2561_LUX_B5T; m=TSL2561_LUX_M5T;}
else if (ratio <= TSL2561_LUX_K6T)
{b=TSL2561_LUX_B6T; m=TSL2561_LUX_M6T;}
else if (ratio <= TSL2561_LUX_K7T)
{b=TSL2561_LUX_B7T; m=TSL2561_LUX_M7T;}
else if (ratio > TSL2561_LUX_K8T)
{b=TSL2561_LUX_B8T; m=TSL2561_LUX_M8T;}
#endif
unsigned long temp;
temp = ((channel0 * b) - (channel1 * m));
// do not allow negative lux value
if (temp < 0) temp = 0;
// round lsb (2^(LUX_SCALE-1))
temp += (1 << (TSL2561_LUX_LUXSCALE-1));
// strip off fractional portion
uint32_t lux = temp >> TSL2561_LUX_LUXSCALE;
// Signal I2C had no errors
return lux;
}
uint32_t TSL2561::getFullLuminosity (void)
{
if (!_initialized) begin();
// Enable the device by setting the control bit to 0x03
enable();
// Wait x ms for ADC to complete
switch (_integration)
{
case TSL2561_INTEGRATIONTIME_13MS:
delay(14);
break;
case TSL2561_INTEGRATIONTIME_101MS:
delay(102);
break;
default:
delay(403);
break;
}
uint32_t x;
x = read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN1_LOW);
x <<= 16;
x |= read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN0_LOW);
disable();
return x;
}
uint16_t TSL2561::getLuminosity (uint8_t channel) {
uint32_t x = getFullLuminosity();
if (channel == 0) {
// Reads two byte value from channel 0 (visible + infrared)
return (x & 0xFFFF);
} else if (channel == 1) {
// Reads two byte value from channel 1 (infrared)
return (x >> 16);
} else if (channel == 2) {
// Reads all and subtracts out just the visible!
return ( (x & 0xFFFF) - (x >> 16));
}
// unknown channel!
return 0;
}
uint16_t TSL2561::read16(uint8_t reg)
{
uint16_t x; uint16_t t;
Wire.beginTransmission(_addr);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.requestFrom(_addr, 2);
#if ARDUINO >= 100
t = Wire.read();
x = Wire.read();
#else
t = Wire.receive();
x = Wire.receive();
#endif
x <<= 8;
x |= t;
return x;
}
void TSL2561::write8 (uint8_t reg, uint8_t value)
{
Wire.beginTransmission(_addr);
#if ARDUINO >= 100
Wire.write(reg);
Wire.write(value);
#else
Wire.send(reg);
Wire.send(value);
#endif
Wire.endTransmission();
}

View File

@ -1,184 +0,0 @@
/**************************************************************************/
/*!
@file tsl2561.h
@author K. Townsend (microBuilder.eu)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2010, microBuilder SARL
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 holders 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 ''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 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 _TSL2561_H_
#define _TSL2561_H_
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include <Wire.h>
#define TSL2561_VISIBLE 2 // channel 0 - channel 1
#define TSL2561_INFRARED 1 // channel 1
#define TSL2561_FULLSPECTRUM 0 // channel 0
// 3 i2c address options!
#define TSL2561_ADDR_LOW 0x29
#define TSL2561_ADDR_FLOAT 0x39
#define TSL2561_ADDR_HIGH 0x49
// Lux calculations differ slightly for CS package
//#define TSL2561_PACKAGE_CS
#define TSL2561_PACKAGE_T_FN_CL
#define TSL2561_READBIT (0x01)
#define TSL2561_COMMAND_BIT (0x80) // Must be 1
#define TSL2561_CLEAR_BIT (0x40) // Clears any pending interrupt (write 1 to clear)
#define TSL2561_WORD_BIT (0x20) // 1 = read/write word (rather than byte)
#define TSL2561_BLOCK_BIT (0x10) // 1 = using block read/write
#define TSL2561_CONTROL_POWERON (0x03)
#define TSL2561_CONTROL_POWEROFF (0x00)
#define TSL2561_LUX_LUXSCALE (14) // Scale by 2^14
#define TSL2561_LUX_RATIOSCALE (9) // Scale ratio by 2^9
#define TSL2561_LUX_CHSCALE (10) // Scale channel values by 2^10
#define TSL2561_LUX_CHSCALE_TINT0 (0x7517) // 322/11 * 2^TSL2561_LUX_CHSCALE
#define TSL2561_LUX_CHSCALE_TINT1 (0x0FE7) // 322/81 * 2^TSL2561_LUX_CHSCALE
// T, FN and CL package values
#define TSL2561_LUX_K1T (0x0040) // 0.125 * 2^RATIO_SCALE
#define TSL2561_LUX_B1T (0x01f2) // 0.0304 * 2^LUX_SCALE
#define TSL2561_LUX_M1T (0x01be) // 0.0272 * 2^LUX_SCALE
#define TSL2561_LUX_K2T (0x0080) // 0.250 * 2^RATIO_SCALE
#define TSL2561_LUX_B2T (0x0214) // 0.0325 * 2^LUX_SCALE
#define TSL2561_LUX_M2T (0x02d1) // 0.0440 * 2^LUX_SCALE
#define TSL2561_LUX_K3T (0x00c0) // 0.375 * 2^RATIO_SCALE
#define TSL2561_LUX_B3T (0x023f) // 0.0351 * 2^LUX_SCALE
#define TSL2561_LUX_M3T (0x037b) // 0.0544 * 2^LUX_SCALE
#define TSL2561_LUX_K4T (0x0100) // 0.50 * 2^RATIO_SCALE
#define TSL2561_LUX_B4T (0x0270) // 0.0381 * 2^LUX_SCALE
#define TSL2561_LUX_M4T (0x03fe) // 0.0624 * 2^LUX_SCALE
#define TSL2561_LUX_K5T (0x0138) // 0.61 * 2^RATIO_SCALE
#define TSL2561_LUX_B5T (0x016f) // 0.0224 * 2^LUX_SCALE
#define TSL2561_LUX_M5T (0x01fc) // 0.0310 * 2^LUX_SCALE
#define TSL2561_LUX_K6T (0x019a) // 0.80 * 2^RATIO_SCALE
#define TSL2561_LUX_B6T (0x00d2) // 0.0128 * 2^LUX_SCALE
#define TSL2561_LUX_M6T (0x00fb) // 0.0153 * 2^LUX_SCALE
#define TSL2561_LUX_K7T (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B7T (0x0018) // 0.00146 * 2^LUX_SCALE
#define TSL2561_LUX_M7T (0x0012) // 0.00112 * 2^LUX_SCALE
#define TSL2561_LUX_K8T (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B8T (0x0000) // 0.000 * 2^LUX_SCALE
#define TSL2561_LUX_M8T (0x0000) // 0.000 * 2^LUX_SCALE
// CS package values
#define TSL2561_LUX_K1C (0x0043) // 0.130 * 2^RATIO_SCALE
#define TSL2561_LUX_B1C (0x0204) // 0.0315 * 2^LUX_SCALE
#define TSL2561_LUX_M1C (0x01ad) // 0.0262 * 2^LUX_SCALE
#define TSL2561_LUX_K2C (0x0085) // 0.260 * 2^RATIO_SCALE
#define TSL2561_LUX_B2C (0x0228) // 0.0337 * 2^LUX_SCALE
#define TSL2561_LUX_M2C (0x02c1) // 0.0430 * 2^LUX_SCALE
#define TSL2561_LUX_K3C (0x00c8) // 0.390 * 2^RATIO_SCALE
#define TSL2561_LUX_B3C (0x0253) // 0.0363 * 2^LUX_SCALE
#define TSL2561_LUX_M3C (0x0363) // 0.0529 * 2^LUX_SCALE
#define TSL2561_LUX_K4C (0x010a) // 0.520 * 2^RATIO_SCALE
#define TSL2561_LUX_B4C (0x0282) // 0.0392 * 2^LUX_SCALE
#define TSL2561_LUX_M4C (0x03df) // 0.0605 * 2^LUX_SCALE
#define TSL2561_LUX_K5C (0x014d) // 0.65 * 2^RATIO_SCALE
#define TSL2561_LUX_B5C (0x0177) // 0.0229 * 2^LUX_SCALE
#define TSL2561_LUX_M5C (0x01dd) // 0.0291 * 2^LUX_SCALE
#define TSL2561_LUX_K6C (0x019a) // 0.80 * 2^RATIO_SCALE
#define TSL2561_LUX_B6C (0x0101) // 0.0157 * 2^LUX_SCALE
#define TSL2561_LUX_M6C (0x0127) // 0.0180 * 2^LUX_SCALE
#define TSL2561_LUX_K7C (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B7C (0x0037) // 0.00338 * 2^LUX_SCALE
#define TSL2561_LUX_M7C (0x002b) // 0.00260 * 2^LUX_SCALE
#define TSL2561_LUX_K8C (0x029a) // 1.3 * 2^RATIO_SCALE
#define TSL2561_LUX_B8C (0x0000) // 0.000 * 2^LUX_SCALE
#define TSL2561_LUX_M8C (0x0000) // 0.000 * 2^LUX_SCALE
enum
{
TSL2561_REGISTER_CONTROL = 0x00,
TSL2561_REGISTER_TIMING = 0x01,
TSL2561_REGISTER_THRESHHOLDL_LOW = 0x02,
TSL2561_REGISTER_THRESHHOLDL_HIGH = 0x03,
TSL2561_REGISTER_THRESHHOLDH_LOW = 0x04,
TSL2561_REGISTER_THRESHHOLDH_HIGH = 0x05,
TSL2561_REGISTER_INTERRUPT = 0x06,
TSL2561_REGISTER_CRC = 0x08,
TSL2561_REGISTER_ID = 0x0A,
TSL2561_REGISTER_CHAN0_LOW = 0x0C,
TSL2561_REGISTER_CHAN0_HIGH = 0x0D,
TSL2561_REGISTER_CHAN1_LOW = 0x0E,
TSL2561_REGISTER_CHAN1_HIGH = 0x0F
};
typedef enum
{
TSL2561_INTEGRATIONTIME_13MS = 0x00, // 13.7ms
TSL2561_INTEGRATIONTIME_101MS = 0x01, // 101ms
TSL2561_INTEGRATIONTIME_402MS = 0x02 // 402ms
}
tsl2561IntegrationTime_t;
typedef enum
{
TSL2561_GAIN_0X = 0x00, // No gain
TSL2561_GAIN_16X = 0x10, // 16x gain
}
tsl2561Gain_t;
class TSL2561 {
public:
TSL2561(uint8_t addr);
boolean begin(void);
void enable(void);
void disable(void);
void write8(uint8_t r, uint8_t v);
uint16_t read16(uint8_t reg);
uint32_t calculateLux(uint16_t ch0, uint16_t ch1);
void setTiming(tsl2561IntegrationTime_t integration);
void setGain(tsl2561Gain_t gain);
uint16_t getLuminosity (uint8_t channel);
uint32_t getFullLuminosity ();
private:
int8_t _addr;
tsl2561IntegrationTime_t _integration;
tsl2561Gain_t _gain;
boolean _initialized;
};
#endif

View File

@ -1,63 +0,0 @@
#include <Wire.h>
#include "TSL2561.h"
// Example for demonstrating the TSL2561 library - public domain!
// connect SCL to analog 5
// connect SDA to analog 4
// connect VDD to 3.3V DC
// connect GROUND to common ground
// ADDR can be connected to ground, or vdd or left floating to change the i2c address
// The address will be different depending on whether you let
// the ADDR pin float (addr 0x39), or tie it to ground or vcc. In those cases
// use TSL2561_ADDR_LOW (0x29) or TSL2561_ADDR_HIGH (0x49) respectively
TSL2561 tsl(TSL2561_ADDR_FLOAT);
void setup(void) {
Serial.begin(9600);
if (tsl.begin()) {
Serial.println("Found sensor");
} else {
Serial.println("No sensor?");
while (1);
}
// You can change the gain on the fly, to adapt to brighter/dimmer light situations
//tsl.setGain(TSL2561_GAIN_0X); // set no gain (for bright situtations)
tsl.setGain(TSL2561_GAIN_16X); // set 16x gain (for dim situations)
// Changing the integration time gives you a longer time over which to sense light
// longer timelines are slower, but are good in very low light situtations!
tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS); // shortest integration time (bright light)
//tsl.setTiming(TSL2561_INTEGRATIONTIME_101MS); // medium integration time (medium light)
//tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS); // longest integration time (dim light)
// Now we're ready to get readings!
}
void loop(void) {
// Simple data read example. Just read the infrared, fullspecrtrum diode
// or 'visible' (difference between the two) channels.
// This can take 13-402 milliseconds! Uncomment whichever of the following you want to read
uint16_t x = tsl.getLuminosity(TSL2561_VISIBLE);
//uint16_t x = tsl.getLuminosity(TSL2561_FULLSPECTRUM);
//uint16_t x = tsl.getLuminosity(TSL2561_INFRARED);
Serial.println(x, DEC);
// More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
// That way you can do whatever math and comparisons you want!
uint32_t lum = tsl.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
Serial.print("IR: "); Serial.print(ir); Serial.print("\t\t");
Serial.print("Full: "); Serial.print(full); Serial.print("\t");
Serial.print("Visible: "); Serial.print(full - ir); Serial.print("\t");
Serial.print("Lux: "); Serial.println(tsl.calculateLux(full, ir));
delay(100);
}

View File

@ -1,9 +0,0 @@
name=TSL2561 Arduino Library
version=1.0.0
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for using the TSL2561 Luminosity sensor
paragraph=Arduino library for using the TSL2561 Luminosity sensor
category=Sensors
url=https://github.com/adafruit/TSL2561-Arduino-Library
architectures=*

28
lib/TasmotaMqtt-1.1.1/.gitignore vendored Normal file
View File

@ -0,0 +1,28 @@
# C++ objects and libs
*.slo
*.lo
*.o
#*.a
*.la
*.lai
*.so
*.dll
*.dylib
#Makefile
*-build-*
build-*
*.autosave
# .log files (usually created by QtTest - thanks to VestniK)
*.log
# Editors temporary files
*~
#OSX
.DS_Store
._*

View File

@ -0,0 +1,8 @@
MQTT
====
A Wrapper around mqtt for Arduino to be used with esp8266 modules.
It wraps a slightly modified version of mqtt for esp8266 ported by Tuan PM.
Original code for esp: https://github.com/tuanpmt/esp_mqtt
Original code for contiki: https://github.com/esar/contiki-mqtt

View File

@ -0,0 +1,102 @@
#include <ESP8266WiFi.h>
#include <MQTT.h>
void myDataCb(String& topic, String& data);
void myPublishedCb();
void myDisconnectedCb();
void myConnectedCb();
#define CLIENT_ID "client1"
// create MQTT object
MQTT myMqtt(CLIENT_ID, "192.168.0.1", 1883);
//
const char* ssid = "ssid";
const char* password = "ssid_password";
//
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Connecting to MQTT server");
// setup callbacks
myMqtt.onConnected(myConnectedCb);
myMqtt.onDisconnected(myDisconnectedCb);
myMqtt.onPublished(myPublishedCb);
myMqtt.onData(myDataCb);
Serial.println("connect mqtt...");
myMqtt.connect();
delay(10);
}
//
void loop() {
int value = analogRead(A0);
String topic("/");
topic += CLIENT_ID;
topic += "/value";
String valueStr(value);
// publish value to topic
boolean result = myMqtt.publish(topic, valueStr);
delay(1000);
}
/*
*
*/
void myConnectedCb()
{
Serial.println("connected to MQTT server");
}
void myDisconnectedCb()
{
Serial.println("disconnected. try to reconnect...");
delay(500);
myMqtt.connect();
}
void myPublishedCb()
{
//Serial.println("published.");
}
void myDataCb(String& topic, String& data)
{
Serial.print(topic);
Serial.print(": ");
Serial.println(data);
}

View File

@ -0,0 +1,97 @@
#include <ESP8266WiFi.h>
#include <TasmotaMqtt.h>
// This needs testing
void myDataCb(char* topic, uint8_t* data, unsigned int data_len);
void myPublishedCb();
void myDisconnectedCb();
void myConnectedCb();
#define CLIENT_ID "client3"
#define TOPIC "/client1/value"
// create MQTT
TasmotaMqtt myMqtt();
const char* ssid = "ssid";
const char* password = "ssid_password";
//
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Connecting to MQTT server");
myMqtt.InitConnection("192.168.0.1", 1883);
myMqtt.InitClient(CLIENT_ID, "", "");
myMqtt.InitLWT("/lwt", "offline");
// setup callbacks
myMqtt.OnConnected(myConnectedCb);
myMqtt.OnDisconnected(myDisconnectedCb);
myMqtt.OnPublished(myPublishedCb);
myMqtt.OnData(myDataCb);
Serial.println("connect mqtt...");
myMqtt.Connect();
Serial.println("subscribe to topic...");
myMqtt.Subscribe(TOPIC);
delay(10);
}
//
void loop() {
}
/*
*
*/
void myConnectedCb()
{
Serial.println("connected to MQTT server");
}
void myDisconnectedCb()
{
Serial.println("disconnected. try to reconnect...");
delay(500);
myMqtt.Connect();
}
void myPublishedCb()
{
//Serial.println("published.");
}
void myDataCb(char* topic, uint8_t* data, unsigned int data_len)
{
Serial.print(topic);
Serial.print(": ");
Serial.println(data);
}

View File

@ -0,0 +1,39 @@
#######################################
# Syntax Coloring Map For Test
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
TasmotaMqtt.h KEYWORD1
TasmotaMqtt KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
InitConnection KEYWORD2
InitClient KEYWORD2
InitLWT KEYWORD2
Connect KEYWORD2
Disconnect KEYWORD2
Connected KEYWORD2
Publish KEYWORD2
Subscribe KEYWORD2
#general
OnConnected KEYWORD2
OnDisconnected KEYWORD2
OnData KEYWORD2
#######################################
# Instances (KEYWORD2)
#######################################
#######################################
# Constants (LITERAL1)
#######################################

View File

@ -0,0 +1,9 @@
name=TasmotaMqtt
version=1.0.0
author=Theo Arends
maintainer=Theo Arends <theo@arends.com>
sentence=A Wrapper around mqtt for Arduino to be used with esp8266 modules.
paragraph=It wraps a slightly modified version of mqtt for esp8266 ported by Tuan PM. Original code for esp: https://github.com/tuanpmt/esp_mqtt Original code for contiki: https://github.com/esar/contiki-mqtt
category=Communication
url=
architectures=esp8266

View File

@ -0,0 +1,194 @@
/*
TasmotaMqtt.cpp - Wrapper for mqtt for esp8266 by Tuan PM for Tasmota
Copyright (C) 2018 Theo Arends and Ingo Randolf
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 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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TasmotaMqtt.h"
#include "user_interface.h"
#include "osapi.h"
#include "os_type.h"
/*********************************************************************************************\
* Prerequisite
*
* Copy .c and .h files from https://github.com/tuanpmt/esp_mqtt folder mqtt to folder mqtt
* - Replace BOOL with bool
* - Remove variables certificate and private_key from file mqtt.c
* - Add file user_config.h with default defines for
* MQTT_BUF_SIZE 256, MQTT_RECONNECT_TIMEOUT 5, QUEUE_BUFFER_SIZE 2048 and PROTOCOL_NAMEv311
\*********************************************************************************************/
/*********************************************************************************************\
* Mqtt internal callbacks
\*********************************************************************************************/
static void mqttConnectedCb(uint32_t *args)
{
MQTT_Client* client = (MQTT_Client*)args;
TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data;
if (_this && _this->onMqttConnectedCb) _this->onMqttConnectedCb();
}
static void mqttDisconnectedCb(uint32_t *args)
{
MQTT_Client* client = (MQTT_Client*)args;
TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data;
if (_this && _this->onMqttDisconnectedCb) _this->onMqttDisconnectedCb();
}
static void mqttPublishedCb(uint32_t *args)
{
MQTT_Client* client = (MQTT_Client*)args;
TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data;
if (_this && _this->onMqttPublishedCb) _this->onMqttPublishedCb();
}
static void mqttTimeoutCb(uint32_t *args)
{
MQTT_Client* client = (MQTT_Client*)args;
TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data;
if (_this && _this->onMqttTimeoutCb) _this->onMqttTimeoutCb();
}
static void mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len)
{
MQTT_Client* client = (MQTT_Client*)args;
TasmotaMqtt* _this = (TasmotaMqtt*)client->user_data;
if (_this) _this->_onMqttDataCb(topic, topic_len, data, data_len);
}
/*********************************************************************************************\
* TasmotaMqtt class implementation
\*********************************************************************************************/
TasmotaMqtt::TasmotaMqtt() :
onMqttConnectedCb(0),
onMqttDisconnectedCb(0),
onMqttPublishedCb(0),
onMqttTimeoutCb(0),
onMqttDataCb(0)
{
}
TasmotaMqtt::~TasmotaMqtt()
{
MQTT_DeleteClient(&mqttClient);
}
void TasmotaMqtt::InitConnection(const char* host, uint32_t port, uint8_t security)
{
MQTT_InitConnection(&mqttClient, (uint8_t*)host, port, security);
// set user data
mqttClient.user_data = (void*)this;
MQTT_OnConnected(&mqttClient, mqttConnectedCb);
MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb);
MQTT_OnPublished(&mqttClient, mqttPublishedCb);
MQTT_OnTimeout(&mqttClient, mqttTimeoutCb);
MQTT_OnData(&mqttClient, mqttDataCb);
}
void TasmotaMqtt::InitClient(const char* client_id, const char* client_user, const char* client_pass, uint32_t keep_alive_time, uint8_t clean_session)
{
MQTT_InitClient(&mqttClient, (uint8_t*)client_id, (uint8_t*)client_user, (uint8_t*)client_pass, keep_alive_time, clean_session);
}
void TasmotaMqtt::DeleteClient()
{
MQTT_DeleteClient(&mqttClient);
}
void TasmotaMqtt::InitLWT(const char* will_topic, const char* will_msg, uint8_t will_qos, bool will_retain)
{
MQTT_InitLWT(&mqttClient, (uint8_t*)will_topic, (uint8_t*)will_msg, will_qos, (uint8_t)will_retain);
}
void TasmotaMqtt::OnConnected( void (*function)(void) )
{
onMqttConnectedCb = function;
}
void TasmotaMqtt::OnDisconnected( void (*function)(void) )
{
onMqttDisconnectedCb = function;
}
void TasmotaMqtt::OnPublished( void (*function)(void) )
{
onMqttPublishedCb = function;
}
void TasmotaMqtt::OnTimeout( void (*function)(void) )
{
onMqttTimeoutCb = function;
}
void TasmotaMqtt::OnData( void (*function)(char*, uint8_t*, unsigned int) )
{
onMqttDataCb = function;
}
bool TasmotaMqtt::Subscribe(const char* topic, uint8_t qos)
{
return MQTT_Subscribe(&mqttClient, (char*)topic, qos);
}
bool TasmotaMqtt::Unsubscribe(const char* topic)
{
return MQTT_UnSubscribe(&mqttClient, (char*)topic);
}
void TasmotaMqtt::Connect()
{
MQTT_Connect(&mqttClient);
}
void TasmotaMqtt::Connect(const char* client_id, const char* client_user, const char* client_pass, const char* will_topic, const char* will_msg, uint8_t will_qos, bool will_retain)
{
MQTT_InitClient(&mqttClient, (uint8_t*)client_id, (uint8_t*)client_user, (uint8_t*)client_pass, MQTT_KEEPALIVE, 1);
MQTT_InitLWT(&mqttClient, (uint8_t*)will_topic, (uint8_t*)will_msg, will_qos, (uint8_t)will_retain);
MQTT_Connect(&mqttClient);
}
void TasmotaMqtt::Disconnect()
{
MQTT_Disconnect(&mqttClient);
}
bool TasmotaMqtt::Publish(const char* topic, const char* data, int data_length, int qos, bool retain)
{
return MQTT_Publish(&mqttClient, topic, data, data_length, qos, (int)retain);
}
bool TasmotaMqtt::Connected()
{
return (mqttClient.connState > TCP_CONNECTED);
}
/*********************************************************************************************/
void TasmotaMqtt::_onMqttDataCb(const char* topic, uint32_t topic_len, const char* data, uint32_t data_len)
{
char topic_copy[topic_len +1];
memcpy(topic_copy, topic, topic_len);
topic_copy[topic_len] = 0;
if (0 == data_len) data = (const char*)&topic_copy + topic_len;
onMqttDataCb((char*)topic_copy, (byte*)data, data_len);
}

View File

@ -0,0 +1,88 @@
/*
TasmotaMqtt.h - Wrapper for mqtt for esp8266 by Tuan PM for Tasmota
Copyright (C) 2018 Theo Arends and Ingo Randolf
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 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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TasmotaMqtt_h
#define TasmotaMqtt_h
/*********************************************************************************************\
* TasmotaMqtt supports currently only non-TLS MQTT
*
* Adapted from esp-mqtt-arduino by Ingo Randolf (https://github.com/i-n-g-o/esp-mqtt-arduino)
\*********************************************************************************************/
#include <Arduino.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
extern "C" {
#include <stddef.h>
#include "mqtt/mqtt.h"
}
// MQTT_KEEPALIVE : keepAlive interval in Seconds
#ifndef MQTT_KEEPALIVE
#define MQTT_KEEPALIVE 15
#endif
class TasmotaMqtt {
public:
TasmotaMqtt();
~TasmotaMqtt();
void InitConnection(const char* host, uint32_t port, uint8_t security = 0);
void InitClient(const char* client_id, const char* client_user, const char* client_pass, uint32_t keep_alive_time = MQTT_KEEPALIVE, uint8_t clean_session = 1);
void DeleteClient();
void InitLWT(const char* will_topic, const char* will_msg, uint8_t will_qos = 0, bool will_retain = false);
void OnConnected( void (*)(void) );
void OnDisconnected( void (*)(void) );
void OnPublished( void (*)(void) );
void OnTimeout( void (*)(void) );
void OnData( void (*)(char*, uint8_t*, unsigned int) );
bool Subscribe(const char* topic, uint8_t qos = 0);
bool Unsubscribe(const char* topic);
void Connect();
void Connect(const char* client_id, const char* client_user, const char* client_pass, const char* will_topic, const char* will_msg, uint8_t will_qos = 0, bool will_retain = false);
void Disconnect();
bool Publish(const char* topic, const char* data, int data_length, int qos = 0, bool retain = false);
bool Connected();
int State() { return mqttClient.connState; };
void (*onMqttConnectedCb)(void);
void (*onMqttDisconnectedCb)(void);
void (*onMqttPublishedCb)(void);
void (*onMqttTimeoutCb)(void);
void (*onMqttDataCb) (char*, uint8_t*, unsigned int);
// internal callback
void _onMqttDataCb(const char*, uint32_t, const char*, uint32_t);
private:
MQTT_Client mqttClient;
};
#endif // TasmotaMqtt_h

View File

@ -0,0 +1,19 @@
/*
* debug.h
*
* Created on: Dec 4, 2014
* Author: Minh
*/
#ifndef USER_DEBUG_H_
#define USER_DEBUG_H_
#if defined(MQTT_DEBUG_ON)
#define MQTT_INFO( format, ... ) os_printf( format, ## __VA_ARGS__ )
#else
#define MQTT_INFO( format, ... )
#endif
#endif /* USER_DEBUG_H_ */

View File

@ -0,0 +1,997 @@
/* mqtt.c
* Protocol: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
*
* Copyright (c) 2014-2015, Tuan PM <tuanpm at live dot 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:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Redis 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 OWNER 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.
*/
#include "user_interface.h"
#include "osapi.h"
#include "espconn.h"
#include "os_type.h"
#include "mem.h"
#include "mqtt_msg.h"
#include "debug.h"
#include "user_config.h"
#include "mqtt.h"
#include "queue.h"
#define MQTT_TASK_PRIO 2
#define MQTT_TASK_QUEUE_SIZE 1
#define MQTT_SEND_TIMOUT 5
#ifndef MQTT_SSL_SIZE
#define MQTT_SSL_SIZE 5120
#endif
#ifndef QUEUE_BUFFER_SIZE
#define QUEUE_BUFFER_SIZE 2048
#endif
/*
unsigned char *default_certificate;
unsigned int default_certificate_len = 0;
unsigned char *default_private_key;
unsigned int default_private_key_len = 0;
*/
os_event_t mqtt_procTaskQueue[MQTT_TASK_QUEUE_SIZE];
#ifdef PROTOCOL_NAMEv311
LOCAL uint8_t zero_len_id[2] = { 0, 0 };
#endif
LOCAL void ICACHE_FLASH_ATTR
mqtt_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
{
struct espconn *pConn = (struct espconn *)arg;
MQTT_Client* client = (MQTT_Client *)pConn->reverse;
if (ipaddr == NULL)
{
MQTT_INFO("DNS: Found, but got no ip, try to reconnect\r\n");
client->connState = TCP_RECONNECT_REQ;
return;
}
MQTT_INFO("DNS: found ip %d.%d.%d.%d\n",
*((uint8 *) &ipaddr->addr),
*((uint8 *) &ipaddr->addr + 1),
*((uint8 *) &ipaddr->addr + 2),
*((uint8 *) &ipaddr->addr + 3));
if (client->ip.addr == 0 && ipaddr->addr != 0)
{
os_memcpy(client->pCon->proto.tcp->remote_ip, &ipaddr->addr, 4);
if (client->security) {
#ifdef MQTT_SSL_ENABLE
espconn_secure_set_size(ESPCONN_CLIENT, MQTT_SSL_SIZE);
espconn_secure_connect(client->pCon);
#else
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
espconn_connect(client->pCon);
}
client->connState = TCP_CONNECTING;
MQTT_INFO("TCP: connecting...\r\n");
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
LOCAL void ICACHE_FLASH_ATTR
deliver_publish(MQTT_Client* client, uint8_t* message, int length)
{
mqtt_event_data_t event_data;
event_data.topic_length = length;
event_data.topic = mqtt_get_publish_topic(message, &event_data.topic_length);
event_data.data_length = length;
event_data.data = mqtt_get_publish_data(message, &event_data.data_length);
if (client->dataCb)
client->dataCb((uint32_t*)client, event_data.topic, event_data.topic_length, event_data.data, event_data.data_length);
}
void ICACHE_FLASH_ATTR
mqtt_send_keepalive(MQTT_Client *client)
{
MQTT_INFO("\r\nMQTT: Send keepalive packet to %s:%d!\r\n", client->host, client->port);
client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection);
client->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_PINGREQ;
client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data);
client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length);
client->sendTimeout = MQTT_SEND_TIMOUT;
MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id);
err_t result = ESPCONN_OK;
if (client->security) {
#ifdef MQTT_SSL_ENABLE
result = espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length);
#else
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
result = espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length);
}
client->mqtt_state.outbound_message = NULL;
if (ESPCONN_OK == result) {
client->keepAliveTick = 0;
client->connState = MQTT_DATA;
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
else {
client->connState = TCP_RECONNECT_DISCONNECTING;
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
}
/**
* @brief Delete tcp client and free all memory
* @param mqttClient: The mqtt client which contain TCP client
* @retval None
*/
void ICACHE_FLASH_ATTR
mqtt_tcpclient_delete(MQTT_Client *mqttClient)
{
if (mqttClient->pCon != NULL) {
MQTT_INFO("TCP: Free memory\r\n");
// Force abort connections
espconn_abort(mqttClient->pCon);
// Delete connections
espconn_delete(mqttClient->pCon);
if (mqttClient->pCon->proto.tcp) {
os_free(mqttClient->pCon->proto.tcp);
mqttClient->pCon->proto.tcp = NULL;
}
os_free(mqttClient->pCon);
mqttClient->pCon = NULL;
}
}
/**
* @brief Delete MQTT client and free all memory
* @param mqttClient: The mqtt client
* @retval None
*/
void ICACHE_FLASH_ATTR
mqtt_client_delete(MQTT_Client *mqttClient)
{
if (mqttClient == NULL)
return;
if (mqttClient->pCon != NULL) {
mqtt_tcpclient_delete(mqttClient);
}
if (mqttClient->host != NULL) {
os_free(mqttClient->host);
mqttClient->host = NULL;
}
if (mqttClient->user_data != NULL) {
os_free(mqttClient->user_data);
mqttClient->user_data = NULL;
}
if (mqttClient->mqtt_state.in_buffer != NULL) {
os_free(mqttClient->mqtt_state.in_buffer);
mqttClient->mqtt_state.in_buffer = NULL;
}
if (mqttClient->mqtt_state.out_buffer != NULL) {
os_free(mqttClient->mqtt_state.out_buffer);
mqttClient->mqtt_state.out_buffer = NULL;
}
if (mqttClient->mqtt_state.outbound_message != NULL) {
if (mqttClient->mqtt_state.outbound_message->data != NULL)
{
os_free(mqttClient->mqtt_state.outbound_message->data);
mqttClient->mqtt_state.outbound_message->data = NULL;
}
}
if (mqttClient->mqtt_state.mqtt_connection.buffer != NULL) {
// Already freed but not NULL
mqttClient->mqtt_state.mqtt_connection.buffer = NULL;
}
if (mqttClient->connect_info.client_id != NULL) {
#ifdef PROTOCOL_NAMEv311
/* Don't attempt to free if it's the zero_len array */
if ( ((uint8_t*)mqttClient->connect_info.client_id) != zero_len_id )
os_free(mqttClient->connect_info.client_id);
#else
os_free(mqttClient->connect_info.client_id);
#endif
mqttClient->connect_info.client_id = NULL;
}
if (mqttClient->connect_info.username != NULL) {
os_free(mqttClient->connect_info.username);
mqttClient->connect_info.username = NULL;
}
if (mqttClient->connect_info.password != NULL) {
os_free(mqttClient->connect_info.password);
mqttClient->connect_info.password = NULL;
}
if (mqttClient->connect_info.will_topic != NULL) {
os_free(mqttClient->connect_info.will_topic);
mqttClient->connect_info.will_topic = NULL;
}
if (mqttClient->connect_info.will_message != NULL) {
os_free(mqttClient->connect_info.will_message);
mqttClient->connect_info.will_message = NULL;
}
if (mqttClient->msgQueue.buf != NULL) {
os_free(mqttClient->msgQueue.buf);
mqttClient->msgQueue.buf = NULL;
}
// Initialize state
mqttClient->connState = WIFI_INIT;
// Clear callback functions to avoid abnormal callback
mqttClient->connectedCb = NULL;
mqttClient->disconnectedCb = NULL;
mqttClient->publishedCb = NULL;
mqttClient->timeoutCb = NULL;
mqttClient->dataCb = NULL;
MQTT_INFO("MQTT: client already deleted\r\n");
}
/**
* @brief Client received callback function.
* @param arg: contain the ip link information
* @param pdata: received data
* @param len: the lenght of received data
* @retval None
*/
void ICACHE_FLASH_ATTR
mqtt_tcpclient_recv(void *arg, char *pdata, unsigned short len)
{
uint8_t msg_type;
uint8_t msg_qos;
uint16_t msg_id;
uint8_t msg_conn_ret;
struct espconn *pCon = (struct espconn*)arg;
MQTT_Client *client = (MQTT_Client *)pCon->reverse;
READPACKET:
MQTT_INFO("TCP: data received %d bytes\r\n", len);
// MQTT_INFO("STATE: %d\r\n", client->connState);
if (len < MQTT_BUF_SIZE && len > 0) {
os_memcpy(client->mqtt_state.in_buffer, pdata, len);
msg_type = mqtt_get_type(client->mqtt_state.in_buffer);
msg_qos = mqtt_get_qos(client->mqtt_state.in_buffer);
msg_id = mqtt_get_id(client->mqtt_state.in_buffer, client->mqtt_state.in_buffer_length);
switch (client->connState) {
case MQTT_CONNECT_SENDING:
if (msg_type == MQTT_MSG_TYPE_CONNACK) {
if (client->mqtt_state.pending_msg_type != MQTT_MSG_TYPE_CONNECT) {
MQTT_INFO("MQTT: Invalid packet\r\n");
if (client->security) {
#ifdef MQTT_SSL_ENABLE
espconn_secure_disconnect(client->pCon);
#else
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
espconn_disconnect(client->pCon);
}
} else {
msg_conn_ret = mqtt_get_connect_return_code(client->mqtt_state.in_buffer);
switch (msg_conn_ret) {
case CONNECTION_ACCEPTED:
MQTT_INFO("MQTT: Connected to %s:%d\r\n", client->host, client->port);
client->connState = MQTT_DATA;
if (client->connectedCb)
client->connectedCb((uint32_t*)client);
break;
case CONNECTION_REFUSE_PROTOCOL:
case CONNECTION_REFUSE_SERVER_UNAVAILABLE:
case CONNECTION_REFUSE_BAD_USERNAME:
case CONNECTION_REFUSE_NOT_AUTHORIZED:
MQTT_INFO("MQTT: Connection refuse, reason code: %d\r\n", msg_conn_ret);
default:
if (client->security) {
#ifdef MQTT_SSL_ENABLE
espconn_secure_disconnect(client->pCon);
#else
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
espconn_disconnect(client->pCon);
}
}
}
}
break;
case MQTT_DATA:
case MQTT_KEEPALIVE_SEND:
client->mqtt_state.message_length_read = len;
client->mqtt_state.message_length = mqtt_get_total_length(client->mqtt_state.in_buffer, client->mqtt_state.message_length_read);
switch (msg_type)
{
case MQTT_MSG_TYPE_SUBACK:
if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_SUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id)
MQTT_INFO("MQTT: Subscribe successful\r\n");
break;
case MQTT_MSG_TYPE_UNSUBACK:
if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id)
MQTT_INFO("MQTT: UnSubscribe successful\r\n");
break;
case MQTT_MSG_TYPE_PUBLISH:
if (msg_qos == 1)
client->mqtt_state.outbound_message = mqtt_msg_puback(&client->mqtt_state.mqtt_connection, msg_id);
else if (msg_qos == 2)
client->mqtt_state.outbound_message = mqtt_msg_pubrec(&client->mqtt_state.mqtt_connection, msg_id);
if (msg_qos == 1 || msg_qos == 2) {
MQTT_INFO("MQTT: Queue response QoS: %d\r\n", msg_qos);
if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) {
MQTT_INFO("MQTT: Queue full\r\n");
}
}
deliver_publish(client, client->mqtt_state.in_buffer, client->mqtt_state.message_length_read);
break;
case MQTT_MSG_TYPE_PUBACK:
if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) {
MQTT_INFO("MQTT: received MQTT_MSG_TYPE_PUBACK, finish QoS1 publish\r\n");
}
break;
case MQTT_MSG_TYPE_PUBREC:
client->mqtt_state.outbound_message = mqtt_msg_pubrel(&client->mqtt_state.mqtt_connection, msg_id);
if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) {
MQTT_INFO("MQTT: Queue full\r\n");
}
break;
case MQTT_MSG_TYPE_PUBREL:
client->mqtt_state.outbound_message = mqtt_msg_pubcomp(&client->mqtt_state.mqtt_connection, msg_id);
if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) {
MQTT_INFO("MQTT: Queue full\r\n");
}
break;
case MQTT_MSG_TYPE_PUBCOMP:
if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) {
MQTT_INFO("MQTT: receive MQTT_MSG_TYPE_PUBCOMP, finish QoS2 publish\r\n");
}
break;
case MQTT_MSG_TYPE_PINGREQ:
client->mqtt_state.outbound_message = mqtt_msg_pingresp(&client->mqtt_state.mqtt_connection);
if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) {
MQTT_INFO("MQTT: Queue full\r\n");
}
break;
case MQTT_MSG_TYPE_PINGRESP:
// Ignore
break;
}
// NOTE: this is done down here and not in the switch case above
// because the PSOCK_READBUF_LEN() won't work inside a switch
// statement due to the way protothreads resume.
if (msg_type == MQTT_MSG_TYPE_PUBLISH)
{
len = client->mqtt_state.message_length_read;
if (client->mqtt_state.message_length < client->mqtt_state.message_length_read)
{
//client->connState = MQTT_PUBLISH_RECV;
//Not Implement yet
len -= client->mqtt_state.message_length;
pdata += client->mqtt_state.message_length;
MQTT_INFO("Get another published message\r\n");
goto READPACKET;
}
}
break;
}
} else {
MQTT_INFO("ERROR: Message too long\r\n");
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
/**
* @brief Client send over callback function.
* @param arg: contain the ip link information
* @retval None
*/
void ICACHE_FLASH_ATTR
mqtt_tcpclient_sent_cb(void *arg)
{
struct espconn *pCon = (struct espconn *)arg;
MQTT_Client* client = (MQTT_Client *)pCon->reverse;
MQTT_INFO("TCP: Sent\r\n");
client->sendTimeout = 0;
client->keepAliveTick = 0;
if ((client->connState == MQTT_DATA || client->connState == MQTT_KEEPALIVE_SEND)
&& client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH) {
if (client->publishedCb)
client->publishedCb((uint32_t*)client);
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
void ICACHE_FLASH_ATTR mqtt_timer(void *arg)
{
MQTT_Client* client = (MQTT_Client*)arg;
if (client->connState == MQTT_DATA) {
client->keepAliveTick ++;
if (client->keepAliveTick > (client->mqtt_state.connect_info->keepalive / 2)) {
client->connState = MQTT_KEEPALIVE_SEND;
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
} else if (client->connState == TCP_RECONNECT_REQ) {
client->reconnectTick ++;
if (client->reconnectTick > MQTT_RECONNECT_TIMEOUT) {
client->reconnectTick = 0;
client->connState = TCP_RECONNECT;
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
if (client->timeoutCb)
client->timeoutCb((uint32_t*)client);
}
}
if (client->sendTimeout > 0)
client->sendTimeout --;
}
void ICACHE_FLASH_ATTR
mqtt_tcpclient_discon_cb(void *arg)
{
struct espconn *pespconn = (struct espconn *)arg;
MQTT_Client* client = (MQTT_Client *)pespconn->reverse;
MQTT_INFO("TCP: Disconnected callback\r\n");
if (TCP_DISCONNECTING == client->connState) {
client->connState = TCP_DISCONNECTED;
}
else if (MQTT_DELETING == client->connState) {
client->connState = MQTT_DELETED;
}
else {
client->connState = TCP_RECONNECT_REQ;
}
if (client->disconnectedCb)
client->disconnectedCb((uint32_t*)client);
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
/**
* @brief Tcp client connect success callback function.
* @param arg: contain the ip link information
* @retval None
*/
void ICACHE_FLASH_ATTR
mqtt_tcpclient_connect_cb(void *arg)
{
struct espconn *pCon = (struct espconn *)arg;
MQTT_Client* client = (MQTT_Client *)pCon->reverse;
espconn_regist_disconcb(client->pCon, mqtt_tcpclient_discon_cb);
espconn_regist_recvcb(client->pCon, mqtt_tcpclient_recv);////////
espconn_regist_sentcb(client->pCon, mqtt_tcpclient_sent_cb);///////
MQTT_INFO("MQTT: Connected to broker %s:%d\r\n", client->host, client->port);
mqtt_msg_init(&client->mqtt_state.mqtt_connection, client->mqtt_state.out_buffer, client->mqtt_state.out_buffer_length);
client->mqtt_state.outbound_message = mqtt_msg_connect(&client->mqtt_state.mqtt_connection, client->mqtt_state.connect_info);
client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data);
client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length);
client->sendTimeout = MQTT_SEND_TIMOUT;
MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id);
if (client->security) {
#ifdef MQTT_SSL_ENABLE
espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length);
#else
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length);
}
client->mqtt_state.outbound_message = NULL;
client->connState = MQTT_CONNECT_SENDING;
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
/**
* @brief Tcp client connect repeat callback function.
* @param arg: contain the ip link information
* @retval None
*/
void ICACHE_FLASH_ATTR
mqtt_tcpclient_recon_cb(void *arg, sint8 errType)
{
struct espconn *pCon = (struct espconn *)arg;
MQTT_Client* client = (MQTT_Client *)pCon->reverse;
MQTT_INFO("TCP: Reconnect to %s:%d\r\n", client->host, client->port);
client->connState = TCP_RECONNECT_REQ;
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
/**
* @brief MQTT publish function.
* @param client: MQTT_Client reference
* @param topic: string topic will publish to
* @param data: buffer data send point to
* @param data_length: length of data
* @param qos: qos
* @param retain: retain
* @retval TRUE if success queue
*/
bool ICACHE_FLASH_ATTR
MQTT_Publish(MQTT_Client *client, const char* topic, const char* data, int data_length, int qos, int retain)
{
uint8_t dataBuffer[MQTT_BUF_SIZE];
uint16_t dataLen;
client->mqtt_state.outbound_message = mqtt_msg_publish(&client->mqtt_state.mqtt_connection,
topic, data, data_length,
qos, retain,
&client->mqtt_state.pending_msg_id);
if (client->mqtt_state.outbound_message->length == 0) {
MQTT_INFO("MQTT: Queuing publish failed\r\n");
return FALSE;
}
MQTT_INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size);
while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) {
MQTT_INFO("MQTT: Queue full\r\n");
if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) {
MQTT_INFO("MQTT: Serious buffer error\r\n");
return FALSE;
}
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
return TRUE;
}
/**
* @brief MQTT subscibe function.
* @param client: MQTT_Client reference
* @param topic: string topic will subscribe
* @param qos: qos
* @retval TRUE if success queue
*/
bool ICACHE_FLASH_ATTR
MQTT_Subscribe(MQTT_Client *client, char* topic, uint8_t qos)
{
uint8_t dataBuffer[MQTT_BUF_SIZE];
uint16_t dataLen;
client->mqtt_state.outbound_message = mqtt_msg_subscribe(&client->mqtt_state.mqtt_connection,
topic, qos,
&client->mqtt_state.pending_msg_id);
MQTT_INFO("MQTT: queue subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id);
while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) {
MQTT_INFO("MQTT: Queue full\r\n");
if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) {
MQTT_INFO("MQTT: Serious buffer error\r\n");
return FALSE;
}
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
return TRUE;
}
/**
* @brief MQTT un-subscibe function.
* @param client: MQTT_Client reference
* @param topic: String topic will un-subscribe
* @retval TRUE if success queue
*/
bool ICACHE_FLASH_ATTR
MQTT_UnSubscribe(MQTT_Client *client, char* topic)
{
uint8_t dataBuffer[MQTT_BUF_SIZE];
uint16_t dataLen;
client->mqtt_state.outbound_message = mqtt_msg_unsubscribe(&client->mqtt_state.mqtt_connection,
topic,
&client->mqtt_state.pending_msg_id);
MQTT_INFO("MQTT: queue un-subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id);
while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) {
MQTT_INFO("MQTT: Queue full\r\n");
if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) {
MQTT_INFO("MQTT: Serious buffer error\r\n");
return FALSE;
}
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
return TRUE;
}
/**
* @brief MQTT ping function.
* @param client: MQTT_Client reference
* @retval TRUE if success queue
*/
bool ICACHE_FLASH_ATTR
MQTT_Ping(MQTT_Client *client)
{
uint8_t dataBuffer[MQTT_BUF_SIZE];
uint16_t dataLen;
client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection);
if (client->mqtt_state.outbound_message->length == 0) {
MQTT_INFO("MQTT: Queuing publish failed\r\n");
return FALSE;
}
MQTT_INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size);
while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) {
MQTT_INFO("MQTT: Queue full\r\n");
if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) {
MQTT_INFO("MQTT: Serious buffer error\r\n");
return FALSE;
}
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
return TRUE;
}
void ICACHE_FLASH_ATTR
MQTT_Task(os_event_t *e)
{
MQTT_Client* client = (MQTT_Client*)e->par;
uint8_t dataBuffer[MQTT_BUF_SIZE];
uint16_t dataLen;
if (e->par == 0)
return;
switch (client->connState) {
case TCP_RECONNECT_REQ:
break;
case TCP_RECONNECT:
mqtt_tcpclient_delete(client);
MQTT_Connect(client);
MQTT_INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port);
client->connState = TCP_CONNECTING;
break;
case MQTT_DELETING:
case TCP_DISCONNECTING:
case TCP_RECONNECT_DISCONNECTING:
if (client->security) {
#ifdef MQTT_SSL_ENABLE
espconn_secure_disconnect(client->pCon);
#else
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
espconn_disconnect(client->pCon);
}
break;
case TCP_DISCONNECTED:
MQTT_INFO("MQTT: Disconnected\r\n");
mqtt_tcpclient_delete(client);
break;
case MQTT_DELETED:
MQTT_INFO("MQTT: Deleted client\r\n");
mqtt_client_delete(client);
break;
case MQTT_KEEPALIVE_SEND:
mqtt_send_keepalive(client);
break;
case MQTT_DATA:
if (QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) {
break;
}
if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0) {
client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer);
client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen);
client->sendTimeout = MQTT_SEND_TIMOUT;
MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id);
client->keepAliveTick = 0;
if (client->security) {
#ifdef MQTT_SSL_ENABLE
espconn_secure_send(client->pCon, dataBuffer, dataLen);
#else
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
espconn_send(client->pCon, dataBuffer, dataLen);
}
client->mqtt_state.outbound_message = NULL;
break;
}
break;
}
}
/**
* @brief MQTT initialization connection function
* @param client: MQTT_Client reference
* @param host: Domain or IP string
* @param port: Port to connect
* @param security: 1 for ssl, 0 for none
* @retval None
*/
void ICACHE_FLASH_ATTR
MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8_t security)
{
uint32_t temp;
MQTT_INFO("MQTT:InitConnection\r\n");
os_memset(mqttClient, 0, sizeof(MQTT_Client));
temp = os_strlen(host);
mqttClient->host = (uint8_t*)os_zalloc(temp + 1);
os_strcpy(mqttClient->host, host);
mqttClient->host[temp] = 0;
mqttClient->port = port;
mqttClient->security = security;
}
/**
* @brief MQTT initialization mqtt client function
* @param client: MQTT_Client reference
* @param clientid: MQTT client id
* @param client_user:MQTT client user
* @param client_pass:MQTT client password
* @param client_pass:MQTT keep alive timer, in second
* @retval None
*/
bool ICACHE_FLASH_ATTR
MQTT_InitClient(MQTT_Client *mqttClient, uint8_t* client_id, uint8_t* client_user, uint8_t* client_pass, uint32_t keepAliveTime, uint8_t cleanSession)
{
uint32_t temp;
MQTT_INFO("MQTT:InitClient\r\n");
os_memset(&mqttClient->connect_info, 0, sizeof(mqtt_connect_info_t));
if ( !client_id )
{
/* Should be allowed by broker, but clean session flag must be set. */
#ifdef PROTOCOL_NAMEv311
if (cleanSession)
{
mqttClient->connect_info.client_id = zero_len_id;
} else {
MQTT_INFO("cleanSession must be set to use 0 length client_id\r\n");
return false;
}
/* Not supported. Return. */
#else
MQTT_INFO("Client ID required for MQTT < 3.1.1!\r\n");
return false;
#endif
}
/* If connect_info's client_id is still NULL and we get here, we can *
* assume the passed client_id is non-NULL. */
if ( !(mqttClient->connect_info.client_id) )
{
temp = os_strlen(client_id);
mqttClient->connect_info.client_id = (uint8_t*)os_zalloc(temp + 1);
os_strcpy(mqttClient->connect_info.client_id, client_id);
mqttClient->connect_info.client_id[temp] = 0;
}
if (client_user)
{
temp = os_strlen(client_user);
mqttClient->connect_info.username = (uint8_t*)os_zalloc(temp + 1);
os_strcpy(mqttClient->connect_info.username, client_user);
mqttClient->connect_info.username[temp] = 0;
}
if (client_pass)
{
temp = os_strlen(client_pass);
mqttClient->connect_info.password = (uint8_t*)os_zalloc(temp + 1);
os_strcpy(mqttClient->connect_info.password, client_pass);
mqttClient->connect_info.password[temp] = 0;
}
mqttClient->connect_info.keepalive = keepAliveTime;
mqttClient->connect_info.clean_session = cleanSession;
mqttClient->mqtt_state.in_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE);
mqttClient->mqtt_state.in_buffer_length = MQTT_BUF_SIZE;
mqttClient->mqtt_state.out_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE);
mqttClient->mqtt_state.out_buffer_length = MQTT_BUF_SIZE;
mqttClient->mqtt_state.connect_info = &mqttClient->connect_info;
mqtt_msg_init(&mqttClient->mqtt_state.mqtt_connection, mqttClient->mqtt_state.out_buffer, mqttClient->mqtt_state.out_buffer_length);
QUEUE_Init(&mqttClient->msgQueue, QUEUE_BUFFER_SIZE);
system_os_task(MQTT_Task, MQTT_TASK_PRIO, mqtt_procTaskQueue, MQTT_TASK_QUEUE_SIZE);
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient);
return true;
}
void ICACHE_FLASH_ATTR
MQTT_InitLWT(MQTT_Client *mqttClient, uint8_t* will_topic, uint8_t* will_msg, uint8_t will_qos, uint8_t will_retain)
{
uint32_t temp;
temp = os_strlen(will_topic);
mqttClient->connect_info.will_topic = (uint8_t*)os_zalloc(temp + 1);
os_strcpy(mqttClient->connect_info.will_topic, will_topic);
mqttClient->connect_info.will_topic[temp] = 0;
temp = os_strlen(will_msg);
mqttClient->connect_info.will_message = (uint8_t*)os_zalloc(temp + 1);
os_strcpy(mqttClient->connect_info.will_message, will_msg);
mqttClient->connect_info.will_message[temp] = 0;
mqttClient->connect_info.will_qos = will_qos;
mqttClient->connect_info.will_retain = will_retain;
}
/**
* @brief Begin connect to MQTT broker
* @param client: MQTT_Client reference
* @retval None
*/
void ICACHE_FLASH_ATTR
MQTT_Connect(MQTT_Client *mqttClient)
{
if (mqttClient->pCon) {
// Clean up the old connection forcefully - using MQTT_Disconnect
// does not actually release the old connection until the
// disconnection callback is invoked.
mqtt_tcpclient_delete(mqttClient);
}
mqttClient->pCon = (struct espconn *)os_zalloc(sizeof(struct espconn));
mqttClient->pCon->type = ESPCONN_TCP;
mqttClient->pCon->state = ESPCONN_NONE;
mqttClient->pCon->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));
mqttClient->pCon->proto.tcp->local_port = espconn_port();
mqttClient->pCon->proto.tcp->remote_port = mqttClient->port;
mqttClient->pCon->reverse = mqttClient;
espconn_regist_connectcb(mqttClient->pCon, mqtt_tcpclient_connect_cb);
espconn_regist_reconcb(mqttClient->pCon, mqtt_tcpclient_recon_cb);
mqttClient->keepAliveTick = 0;
mqttClient->reconnectTick = 0;
os_timer_disarm(&mqttClient->mqttTimer);
os_timer_setfn(&mqttClient->mqttTimer, (os_timer_func_t *)mqtt_timer, mqttClient);
os_timer_arm(&mqttClient->mqttTimer, 1000, 1);
if (UTILS_StrToIP(mqttClient->host, &mqttClient->pCon->proto.tcp->remote_ip)) {
MQTT_INFO("TCP: Connect to ip %s:%d\r\n", mqttClient->host, mqttClient->port);
if (mqttClient->security)
{
#ifdef MQTT_SSL_ENABLE
espconn_secure_set_size(ESPCONN_CLIENT, MQTT_SSL_SIZE);
espconn_secure_connect(mqttClient->pCon);
#else
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else
{
espconn_connect(mqttClient->pCon);
}
}
else {
MQTT_INFO("TCP: Connect to domain %s:%d\r\n", mqttClient->host, mqttClient->port);
espconn_gethostbyname(mqttClient->pCon, mqttClient->host, &mqttClient->ip, mqtt_dns_found);
}
mqttClient->connState = TCP_CONNECTING;
}
void ICACHE_FLASH_ATTR
MQTT_Disconnect(MQTT_Client *mqttClient)
{
mqttClient->connState = TCP_DISCONNECTING;
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient);
os_timer_disarm(&mqttClient->mqttTimer);
}
void ICACHE_FLASH_ATTR
MQTT_DeleteClient(MQTT_Client *mqttClient)
{
if (NULL == mqttClient)
return;
mqttClient->connState = MQTT_DELETED;
// if(TCP_DISCONNECTED == mqttClient->connState) {
// mqttClient->connState = MQTT_DELETED;
// } else if(MQTT_DELETED != mqttClient->connState) {
// mqttClient->connState = MQTT_DELETING;
// }
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient);
os_timer_disarm(&mqttClient->mqttTimer);
}
void ICACHE_FLASH_ATTR
MQTT_OnConnected(MQTT_Client *mqttClient, MqttCallback connectedCb)
{
mqttClient->connectedCb = connectedCb;
}
void ICACHE_FLASH_ATTR
MQTT_OnDisconnected(MQTT_Client *mqttClient, MqttCallback disconnectedCb)
{
mqttClient->disconnectedCb = disconnectedCb;
}
void ICACHE_FLASH_ATTR
MQTT_OnData(MQTT_Client *mqttClient, MqttDataCallback dataCb)
{
mqttClient->dataCb = dataCb;
}
void ICACHE_FLASH_ATTR
MQTT_OnPublished(MQTT_Client *mqttClient, MqttCallback publishedCb)
{
mqttClient->publishedCb = publishedCb;
}
void ICACHE_FLASH_ATTR
MQTT_OnTimeout(MQTT_Client *mqttClient, MqttCallback timeoutCb)
{
mqttClient->timeoutCb = timeoutCb;
}

View File

@ -0,0 +1,148 @@
/* mqtt.h
*
* Copyright (c) 2014-2015, Tuan PM <tuanpm at live dot 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:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Redis 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 OWNER 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 USER_AT_MQTT_H_
#define USER_AT_MQTT_H_
#include "user_config.h"
#include "mqtt_msg.h"
#include "user_interface.h"
#include "queue.h"
typedef struct mqtt_event_data_t
{
uint8_t type;
const char* topic;
const char* data;
uint16_t topic_length;
uint16_t data_length;
uint16_t data_offset;
} mqtt_event_data_t;
typedef struct mqtt_state_t
{
uint16_t port;
int auto_reconnect;
mqtt_connect_info_t* connect_info;
uint8_t* in_buffer;
uint8_t* out_buffer;
int in_buffer_length;
int out_buffer_length;
uint16_t message_length;
uint16_t message_length_read;
mqtt_message_t* outbound_message;
mqtt_connection_t mqtt_connection;
uint16_t pending_msg_id;
int pending_msg_type;
int pending_publish_qos;
} mqtt_state_t;
typedef enum {
WIFI_INIT,
WIFI_CONNECTING,
WIFI_CONNECTING_ERROR,
WIFI_CONNECTED,
DNS_RESOLVE,
TCP_DISCONNECTING,
TCP_DISCONNECTED,
TCP_RECONNECT_DISCONNECTING,
TCP_RECONNECT_REQ,
TCP_RECONNECT,
TCP_CONNECTING,
TCP_CONNECTING_ERROR,
TCP_CONNECTED,
MQTT_CONNECT_SEND,
MQTT_CONNECT_SENDING,
MQTT_SUBSCIBE_SEND,
MQTT_SUBSCIBE_SENDING,
MQTT_DATA,
MQTT_KEEPALIVE_SEND,
MQTT_PUBLISH_RECV,
MQTT_PUBLISHING,
MQTT_DELETING,
MQTT_DELETED,
} tConnState;
typedef void (*MqttCallback)(uint32_t *args);
typedef void (*MqttDataCallback)(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t lengh);
typedef struct {
struct espconn *pCon;
uint8_t security;
uint8_t* host;
uint32_t port;
ip_addr_t ip;
mqtt_state_t mqtt_state;
mqtt_connect_info_t connect_info;
MqttCallback connectedCb;
MqttCallback disconnectedCb;
MqttCallback publishedCb;
MqttCallback timeoutCb;
MqttDataCallback dataCb;
ETSTimer mqttTimer;
uint32_t keepAliveTick;
uint32_t reconnectTick;
uint32_t sendTimeout;
tConnState connState;
QUEUE msgQueue;
void* user_data;
} MQTT_Client;
#define SEC_NONSSL 0
#define SEC_SSL 1
#define MQTT_FLAG_CONNECTED 1
#define MQTT_FLAG_READY 2
#define MQTT_FLAG_EXIT 4
#define MQTT_EVENT_TYPE_NONE 0
#define MQTT_EVENT_TYPE_CONNECTED 1
#define MQTT_EVENT_TYPE_DISCONNECTED 2
#define MQTT_EVENT_TYPE_SUBSCRIBED 3
#define MQTT_EVENT_TYPE_UNSUBSCRIBED 4
#define MQTT_EVENT_TYPE_PUBLISH 5
#define MQTT_EVENT_TYPE_PUBLISHED 6
#define MQTT_EVENT_TYPE_EXITED 7
#define MQTT_EVENT_TYPE_PUBLISH_CONTINUATION 8
void ICACHE_FLASH_ATTR MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8_t security);
bool ICACHE_FLASH_ATTR MQTT_InitClient(MQTT_Client *mqttClient, uint8_t* client_id, uint8_t* client_user, uint8_t* client_pass, uint32_t keepAliveTime, uint8_t cleanSession);
void ICACHE_FLASH_ATTR MQTT_DeleteClient(MQTT_Client *mqttClient);
void ICACHE_FLASH_ATTR MQTT_InitLWT(MQTT_Client *mqttClient, uint8_t* will_topic, uint8_t* will_msg, uint8_t will_qos, uint8_t will_retain);
void ICACHE_FLASH_ATTR MQTT_OnConnected(MQTT_Client *mqttClient, MqttCallback connectedCb);
void ICACHE_FLASH_ATTR MQTT_OnDisconnected(MQTT_Client *mqttClient, MqttCallback disconnectedCb);
void ICACHE_FLASH_ATTR MQTT_OnPublished(MQTT_Client *mqttClient, MqttCallback publishedCb);
void ICACHE_FLASH_ATTR MQTT_OnTimeout(MQTT_Client *mqttClient, MqttCallback timeoutCb);
void ICACHE_FLASH_ATTR MQTT_OnData(MQTT_Client *mqttClient, MqttDataCallback dataCb);
bool ICACHE_FLASH_ATTR MQTT_Subscribe(MQTT_Client *client, char* topic, uint8_t qos);
bool ICACHE_FLASH_ATTR MQTT_UnSubscribe(MQTT_Client *client, char* topic);
void ICACHE_FLASH_ATTR MQTT_Connect(MQTT_Client *mqttClient);
void ICACHE_FLASH_ATTR MQTT_Disconnect(MQTT_Client *mqttClient);
bool ICACHE_FLASH_ATTR MQTT_Publish(MQTT_Client *client, const char* topic, const char* data, int data_length, int qos, int retain);
#endif /* USER_AT_MQTT_H_ */

View File

@ -0,0 +1,487 @@
/*
* Copyright (c) 2014, Stephen Robinson
* 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.
*
*/
#include <string.h>
#include "mqtt_msg.h"
#include "user_config.h"
#define MQTT_MAX_FIXED_HEADER_SIZE 3
enum mqtt_connect_flag
{
MQTT_CONNECT_FLAG_USERNAME = 1 << 7,
MQTT_CONNECT_FLAG_PASSWORD = 1 << 6,
MQTT_CONNECT_FLAG_WILL_RETAIN = 1 << 5,
MQTT_CONNECT_FLAG_WILL = 1 << 2,
MQTT_CONNECT_FLAG_CLEAN_SESSION = 1 << 1
};
struct __attribute((__packed__)) mqtt_connect_variable_header
{
uint8_t lengthMsb;
uint8_t lengthLsb;
#if defined(PROTOCOL_NAMEv31)
uint8_t magic[6];
#elif defined(PROTOCOL_NAMEv311)
uint8_t magic[4];
#else
#error "Please define protocol name"
#endif
uint8_t version;
uint8_t flags;
uint8_t keepaliveMsb;
uint8_t keepaliveLsb;
};
static int ICACHE_FLASH_ATTR append_string(mqtt_connection_t* connection, const char* string, int len)
{
if (connection->message.length + len + 2 > connection->buffer_length)
return -1;
connection->buffer[connection->message.length++] = len >> 8;
connection->buffer[connection->message.length++] = len & 0xff;
memcpy(connection->buffer + connection->message.length, string, len);
connection->message.length += len;
return len + 2;
}
static uint16_t ICACHE_FLASH_ATTR append_message_id(mqtt_connection_t* connection, uint16_t message_id)
{
// If message_id is zero then we should assign one, otherwise
// we'll use the one supplied by the caller
while (message_id == 0)
message_id = ++connection->message_id;
if (connection->message.length + 2 > connection->buffer_length)
return 0;
connection->buffer[connection->message.length++] = message_id >> 8;
connection->buffer[connection->message.length++] = message_id & 0xff;
return message_id;
}
static int ICACHE_FLASH_ATTR init_message(mqtt_connection_t* connection)
{
connection->message.length = MQTT_MAX_FIXED_HEADER_SIZE;
return MQTT_MAX_FIXED_HEADER_SIZE;
}
static mqtt_message_t* ICACHE_FLASH_ATTR fail_message(mqtt_connection_t* connection)
{
connection->message.data = connection->buffer;
connection->message.length = 0;
return &connection->message;
}
static mqtt_message_t* ICACHE_FLASH_ATTR fini_message(mqtt_connection_t* connection, int type, int dup, int qos, int retain)
{
int remaining_length = connection->message.length - MQTT_MAX_FIXED_HEADER_SIZE;
if (remaining_length > 127)
{
connection->buffer[0] = ((type & 0x0f) << 4) | ((dup & 1) << 3) | ((qos & 3) << 1) | (retain & 1);
connection->buffer[1] = 0x80 | (remaining_length % 128);
connection->buffer[2] = remaining_length / 128;
connection->message.length = remaining_length + 3;
connection->message.data = connection->buffer;
}
else
{
connection->buffer[1] = ((type & 0x0f) << 4) | ((dup & 1) << 3) | ((qos & 3) << 1) | (retain & 1);
connection->buffer[2] = remaining_length;
connection->message.length = remaining_length + 2;
connection->message.data = connection->buffer + 1;
}
return &connection->message;
}
void ICACHE_FLASH_ATTR mqtt_msg_init(mqtt_connection_t* connection, uint8_t* buffer, uint16_t buffer_length)
{
memset(connection, 0, sizeof(mqtt_connection_t));
connection->buffer = buffer;
connection->buffer_length = buffer_length;
}
int ICACHE_FLASH_ATTR mqtt_get_total_length(uint8_t* buffer, uint16_t length)
{
int i;
int totlen = 0;
for (i = 1; i < length; ++i)
{
totlen += (buffer[i] & 0x7f) << (7 * (i - 1));
if ((buffer[i] & 0x80) == 0)
{
++i;
break;
}
}
totlen += i;
return totlen;
}
const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t* length)
{
int i;
int totlen = 0;
int topiclen;
for (i = 1; i < *length; ++i)
{
totlen += (buffer[i] & 0x7f) << (7 * (i - 1));
if ((buffer[i] & 0x80) == 0)
{
++i;
break;
}
}
totlen += i;
if (i + 2 >= *length)
return NULL;
topiclen = buffer[i++] << 8;
topiclen |= buffer[i++];
if (i + topiclen > *length)
return NULL;
*length = topiclen;
return (const char*)(buffer + i);
}
const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* length)
{
int i;
int totlen = 0;
int topiclen;
int blength = *length;
*length = 0;
for (i = 1; i < blength; ++i)
{
totlen += (buffer[i] & 0x7f) << (7 * (i - 1));
if ((buffer[i] & 0x80) == 0)
{
++i;
break;
}
}
totlen += i;
if (i + 2 >= blength)
return NULL;
topiclen = buffer[i++] << 8;
topiclen |= buffer[i++];
if (i + topiclen >= blength)
return NULL;
i += topiclen;
if (mqtt_get_qos(buffer) > 0)
{
if (i + 2 >= blength)
return NULL;
i += 2;
}
if (totlen < i)
return NULL;
if (totlen <= blength)
*length = totlen - i;
else
*length = blength - i;
return (const char*)(buffer + i);
}
uint16_t ICACHE_FLASH_ATTR mqtt_get_id(uint8_t* buffer, uint16_t length)
{
if (length < 1)
return 0;
switch (mqtt_get_type(buffer))
{
case MQTT_MSG_TYPE_PUBLISH:
{
int i;
int topiclen;
for (i = 1; i < length; ++i)
{
if ((buffer[i] & 0x80) == 0)
{
++i;
break;
}
}
if (i + 2 >= length)
return 0;
topiclen = buffer[i++] << 8;
topiclen |= buffer[i++];
if (i + topiclen >= length)
return 0;
i += topiclen;
if (mqtt_get_qos(buffer) > 0)
{
if (i + 2 >= length)
return 0;
//i += 2;
} else {
return 0;
}
return (buffer[i] << 8) | buffer[i + 1];
}
case MQTT_MSG_TYPE_PUBACK:
case MQTT_MSG_TYPE_PUBREC:
case MQTT_MSG_TYPE_PUBREL:
case MQTT_MSG_TYPE_PUBCOMP:
case MQTT_MSG_TYPE_SUBACK:
case MQTT_MSG_TYPE_UNSUBACK:
case MQTT_MSG_TYPE_SUBSCRIBE:
{
// This requires the remaining length to be encoded in 1 byte,
// which it should be.
if (length >= 4 && (buffer[1] & 0x80) == 0)
return (buffer[2] << 8) | buffer[3];
else
return 0;
}
default:
return 0;
}
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_info_t* info)
{
struct mqtt_connect_variable_header* variable_header;
init_message(connection);
if (connection->message.length + sizeof(*variable_header) > connection->buffer_length)
return fail_message(connection);
variable_header = (void*)(connection->buffer + connection->message.length);
connection->message.length += sizeof(*variable_header);
variable_header->lengthMsb = 0;
#if defined(PROTOCOL_NAMEv31)
variable_header->lengthLsb = 6;
memcpy(variable_header->magic, "MQIsdp", 6);
variable_header->version = 3;
#elif defined(PROTOCOL_NAMEv311)
variable_header->lengthLsb = 4;
memcpy(variable_header->magic, "MQTT", 4);
variable_header->version = 4;
#else
#error "Please define protocol name"
#endif
variable_header->flags = 0;
variable_header->keepaliveMsb = info->keepalive >> 8;
variable_header->keepaliveLsb = info->keepalive & 0xff;
if (info->clean_session)
variable_header->flags |= MQTT_CONNECT_FLAG_CLEAN_SESSION;
if (info->client_id == NULL)
{
/* Never allowed */
return fail_message(connection);
}
else if (info->client_id[0] == '\0')
{
#ifdef PROTOCOL_NAMEv311
/* Allowed. Format 0 Length ID */
append_string(connection, info->client_id, 2) ;
#else
/* 0 Length not allowed */
return fail_message(connection);
#endif
}
else
{
/* No 0 data and at least 1 long. Good to go. */
if(append_string(connection, info->client_id, strlen(info->client_id)) < 0)
return fail_message(connection);
}
if (info->will_topic != NULL && info->will_topic[0] != '\0')
{
if (append_string(connection, info->will_topic, strlen(info->will_topic)) < 0)
return fail_message(connection);
if (append_string(connection, info->will_message, strlen(info->will_message)) < 0)
return fail_message(connection);
variable_header->flags |= MQTT_CONNECT_FLAG_WILL;
if (info->will_retain)
variable_header->flags |= MQTT_CONNECT_FLAG_WILL_RETAIN;
variable_header->flags |= (info->will_qos & 3) << 3;
}
if (info->username != NULL && info->username[0] != '\0')
{
if (append_string(connection, info->username, strlen(info->username)) < 0)
return fail_message(connection);
variable_header->flags |= MQTT_CONNECT_FLAG_USERNAME;
}
if (info->password != NULL && info->password[0] != '\0')
{
if (append_string(connection, info->password, strlen(info->password)) < 0)
return fail_message(connection);
variable_header->flags |= MQTT_CONNECT_FLAG_PASSWORD;
}
return fini_message(connection, MQTT_MSG_TYPE_CONNECT, 0, 0, 0);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_publish(mqtt_connection_t* connection, const char* topic, const char* data, int data_length, int qos, int retain, uint16_t* message_id)
{
init_message(connection);
if (topic == NULL || topic[0] == '\0')
return fail_message(connection);
if (append_string(connection, topic, strlen(topic)) < 0)
return fail_message(connection);
if (qos > 0)
{
if ((*message_id = append_message_id(connection, 0)) == 0)
return fail_message(connection);
}
else
*message_id = 0;
if (connection->message.length + data_length > connection->buffer_length)
return fail_message(connection);
memcpy(connection->buffer + connection->message.length, data, data_length);
connection->message.length += data_length;
return fini_message(connection, MQTT_MSG_TYPE_PUBLISH, 0, qos, retain);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_puback(mqtt_connection_t* connection, uint16_t message_id)
{
init_message(connection);
if (append_message_id(connection, message_id) == 0)
return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PUBACK, 0, 0, 0);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrec(mqtt_connection_t* connection, uint16_t message_id)
{
init_message(connection);
if (append_message_id(connection, message_id) == 0)
return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PUBREC, 0, 0, 0);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrel(mqtt_connection_t* connection, uint16_t message_id)
{
init_message(connection);
if (append_message_id(connection, message_id) == 0)
return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PUBREL, 0, 1, 0);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubcomp(mqtt_connection_t* connection, uint16_t message_id)
{
init_message(connection);
if (append_message_id(connection, message_id) == 0)
return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PUBCOMP, 0, 0, 0);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_subscribe(mqtt_connection_t* connection, const char* topic, int qos, uint16_t* message_id)
{
init_message(connection);
if (topic == NULL || topic[0] == '\0')
return fail_message(connection);
if ((*message_id = append_message_id(connection, 0)) == 0)
return fail_message(connection);
if (append_string(connection, topic, strlen(topic)) < 0)
return fail_message(connection);
if (connection->message.length + 1 > connection->buffer_length)
return fail_message(connection);
connection->buffer[connection->message.length++] = qos;
return fini_message(connection, MQTT_MSG_TYPE_SUBSCRIBE, 0, 1, 0);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_unsubscribe(mqtt_connection_t* connection, const char* topic, uint16_t* message_id)
{
init_message(connection);
if (topic == NULL || topic[0] == '\0')
return fail_message(connection);
if ((*message_id = append_message_id(connection, 0)) == 0)
return fail_message(connection);
if (append_string(connection, topic, strlen(topic)) < 0)
return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_UNSUBSCRIBE, 0, 1, 0);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingreq(mqtt_connection_t* connection)
{
init_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PINGREQ, 0, 0, 0);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingresp(mqtt_connection_t* connection)
{
init_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PINGRESP, 0, 0, 0);
}
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_disconnect(mqtt_connection_t* connection)
{
init_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_DISCONNECT, 0, 0, 0);
}

View File

@ -0,0 +1,141 @@
/*
* File: mqtt_msg.h
* Author: Minh Tuan
*
* Created on July 12, 2014, 1:05 PM
*/
#ifndef MQTT_MSG_H
#define MQTT_MSG_H
#include "user_config.h"
#include "c_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Copyright (c) 2014, Stephen Robinson
* 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.
*
*/
/* 7 6 5 4 3 2 1 0*/
/*| --- Message Type---- | DUP Flag | QoS Level | Retain |
/* Remaining Length */
enum mqtt_message_type
{
MQTT_MSG_TYPE_CONNECT = 1,
MQTT_MSG_TYPE_CONNACK = 2,
MQTT_MSG_TYPE_PUBLISH = 3,
MQTT_MSG_TYPE_PUBACK = 4,
MQTT_MSG_TYPE_PUBREC = 5,
MQTT_MSG_TYPE_PUBREL = 6,
MQTT_MSG_TYPE_PUBCOMP = 7,
MQTT_MSG_TYPE_SUBSCRIBE = 8,
MQTT_MSG_TYPE_SUBACK = 9,
MQTT_MSG_TYPE_UNSUBSCRIBE = 10,
MQTT_MSG_TYPE_UNSUBACK = 11,
MQTT_MSG_TYPE_PINGREQ = 12,
MQTT_MSG_TYPE_PINGRESP = 13,
MQTT_MSG_TYPE_DISCONNECT = 14
};
enum mqtt_connect_return_code
{
CONNECTION_ACCEPTED = 0,
CONNECTION_REFUSE_PROTOCOL,
CONNECTION_REFUSE_ID_REJECTED,
CONNECTION_REFUSE_SERVER_UNAVAILABLE,
CONNECTION_REFUSE_BAD_USERNAME,
CONNECTION_REFUSE_NOT_AUTHORIZED
};
typedef struct mqtt_message
{
uint8_t* data;
uint16_t length;
} mqtt_message_t;
typedef struct mqtt_connection
{
mqtt_message_t message;
uint16_t message_id;
uint8_t* buffer;
uint16_t buffer_length;
} mqtt_connection_t;
typedef struct mqtt_connect_info
{
char* client_id;
char* username;
char* password;
char* will_topic;
char* will_message;
uint32_t keepalive;
int will_qos;
int will_retain;
int clean_session;
} mqtt_connect_info_t;
static inline int ICACHE_FLASH_ATTR mqtt_get_type(uint8_t* buffer) { return (buffer[0] & 0xf0) >> 4; }
static inline int ICACHE_FLASH_ATTR mqtt_get_connect_return_code(uint8_t* buffer) { return buffer[3]; }
static inline int ICACHE_FLASH_ATTR mqtt_get_dup(uint8_t* buffer) { return (buffer[0] & 0x08) >> 3; }
static inline int ICACHE_FLASH_ATTR mqtt_get_qos(uint8_t* buffer) { return (buffer[0] & 0x06) >> 1; }
static inline int ICACHE_FLASH_ATTR mqtt_get_retain(uint8_t* buffer) { return (buffer[0] & 0x01); }
void ICACHE_FLASH_ATTR mqtt_msg_init(mqtt_connection_t* connection, uint8_t* buffer, uint16_t buffer_length);
int ICACHE_FLASH_ATTR mqtt_get_total_length(uint8_t* buffer, uint16_t length);
const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t* length);
const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* length);
uint16_t ICACHE_FLASH_ATTR mqtt_get_id(uint8_t* buffer, uint16_t length);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_info_t* info);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_publish(mqtt_connection_t* connection, const char* topic, const char* data, int data_length, int qos, int retain, uint16_t* message_id);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_puback(mqtt_connection_t* connection, uint16_t message_id);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrec(mqtt_connection_t* connection, uint16_t message_id);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrel(mqtt_connection_t* connection, uint16_t message_id);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubcomp(mqtt_connection_t* connection, uint16_t message_id);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_subscribe(mqtt_connection_t* connection, const char* topic, int qos, uint16_t* message_id);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_unsubscribe(mqtt_connection_t* connection, const char* topic, uint16_t* message_id);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingreq(mqtt_connection_t* connection);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingresp(mqtt_connection_t* connection);
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_disconnect(mqtt_connection_t* connection);
#ifdef __cplusplus
}
#endif
#endif /* MQTT_MSG_H */

View File

@ -0,0 +1,129 @@
#include "proto.h"
#include "ringbuf.h"
I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize)
{
parser->buf = buf;
parser->bufSize = bufSize;
parser->dataLen = 0;
parser->callback = completeCallback;
parser->isEsc = 0;
return 0;
}
I8 ICACHE_FLASH_ATTR PROTO_ParseByte(PROTO_PARSER *parser, U8 value)
{
switch (value) {
case 0x7D:
parser->isEsc = 1;
break;
case 0x7E:
parser->dataLen = 0;
parser->isEsc = 0;
parser->isBegin = 1;
break;
case 0x7F:
if (parser->callback != NULL)
parser->callback();
parser->isBegin = 0;
return 0;
break;
default:
if (parser->isBegin == 0) break;
if (parser->isEsc) {
value ^= 0x20;
parser->isEsc = 0;
}
if (parser->dataLen < parser->bufSize)
parser->buf[parser->dataLen++] = value;
break;
}
return -1;
}
I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len)
{
while (len--)
PROTO_ParseByte(parser, *buf++);
return 0;
}
I16 ICACHE_FLASH_ATTR PROTO_ParseRb(RINGBUF* rb, U8 *bufOut, U16* len, U16 maxBufLen)
{
U8 c;
PROTO_PARSER proto;
PROTO_Init(&proto, NULL, bufOut, maxBufLen);
while (RINGBUF_Get(rb, &c) == 0) {
if (PROTO_ParseByte(&proto, c) == 0) {
*len = proto.dataLen;
return 0;
}
}
return -1;
}
I16 ICACHE_FLASH_ATTR PROTO_Add(U8 *buf, const U8 *packet, I16 bufSize)
{
U16 i = 2;
U16 len = *(U16*) packet;
if (bufSize < 1) return -1;
*buf++ = 0x7E;
bufSize--;
while (len--) {
switch (*packet) {
case 0x7D:
case 0x7E:
case 0x7F:
if (bufSize < 2) return -1;
*buf++ = 0x7D;
*buf++ = *packet++ ^ 0x20;
i += 2;
bufSize -= 2;
break;
default:
if (bufSize < 1) return -1;
*buf++ = *packet++;
i++;
bufSize--;
break;
}
}
if (bufSize < 1) return -1;
*buf++ = 0x7F;
return i;
}
I16 ICACHE_FLASH_ATTR PROTO_AddRb(RINGBUF *rb, const U8 *packet, I16 len)
{
U16 i = 2;
if (RINGBUF_Put(rb, 0x7E) == -1) return -1;
while (len--) {
switch (*packet) {
case 0x7D:
case 0x7E:
case 0x7F:
if (RINGBUF_Put(rb, 0x7D) == -1) return -1;
if (RINGBUF_Put(rb, *packet++ ^ 0x20) == -1) return -1;
i += 2;
break;
default:
if (RINGBUF_Put(rb, *packet++) == -1) return -1;
i++;
break;
}
}
if (RINGBUF_Put(rb, 0x7F) == -1) return -1;
return i;
}

View File

@ -0,0 +1,32 @@
/*
* File: proto.h
* Author: ThuHien
*
* Created on November 23, 2012, 8:57 AM
*/
#ifndef _PROTO_H_
#define _PROTO_H_
#include <stdlib.h>
#include "typedef.h"
#include "ringbuf.h"
typedef void(PROTO_PARSE_CALLBACK)();
typedef struct {
U8 *buf;
U16 bufSize;
U16 dataLen;
U8 isEsc;
U8 isBegin;
PROTO_PARSE_CALLBACK* callback;
} PROTO_PARSER;
I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize);
I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len);
I16 ICACHE_FLASH_ATTR PROTO_Add(U8 *buf, const U8 *packet, I16 bufSize);
I16 ICACHE_FLASH_ATTR PROTO_AddRb(RINGBUF *rb, const U8 *packet, I16 len);
I8 ICACHE_FLASH_ATTR PROTO_ParseByte(PROTO_PARSER *parser, U8 value);
I16 ICACHE_FLASH_ATTR PROTO_ParseRb(RINGBUF *rb, U8 *bufOut, U16* len, U16 maxBufLen);
#endif

View File

@ -0,0 +1,75 @@
/* str_queue.c
*
* Copyright (c) 2014-2015, Tuan PM <tuanpm at live dot 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:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Redis 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 OWNER 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.
*/
#include "queue.h"
#include "user_interface.h"
#include "osapi.h"
#include "os_type.h"
#include "mem.h"
#include "proto.h"
uint8_t *last_rb_p_r;
uint8_t *last_rb_p_w;
uint32_t last_fill_cnt;
void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize)
{
queue->buf = (uint8_t*)os_zalloc(bufferSize);
RINGBUF_Init(&queue->rb, queue->buf, bufferSize);
}
int32_t ICACHE_FLASH_ATTR QUEUE_Puts(QUEUE *queue, uint8_t* buffer, uint16_t len)
{
uint32_t ret;
last_rb_p_r = queue->rb.p_r;
last_rb_p_w = queue->rb.p_w;
last_fill_cnt = queue->rb.fill_cnt;
ret = PROTO_AddRb(&queue->rb, buffer, len);
if (ret == -1) {
// rolling ring buffer back
queue->rb.p_r = last_rb_p_r;
queue->rb.p_w = last_rb_p_w;
queue->rb.fill_cnt = last_fill_cnt;
}
return ret;
}
int32_t ICACHE_FLASH_ATTR QUEUE_Gets(QUEUE *queue, uint8_t* buffer, uint16_t* len, uint16_t maxLen)
{
return PROTO_ParseRb(&queue->rb, buffer, len, maxLen);
}
bool ICACHE_FLASH_ATTR QUEUE_IsEmpty(QUEUE *queue)
{
if (queue->rb.fill_cnt <= 0)
return TRUE;
return FALSE;
}

View File

@ -0,0 +1,44 @@
/* str_queue.h --
*
* Copyright (c) 2014-2015, Tuan PM <tuanpm at live dot 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:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Redis 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 OWNER 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 USER_QUEUE_H_
#define USER_QUEUE_H_
#include "os_type.h"
#include "ringbuf.h"
typedef struct {
uint8_t *buf;
RINGBUF rb;
} QUEUE;
void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize);
int32_t ICACHE_FLASH_ATTR QUEUE_Puts(QUEUE *queue, uint8_t* buffer, uint16_t len);
int32_t ICACHE_FLASH_ATTR QUEUE_Gets(QUEUE *queue, uint8_t* buffer, uint16_t* len, uint16_t maxLen);
bool ICACHE_FLASH_ATTR QUEUE_IsEmpty(QUEUE *queue);
#endif /* USER_QUEUE_H_ */

View File

@ -0,0 +1,67 @@
/**
* \file
* Ring Buffer library
*/
#include "ringbuf.h"
/**
* \brief init a RINGBUF object
* \param r pointer to a RINGBUF object
* \param buf pointer to a byte array
* \param size size of buf
* \return 0 if successfull, otherwise failed
*/
I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size)
{
if (r == NULL || buf == NULL || size < 2) return -1;
r->p_o = r->p_r = r->p_w = buf;
r->fill_cnt = 0;
r->size = size;
return 0;
}
/**
* \brief put a character into ring buffer
* \param r pointer to a ringbuf object
* \param c character to be put
* \return 0 if successfull, otherwise failed
*/
I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c)
{
if (r->fill_cnt >= r->size)return -1; // ring buffer is full, this should be atomic operation
r->fill_cnt++; // increase filled slots count, this should be atomic operation
*r->p_w++ = c; // put character into buffer
if (r->p_w >= r->p_o + r->size) // rollback if write pointer go pass
r->p_w = r->p_o; // the physical boundary
return 0;
}
/**
* \brief get a character from ring buffer
* \param r pointer to a ringbuf object
* \param c read character
* \return 0 if successfull, otherwise failed
*/
I16 ICACHE_FLASH_ATTR RINGBUF_Get(RINGBUF *r, U8* c)
{
if (r->fill_cnt <= 0)return -1; // ring buffer is empty, this should be atomic operation
r->fill_cnt--; // decrease filled slots count
*c = *r->p_r++; // get the character out
if (r->p_r >= r->p_o + r->size) // rollback if write pointer go pass
r->p_r = r->p_o; // the physical boundary
return 0;
}

View File

@ -0,0 +1,19 @@
#ifndef _RING_BUF_H_
#define _RING_BUF_H_
#include <os_type.h>
#include <stdlib.h>
#include "typedef.h"
typedef struct {
U8* p_o; /**< Original pointer */
U8* volatile p_r; /**< Read pointer */
U8* volatile p_w; /**< Write pointer */
volatile I32 fill_cnt; /**< Number of filled slots */
I32 size; /**< Buffer size */
} RINGBUF;
I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size);
I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c);
I16 ICACHE_FLASH_ATTR RINGBUF_Get(RINGBUF *r, U8* c);
#endif

View File

@ -0,0 +1,17 @@
/**
* \file
* Standard Types definition
*/
#ifndef _TYPE_DEF_H_
#define _TYPE_DEF_H_
typedef char I8;
typedef unsigned char U8;
typedef short I16;
typedef unsigned short U16;
typedef long I32;
typedef unsigned long U32;
typedef unsigned long long U64;
#endif

View File

@ -0,0 +1,15 @@
#ifndef __MQTT_CONFIG_H__
#define __MQTT_CONFIG_H__
//#define MQTT_SSL_ENABLE
#define MQTT_RECONNECT_TIMEOUT 5 /*second*/
//#define MQTT_BUF_SIZE 1024
#define MQTT_BUF_SIZE 512
#define QUEUE_BUFFER_SIZE 2048
//#define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/
#define PROTOCOL_NAMEv311 /*MQTT version 3.11 compatible with https://eclipse.org/paho/clients/testing/*/
#endif // __MQTT_CONFIG_H__

View File

@ -0,0 +1,149 @@
/*
* Copyright (c) 2014, Tuan PM
* Email: tuanpm@live.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.
*
*/
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stddef.h>
#include "utils.h"
uint8_t ICACHE_FLASH_ATTR UTILS_IsIPV4 (int8_t *str)
{
uint8_t segs = 0; /* Segment count. */
uint8_t chcnt = 0; /* Character count within segment. */
uint8_t accum = 0; /* Accumulator for segment. */
/* Catch NULL pointer. */
if (str == 0)
return 0;
/* Process every character in string. */
while (*str != '\0') {
/* Segment changeover. */
if (*str == '.') {
/* Must have some digits in segment. */
if (chcnt == 0)
return 0;
/* Limit number of segments. */
if (++segs == 4)
return 0;
/* Reset segment values and restart loop. */
chcnt = accum = 0;
str++;
continue;
}
/* Check numeric. */
if ((*str < '0') || (*str > '9'))
return 0;
/* Accumulate and check segment. */
if ((accum = accum * 10 + *str - '0') > 255)
return 0;
/* Advance other segment specific stuff and continue loop. */
chcnt++;
str++;
}
/* Check enough segments and enough characters in last segment. */
if (segs != 3)
return 0;
if (chcnt == 0)
return 0;
/* Address okay. */
return 1;
}
uint8_t ICACHE_FLASH_ATTR UTILS_StrToIP(const int8_t* str, void *ip)
{
/* The count of the number of bytes processed. */
int i;
/* A pointer to the next digit to process. */
const char * start;
start = str;
for (i = 0; i < 4; i++) {
/* The digit being processed. */
char c;
/* The value of this byte. */
int n = 0;
while (1) {
c = * start;
start++;
if (c >= '0' && c <= '9') {
n *= 10;
n += c - '0';
}
/* We insist on stopping at "." if we are still parsing
the first, second, or third numbers. If we have reached
the end of the numbers, we will allow any character. */
else if ((i < 3 && c == '.') || i == 3) {
break;
}
else {
return 0;
}
}
if (n >= 256) {
return 0;
}
((uint8_t*)ip)[i] = n;
}
return 1;
}
uint32_t ICACHE_FLASH_ATTR UTILS_Atoh(const int8_t *s)
{
uint32_t value = 0, digit;
int8_t c;
while ((c = *s++)) {
if ('0' <= c && c <= '9')
digit = c - '0';
else if ('A' <= c && c <= 'F')
digit = c - 'A' + 10;
else if ('a' <= c && c <= 'f')
digit = c - 'a' + 10;
else break;
value = (value << 4) | digit;
}
return value;
}

View File

@ -0,0 +1,9 @@
#ifndef _UTILS_H_
#define _UTILS_H_
#include "c_types.h"
uint32_t ICACHE_FLASH_ATTR UTILS_Atoh(const int8_t *s);
uint8_t ICACHE_FLASH_ATTR UTILS_StrToIP(const int8_t* str, void *ip);
uint8_t ICACHE_FLASH_ATTR UTILS_IsIPV4 (int8_t *str);
#endif

View File

@ -1,6 +1,6 @@
# TasmotaSerial
Implementation of software serial library for the ESP8266 at 9600 baud
Implementation of software serial library for the ESP8266
Allows for several instances to be active at the same time.

View File

@ -1,10 +1,10 @@
{
"name": "TasmotaSerial",
"version": "1.0.0",
"version": "1.2.0",
"keywords": [
"serial", "io", "TasmotaSerial"
],
"description": "Implementation of software serial for ESP8266 at 9600 baud.",
"description": "Implementation of software serial for ESP8266.",
"repository":
{
"type": "git",

View File

@ -1,8 +1,8 @@
name=TasmotaSerial
version=1.0
version=1.2.0
author=Theo Arends
maintainer=Theo Arends <theo@arends.com>
sentence=Implementation of software serial for ESP8266 at 9600 baud.
sentence=Implementation of software serial for ESP8266.
paragraph=
category=Signal Input/Output
url=

View File

@ -87,9 +87,7 @@ TasmotaSerial::TasmotaSerial(int receive_pin, int transmit_pin)
m_in_pos = m_out_pos = 0;
if (m_rx_pin > -1) {
m_buffer = (uint8_t*)malloc(TM_SERIAL_BUFFER_SIZE);
if (m_buffer == NULL) {
return;
}
if (m_buffer == NULL) return;
// Use getCycleCount() loop to get as exact timing as possible
m_bit_time = ESP.getCpuFreqMHz() *1000000 /TM_SERIAL_BAUDRATE;
pinMode(m_rx_pin, INPUT);
@ -111,7 +109,8 @@ bool TasmotaSerial::isValidGPIOpin(int pin)
bool TasmotaSerial::begin(long speed) {
// Use getCycleCount() loop to get as exact timing as possible
m_bit_time = ESP.getCpuFreqMHz() *1000000 /speed;
return m_valid && (speed <= TM_SERIAL_BAUDRATE);
m_high_speed = (speed > 9600);
return m_valid;
}
bool TasmotaSerial::begin() {
@ -123,17 +122,13 @@ void TasmotaSerial::flush() {
}
int TasmotaSerial::peek() {
if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) {
return -1;
}
if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) return -1;
return m_buffer[m_out_pos];
}
int TasmotaSerial::read()
{
if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) {
return -1;
}
if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) return -1;
uint8_t ch = m_buffer[m_out_pos];
m_out_pos = (m_out_pos +1) % TM_SERIAL_BUFFER_SIZE;
return ch;
@ -142,23 +137,20 @@ int TasmotaSerial::read()
int TasmotaSerial::available()
{
int avail = m_in_pos - m_out_pos;
if (avail < 0) {
avail += TM_SERIAL_BUFFER_SIZE;
}
if (avail < 0) avail += TM_SERIAL_BUFFER_SIZE;
return avail;
}
#ifdef TM_SERIAL_USE_IRAM
#define TM_SERIAL_WAIT { while (ESP.getCycleCount()-start < wait) optimistic_yield(1); wait += m_bit_time; } // Watchdog timeouts
#define TM_SERIAL_WAIT { while (ESP.getCycleCount()-start < wait) if (!m_high_speed) optimistic_yield(1); wait += m_bit_time; } // Watchdog timeouts
#else
#define TM_SERIAL_WAIT { while (ESP.getCycleCount()-start < wait); wait += m_bit_time; }
#endif
size_t TasmotaSerial::write(uint8_t b)
{
if (-1 == m_tx_pin) {
return 0;
}
if (-1 == m_tx_pin) return 0;
if (m_high_speed) cli(); // Disable interrupts in order to get a clean transmit
unsigned long wait = m_bit_time;
digitalWrite(m_tx_pin, HIGH);
unsigned long start = ESP.getCycleCount();
@ -173,6 +165,7 @@ size_t TasmotaSerial::write(uint8_t b)
// Stop bit
digitalWrite(m_tx_pin, HIGH);
TM_SERIAL_WAIT;
if (m_high_speed) sei();
return 1;
}
@ -191,9 +184,7 @@ void TasmotaSerial::rxRead()
for (int i = 0; i < 8; i++) {
TM_SERIAL_WAIT;
rec >>= 1;
if (digitalRead(m_rx_pin)) {
rec |= 0x80;
}
if (digitalRead(m_rx_pin)) rec |= 0x80;
}
// Stop bit
TM_SERIAL_WAIT;

View File

@ -20,12 +20,12 @@
#ifndef TasmotaSerial_h
#define TasmotaSerial_h
/*********************************************************************************************\
* TasmotaSerial supports up to 9600 baud with fixed buffer size of 64 bytes using optional no iram
* TasmotaSerial supports up to 115200 baud with fixed buffer size of 64 bytes using optional no iram
*
* Based on EspSoftwareSerial v3.3.1 by Peter Lerup (https://github.com/plerup/espsoftwareserial)
\*********************************************************************************************/
#define TM_SERIAL_BAUDRATE 9600 // Max supported baudrate
#define TM_SERIAL_BAUDRATE 9600 // Default baudrate
#define TM_SERIAL_BUFFER_SIZE 64 // Receive buffer size
#include <core_version.h> // Arduino_Esp8266 version information (ARDUINO_ESP8266_RELEASE and ARDUINO_ESP8266_RELEASE_2_3_0)
@ -57,6 +57,7 @@ class TasmotaSerial : public Stream {
// Member variables
bool m_valid;
bool m_high_speed;
int m_rx_pin;
int m_tx_pin;
unsigned long m_bit_time;

View File

@ -0,0 +1,72 @@
/**
* esp-knx-ip library for KNX/IP communication on an ESP8266
* Author: Nico Weichbrodt <envy>
* License: MIT
*/
typedef enum __dpt_1_001
{
DPT_1_001_OFF = 0x00,
DPT_1_001_ON = 0x01,
} dpt_1_001_t;
typedef enum __dpt_2_001
{
DPT_2_001_NO_OFF = 0b00,
DPT_2_001_NO_ON = 0b01,
DPT_2_001_YES_OFF = 0b10,
DPT_2_001_YES_ON = 0b11,
} dpt_2_001_t;
typedef enum __dpt_3_007
{
DPT_3_007_DECREASE_STOP = 0x00,
DPT_3_007_DECREASE_100 = 0x01,
DPT_3_007_DECREASE_50 = 0x02,
DPT_3_007_DECREASE_25 = 0x03,
DPT_3_007_DECREASE_12 = 0x04,
DPT_3_007_DECREASE_6 = 0x05,
DPT_3_007_DECREASE_3 = 0x06,
DPT_3_007_DECREASE_1 = 0x07,
DPT_3_007_INCREASE_STOP = 0x08,
DPT_3_007_INCREASE_100 = 0x09,
DPT_3_007_INCREASE_50 = 0x0A,
DPT_3_007_INCREASE_25 = 0x0B,
DPT_3_007_INCREASE_12 = 0x0C,
DPT_3_007_INCREASE_6 = 0x0D,
DPT_3_007_INCREASE_3 = 0x0E,
DPT_3_007_INCREASE_1 = 0x0F,
} dpt_3_007_t;
typedef enum __weekday
{
DPT_10_001_WEEKDAY_MONDAY = 1,
DPT_10_001_WEEKDAY_TUESDAY = 2,
DPT_10_001_WEEKDAY_WEDNESDAY = 3,
DPT_10_001_WEEKDAY_THURSDAY = 4,
DPT_10_001_WEEKDAY_FRIDAY = 5,
DPT_10_001_WEEKDAY_SATURDAY = 6,
DPT_10_001_WEEKDAY_SUNDAY = 8,
} weekday_t;
typedef struct __time_of_day
{
weekday_t weekday;
uint8_t hours;
uint8_t minutes;
uint8_t seconds;
} time_of_day_t;
typedef struct __date
{
uint8_t day;
uint8_t month;
uint8_t year;
} date_t;
typedef struct __color
{
uint8_t red;
uint8_t green;
uint8_t blue;
} color_t;

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Nico Weichbrodt <nico@weichbrodt.me>
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.

View File

@ -0,0 +1,94 @@
# ESP-KNX-IP #
This is a library for the ESP8266 to enable KNXnet/IP communication. It uses UDP multicast on 224.0.23.12:3671.
It is intended to be used with the Arduino platform for the ESP8266.
## How to use ##
The library is under development. API may change multiple times in the future.
API documentation is available [here](https://github.com/envy/esp-knx-ip/wiki/API)
A simple example:
```c++
#include <esp-knx-ip.h>
const char* ssid = "my-ssid"; // your network SSID (name)
const char* pass = "my-pw"; // your network password
config_id_t my_GA;
config_id_t param_id;
int8_t some_var = 0;
void setup()
{
// Register a callback that is called when a configurable group address is receiving a telegram
knx.register_callback("Set/Get callback", my_callback);
knx.register_callback("Write callback", my_other_callback);
int default_val = 21;
param_id = knx.config_register_int("My Parameter", default_val);
// Register a configurable group address for sending out answers
my_GA = knx.config_register_ga("Answer GA");
knx.load(); // Try to load a config from EEPROM
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
knx.start(); // Start everything. Must be called after WiFi connection has been established
}
void loop()
{
knx.loop();
}
void my_callback(message_t const &msg, void *arg)
{
switch (msg.ct)
{
case KNX_CT_WRITE:
// Save received data
some_var = knx.data_to_1byte_int(msg.data);
break;
case KNX_CT_READ:
// Answer with saved data
knx.answer1ByteInt(msg.received_on, some_var);
break;
}
}
void my_other_callback(message_t const &msg, void *arg)
{
switch (msg.ct)
{
case KNX_CT_WRITE:
// Write an answer somewhere else
int value = knx.config_get_int(param_id);
address_t ga = knx.config_get_ga(my_GA);
knx.answer1ByteInt(ga, (int8_t)value);
break;
}
}
```
## How to configure (buildtime) ##
Open the `esp-knx-ip.h` and take a look at the config options at the top inside the block marked `CONFIG`
## How to configure (runtime) ##
Simply visit the IP of your ESP with a webbrowser. You can configure the following:
* KNX physical address
* Which group address should trigger which callback
* Which group address are to be used by the program (e.g. for status replies)
The configuration is dynamically generated from the code.

View File

@ -0,0 +1,358 @@
/**
* esp-knx-ip library for KNX/IP communication on an ESP8266
* Author: Nico Weichbrodt <envy>
* License: MIT
*/
#include "esp-knx-ip.h"
/**
* Physical address functions
*/
void ESPKNXIP::physical_address_set(address_t const &addr)
{
physaddr = addr;
}
address_t ESPKNXIP::physical_address_get()
{
return physaddr;
}
/**
* Configuration functions start here
*/
config_id_t ESPKNXIP::config_register_string(String name, uint8_t len, String _default, enable_condition_t cond)
{
if (registered_configs >= MAX_CONFIGS)
return -1;
if (_default.length() >= len)
return -1;
config_id_t id = registered_configs;
custom_configs[id].name = name;
custom_configs[id].type = CONFIG_TYPE_STRING;
custom_configs[id].len = sizeof(uint8_t) + len;
custom_configs[id].cond = cond;
if (id == 0)
custom_configs[id].offset = 0;
else
custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len;
__config_set_string(id, _default);
registered_configs++;
DEBUG_PRINT("Registered config >");
DEBUG_PRINT(name);
DEBUG_PRINT("< @ ");
DEBUG_PRINT(id);
DEBUG_PRINT("/string[");
DEBUG_PRINT(custom_configs[id].offset);
DEBUG_PRINT("+");
DEBUG_PRINT(custom_configs[id].len);
DEBUG_PRINTLN("]");
return id;
}
config_id_t ESPKNXIP::config_register_int(String name, int32_t _default, enable_condition_t cond)
{
if (registered_configs >= MAX_CONFIGS)
return -1;
config_id_t id = registered_configs;
custom_configs[id].name = name;
custom_configs[id].type = CONFIG_TYPE_INT;
custom_configs[id].len = sizeof(uint8_t) + sizeof(int32_t);
custom_configs[id].cond = cond;
if (id == 0)
custom_configs[id].offset = 0;
else
custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len;
__config_set_int(id, _default);
registered_configs++;
DEBUG_PRINT("Registered config >");
DEBUG_PRINT(name);
DEBUG_PRINT("< @ ");
DEBUG_PRINT(id);
DEBUG_PRINT("/int[");
DEBUG_PRINT(custom_configs[id].offset);
DEBUG_PRINT("+");
DEBUG_PRINT(custom_configs[id].len);
DEBUG_PRINTLN("]");
return id;
}
config_id_t ESPKNXIP::config_register_bool(String name, bool _default, enable_condition_t cond)
{
if (registered_configs >= MAX_CONFIGS)
return -1;
config_id_t id = registered_configs;
custom_configs[id].name = name;
custom_configs[id].type = CONFIG_TYPE_BOOL;
custom_configs[id].len = sizeof(uint8_t) + sizeof(uint8_t);
custom_configs[id].cond = cond;
if (id == 0)
custom_configs[id].offset = 0;
else
custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len;
__config_set_bool(id, _default);
registered_configs++;
DEBUG_PRINT("Registered config >");
DEBUG_PRINT(name);
DEBUG_PRINT("< @ ");
DEBUG_PRINT(id);
DEBUG_PRINT("/bool[");
DEBUG_PRINT(custom_configs[id].offset);
DEBUG_PRINT("+");
DEBUG_PRINT(custom_configs[id].len);
DEBUG_PRINTLN("]");
return id;
}
config_id_t ESPKNXIP::config_register_options(String name, option_entry_t *options, uint8_t _default, enable_condition_t cond)
{
if (registered_configs >= MAX_CONFIGS)
return -1;
if (options == nullptr || options->name == nullptr)
return -1;
config_id_t id = registered_configs;
custom_configs[id].name = name;
custom_configs[id].type = CONFIG_TYPE_OPTIONS;
custom_configs[id].len = sizeof(uint8_t) + sizeof(uint8_t);
custom_configs[id].cond = cond;
if (id == 0)
custom_configs[id].offset = 0;
else
custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len;
custom_configs[id].data.options = options;
__config_set_options(id, _default);
registered_configs++;
DEBUG_PRINT("Registered config >");
DEBUG_PRINT(name);
DEBUG_PRINT("< @ ");
DEBUG_PRINT(id);
DEBUG_PRINT("/opt[");
DEBUG_PRINT(custom_configs[id].offset);
DEBUG_PRINT("+");
DEBUG_PRINT(custom_configs[id].len);
DEBUG_PRINTLN("]");
return id;
}
config_id_t ESPKNXIP::config_register_ga(String name, enable_condition_t cond)
{
if (registered_configs >= MAX_CONFIGS)
return -1;
config_id_t id = registered_configs;
custom_configs[id].name = name;
custom_configs[id].type = CONFIG_TYPE_GA;
custom_configs[id].len = sizeof(uint8_t) + sizeof(address_t);
custom_configs[id].cond = cond;
if (id == 0)
custom_configs[id].offset = 0;
else
custom_configs[id].offset = custom_configs[id - 1].offset + custom_configs[id - 1].len;
address_t t;
t.value = 0;
__config_set_ga(id, t);
registered_configs++;
DEBUG_PRINT("Registered config >");
DEBUG_PRINT(name);
DEBUG_PRINT("< @ ");
DEBUG_PRINT(id);
DEBUG_PRINT("/ga[");
DEBUG_PRINT(custom_configs[id].offset);
DEBUG_PRINT("+");
DEBUG_PRINT(custom_configs[id].len);
DEBUG_PRINTLN("]");
return id;
}
void ESPKNXIP::__config_set_flags(config_id_t id, config_flags_t flags)
{
DEBUG_PRINT("Setting flag @ ");
DEBUG_PRINT(custom_configs[id].offset);
DEBUG_PRINT(" to ");
DEBUG_PRINT(custom_config_data[custom_configs[id].offset], BIN);
DEBUG_PRINT(" | ");
DEBUG_PRINT(flags, BIN);
custom_config_data[custom_configs[id].offset] |= (uint8_t)flags;
DEBUG_PRINT(" = ");
DEBUG_PRINTLN(custom_config_data[custom_configs[id].offset], BIN);
}
void ESPKNXIP::config_set_string(config_id_t id, String val)
{
if (id >= registered_configs)
return;
if (custom_configs[id].type != CONFIG_TYPE_STRING)
return;
if (val.length() >= custom_configs[id].len)
return;
__config_set_flags(id, CONFIG_FLAGS_VALUE_SET);
__config_set_string(id, val);
}
void ESPKNXIP::__config_set_string(config_id_t id, String &val)
{
memcpy(&custom_config_data[custom_configs[id].offset + sizeof(uint8_t)], val.c_str(), val.length()+1);
}
void ESPKNXIP::config_set_int(config_id_t id, int32_t val)
{
if (id >= registered_configs)
return;
if (custom_configs[id].type != CONFIG_TYPE_INT)
return;
__config_set_flags(id, CONFIG_FLAGS_VALUE_SET);
__config_set_int(id, val);
}
void ESPKNXIP::__config_set_int(config_id_t id, int32_t val)
{
// This does not work for some reason:
// Could be due to pointer alignment
//int32_t *v = (int32_t *)(custom_config_data + custom_configs[id].offset);
//*v = val;
custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 0] = (uint8_t)((val & 0xFF000000) >> 24);
custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 1] = (uint8_t)((val & 0x00FF0000) >> 16);
custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 2] = (uint8_t)((val & 0x0000FF00) >> 8);
custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 3] = (uint8_t)((val & 0x000000FF) >> 0);
}
void ESPKNXIP::config_set_bool(config_id_t id, bool val)
{
if (id >= registered_configs)
return;
if (custom_configs[id].type != CONFIG_TYPE_BOOL)
return;
__config_set_flags(id, CONFIG_FLAGS_VALUE_SET);
__config_set_bool(id, val);
}
void ESPKNXIP::__config_set_bool(config_id_t id, bool val)
{
custom_config_data[custom_configs[id].offset + sizeof(uint8_t)] = val ? 1 : 0;
}
void ESPKNXIP::config_set_options(config_id_t id, uint8_t val)
{
if (id >= registered_configs)
return;
if (custom_configs[id].type != CONFIG_TYPE_OPTIONS)
return;
option_entry_t *cur = custom_configs[id].data.options;
while (cur->name != nullptr)
{
if (cur->value == val)
{
__config_set_flags(id, CONFIG_FLAGS_VALUE_SET);
__config_set_options(id, val);
break;
}
cur++;
}
}
void ESPKNXIP::__config_set_options(config_id_t id, uint8_t val)
{
custom_config_data[custom_configs[id].offset + sizeof(uint8_t)] = val;
}
void ESPKNXIP::config_set_ga(config_id_t id, address_t const &val)
{
if (id >= registered_configs)
return;
if (custom_configs[id].type != CONFIG_TYPE_GA)
return;
__config_set_flags(id, CONFIG_FLAGS_VALUE_SET);
__config_set_ga(id, val);
}
void ESPKNXIP::__config_set_ga(config_id_t id, address_t const &val)
{
custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 0] = val.bytes.high;
custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 1] = val.bytes.low;
}
String ESPKNXIP::config_get_string(config_id_t id)
{
if (id >= registered_configs)
return String("");
return String((char *)&custom_config_data[custom_configs[id].offset + sizeof(uint8_t)]);
}
int32_t ESPKNXIP::config_get_int(config_id_t id)
{
if (id >= registered_configs)
return 0;
int32_t v = (custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 0] << 24) +
(custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 1] << 16) +
(custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 2] << 8) +
(custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 3] << 0);
return v;
}
bool ESPKNXIP::config_get_bool(config_id_t id)
{
if (id >= registered_configs)
return false;
return custom_config_data[custom_configs[id].offset + sizeof(uint8_t)] != 0;
}
uint8_t ESPKNXIP::config_get_options(config_id_t id)
{
if (id >= registered_configs)
return false;
return custom_config_data[custom_configs[id].offset + sizeof(uint8_t)];
}
address_t ESPKNXIP::config_get_ga(config_id_t id)
{
address_t t;
if (id >= registered_configs)
{
t.value = 0;
return t;
}
t.bytes.high = custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 0];
t.bytes.low = custom_config_data[custom_configs[id].offset + sizeof(uint8_t) + 1];
return t;
}

View File

@ -0,0 +1,87 @@
/**
* esp-knx-ip library for KNX/IP communication on an ESP8266
* Author: Nico Weichbrodt <envy>
* License: MIT
*/
#include "esp-knx-ip.h"
/**
* Conversion functions
*/
bool ESPKNXIP::data_to_bool(uint8_t *data)
{
return (data[0] & 0x01) == 1 ? true : false;
}
int8_t ESPKNXIP::data_to_1byte_int(uint8_t *data)
{
return (int8_t)data[1];
}
uint8_t ESPKNXIP::data_to_1byte_uint(uint8_t *data)
{
return data[1];
}
int16_t ESPKNXIP::data_to_2byte_int(uint8_t *data)
{
return (int16_t)((data[1] << 8) | data[2]);
}
uint16_t ESPKNXIP::data_to_2byte_uint(uint8_t *data)
{
return (uint16_t)((data[1] << 8) | data[2]);
}
float ESPKNXIP::data_to_2byte_float(uint8_t *data)
{
//uint8_t sign = (data[1] & 0b10000000) >> 7;
uint8_t expo = (data[1] & 0b01111000) >> 3;
int16_t mant = ((data[1] & 0b10000111) << 8) | data[2];
return 0.01f * mant * pow(2, expo);
}
time_of_day_t ESPKNXIP::data_to_3byte_time(uint8_t *data)
{
time_of_day_t time;
time.weekday = (weekday_t)((data[1] & 0b11100000) >> 5);
time.hours = (data[1] & 0b00011111);
time.minutes = (data[2] & 0b00111111);
time.seconds = (data[3] & 0b00111111);
return time;
}
date_t ESPKNXIP::data_to_3byte_data(uint8_t *data)
{
date_t date;
date.day = (data[1] & 0b00011111);
date.month = (data[2] & 0b00001111);
date.year = (data[3] & 0b01111111);
return date;
}
color_t ESPKNXIP::data_to_3byte_color(uint8_t *data)
{
color_t color;
color.red = data[1];
color.green = data[2];
color.blue = data[3];
return color;
}
int32_t ESPKNXIP::data_to_4byte_int(uint8_t *data)
{
return (int32_t)((data[1] << 24) | (data[2] << 16) | (data[3] << 8) | (data[4] << 0));
}
uint32_t ESPKNXIP::data_to_4byte_uint(uint8_t *data)
{
return (uint32_t)((data[1] << 24) | (data[2] << 16) | (data[3] << 8) | (data[4] << 0));
}
float ESPKNXIP::data_to_4byte_float(uint8_t *data)
{
return (float)((data[1] << 24) | (data[2] << 16) | (data[3] << 8) |data[4]);
}

View File

@ -0,0 +1,182 @@
/**
* esp-knx-ip library for KNX/IP communication on an ESP8266
* Author: Nico Weichbrodt <envy>
* License: MIT
*/
#include "esp-knx-ip.h"
/**
* Send functions
*/
void ESPKNXIP::send(address_t const &receiver, knx_command_type_t ct, uint8_t data_len, uint8_t *data)
{
if (receiver.value == 0)
return;
#if SEND_CHECKSUM
uint32_t len = 6 + 2 + 8 + data_len + 1; // knx_pkt + cemi_msg + cemi_service + data + checksum
#else
uint32_t len = 6 + 2 + 8 + data_len; // knx_pkt + cemi_msg + cemi_service + data
#endif
DEBUG_PRINT(F("Creating packet with len "));
DEBUG_PRINTLN(len)
uint8_t buf[len];
knx_ip_pkt_t *knx_pkt = (knx_ip_pkt_t *)buf;
knx_pkt->header_len = 0x06;
knx_pkt->protocol_version = 0x10;
knx_pkt->service_type = __ntohs(KNX_ST_ROUTING_INDICATION);
knx_pkt->total_len.len = __ntohs(len);
cemi_msg_t *cemi_msg = (cemi_msg_t *)knx_pkt->pkt_data;
cemi_msg->message_code = KNX_MT_L_DATA_IND;
cemi_msg->additional_info_len = 0;
cemi_service_t *cemi_data = &cemi_msg->data.service_information;
cemi_data->control_1.bits.confirm = 0;
cemi_data->control_1.bits.ack = 0;
cemi_data->control_1.bits.priority = B11;
cemi_data->control_1.bits.system_broadcast = 0x01;
cemi_data->control_1.bits.repeat = 0x01;
cemi_data->control_1.bits.reserved = 0;
cemi_data->control_1.bits.frame_type = 0x01;
cemi_data->control_2.bits.extended_frame_format = 0x00;
cemi_data->control_2.bits.hop_count = 0x06;
cemi_data->control_2.bits.dest_addr_type = 0x01;
cemi_data->source = physaddr;
cemi_data->destination = receiver;
//cemi_data->destination.bytes.high = (area << 3) | line;
//cemi_data->destination.bytes.low = member;
cemi_data->data_len = data_len;
cemi_data->pci.apci = (ct & 0x0C) >> 2;
cemi_data->pci.tpci_seq_number = 0x00; // ???
cemi_data->pci.tpci_comm_type = KNX_COT_UDP; // ???
memcpy(cemi_data->data, data, data_len);
cemi_data->data[0] = (cemi_data->data[0] & 0x3F) | ((ct & 0x03) << 6);
#if SEND_CHECKSUM
// Calculate checksum, which is just XOR of all bytes
uint8_t cs = buf[0] ^ buf[1];
for (uint32_t i = 2; i < len - 1; ++i)
{
cs ^= buf[i];
}
buf[len - 1] = cs;
#endif
#ifdef ESP_KNX_DEBUG
DEBUG_PRINT(F("Sending packet:"));
for (int i = 0; i < len; ++i)
{
DEBUG_PRINT(F(" 0x"));
DEBUG_PRINT(buf[i], 16);
}
DEBUG_PRINTLN(F(""));
#endif
udp.beginPacketMulticast(MULTICAST_IP, MULTICAST_PORT, WiFi.localIP());
udp.write(buf, len);
udp.endPacket();
}
void ESPKNXIP::send_1bit(address_t const &receiver, knx_command_type_t ct, uint8_t bit)
{
uint8_t buf[] = {(uint8_t)(bit & 0b00000001)};
send(receiver, ct, 1, buf);
}
void ESPKNXIP::send_2bit(address_t const &receiver, knx_command_type_t ct, uint8_t twobit)
{
uint8_t buf[] = {(uint8_t)(twobit & 0b00000011)};
send(receiver, ct, 1, buf);
}
void ESPKNXIP::send_4bit(address_t const &receiver, knx_command_type_t ct, uint8_t fourbit)
{
uint8_t buf[] = {(uint8_t)(fourbit & 0b00001111)};
send(receiver, ct, 1, buf);
}
void ESPKNXIP::send_1byte_int(address_t const &receiver, knx_command_type_t ct, int8_t val)
{
uint8_t buf[] = {0x00, (uint8_t)val};
send(receiver, ct, 2, buf);
}
void ESPKNXIP::send_1byte_uint(address_t const &receiver, knx_command_type_t ct, uint8_t val)
{
uint8_t buf[] = {0x00, val};
send(receiver, ct, 2, buf);
}
void ESPKNXIP::send_2byte_int(address_t const &receiver, knx_command_type_t ct, int16_t val)
{
uint8_t buf[] = {0x00, (uint8_t)(val >> 8), (uint8_t)(val & 0x00FF)};
send(receiver, ct, 3, buf);
}
void ESPKNXIP::send_2byte_uint(address_t const &receiver, knx_command_type_t ct, uint16_t val)
{
uint8_t buf[] = {0x00, (uint8_t)(val >> 8), (uint8_t)(val & 0x00FF)};
send(receiver, ct, 3, buf);
}
void ESPKNXIP::send_2byte_float(address_t const &receiver, knx_command_type_t ct, float val)
{
float v = val * 100.0f;
int e = 0;
for (; v < -2048.0f; v /= 2)
++e;
for (; v > 2047.0f; v /= 2)
++e;
long m = round(v) & 0x7FF;
short msb = (short) (e << 3 | m >> 8);
if (val < 0.0f)
msb |= 0x80;
uint8_t buf[] = {0x00, (uint8_t)msb, (uint8_t)m};
send(receiver, ct, 3, buf);
}
void ESPKNXIP::send_3byte_time(address_t const &receiver, knx_command_type_t ct, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds)
{
weekday <<= 5;
uint8_t buf[] = {0x00, (uint8_t)(((weekday << 5) & 0xE0) | (hours & 0x1F)), (uint8_t)(minutes & 0x3F), (uint8_t)(seconds & 0x3F)};
send(receiver, ct, 4, buf);
}
void ESPKNXIP::send_3byte_date(address_t const &receiver, knx_command_type_t ct, uint8_t day, uint8_t month, uint8_t year)
{
uint8_t buf[] = {0x00, (uint8_t)(day & 0x1F), (uint8_t)(month & 0x0F), year};
send(receiver, ct, 4, buf);
}
void ESPKNXIP::send_3byte_color(address_t const &receiver, knx_command_type_t ct, uint8_t red, uint8_t green, uint8_t blue)
{
uint8_t buf[] = {0x00, red, green, blue};
send(receiver, ct, 4, buf);
}
void ESPKNXIP::send_4byte_int(address_t const &receiver, knx_command_type_t ct, int32_t val)
{
uint8_t buf[] = {0x00,
(uint8_t)((val & 0xFF000000) >> 24),
(uint8_t)((val & 0x00FF0000) >> 16),
(uint8_t)((val & 0x0000FF00) >> 8),
(uint8_t)((val & 0x000000FF) >> 0)};
send(receiver, ct, 5, buf);
}
void ESPKNXIP::send_4byte_uint(address_t const &receiver, knx_command_type_t ct, uint32_t val)
{
uint8_t buf[] = {0x00,
(uint8_t)((val & 0xFF000000) >> 24),
(uint8_t)((val & 0x00FF0000) >> 16),
(uint8_t)((val & 0x0000FF00) >> 8),
(uint8_t)((val & 0x000000FF) >> 0)};
send(receiver, ct, 5, buf);
}
void ESPKNXIP::send_4byte_float(address_t const &receiver, knx_command_type_t ct, float val)
{
uint8_t buf[] = {0x00, ((uint8_t *)&val)[3], ((uint8_t *)&val)[2], ((uint8_t *)&val)[1], ((uint8_t *)&val)[0]};
send(receiver, ct, 5, buf);
}

View File

@ -0,0 +1,540 @@
/**
* esp-knx-ip library for KNX/IP communication on an ESP8266
* Author: Nico Weichbrodt <envy>
* License: MIT
*/
#include "esp-knx-ip.h"
void ESPKNXIP::__handle_root()
{
String m = F("<html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>");
#if USE_BOOTSTRAP
m += F("<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>");
m += F("<style>.input-group-insert > .input-group-text { border-radius: 0; }</style>");
#endif
m += F("</head><body><div class='container-fluid'>");
m += F("<h2>ESP KNX</h2>");
// Feedback
if (registered_feedbacks > 0)
{
m += F("<h4>Feedback</h4>");
for (feedback_id_t i = 0; i < registered_feedbacks; ++i)
{
if (feedbacks[i].cond && !feedbacks[i].cond())
{
continue;
}
m += F("<form action='" __FEEDBACK_PATH "' method='POST'>");
m += F("<div class='row'><div class='col-auto'><div class='input-group'>");
m += F("<div class='input-group-prepend'><span class='input-group-text'>");
m += feedbacks[i].name;
m += F("</span></div>");
switch (feedbacks[i].type)
{
case FEEDBACK_TYPE_INT:
m += F("<span class='input-group-text'>");
m += String(*(int32_t *)feedbacks[i].data);
m += F("</span>");
break;
case FEEDBACK_TYPE_FLOAT:
m += F("<span class='input-group-text'>");
m += feedbacks[i].options.float_options.prefix;
m += String(*(float *)feedbacks[i].data, feedbacks[i].options.float_options.precision);
m += feedbacks[i].options.float_options.suffix;
m += F("</span>");
break;
case FEEDBACK_TYPE_BOOL:
m += F("<span class='input-group-text'>");
m += (*(bool *)feedbacks[i].data) ? F("True") : F("False");
m += F("</span>");
break;
case FEEDBACK_TYPE_ACTION:
m += F("<input class='form-control' type='hidden' name='id' value='");
m += i;
m += F("' /><div class='input-group-append'><button type='submit' class='btn btn-primary'>");
m += feedbacks[i].options.action_options.btn_text;
m += F("</button></div>");
break;
}
m += F("</div></div></div>");
m += F("</form>");
}
}
if (registered_callbacks > 0)
m += F("<h4>Callbacks</h4>");
if (registered_callback_assignments > 0)
{
for (uint8_t i = 0; i < registered_callback_assignments; ++i)
{
// Skip empty slots
if ((callback_assignments[i].slot_flags & SLOT_FLAGS_USED) == 0)
{
continue;
}
// Skip disabled callbacks
if (callbacks[callback_assignments[i].callback_id].cond && !callbacks[callback_assignments[i].callback_id].cond())
{
continue;
}
address_t &addr = callback_assignments[i].address;
m += F("<form action='" __DELETE_PATH "' method='POST'>");
m += F("<div class='row'><div class='col-auto'><div class='input-group'>");
m += F("<div class='input-group-prepend'><span class='input-group-text'>");
m += addr.ga.area;
m += F("/");
m += addr.ga.line;
m += F("/");
m += addr.ga.member;
m += F("</span>");
m += F("<span class='input-group-text'>");
m += callbacks[callback_assignments[i].callback_id].name;
m += F("</span></div>");
m += F("<input class='form-control' type='hidden' name='id' value='");
m += i;
m += F("' /><div class='input-group-append'><button type='submit' class='btn btn-danger'>Delete</button></div>");
m += F("</div></div></div>");
m += F("</form>");
}
}
if (registered_callbacks > 0)
{
m += F("<form action='" __REGISTER_PATH "' method='POST'>");
m += F("<div class='row'><div class='col-auto'><div class='input-group'>");
m += F("<input class='form-control' type='number' name='area' min='0' max='31'/>");
m += F("<div class='input-group-insert'><span class='input-group-text'>/</span></div>");
m += F("<input class='form-control' type='number' name='line' min='0' max='7'/>");
m += F("<div class='input-group-insert'><span class='input-group-text'>/</span></div>");
m += F("<input class='form-control' type='number' name='member' min='0' max='255'/>");
m += F("<div class='input-group-insert'><span class='input-group-text'>-&gt;</span></div>");
m += F("<select class='form-control' name='cb'>");
for (callback_id_t i = 0; i < registered_callbacks; ++i)
{
// Skip empty slots
if ((callbacks[i].slot_flags & SLOT_FLAGS_USED) == 0)
{
continue;
}
// Skip disabled callbacks
if (callbacks[i].cond && !callbacks[i].cond())
{
continue;
}
m += F("<option value=\"");
m += i;
m += F("\">");
m += callbacks[i].name;
m += F("</option>");
}
m += F("</select>");
m += F("<div class='input-group-append'><button type='submit' class='btn btn-primary'>Set</button></div>");
m += F("</div></div></div>");
m += F("</form>");
}
m += F("<h4>Configuration</h4>");
// Physical address
m += F("<form action='" __PHYS_PATH "' method='POST'>");
m += F("<div class='row'><div class='col-auto'><div class='input-group'>");
m += F("<div class='input-group-prepend'><span class='input-group-text'>Physical address</span></div>");
m += F("<input class='form-control' type='number' name='area' min='0' max='15' value='");
m += physaddr.pa.area;
m += F("'/>");
m += F("<div class='input-group-insert'><span class='input-group-text'>.</span></div>");
m += F("<input class='form-control' type='number' name='line' min='0' max='15' value='");
m += physaddr.pa.line;
m += F("'/>");
m += F("<div class='input-group-insert'><span class='input-group-text'>.</span></div>");
m += F("<input class='form-control' type='number' name='member' min='0' max='255' value='");
m += physaddr.pa.member;
m += F("'/>");
m += F("<div class='input-group-append'><button type='submit' class='btn btn-primary'>Set</button></div>");
m += F("</div></div></div>");
m += F("</form>");
if (registered_configs > 0)
{
for (config_id_t i = 0; i < registered_configs; ++i)
{
// Check if this config option has a enable condition and if so check that condition
if (custom_configs[i].cond && !custom_configs[i].cond())
continue;
m += F("<form action='" __CONFIG_PATH "' method='POST'>");
m += F("<div class='row'><div class='col-auto'><div class='input-group'>");
m += F("<div class='input-group-prepend'><span class='input-group-text'>");
m += custom_configs[i].name;
m += F("</span></div>");
switch (custom_configs[i].type)
{
case CONFIG_TYPE_STRING:
m += F("<input class='form-control' type='text' name='value' value='");
m += config_get_string(i);
m += F("' maxlength='");
m += custom_configs[i].len - 1; // Subtract \0 byte
m += F("'/>");
break;
case CONFIG_TYPE_INT:
m += F("<input class='form-control' type='number' name='value' value='");
m += config_get_int(i);
m += F("'/>");
break;
case CONFIG_TYPE_BOOL:
m += F("<div class='input-group-insert'><span class='input-group-text'>");
m += F("<input type='checkbox' name='value' ");
if (config_get_bool(i))
m += F("checked ");
m += F("/>");
m += F("</span></div>");
break;
case CONFIG_TYPE_OPTIONS:
{
m += F("<select class='custom-select' name='value'>");
option_entry_t *cur = custom_configs[i].data.options;
while (cur->name != nullptr)
{
if (config_get_options(i) == cur->value)
{
m += F("<option selected value='");
}
else
{
m += F("<option value='");
}
m += cur->value;
m += F("'>");
m += String(cur->name);
m += F("</option>");
cur++;
}
m += F("");
m += F("</select>");
break;
}
case CONFIG_TYPE_GA:
address_t a = config_get_ga(i);
m += F("<input class='form-control' type='number' name='area' min='0' max='31' value='");
m += a.ga.area;
m += F("'/>");
m += F("<div class='input-group-insert'><span class='input-group-text'>/</span></div>");
m += F("<input class='form-control' type='number' name='line' min='0' max='7' value='");
m += a.ga.line;
m += F("'/>");
m += F("<div class='input-group-insert'><span class='input-group-text'>/</span></div>");
m += F("<input class='form-control' type='number' name='member' min='0' max='255' value='");
m += a.ga.member;
m += F("'/>");
break;
}
m += F("<input type='hidden' name='id' value='");
m += i;
m += F("'/>");
m += F("<div class='input-group-append'><button type='submit' class='btn btn-primary'>Set</button></div>");
m += F("</div></div></div>");
m += F("</form>");
}
}
#if !(DISABLE_EEPROM_BUTTONS && DISABLE_RESTORE_BUTTON && DISABLE_REBOOT_BUTTON)
// EEPROM save and restore
m += F("<div class='row'>");
// Save to EEPROM
#if !DISABLE_EEPROM_BUTTONS
m += F("<div class='col-auto'>");
m += F("<form action='" __EEPROM_PATH "' method='POST'>");
m += F("<input type='hidden' name='mode' value='1'>");
m += F("<button type='submit' class='btn btn-success'>Save to EEPROM</button>");
m += F("</form>");
m += F("</div>");
// Restore from EEPROM
m += F("<div class='col-auto'>");
m += F("<form action='" __EEPROM_PATH "' method='POST'>");
m += F("<input type='hidden' name='mode' value='2'>");
m += F("<button type='submit' class='btn btn-info'>Restore from EEPROM</button>");
m += F("</form>");
m += F("</div>");
#endif
#if !DISABLE_RESTORE_BUTTON
// Load Defaults
m += F("<div class='col-auto'>");
m += F("<form action='" __RESTORE_PATH "' method='POST'>");
m += F("<button type='submit' class='btn btn-warning'>Restore defaults</button>");
m += F("</form>");
m += F("</div>");
#endif
#if !DISABLE_REBOOT_BUTTON
// Reboot
m += F("<div class='col-auto'>");
m += F("<form action='" __REBOOT_PATH "' method='POST'>");
m += F("<button type='submit' class='btn btn-danger'>Reboot</button>");
m += F("</form>");
m += F("</div>");
#endif
m += F("</div>"); // row
#endif
// End of page
m += F("</div></body></html>");
server->send(200, F("text/html"), m);
}
void ESPKNXIP::__handle_register()
{
DEBUG_PRINTLN(F("Register called"));
if (server->hasArg(F("area")) && server->hasArg(F("line")) && server->hasArg(F("member")) && server->hasArg(F("cb")))
{
uint8_t area = server->arg(F("area")).toInt();
uint8_t line = server->arg(F("line")).toInt();
uint8_t member = server->arg(F("member")).toInt();
callback_id_t cb = (callback_id_t)server->arg(F("cb")).toInt();
DEBUG_PRINT(F("Got args: "));
DEBUG_PRINT(area);
DEBUG_PRINT(F("/"));
DEBUG_PRINT(line);
DEBUG_PRINT(F("/"));
DEBUG_PRINT(member);
DEBUG_PRINT(F("/"));
DEBUG_PRINT(cb);
DEBUG_PRINTLN(F(""));
if (area > 31 || line > 7)
{
DEBUG_PRINTLN(F("Area or Line wrong"));
goto end;
}
if (!__callback_is_id_valid(cb))
{
DEBUG_PRINTLN(F("Invalid callback id"));
goto end;
}
address_t ga = {.ga={line, area, member}};
__callback_register_assignment(ga, cb);
}
end:
server->sendHeader(F("Location"),F(__ROOT_PATH));
server->send(302);
}
void ESPKNXIP::__handle_delete()
{
DEBUG_PRINTLN(F("Delete called"));
if (server->hasArg(F("id")))
{
callback_assignment_id_t id = (callback_assignment_id_t)server->arg(F("id")).toInt();
DEBUG_PRINT(F("Got args: "));
DEBUG_PRINT(id);
DEBUG_PRINTLN(F(""));
if (id >= registered_callback_assignments || (callback_assignments[id].slot_flags & SLOT_FLAGS_USED) == 0)
{
DEBUG_PRINTLN(F("ID wrong"));
goto end;
}
__callback_delete_assignment(id);
}
end:
server->sendHeader(F("Location"),F(__ROOT_PATH));
server->send(302);
}
void ESPKNXIP::__handle_set()
{
DEBUG_PRINTLN(F("Set called"));
if (server->hasArg(F("area")) && server->hasArg(F("line")) && server->hasArg(F("member")))
{
uint8_t area = server->arg(F("area")).toInt();
uint8_t line = server->arg(F("line")).toInt();
uint8_t member = server->arg(F("member")).toInt();
DEBUG_PRINT(F("Got args: "));
DEBUG_PRINT(area);
DEBUG_PRINT(F("."));
DEBUG_PRINT(line);
DEBUG_PRINT(F("."));
DEBUG_PRINT(member);
DEBUG_PRINTLN(F(""));
if (area > 31 || line > 7)
{
DEBUG_PRINTLN(F("Area or Line wrong"));
goto end;
}
physaddr.bytes.high = (area << 4) | line;
physaddr.bytes.low = member;
}
end:
server->sendHeader(F("Location"),F(__ROOT_PATH));
server->send(302);
}
void ESPKNXIP::__handle_config()
{
DEBUG_PRINTLN(F("Config called"));
if (server->hasArg(F("id")))
{
config_id_t id = server->arg(F("id")).toInt();
DEBUG_PRINT(F("Got args: "));
DEBUG_PRINT(id);
DEBUG_PRINTLN(F(""));
if (id < 0 || id >= registered_configs)
{
DEBUG_PRINTLN(F("ID wrong"));
goto end;
}
switch (custom_configs[id].type)
{
case CONFIG_TYPE_STRING:
{
String v = server->arg(F("value"));
if (v.length() >= custom_configs[id].len)
goto end;
__config_set_flags(id, CONFIG_FLAGS_VALUE_SET);
__config_set_string(id, v);
break;
}
case CONFIG_TYPE_INT:
{
__config_set_flags(id, CONFIG_FLAGS_VALUE_SET);
__config_set_int(id, server->arg(F("value")).toInt());
break;
}
case CONFIG_TYPE_BOOL:
{
__config_set_flags(id, CONFIG_FLAGS_VALUE_SET);
__config_set_bool(id, server->arg(F("value")).compareTo(F("on")) == 0);
break;
}
case CONFIG_TYPE_OPTIONS:
{
uint8_t val = (uint8_t)server->arg(F("value")).toInt();
DEBUG_PRINT(F("Value: "));
DEBUG_PRINTLN(val);
config_set_options(id, val);
break;
}
case CONFIG_TYPE_GA:
{
uint8_t area = server->arg(F("area")).toInt();
uint8_t line = server->arg(F("line")).toInt();
uint8_t member = server->arg(F("member")).toInt();
if (area > 31 || line > 7)
{
DEBUG_PRINTLN(F("Area or Line wrong"));
goto end;
}
address_t tmp;
tmp.bytes.high = (area << 3) | line;
tmp.bytes.low = member;
__config_set_flags(id, CONFIG_FLAGS_VALUE_SET);
__config_set_ga(id, tmp);
break;
}
}
}
end:
server->sendHeader(F("Location"),F(__ROOT_PATH));
server->send(302);
}
void ESPKNXIP::__handle_feedback()
{
DEBUG_PRINTLN(F("Feedback called"));
if (server->hasArg(F("id")))
{
config_id_t id = server->arg(F("id")).toInt();
DEBUG_PRINT(F("Got args: "));
DEBUG_PRINT(id);
DEBUG_PRINTLN(F(""));
if (id < 0 || id >= registered_feedbacks)
{
DEBUG_PRINTLN(F("ID wrong"));
goto end;
}
switch (feedbacks[id].type)
{
case FEEDBACK_TYPE_ACTION:
{
feedback_action_fptr_t func = (feedback_action_fptr_t)feedbacks[id].data;
void *arg = feedbacks[id].options.action_options.arg;
func(arg);
break;
}
default:
DEBUG_PRINTLN(F("Feedback has no action"));
break;
}
}
end:
server->sendHeader(F("Location"),F(__ROOT_PATH));
server->send(302);
}
#if !DISABLE_RESTORE_BUTTONS
void ESPKNXIP::__handle_restore()
{
DEBUG_PRINTLN(F("Restore called"));
memcpy(custom_config_data, custom_config_default_data, MAX_CONFIG_SPACE);
end:
server->sendHeader(F("Location"),F(__ROOT_PATH));
server->send(302);
}
#endif
#if !DISABLE_REBOOT_BUTTONS
void ESPKNXIP::__handle_reboot()
{
DEBUG_PRINTLN(F("Rebooting!"));
server->sendHeader(F("Location"),F(__ROOT_PATH));
server->send(302);
delay(1000);
ESP.restart();
//while(1);
}
#endif
#if !DISABLE_EEPROM_BUTTONS
void ESPKNXIP::__handle_eeprom()
{
DEBUG_PRINTLN(F("EEPROM called"));
if (server->hasArg(F("mode")))
{
uint8_t mode = server->arg(F("mode")).toInt();
DEBUG_PRINT(F("Got args: "));
DEBUG_PRINT(mode);
DEBUG_PRINTLN(F(""));
if (mode == 1)
{
// save
save_to_eeprom();
}
else if (mode == 2)
{
// restore
restore_from_eeprom();
}
}
end:
server->sendHeader(F("Location"),F(__ROOT_PATH));
server->send(302);
}
#endif

View File

@ -0,0 +1,659 @@
/**
* esp-knx-ip library for KNX/IP communication on an ESP8266
* Author: Nico Weichbrodt <envy>
* License: MIT
*/
#include "esp-knx-ip.h"
char const *string_defaults[] =
{
"Do this",
"True",
"False",
""
};
ESPKNXIP::ESPKNXIP() : server(nullptr),
registered_callback_assignments(0),
free_callback_assignment_slots(0),
registered_callbacks(0),
free_callback_slots(0),
registered_configs(0),
registered_feedbacks(0)
{
DEBUG_PRINTLN();
DEBUG_PRINTLN("ESPKNXIP starting up");
// Default physical address is 1.1.0
physaddr.bytes.high = (/*area*/1 << 4) | /*line*/1;
physaddr.bytes.low = /*member*/0;
memset(callback_assignments, 0, MAX_CALLBACK_ASSIGNMENTS * sizeof(callback_assignment_t));
memset(callbacks, 0, MAX_CALLBACKS * sizeof(callback_fptr_t));
memset(custom_config_data, 0, MAX_CONFIG_SPACE * sizeof(uint8_t));
memset(custom_config_default_data, 0, MAX_CONFIG_SPACE * sizeof(uint8_t));
memset(custom_configs, 0, MAX_CONFIGS * sizeof(config_t));
}
void ESPKNXIP::load()
{
memcpy(custom_config_default_data, custom_config_data, MAX_CONFIG_SPACE);
EEPROM.begin(EEPROM_SIZE);
restore_from_eeprom();
}
void ESPKNXIP::start(ESP8266WebServer *srv)
{
server = srv;
__start();
}
void ESPKNXIP::start()
{
server = new ESP8266WebServer(80);
__start();
}
void ESPKNXIP::__start()
{
if (server != nullptr)
{
server->on(ROOT_PREFIX, [this](){
__handle_root();
});
server->on(__ROOT_PATH, [this](){
__handle_root();
});
server->on(__REGISTER_PATH, [this](){
__handle_register();
});
server->on(__DELETE_PATH, [this](){
__handle_delete();
});
server->on(__PHYS_PATH, [this](){
__handle_set();
});
#if !DISABLE_EEPROM_BUTTONS
server->on(__EEPROM_PATH, [this](){
__handle_eeprom();
});
#endif
server->on(__CONFIG_PATH, [this](){
__handle_config();
});
server->on(__FEEDBACK_PATH, [this](){
__handle_feedback();
});
#if !DISABLE_RESTORE_BUTTON
server->on(__RESTORE_PATH, [this](){
__handle_restore();
});
#endif
#if !DISABLE_REBOOT_BUTTON
server->on(__REBOOT_PATH, [this](){
__handle_reboot();
});
#endif
server->begin();
}
udp.beginMulticast(WiFi.localIP(), MULTICAST_IP, MULTICAST_PORT);
}
void ESPKNXIP::save_to_eeprom()
{
uint32_t address = 0;
uint64_t magic = EEPROM_MAGIC;
EEPROM.put(address, magic);
address += sizeof(uint64_t);
EEPROM.put(address++, registered_callback_assignments);
for (uint8_t i = 0; i < MAX_CALLBACK_ASSIGNMENTS; ++i)
{
EEPROM.put(address, callback_assignments[i].address);
address += sizeof(address_t);
}
for (uint8_t i = 0; i < MAX_CALLBACK_ASSIGNMENTS; ++i)
{
EEPROM.put(address, callback_assignments[i].callback_id);
address += sizeof(callback_id_t);
}
EEPROM.put(address, physaddr);
address += sizeof(address_t);
EEPROM.put(address, custom_config_data);
address += sizeof(custom_config_data);
EEPROM.commit();
DEBUG_PRINT("Wrote to EEPROM: 0x");
DEBUG_PRINTLN(address, HEX);
}
void ESPKNXIP::restore_from_eeprom()
{
uint32_t address = 0;
uint64_t magic = 0;
EEPROM.get(address, magic);
if (magic != EEPROM_MAGIC)
{
DEBUG_PRINTLN("No valid magic in EEPROM, aborting restore.");
DEBUG_PRINT("Expected 0x");
DEBUG_PRINT((unsigned long)(EEPROM_MAGIC >> 32), HEX);
DEBUG_PRINT(" 0x");
DEBUG_PRINT((unsigned long)(EEPROM_MAGIC), HEX);
DEBUG_PRINT(" got 0x");
DEBUG_PRINT((unsigned long)(magic >> 32), HEX);
DEBUG_PRINT(" 0x");
DEBUG_PRINTLN((unsigned long)magic, HEX);
return;
}
address += sizeof(uint64_t);
EEPROM.get(address++, registered_callback_assignments);
for (uint8_t i = 0; i < MAX_CALLBACK_ASSIGNMENTS; ++i)
{
EEPROM.get(address, callback_assignments[i].address);
if (callback_assignments[i].address.value != 0)
{
// if address is not 0/0/0 then mark slot as used
callback_assignments[i].slot_flags |= SLOT_FLAGS_USED;
DEBUG_PRINTLN("used slot");
}
else
{
// if address is 0/0/0, then we found a free slot, yay!
// however, only count those slots, if we have not reached registered_callback_assignments yet
if (i < registered_callback_assignments)
{
DEBUG_PRINTLN("free slot before reaching registered_callback_assignments");
free_callback_assignment_slots++;
}
else
{
DEBUG_PRINTLN("free slot");
}
}
address += sizeof(address_t);
}
for (uint8_t i = 0; i < MAX_CALLBACK_ASSIGNMENTS; ++i)
{
EEPROM.get(address, callback_assignments[i].callback_id);
address += sizeof(callback_id_t);
}
EEPROM.get(address, physaddr);
address += sizeof(address_t);
//EEPROM.get(address, custom_config_data);
//address += sizeof(custom_config_data);
uint32_t conf_offset = address;
for (uint8_t i = 0; i < registered_configs; ++i)
{
// First byte is flags.
config_flags_t flags = CONFIG_FLAGS_NO_FLAGS;
flags = (config_flags_t)EEPROM.read(address);
DEBUG_PRINT("Flag in EEPROM @ ");
DEBUG_PRINT(address - conf_offset);
DEBUG_PRINT(": ");
DEBUG_PRINTLN(flags, BIN);
custom_config_data[custom_configs[i].offset] = flags;
if (flags & CONFIG_FLAGS_VALUE_SET)
{
DEBUG_PRINTLN("Non-default value");
for (int j = 0; j < custom_configs[i].len - sizeof(uint8_t); ++j)
{
custom_config_data[custom_configs[i].offset + sizeof(uint8_t) + j] = EEPROM.read(address + sizeof(uint8_t) + j);
}
}
address += custom_configs[i].len;
}
DEBUG_PRINT("Restored from EEPROM: 0x");
DEBUG_PRINTLN(address, HEX);
}
uint16_t ESPKNXIP::__ntohs(uint16_t n)
{
return (uint16_t)((((uint8_t*)&n)[0] << 8) | (((uint8_t*)&n)[1]));
}
callback_assignment_id_t ESPKNXIP::__callback_register_assignment(address_t address, callback_id_t id)
{
if (registered_callback_assignments >= MAX_CALLBACK_ASSIGNMENTS)
return -1;
if (free_callback_assignment_slots == 0)
{
callback_assignment_id_t aid = registered_callback_assignments;
callback_assignments[aid].slot_flags |= SLOT_FLAGS_USED;
callback_assignments[aid].address = address;
callback_assignments[aid].callback_id = id;
registered_callback_assignments++;
return aid;
}
else
{
// find the free slot
for (callback_assignment_id_t aid = 0; aid < registered_callback_assignments; ++aid)
{
if (callback_assignments[aid].slot_flags & SLOT_FLAGS_USED)
{
// found a used slot
continue;
}
// and now an empty one
callback_assignments[aid].slot_flags |= SLOT_FLAGS_USED;
callback_assignments[aid].address = address;
callback_assignments[aid].callback_id = id;
free_callback_assignment_slots--;
return id;
}
}
}
void ESPKNXIP::__callback_delete_assignment(callback_assignment_id_t id)
{
// TODO this can be optimized if we are deleting the last element
// as then we can decrement registered_callback_assignments
// clear slot and mark it as empty
callback_assignments[id].slot_flags = SLOT_FLAGS_EMPTY;
callback_assignments[id].address.value = 0;
callback_assignments[id].callback_id = 0;
if (id == registered_callback_assignments - 1)
{
DEBUG_PRINTLN("last cba deleted");
// If this is the last callback, we can delete it by decrementing registered_callbacks.
registered_callback_assignments--;
// However, if the assignment before this slot are also empty, we can decrement even further
// First check if this was also the first element
if (id == 0)
{
DEBUG_PRINTLN("really last cba");
// If this was the last, then we are done.
return;
}
id--;
while(true)
{
DEBUG_PRINT("checking ");
DEBUG_PRINTLN((int32_t)id);
if ((callback_assignments[id].slot_flags & SLOT_FLAGS_USED) == 0)
{
DEBUG_PRINTLN("merged free slot");
// Slot before is empty
free_callback_assignment_slots--;
registered_callback_assignments--;
}
else
{
DEBUG_PRINTLN("aborted on used slot");
// Slot is used, abort
return;
}
id--;
if (id == CALLBACK_ASSIGNMENT_ID_MAX)
{
DEBUG_PRINTLN("abort on wrap");
// Wrap around, abort
return;
}
}
}
else
{
DEBUG_PRINTLN("free slot created");
// there is now one more free slot
free_callback_assignment_slots++;
}
}
bool ESPKNXIP::__callback_is_id_valid(callback_id_t id)
{
if (id < registered_callbacks)
return true;
if (callbacks[id].slot_flags & SLOT_FLAGS_USED)
return true;
return false;
}
callback_id_t ESPKNXIP::callback_register(String name, callback_fptr_t cb, void *arg, enable_condition_t cond)
{
if (registered_callbacks >= MAX_CALLBACKS)
return -1;
if (free_callback_slots == 0)
{
callback_id_t id = registered_callbacks;
callbacks[id].slot_flags |= SLOT_FLAGS_USED;
callbacks[id].name = name;
callbacks[id].fkt = cb;
callbacks[id].cond = cond;
callbacks[id].arg = arg;
registered_callbacks++;
return id;
}
else
{
// find the free slot
for (callback_id_t id = 0; id < registered_callbacks; ++id)
{
if (callbacks[id].slot_flags & SLOT_FLAGS_USED)
{
// found a used slot
continue;
}
// and now an empty one
callbacks[id].slot_flags |= SLOT_FLAGS_USED;
callbacks[id].name = name;
callbacks[id].fkt = cb;
callbacks[id].cond = cond;
callbacks[id].arg = arg;
free_callback_slots--;
return id;
}
}
}
void ESPKNXIP::callback_deregister(callback_id_t id)
{
if (!__callback_is_id_valid(id))
return;
// clear slot and mark it as empty
callbacks[id].slot_flags = SLOT_FLAGS_EMPTY;
callbacks[id].fkt = nullptr;
callbacks[id].cond = nullptr;
callbacks[id].arg = nullptr;
if (id == registered_callbacks - 1)
{
// If this is the last callback, we can delete it by decrementing registered_callbacks.
registered_callbacks--;
// However, if the callbacks before this slot are also empty, we can decrement even further
// First check if this was also the first element
if (id == 0)
{
// If this was the last, then we are done.
return;
}
id--;
while(true)
{
if ((callbacks[id].slot_flags & SLOT_FLAGS_USED) == 0)
{
// Slot is empty
free_callback_slots--;
registered_callbacks--;
}
else
{
// Slot is used, abort
return;
}
id--;
if (id == CALLBACK_ASSIGNMENT_ID_MAX)
{
// Wrap around, abort
return;
}
}
}
else
{
// there is now one more free slot
free_callback_slots++;
}
}
callback_assignment_id_t ESPKNXIP::callback_assign(callback_id_t id, address_t val)
{
if (!__callback_is_id_valid(id))
return -1;
return __callback_register_assignment(val, id);
}
void ESPKNXIP::callback_unassign(callback_assignment_id_t id)
{
if (!__callback_is_id_valid(id))
return;
__callback_delete_assignment(id);
}
/**
* Feedback functions start here
*/
feedback_id_t ESPKNXIP::feedback_register_int(String name, int32_t *value, enable_condition_t cond)
{
if (registered_feedbacks >= MAX_FEEDBACKS)
return -1;
feedback_id_t id = registered_feedbacks;
feedbacks[id].type = FEEDBACK_TYPE_INT;
feedbacks[id].name = name;
feedbacks[id].cond = cond;
feedbacks[id].data = (void *)value;
registered_feedbacks++;
return id;
}
feedback_id_t ESPKNXIP::feedback_register_float(String name, float *value, uint8_t precision, char const *prefix, char const *suffix, enable_condition_t cond)
{
if (registered_feedbacks >= MAX_FEEDBACKS)
return -1;
feedback_id_t id = registered_feedbacks;
feedbacks[id].type = FEEDBACK_TYPE_FLOAT;
feedbacks[id].name = name;
feedbacks[id].cond = cond;
feedbacks[id].data = (void *)value;
feedbacks[id].options.float_options.precision = precision;
feedbacks[id].options.float_options.prefix = prefix ? strdup(prefix) : STRING_DEFAULT_EMPTY;
feedbacks[id].options.float_options.suffix = suffix ? strdup(suffix) : STRING_DEFAULT_EMPTY;
registered_feedbacks++;
return id;
}
feedback_id_t ESPKNXIP::feedback_register_bool(String name, bool *value, char const *true_text, char const *false_text, enable_condition_t cond)
{
if (registered_feedbacks >= MAX_FEEDBACKS)
return -1;
feedback_id_t id = registered_feedbacks;
feedbacks[id].type = FEEDBACK_TYPE_BOOL;
feedbacks[id].name = name;
feedbacks[id].cond = cond;
feedbacks[id].data = (void *)value;
feedbacks[id].options.bool_options.true_text = true_text ? strdup(true_text) : STRING_DEFAULT_TRUE;
feedbacks[id].options.bool_options.false_text = false_text ? strdup(false_text) : STRING_DEFAULT_FALSE;
registered_feedbacks++;
return id;
}
feedback_id_t ESPKNXIP::feedback_register_action(String name, feedback_action_fptr_t value, const char *btn_text, void *arg, enable_condition_t cond)
{
if (registered_feedbacks >= MAX_FEEDBACKS)
return -1;
feedback_id_t id = registered_feedbacks;
feedbacks[id].type = FEEDBACK_TYPE_ACTION;
feedbacks[id].name = name;
feedbacks[id].cond = cond;
feedbacks[id].data = (void *)value;
feedbacks[id].options.action_options.arg = arg;
feedbacks[id].options.action_options.btn_text = btn_text ? strdup(btn_text) : STRING_DEFAULT_DO_THIS;
registered_feedbacks++;
return id;
}
void ESPKNXIP::loop()
{
__loop_knx();
if (server != nullptr)
{
__loop_webserver();
}
}
void ESPKNXIP::__loop_webserver()
{
server->handleClient();
}
void ESPKNXIP::__loop_knx()
{
int read = udp.parsePacket();
if (!read)
{
return;
}
DEBUG_PRINTLN(F(""));
DEBUG_PRINT(F("LEN: "));
DEBUG_PRINTLN(read);
uint8_t buf[read];
udp.read(buf, read);
udp.flush();
DEBUG_PRINT(F("Got packet:"));
#ifdef ESP_KNX_DEBUG
for (int i = 0; i < read; ++i)
{
DEBUG_PRINT(F(" 0x"));
DEBUG_PRINT(buf[i], 16);
}
#endif
DEBUG_PRINTLN(F(""));
knx_ip_pkt_t *knx_pkt = (knx_ip_pkt_t *)buf;
DEBUG_PRINT(F("ST: 0x"));
DEBUG_PRINTLN(__ntohs(knx_pkt->service_type), 16);
if (knx_pkt->header_len != 0x06 && knx_pkt->protocol_version != 0x10 && knx_pkt->service_type != KNX_ST_ROUTING_INDICATION)
return;
cemi_msg_t *cemi_msg = (cemi_msg_t *)knx_pkt->pkt_data;
DEBUG_PRINT(F("MT: 0x"));
DEBUG_PRINTLN(cemi_msg->message_code, 16);
if (cemi_msg->message_code != KNX_MT_L_DATA_IND)
return;
DEBUG_PRINT(F("ADDI: 0x"));
DEBUG_PRINTLN(cemi_msg->additional_info_len, 16);
cemi_service_t *cemi_data = &cemi_msg->data.service_information;
if (cemi_msg->additional_info_len > 0)
cemi_data = (cemi_service_t *)(((uint8_t *)cemi_data) + cemi_msg->additional_info_len);
DEBUG_PRINT(F("C1: 0x"));
DEBUG_PRINTLN(cemi_data->control_1.byte, 16);
DEBUG_PRINT(F("C2: 0x"));
DEBUG_PRINTLN(cemi_data->control_2.byte, 16);
DEBUG_PRINT(F("DT: 0x"));
DEBUG_PRINTLN(cemi_data->control_2.bits.dest_addr_type, 16);
if (cemi_data->control_2.bits.dest_addr_type != 0x01)
return;
DEBUG_PRINT(F("HC: 0x"));
DEBUG_PRINTLN(cemi_data->control_2.bits.hop_count, 16);
DEBUG_PRINT(F("EFF: 0x"));
DEBUG_PRINTLN(cemi_data->control_2.bits.extended_frame_format, 16);
DEBUG_PRINT(F("Source: 0x"));
DEBUG_PRINT(cemi_data->source.bytes.high, 16);
DEBUG_PRINT(F(" 0x"));
DEBUG_PRINTLN(cemi_data->source.bytes.low, 16);
DEBUG_PRINT(F("Dest: 0x"));
DEBUG_PRINT(cemi_data->destination.bytes.high, 16);
DEBUG_PRINT(F(" 0x"));
DEBUG_PRINTLN(cemi_data->destination.bytes.low, 16);
knx_command_type_t ct = (knx_command_type_t)(((cemi_data->data[0] & 0xC0) >> 6) | ((cemi_data->pci.apci & 0x03) << 2));
DEBUG_PRINT(F("CT: 0x"));
DEBUG_PRINTLN(ct, 16);
#ifdef ESP_KNX_DEBUG
for (int i = 0; i < cemi_data->data_len; ++i)
{
DEBUG_PRINT(F(" 0x"));
DEBUG_PRINT(cemi_data->data[i], 16);
}
#endif
DEBUG_PRINTLN(F("=="));
// Call callbacks
for (int i = 0; i < registered_callback_assignments; ++i)
{
DEBUG_PRINT(F("Testing: 0x"));
DEBUG_PRINT(callback_assignments[i].address.bytes.high, 16);
DEBUG_PRINT(F(" 0x"));
DEBUG_PRINTLN(callback_assignments[i].address.bytes.low, 16);
if (cemi_data->destination.value == callback_assignments[i].address.value)
{
DEBUG_PRINTLN(F("Found match"));
if (callbacks[callback_assignments[i].callback_id].cond && !callbacks[callback_assignments[i].callback_id].cond())
{
DEBUG_PRINTLN(F("But it's disabled"));
#if ALLOW_MULTIPLE_CALLBACKS_PER_ADDRESS
continue;
#else
return;
#endif
}
uint8_t data[cemi_data->data_len];
memcpy(data, cemi_data->data, cemi_data->data_len);
data[0] = data[0] & 0x3F;
message_t msg = {};
msg.ct = ct;
msg.received_on = cemi_data->destination;
msg.data_len = cemi_data->data_len;
msg.data = data;
callbacks[callback_assignments[i].callback_id].fkt(msg, callbacks[callback_assignments[i].callback_id].arg);
#if ALLOW_MULTIPLE_CALLBACKS_PER_ADDRESS
continue;
#else
return;
#endif
}
}
return;
}
// Global "singleton" object
ESPKNXIP knx;

View File

@ -0,0 +1,571 @@
/**
* esp-knx-ip library for KNX/IP communication on an ESP8266
* Author: Nico Weichbrodt <envy>
* License: MIT
*/
#ifndef ESP_KNX_IP_H
#define ESP_KNX_IP_H
/**
* CONFIG
* All MAX_ values must not exceed 255 (1 byte, except MAC_CONFIG_SPACE which can go up to 2 bytes, so 0xffff in theory) and must not be negative!
* Config space is restriced by EEPROM_SIZE (default 1024).
* Required EEPROM size is 8 + MAX_GA_CALLBACKS * 3 + 2 + MAX_CONFIG_SPACE which is 552 by default
*/
#define EEPROM_SIZE 1024 // [Default 1024]
#define MAX_CALLBACK_ASSIGNMENTS 10 // [Default 10] Maximum number of group address callbacks that can be stored
#define MAX_CALLBACKS 10 // [Default 10] Maximum number of callbacks that can be stored
#define MAX_CONFIGS 20 // [Default 20] Maximum number of config items that can be stored
#define MAX_CONFIG_SPACE 0x0200 // [Default 0x0200] Maximum number of bytes that can be stored for custom config
#define MAX_FEEDBACKS 20 // [Default 20] Maximum number of feedbacks that can be shown
// Callbacks
#define ALLOW_MULTIPLE_CALLBACKS_PER_ADDRESS 1 // [Default 0] Set to 1 to always test all assigned callbacks. This allows for multiple callbacks being assigned to the same address. If disabled, only the first assigned will be called.
// Webserver related
#define USE_BOOTSTRAP 1 // [Default 1] Set to 1 to enable use of bootstrap CSS for nicer webconfig. CSS is loaded from bootstrapcdn.com. Set to 0 to disable
#define ROOT_PREFIX "" // [Default ""] This gets prepended to all webserver paths, default is empty string "". Set this to "/knx" if you want the config to be available on http://<ip>/knx
#define DISABLE_EEPROM_BUTTONS 1 // [Default 0] Set to 1 to disable the EEPROM buttons in the web ui.
#define DISABLE_REBOOT_BUTTON 1 // [Default 0] Set to 1 to disable the reboot button in the web ui.
#define DISABLE_RESTORE_BUTTON 1 // [Default 0] Set to 1 to disable the "restore defaults" button in the web ui.
// These values normally don't need adjustment
#define MULTICAST_PORT 3671 // [Default 3671]
#define MULTICAST_IP IPAddress(224, 0, 23, 12) // [Default IPAddress(224, 0, 23, 12)]
#define SEND_CHECKSUM 0
// Uncomment to enable printing out debug messages.
//#define ESP_KNX_DEBUG
/**
* END CONFIG
*/
#include "Arduino.h"
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include "DPT.h"
#define EEPROM_MAGIC (0xDEADBEEF00000000 + (MAX_CONFIG_SPACE) + (MAX_CALLBACK_ASSIGNMENTS << 16) + (MAX_CALLBACKS << 8))
// Define where debug output will be printed.
#ifndef DEBUG_PRINTER
#define DEBUG_PRINTER Serial
#endif
// Setup debug printing macros.
#ifdef ESP_KNX_DEBUG
#define DEBUG_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); }
#define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); }
#else
#define DEBUG_PRINT(...) {}
#define DEBUG_PRINTLN(...) {}
#endif
#define __ROOT_PATH ROOT_PREFIX"/"
#define __REGISTER_PATH ROOT_PREFIX"/register"
#define __DELETE_PATH ROOT_PREFIX"/delete"
#define __PHYS_PATH ROOT_PREFIX"/phys"
#define __EEPROM_PATH ROOT_PREFIX"/eeprom"
#define __CONFIG_PATH ROOT_PREFIX"/config"
#define __FEEDBACK_PATH ROOT_PREFIX"/feedback"
#define __RESTORE_PATH ROOT_PREFIX"/restore"
#define __REBOOT_PATH ROOT_PREFIX"/reboot"
/**
* Different service types, we are mainly interested in KNX_ST_ROUTING_INDICATION
*/
typedef enum __knx_service_type
{
KNX_ST_SEARCH_REQUEST = 0x0201,
KNX_ST_SEARCH_RESPONSE = 0x0202,
KNX_ST_DESCRIPTION_REQUEST = 0x0203,
KNX_ST_DESCRIPTION_RESPONSE = 0x0204,
KNX_ST_CONNECT_REQUEST = 0x0205,
KNX_ST_CONNECT_RESPONSE = 0x0206,
KNX_ST_CONNECTIONSTATE_REQUEST = 0x0207,
KNX_ST_CONNECTIONSTATE_RESPONSE = 0x0208,
KNX_ST_DISCONNECT_REQUEST = 0x0209,
KNX_ST_DISCONNECT_RESPONSE = 0x020A,
KNX_ST_DEVICE_CONFIGURATION_REQUEST = 0x0310,
KNX_ST_DEVICE_CONFIGURATION_ACK = 0x0311,
KNX_ST_TUNNELING_REQUEST = 0x0420,
KNX_ST_TUNNELING_ACK = 0x0421,
KNX_ST_ROUTING_INDICATION = 0x0530,
KNX_ST_ROUTING_LOST_MESSAGE = 0x0531,
KNX_ST_ROUTING_BUSY = 0x0532,
// KNX_ST_RLOG_START = 0x0600,
// KNX_ST_RLOG_END = 0x06FF,
KNX_ST_REMOTE_DIAGNOSTIC_REQUEST = 0x0740,
KNX_ST_REMOTE_DIAGNOSTIC_RESPONSE = 0x0741,
KNX_ST_REMOTE_BASIC_CONFIGURATION_REQUEST = 0x0742,
KNX_ST_REMOTE_RESET_REQUEST = 0x0743,
// KNX_ST_OBJSRV_START = 0x0800,
// KNX_ST_OBJSRV_END = 0x08FF,
} knx_service_type_t;
/**
* Differnt command types, first three are of main interest
*/
typedef enum __knx_command_type
{
KNX_CT_READ = 0x00,
KNX_CT_ANSWER = 0x01,
KNX_CT_WRITE = 0x02,
KNX_CT_INDIVIDUAL_ADDR_WRITE = 0x03,
KNX_CT_INDIVIDUAL_ADDR_REQUEST = 0x04,
KNX_CT_INDIVIDUAL_ADDR_RESPONSE = 0x05,
KNX_CT_ADC_READ = 0x06,
KNX_CT_ADC_ANSWER = 0x07,
KNX_CT_MEM_READ = 0x08,
KNX_CT_MEM_ANSWER = 0x09,
KNX_CT_MEM_WRITE = 0x0A,
//KNX_CT_UNKNOWN = 0x0B,
KNX_CT_MASK_VERSION_READ = 0x0C,
KNX_CT_MASK_VERSION_RESPONSE = 0x0D,
KNX_CT_RESTART = 0x0E,
KNX_CT_ESCAPE = 0x0F,
} knx_command_type_t;
/**
* cEMI message types, mainly KNX_MT_L_DATA_IND is interesting
*/
typedef enum __knx_cemi_msg_type
{
KNX_MT_L_DATA_REQ = 0x11,
KNX_MT_L_DATA_IND = 0x29,
KNX_MT_L_DATA_CON = 0x2E,
} knx_cemi_msg_type_t;
/**
* TCPI communication type
*/
typedef enum __knx_communication_type {
KNX_COT_UDP = 0x00, // Unnumbered Data Packet
KNX_COT_NDP = 0x01, // Numbered Data Packet
KNX_COT_UCD = 0x02, // Unnumbered Control Data
KNX_COT_NCD = 0x03, // Numbered Control Data
} knx_communication_type_t;
/**
* KNX/IP header
*/
typedef struct __knx_ip_pkt
{
uint8_t header_len; // Should always be 0x06
uint8_t protocol_version; // Should be version 1.0, transmitted as 0x10
uint16_t service_type; // See knx_service_type_t
union
{
struct {
uint8_t first_byte;
uint8_t second_byte;
} bytes;
uint16_t len;
} total_len; // header_len + rest of pkt. This is a bit weird as the spec says this: If the total number of bytes transmitted is greater than 252 bytes, the first “Total Length” byte is set to FF (255). Only in this case the second byte includes additional length information
uint8_t pkt_data[]; // This is of type cemi_msg_t
} knx_ip_pkt_t;
typedef struct __cemi_addi
{
uint8_t type_id;
uint8_t len;
uint8_t data[];
} cemi_addi_t;
typedef union __address
{
uint16_t value;
struct
{
uint8_t high;
uint8_t low;
} bytes;
struct __attribute__((packed))
{
uint8_t line:3;
uint8_t area:5;
uint8_t member;
} ga;
struct __attribute__((packed))
{
uint8_t line:4;
uint8_t area:4;
uint8_t member;
} pa;
uint8_t array[2];
} address_t;
typedef struct __cemi_service
{
union
{
struct
{
// Struct is reversed due to bit order
uint8_t confirm:1; // 0 = no error, 1 = error
uint8_t ack:1; // 0 = no ack, 1 = ack
uint8_t priority:2; // 0 = system, 1 = high, 2 = urgent/alarm, 3 = normal
uint8_t system_broadcast:1; // 0 = system broadcast, 1 = broadcast
uint8_t repeat:1; // 0 = repeat on error, 1 = do not repeat
uint8_t reserved:1; // always zero
uint8_t frame_type:1; // 0 = extended, 1 = standard
} bits;
uint8_t byte;
} control_1;
union
{
struct
{
// Struct is reversed due to bit order
uint8_t extended_frame_format:4;
uint8_t hop_count:3;
uint8_t dest_addr_type:1; // 0 = individual, 1 = group
} bits;
uint8_t byte;
} control_2;
address_t source;
address_t destination;
uint8_t data_len; // length of data, excluding the tpci byte
struct
{
uint8_t apci:2; // If tpci.comm_type == KNX_COT_UCD or KNX_COT_NCD, then this is apparently control data?
uint8_t tpci_seq_number:4;
uint8_t tpci_comm_type:2; // See knx_communication_type_t
} pci;
uint8_t data[];
} cemi_service_t;
typedef struct __cemi_msg
{
uint8_t message_code;
uint8_t additional_info_len;
union
{
cemi_addi_t additional_info[];
cemi_service_t service_information;
} data;
} cemi_msg_t;
typedef enum __config_type
{
CONFIG_TYPE_UNKNOWN,
CONFIG_TYPE_INT,
CONFIG_TYPE_BOOL,
CONFIG_TYPE_STRING,
CONFIG_TYPE_OPTIONS,
CONFIG_TYPE_GA,
} config_type_t;
typedef enum __feedback_type
{
FEEDBACK_TYPE_UNKNOWN,
FEEDBACK_TYPE_INT,
FEEDBACK_TYPE_FLOAT,
FEEDBACK_TYPE_BOOL,
FEEDBACK_TYPE_ACTION,
} feedback_type_t;
typedef enum __config_flags
{
CONFIG_FLAGS_NO_FLAGS = 0,
CONFIG_FLAGS_VALUE_SET = 1,
} config_flags_t;
typedef enum __slot_flags
{
SLOT_FLAGS_EMPTY = 0, // Empty slots have no flags
SLOT_FLAGS_USED = 1,
} slot_flags_t;
typedef struct __message
{
knx_command_type_t ct;
address_t received_on;
uint8_t data_len;
uint8_t *data;
} message_t;
typedef bool (*enable_condition_t)(void);
typedef void (*callback_fptr_t)(message_t const &msg, void *arg);
typedef void (*feedback_action_fptr_t)(void *arg);
typedef uint8_t callback_id_t;
#define CALLBACK_ID_MAX UINT8_MAX
typedef uint8_t callback_assignment_id_t;
#define CALLBACK_ASSIGNMENT_ID_MAX UINT8_MAX
typedef uint8_t config_id_t;
typedef uint8_t feedback_id_t;
typedef struct __option_entry
{
char const *name;
uint8_t value;
} option_entry_t;
typedef struct __config
{
config_type_t type;
String name;
uint8_t offset;
uint8_t len;
enable_condition_t cond;
union {
option_entry_t *options;
} data;
} config_t;
extern char const *string_defaults[];
#define STRING_DEFAULT_DO_THIS (string_defaults[0])
#define STRING_DEFAULT_TRUE (string_defaults[1])
#define STRING_DEFAULT_FALSE (string_defaults[2])
#define STRING_DEFAULT_EMPTY (string_defaults[3])
typedef struct __feedback_float_options
{
uint8_t precision;
char const *prefix;
char const *suffix;
} feedback_float_options_t;
typedef struct __feedback_bool_options
{
char const *true_text;
char const *false_text;
} feedback_bool_options_t;
typedef struct __feedback_action_options
{
void *arg;
char const *btn_text;
} feedback_action_options_t;
typedef struct __feedback
{
feedback_type_t type;
String name;
enable_condition_t cond;
void *data;
union {
feedback_bool_options_t bool_options;
feedback_float_options_t float_options;
feedback_action_options_t action_options;
} options;
} feedback_t;
typedef struct __callback
{
uint8_t slot_flags;
callback_fptr_t fkt;
enable_condition_t cond;
void *arg;
String name;
} callback_t;
typedef struct __callback_assignment
{
uint8_t slot_flags;
address_t address;
callback_id_t callback_id;
} callback_assignment_t;
class ESPKNXIP {
public:
ESPKNXIP();
void load();
void start();
void start(ESP8266WebServer *srv);
void loop();
void save_to_eeprom();
void restore_from_eeprom();
callback_id_t callback_register(String name, callback_fptr_t cb, void *arg = nullptr, enable_condition_t cond = nullptr);
callback_assignment_id_t callback_assign(callback_id_t id, address_t val);
void callback_deregister(callback_id_t id);
void callback_unassign(callback_assignment_id_t id);
void physical_address_set(address_t const &addr);
address_t physical_address_get();
// Configuration functions
config_id_t config_register_string(String name, uint8_t len, String _default, enable_condition_t cond = nullptr);
config_id_t config_register_int(String name, int32_t _default, enable_condition_t cond = nullptr);
config_id_t config_register_bool(String name, bool _default, enable_condition_t cond = nullptr);
config_id_t config_register_options(String name, option_entry_t *options, uint8_t _default, enable_condition_t cond = nullptr);
config_id_t config_register_ga(String name, enable_condition_t cond = nullptr);
String config_get_string(config_id_t id);
int32_t config_get_int(config_id_t id);
bool config_get_bool(config_id_t id);
uint8_t config_get_options(config_id_t id);
address_t config_get_ga(config_id_t id);
void config_set_string(config_id_t id, String val);
void config_set_int(config_id_t id, int32_t val);
void config_set_bool(config_id_t, bool val);
void config_set_options(config_id_t id, uint8_t val);
void config_set_ga(config_id_t id, address_t const &val);
// Feedback functions
feedback_id_t feedback_register_int(String name, int32_t *value, enable_condition_t cond = nullptr);
feedback_id_t feedback_register_float(String name, float *value, uint8_t precision = 2, char const *prefix = nullptr, char const *suffix = nullptr, enable_condition_t cond = nullptr);
feedback_id_t feedback_register_bool(String name, bool *value, char const *true_text = nullptr, char const *false_text = nullptr, enable_condition_t cond = nullptr);
feedback_id_t feedback_register_action(String name, feedback_action_fptr_t value, char const *btn_text = nullptr, void *arg = nullptr, enable_condition_t = nullptr);
// Send functions
void send(address_t const &receiver, knx_command_type_t ct, uint8_t data_len, uint8_t *data);
void send_1bit(address_t const &receiver, knx_command_type_t ct, uint8_t bit);
void send_2bit(address_t const &receiver, knx_command_type_t ct, uint8_t twobit);
void send_4bit(address_t const &receiver, knx_command_type_t ct, uint8_t fourbit);
void send_1byte_int(address_t const &receiver, knx_command_type_t ct, int8_t val);
void send_1byte_uint(address_t const &receiver, knx_command_type_t ct, uint8_t val);
void send_2byte_int(address_t const &receiver, knx_command_type_t ct, int16_t val);
void send_2byte_uint(address_t const &receiver, knx_command_type_t ct, uint16_t val);
void send_2byte_float(address_t const &receiver, knx_command_type_t ct, float val);
void send_3byte_time(address_t const &receiver, knx_command_type_t ct, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds);
void send_3byte_time(address_t const &receiver, knx_command_type_t ct, time_of_day_t const &time) { send_3byte_time(receiver, ct, time.weekday, time.hours, time.minutes, time.seconds); }
void send_3byte_date(address_t const &receiver, knx_command_type_t ct, uint8_t day, uint8_t month, uint8_t year);
void send_3byte_date(address_t const &receiver, knx_command_type_t ct, date_t const &date) { send_3byte_date(receiver, ct, date.day, date.month, date.year); }
void send_3byte_color(address_t const &receiver, knx_command_type_t ct, uint8_t red, uint8_t green, uint8_t blue);
void send_3byte_color(address_t const &receiver, knx_command_type_t ct, color_t const &color) { send_3byte_color(receiver, ct, color.red, color.green, color.blue); }
void send_4byte_int(address_t const &receiver, knx_command_type_t ct, int32_t val);
void send_4byte_uint(address_t const &receiver, knx_command_type_t ct, uint32_t val);
void send_4byte_float(address_t const &receiver, knx_command_type_t ct, float val);
void write_1bit(address_t const &receiver, uint8_t bit) { send_1bit(receiver, KNX_CT_WRITE, bit); }
void write_2bit(address_t const &receiver, uint8_t twobit) { send_2bit(receiver, KNX_CT_WRITE, twobit); }
void write_4bit(address_t const &receiver, uint8_t fourbit) { send_4bit(receiver, KNX_CT_WRITE, fourbit); }
void write_1byte_int(address_t const &receiver, int8_t val) { send_1byte_int(receiver, KNX_CT_WRITE, val); }
void write_1byte_uint(address_t const &receiver, uint8_t val) { send_1byte_uint(receiver, KNX_CT_WRITE, val); }
void write_2byte_int(address_t const &receiver, int16_t val) { send_2byte_int(receiver, KNX_CT_WRITE, val); }
void write_2byte_uint(address_t const &receiver, uint16_t val) { send_2byte_uint(receiver, KNX_CT_WRITE, val); }
void write_2byte_float(address_t const &receiver, float val) { send_2byte_float(receiver, KNX_CT_WRITE, val); }
void write_3byte_time(address_t const &receiver, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds) { send_3byte_time(receiver, KNX_CT_WRITE, weekday, hours, minutes, seconds); }
void write_3byte_time(address_t const &receiver, time_of_day_t const &time) { send_3byte_time(receiver, KNX_CT_WRITE, time.weekday, time.hours, time.minutes, time.seconds); }
void write_3byte_date(address_t const &receiver, uint8_t day, uint8_t month, uint8_t year) { send_3byte_date(receiver, KNX_CT_WRITE, day, month, year); }
void write_3byte_date(address_t const &receiver, date_t const &date) { send_3byte_date(receiver, KNX_CT_WRITE, date.day, date.month, date.year); }
void write_3byte_color(address_t const &receiver, uint8_t red, uint8_t green, uint8_t blue) { send_3byte_color(receiver, KNX_CT_WRITE, red, green, blue); }
void write_3byte_color(address_t const &receiver, color_t const &color) { send_3byte_color(receiver, KNX_CT_WRITE, color); }
void write_4byte_int(address_t const &receiver, int32_t val) { send_4byte_int(receiver, KNX_CT_WRITE, val); }
void write_4byte_uint(address_t const &receiver, uint32_t val) { send_4byte_uint(receiver, KNX_CT_WRITE, val); }
void write_4byte_float(address_t const &receiver, float val) { send_4byte_float(receiver, KNX_CT_WRITE, val);}
void answer_1bit(address_t const &receiver, uint8_t bit) { send_1bit(receiver, KNX_CT_ANSWER, bit); }
void answer_2bit(address_t const &receiver, uint8_t twobit) { send_2bit(receiver, KNX_CT_ANSWER, twobit); }
void answer_4bit(address_t const &receiver, uint8_t fourbit) { send_4bit(receiver, KNX_CT_ANSWER, fourbit); }
void answer_1byte_int(address_t const &receiver, int8_t val) { send_1byte_int(receiver, KNX_CT_ANSWER, val); }
void answer_1byte_uint(address_t const &receiver, uint8_t val) { send_1byte_uint(receiver, KNX_CT_ANSWER, val); }
void answer_2byte_int(address_t const &receiver, int16_t val) { send_2byte_int(receiver, KNX_CT_ANSWER, val); }
void answer_2byte_uint(address_t const &receiver, uint16_t val) { send_2byte_uint(receiver, KNX_CT_ANSWER, val); }
void answer_2byte_float(address_t const &receiver, float val) { send_2byte_float(receiver, KNX_CT_ANSWER, val); }
void answer_3byte_time(address_t const &receiver, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds) { send_3byte_time(receiver, KNX_CT_ANSWER, weekday, hours, minutes, seconds); }
void answer_3byte_time(address_t const &receiver, time_of_day_t const &time) { send_3byte_time(receiver, KNX_CT_ANSWER, time.weekday, time.hours, time.minutes, time.seconds); }
void answer_3byte_date(address_t const &receiver, uint8_t day, uint8_t month, uint8_t year) { send_3byte_date(receiver, KNX_CT_ANSWER, day, month, year); }
void answer_3byte_date(address_t const &receiver, date_t const &date) { send_3byte_date(receiver, KNX_CT_ANSWER, date.day, date.month, date.year); }
void answer_3byte_color(address_t const &receiver, uint8_t red, uint8_t green, uint8_t blue) { send_3byte_color(receiver, KNX_CT_ANSWER, red, green, blue); }
void answer_3byte_color(address_t const &receiver, color_t const &color) { send_3byte_color(receiver, KNX_CT_ANSWER, color); }
void answer_4byte_int(address_t const &receiver, int32_t val) { send_4byte_int(receiver, KNX_CT_ANSWER, val); }
void answer_4byte_uint(address_t const &receiver, uint32_t val) { send_4byte_uint(receiver, KNX_CT_ANSWER, val); }
void answer_4byte_float(address_t const &receiver, float val) { send_4byte_float(receiver, KNX_CT_ANSWER, val);}
bool data_to_bool(uint8_t *data);
int8_t data_to_1byte_int(uint8_t *data);
uint8_t data_to_1byte_uint(uint8_t *data);
int16_t data_to_2byte_int(uint8_t *data);
uint16_t data_to_2byte_uint(uint8_t *data);
float data_to_2byte_float(uint8_t *data);
color_t data_to_3byte_color(uint8_t *data);
time_of_day_t data_to_3byte_time(uint8_t *data);
date_t data_to_3byte_data(uint8_t *data);
int32_t data_to_4byte_int(uint8_t *data);
uint32_t data_to_4byte_uint(uint8_t *data);
float data_to_4byte_float(uint8_t *data);
static address_t GA_to_address(uint8_t area, uint8_t line, uint8_t member)
{
// Yes, the order is correct, see the struct definition above
address_t tmp = {.ga={line, area, member}};
return tmp;
}
static address_t PA_to_address(uint8_t area, uint8_t line, uint8_t member)
{
// Yes, the order is correct, see the struct definition above
address_t tmp = {.pa={line, area, member}};
return tmp;
}
private:
void __start();
void __loop_knx();
// Webserver functions
void __loop_webserver();
void __handle_root();
void __handle_register();
void __handle_delete();
void __handle_set();
#if !DISABLE_EEPROM_BUTTONS
void __handle_eeprom();
#endif
void __handle_config();
void __handle_feedback();
#if !DISABLE_RESTORE_BUTTONS
void __handle_restore();
#endif
#if !DISABLE_REBOOT_BUTTONS
void __handle_reboot();
#endif
void __config_set_flags(config_id_t id, config_flags_t flags);
void __config_set_string(config_id_t id, String &val);
void __config_set_int(config_id_t id, int32_t val);
void __config_set_bool(config_id_t id, bool val);
void __config_set_options(config_id_t id, uint8_t val);
void __config_set_ga(config_id_t id, address_t const &val);
bool __callback_is_id_valid(callback_id_t id);
callback_assignment_id_t __callback_register_assignment(address_t address, callback_id_t id);
void __callback_delete_assignment(callback_assignment_id_t id);
ESP8266WebServer *server;
address_t physaddr;
WiFiUDP udp;
callback_assignment_id_t registered_callback_assignments;
callback_assignment_id_t free_callback_assignment_slots;
callback_assignment_t callback_assignments[MAX_CALLBACK_ASSIGNMENTS];
callback_id_t registered_callbacks;
callback_id_t free_callback_slots;
callback_t callbacks[MAX_CALLBACKS];
config_id_t registered_configs;
uint8_t custom_config_data[MAX_CONFIG_SPACE];
uint8_t custom_config_default_data[MAX_CONFIG_SPACE];
config_t custom_configs[MAX_CONFIGS];
feedback_id_t registered_feedbacks;
feedback_t feedbacks[MAX_FEEDBACKS];
uint16_t __ntohs(uint16_t);
};
// Global "singleton" object
extern ESPKNXIP knx;
#endif

View File

@ -0,0 +1,159 @@
/*
* This is an example showing a simple environment sensor based on a BME280 attached via I2C.
* This sketch was tested on a WeMos D1 mini
*/
#include <Adafruit_BME280.h>
#include <esp-knx-ip.h>
// WiFi config here
const char* ssid = "myssid";
const char* pass = "mypassword";
#define LED_PIN D4
#define UPDATE_INTERVAL 10000
unsigned long next_change = 0;
float last_temp = 0.0;
float last_hum = 0.0;
float last_pres = 0.0;
config_id_t temp_ga, hum_ga, pres_ga;
config_id_t hostname_id;
config_id_t update_rate_id, send_rate_id;
config_id_t enable_sending_id;
config_id_t enable_reading_id;
Adafruit_BME280 bme;
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
hostname_id = knx.config_register_string("Hostname", 20, String("env"));
enable_sending_id = knx.config_register_bool("Send on update", true);
update_rate_id = knx.config_register_int("Update rate (ms)", UPDATE_INTERVAL);
temp_ga = knx.config_register_ga("Temperature", show_periodic_options);
hum_ga = knx.config_register_ga("Humidity", show_periodic_options);
pres_ga = knx.config_register_ga("Pressure", show_periodic_options);
knx.callback_register("Read Temperature", temp_cb);
knx.callback_register("Read Humidity", hum_cb);
knx.callback_register("Read Pressure", pres_cb);
knx.feedback_register_float("Temperature (°C)", &last_temp);
knx.feedback_register_float("Humidity (%)", &last_hum);
knx.feedback_register_float("Pressure (hPa)", &last_pres, 0);
// Load previous config from EEPROM
knx.load();
// Init sensor
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
}
// Init WiFi
WiFi.hostname(knx.config_get_string(hostname_id));
WiFi.begin(ssid, pass);
Serial.println("");
Serial.print("[Connecting]");
Serial.print(ssid);
digitalWrite(LED_PIN, LOW);
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(LED_PIN, HIGH);
delay(250);
Serial.print(".");
digitalWrite(LED_PIN, LOW);
delay(250);
}
digitalWrite(LED_PIN, HIGH);
// Start knx
knx.start();
Serial.println();
Serial.println("Connected to wifi");
Serial.println(WiFi.localIP());
}
void loop() {
knx.loop();
unsigned long now = millis();
if (next_change < now)
{
next_change = now + knx.config_get_int(update_rate_id);
last_temp = bme.readTemperature();
last_hum = bme.readHumidity();
last_pres = bme.readPressure()/100.0f;
Serial.print("T: ");
Serial.print(last_temp);
Serial.print("°C H: ");
Serial.print(last_hum);
Serial.print("% P: ");
Serial.print(last_pres);
Serial.println("hPa");
if (knx.config_get_bool(enable_sending_id))
{
knx.write_2byte_float(knx.config_get_ga(temp_ga), last_temp);
knx.write_2byte_float(knx.config_get_ga(hum_ga), last_hum);
knx.write_2byte_float(knx.config_get_ga(pres_ga), last_pres);
}
}
delay(50);
}
bool show_periodic_options()
{
return knx.config_get_bool(enable_sending_id);
}
bool enable_reading_callback()
{
return knx.config_get_bool(enable_reading_id);
}
void temp_cb(message_t const &msg, void *arg)
{
switch (msg.ct)
{
case KNX_CT_READ:
{
knx.answer_2byte_float(msg.received_on, last_temp);
break;
}
}
}
void hum_cb(message_t const &msg, void *arg)
{
switch (msg.ct)
{
case KNX_CT_READ:
{
knx.answer_2byte_float(msg.received_on, last_hum);
break;
}
}
}
void pres_cb(message_t const &msg, void *arg)
{
switch (msg.ct)
{
case KNX_CT_READ:
{
knx.answer_2byte_float(msg.received_on, last_pres);
break;
}
}
}

View File

@ -0,0 +1,183 @@
#include <esp-knx-ip.h>
// WiFi config here
const char* ssid = "ssid";
const char* pass = "pass";
// Common
#define LED_PIN 13
// For Basic and S20
#define BTN1_PIN 0
#define CH1_PIN 12
// For 4CH
#define BTN2_PIN 9
#define CH2_PIN 5
#define BTN3_PIN 10
#define CH3_PIN 4
#define BTN4_PIN 14
#define CH4_PIN 15
typedef enum __type_option
{
SONOFF_TYPE_NONE = 0,
SONOFF_TYPE_BASIC = 1,
SONOFF_TYPE_S20 = 2,
SONOFF_TYPE_4CH = 3,
SONOFF_TYPE_4CH_PRO = 4,
} type_option_t;
option_entry_t type_options[] = {
{"Sonoff Basic", SONOFF_TYPE_BASIC},
{"Sonoff S20", SONOFF_TYPE_S20},
{"Sonoff 4CH", SONOFF_TYPE_4CH},
{"Sonoff 4CH Pro", SONOFF_TYPE_4CH_PRO},
{nullptr, 0}
};
config_id_t hostname_id;
config_id_t type_id;
typedef struct __sonoff_channel
{
int pin;
int btn_pin;
config_id_t status_ga_id;
bool state;
bool last_btn_state;
} sonoff_channel_t;
sonoff_channel_t channels[] = {
{CH1_PIN, BTN1_PIN, 0, false, false},
{CH2_PIN, BTN2_PIN, 0, false, false},
{CH3_PIN, BTN3_PIN, 0, false, false},
{CH4_PIN, BTN4_PIN, 0, false, false},
};
void setup()
{
pinMode(LED_PIN, OUTPUT);
pinMode(BTN1_PIN, INPUT_PULLUP);
pinMode(BTN2_PIN, INPUT_PULLUP);
pinMode(BTN3_PIN, INPUT_PULLUP);
pinMode(BTN4_PIN, INPUT_PULLUP);
pinMode(CH1_PIN, OUTPUT);
pinMode(CH2_PIN, OUTPUT);
pinMode(CH3_PIN, OUTPUT);
pinMode(CH4_PIN, OUTPUT);
Serial.begin(115200);
// Register the config options
hostname_id = knx.config_register_string("Hostname", 20, String("sonoff"));
type_id = knx.config_register_options("Type", type_options, SONOFF_TYPE_BASIC);
channels[0].status_ga_id = knx.config_register_ga("Channel 1 Status GA");
channels[1].status_ga_id = knx.config_register_ga("Channel 2 Status GA", is_4ch_or_4ch_pro);
channels[2].status_ga_id = knx.config_register_ga("Channel 3 Status GA", is_4ch_or_4ch_pro);
channels[3].status_ga_id = knx.config_register_ga("Channel 4 Status GA", is_4ch_or_4ch_pro);
knx.callback_register("Channel 1", channel_cb, &channels[0]);
knx.callback_register("Channel 2", channel_cb, &channels[1], is_4ch_or_4ch_pro);
knx.callback_register("Channel 3", channel_cb, &channels[2], is_4ch_or_4ch_pro);
knx.callback_register("Channel 4", channel_cb, &channels[3], is_4ch_or_4ch_pro);
knx.feedback_register_bool("Channel 1 is on", &(channels[0].state));
knx.feedback_register_action("Toogle channel 1", toggle_chan, &channels[0]);
knx.feedback_register_bool("Channel 2 is on", &(channels[1].state), is_4ch_or_4ch_pro);
knx.feedback_register_action("Toogle channel 2", toggle_chan, &channels[1], is_4ch_or_4ch_pro);
knx.feedback_register_bool("Channel 3 is on", &(channels[2].state), is_4ch_or_4ch_pro);
knx.feedback_register_action("Toogle channel 3", toggle_chan, &channels[2], is_4ch_or_4ch_pro);
knx.feedback_register_bool("Channel 4 is on", &(channels[3].state), is_4ch_or_4ch_pro);
knx.feedback_register_action("Toogle channel 4", toggle_chan, &channels[3], is_4ch_or_4ch_pro);
knx.load();
// Init WiFi
WiFi.hostname(knx.config_get_string(hostname_id));
WiFi.begin(ssid, pass);
Serial.println("");
Serial.print("[Connecting]");
Serial.print(ssid);
digitalWrite(LED_PIN, LOW);
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(LED_PIN, HIGH);
delay(500);
Serial.print(".");
digitalWrite(LED_PIN, LOW);
}
digitalWrite(LED_PIN, HIGH);
// Start knx
knx.start();
Serial.println();
Serial.println("Connected to wifi");
Serial.println(WiFi.localIP());
}
void loop()
{
knx.loop();
// Check local buttons
check_button(&channels[0]);
if (is_4ch_or_4ch_pro())
{
check_button(&channels[1]);
check_button(&channels[2]);
check_button(&channels[3]);
}
delay(50);
}
bool is_basic_or_s20()
{
uint8_t type = knx.config_get_options(type_id);
return type == SONOFF_TYPE_BASIC || type == SONOFF_TYPE_S20;
}
bool is_4ch_or_4ch_pro()
{
uint8_t type = knx.config_get_options(type_id);
return type == SONOFF_TYPE_4CH ||type == SONOFF_TYPE_4CH_PRO;
}
void check_button(sonoff_channel_t *chan)
{
bool state_now = digitalRead(chan->btn_pin) == HIGH ? true : false;
if (state_now != chan->last_btn_state && state_now == LOW)
{
chan->state = !chan->state;
digitalWrite(chan->pin, chan->state ? HIGH : LOW);
knx.write_1bit(knx.config_get_ga(chan->status_ga_id), chan->state);
}
chan->last_btn_state = state_now;
}
void toggle_chan(void *arg)
{
sonoff_channel_t *chan = (sonoff_channel_t *)arg;
chan->state = !chan->state;
digitalWrite(chan->pin, chan->state ? HIGH : LOW);
knx.write_1bit(knx.config_get_ga(chan->status_ga_id), chan->state);
}
void channel_cb(message_t const &msg, void *arg)
{
sonoff_channel_t *chan = (sonoff_channel_t *)arg;
switch (msg.ct)
{
case KNX_CT_WRITE:
chan->state = msg.data[0];
Serial.println(chan->state ? "Toggle on" : "Toggle off");
digitalWrite(chan->pin, chan->state ? HIGH : LOW);
knx.write_1bit(knx.config_get_ga(chan->status_ga_id), chan->state);
break;
case KNX_CT_READ:
knx.answer_1bit(msg.received_on, chan->state);
}
}

View File

@ -0,0 +1,142 @@
/*
* This is an example showing a simple environment sensor based on a BME280 attached via I2C.
* It shows, how the library can used to statically configure a device without a webserver for config.
* This sketch was tested on a WeMos D1 mini
*/
#include <Adafruit_BME280.h>
#include <esp-knx-ip.h>
// WiFi config here
const char* ssid = "myssid";
const char* pass = "mypassword";
#define LED_PIN D4
#define UPDATE_INTERVAL 10000
unsigned long next_change = 0;
float last_temp = 0.0;
float last_hum = 0.0;
float last_pres = 0.0;
Adafruit_BME280 bme;
// Group addresses to send to (1/1/1, 1/1/2 and 1/1/3)
address_t temp_ga = knx.GA_to_address(1, 1, 1);
address_t hum_ga = knx.GA_to_address(1, 1, 2);
address_t pres_ga = knx.GA_to_address(1, 1, 3);
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
callback_id_t temp_cb = knx.callback_register("Read Temperature", temp_cb);
callback_id_t hum_cb =knx.callback_register("Read Humidity", hum_cb);
callback_id_t pres_cb =knx.callback_register("Read Pressure", pres_cb);
// Assign callbacks to group addresses (2/1/1, 2/1/2, 2/1/3)
knx.callback_assign(temp_cb, knx.GA_to_address(2, 1, 1));
knx.callback_assign(hum_cb, knx.GA_to_address(2, 1, 2));
knx.callback_assign(pres_cb, knx.GA_to_address(2, 1, 3));
// Set physical address (1.1.1)
knx.physical_address_set(knx.PA_to_address(1, 1, 1));
// Do not call knx.load() for static config, it will try to load config from EEPROM which we don't have here
// Init sensor
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
}
// Init WiFi
WiFi.hostname("env");
WiFi.begin(ssid, pass);
Serial.println("");
Serial.print("[Connecting]");
Serial.print(ssid);
digitalWrite(LED_PIN, LOW);
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(LED_PIN, HIGH);
delay(250);
Serial.print(".");
digitalWrite(LED_PIN, LOW);
delay(250);
}
digitalWrite(LED_PIN, HIGH);
// Start knx, disable webserver by passing nullptr
knx.start(nullptr);
Serial.println();
Serial.println("Connected to wifi");
Serial.println(WiFi.localIP());
}
void loop() {
knx.loop();
unsigned long now = millis();
if (next_change < now)
{
next_change = now + UPDATE_INTERVAL;
last_temp = bme.readTemperature();
last_hum = bme.readHumidity();
last_pres = bme.readPressure()/100.0f;
Serial.print("T: ");
Serial.print(last_temp);
Serial.print("°C H: ");
Serial.print(last_hum);
Serial.print("% P: ");
Serial.print(last_pres);
Serial.println("hPa");
knx.write_2byte_float(temp_ga, last_temp);
knx.write_2byte_float(hum_ga, last_hum);
knx.write_2byte_float(pres_ga, last_pres);
}
delay(50);
}
void temp_cb(message_t const &msg, void *arg)
{
switch (msg.ct)
{
case KNX_CT_READ:
{
knx.answer_2byte_float(msg.received_on, last_temp);
break;
}
}
}
void hum_cb(message_t const &msg, void *arg)
{
switch (msg.ct)
{
case KNX_CT_READ:
{
knx.answer_2byte_float(msg.received_on, last_hum);
break;
}
}
}
void pres_cb(message_t const &msg, void *arg)
{
switch (msg.ct)
{
case KNX_CT_READ:
{
knx.answer_2byte_float(msg.received_on, last_pres);
break;
}
}
}

View File

@ -0,0 +1,104 @@
# datatypes
address_t DATA_TYPE
message_t DATA_TYPE
callback_id_t DATA_TYPE
callback_assignment_id_t DATA_TYPE
option_entry_t DATA_TYPE
config_id_t DATA_TYPE
enable_condition_t DATA_TYPE
callback_fptr_t DATA_TYPE
feedback_action_fptr_t DATA_TYPE
knx_command_type_t DATA_TYPE
# methods
setup KEYWORD2
loop KEYWORD2
GA_to_address KEYWORD2
PA_to_address KEYWORD2
callback_register KEYWORD2
callback_assign KEYWORD2
callback_deregister KEYWORD2
callback_unassign KEYWORD2
physical_address_set KEYWORD2
physical_address_get KEYWORD2
config_register_string KEYWORD2
config_register_int KEYWORD2
config_register_bool KEYWORD2
config_register_options KEYWORD2
config_register_ga KEYWORD2
config_get_string KEYWORD2
config_get_int KEYWORD2
config_get_bool KEYWORD2
config_get_options KEYWORD2
config_get_ga KEYWORD2
config_set_string KEYWORD2
config_set_int KEYWORD2
config_set_bool KEYWORD2
config_set_options KEYWORD2
config_set_ga KEYWORD2
feedback_register_int KEYWORD2
feedback_register_float KEYWORD2
feedback_register_bool KEYWORD2
feedback_register_action KEYWORD2
send_1bit KEYWORD2
send_2bit KEYWORD2
send_4bit KEYWORD2
send_1byte_int KEYWORD2
send_1byte_uint KEYWORD2
send_2byte_int KEYWORD2
send_2byte_uint KEYWORD2
send_2byte_float KEYWORD2
send_3byte_time KEYWORD2
send_3byte_time KEYWORD2
send_3byte_date KEYWORD2
send_3byte_date KEYWORD2
send_3byte_color KEYWORD2
send_3byte_color KEYWORD2
send_4byte_int KEYWORD2
send_4byte_uint KEYWORD2
send_4byte_float KEYWORD2
write_1bit KEYWORD2
write_2bit KEYWORD2
write_4bit KEYWORD2
write_1byte_int KEYWORD2
write_1byte_uint KEYWORD2
write_2byte_int KEYWORD2
write_2byte_uint KEYWORD2
write_2byte_float KEYWORD2
write_3byte_time KEYWORD2
write_3byte_time KEYWORD2
write_3byte_date KEYWORD2
write_3byte_date KEYWORD2
write_3byte_color KEYWORD2
write_3byte_color KEYWORD2
write_4byte_int KEYWORD2
write_4byte_uint KEYWORD2
write_4byte_float KEYWORD2
answer_1bit KEYWORD2
answer_2bit KEYWORD2
answer_4bit KEYWORD2
answer_1byte_int KEYWORD2
answer_1byte_uint KEYWORD2
answer_2byte_int KEYWORD2
answer_2byte_uint KEYWORD2
answer_2byte_float KEYWORD2
answer_3byte_time KEYWORD2
answer_3byte_time KEYWORD2
answer_3byte_date KEYWORD2
answer_3byte_date KEYWORD2
answer_3byte_color KEYWORD2
answer_3byte_color KEYWORD2
answer_4byte_int KEYWORD2
answer_4byte_uint KEYWORD2
answer_4byte_float KEYWORD2
data_to_1byte_int KEYWORD 2
data_to_2byte_int KEYWORD 2
data_to_2byte_float KEYWORD 2
data_to_4byte_float KEYWORD 2
data_to_3byte_color KEYWORD 2
data_to_3byte_time KEYWORD 2
data_to_3byte_data KEYWORD 2
# constants
knx LITERAL1

View File

@ -0,0 +1,10 @@
name=ESP KNX IP Library
version=0.5
author=Nico Weichbrodt <envy>
maintainer=Nico Weichbrodt <envy>
sentence=ESP8266 library for KNX/IP communication.
paragraph=Build your own IoT devices with KNX/IP connectivity!
category=Communication
url=https://github.com/envy/esp-knx-ip
architectures=esp8266
includes=esp-knx-ip.h

View File

@ -0,0 +1,28 @@
# C++ objects and libs
*.slo
*.lo
*.o
#*.a
*.la
*.lai
*.so
*.dll
*.dylib
#Makefile
*-build-*
build-*
*.autosave
# .log files (usually created by QtTest - thanks to VestniK)
*.log
# Editors temporary files
*~
#OSX
.DS_Store
._*

View File

@ -0,0 +1,15 @@
MQTT
====
A Wrapper around mqtt for Arduino to be used with esp8266 modules.
It wraps a slightly modified version of mqtt for esp8266 ported by Tuan PM.
Original code for esp: https://github.com/tuanpmt/esp_mqtt
Original code for contiki: https://github.com/esar/contiki-mqtt
====
**secure libssl:**
If you want to use secure communication, please use the `secure`-branch!

View File

@ -0,0 +1,102 @@
#include <ESP8266WiFi.h>
#include <MQTT.h>
void myDataCb(String& topic, String& data);
void myPublishedCb();
void myDisconnectedCb();
void myConnectedCb();
#define CLIENT_ID "client1"
// create MQTT object
MQTT myMqtt(CLIENT_ID, "192.168.0.1", 1883);
//
const char* ssid = "ssid";
const char* password = "ssid_password";
//
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Connecting to MQTT server");
// setup callbacks
myMqtt.onConnected(myConnectedCb);
myMqtt.onDisconnected(myDisconnectedCb);
myMqtt.onPublished(myPublishedCb);
myMqtt.onData(myDataCb);
Serial.println("connect mqtt...");
myMqtt.connect();
delay(10);
}
//
void loop() {
int value = analogRead(A0);
String topic("/");
topic += CLIENT_ID;
topic += "/value";
String valueStr(value);
// publish value to topic
boolean result = myMqtt.publish(topic, valueStr);
delay(1000);
}
/*
*
*/
void myConnectedCb()
{
Serial.println("connected to MQTT server");
}
void myDisconnectedCb()
{
Serial.println("disconnected. try to reconnect...");
delay(500);
myMqtt.connect();
}
void myPublishedCb()
{
//Serial.println("published.");
}
void myDataCb(String& topic, String& data)
{
Serial.print(topic);
Serial.print(": ");
Serial.println(data);
}

View File

@ -0,0 +1,95 @@
#include <ESP8266WiFi.h>
#include <MQTT.h>
void myDataCb(String& topic, String& data);
void myPublishedCb();
void myDisconnectedCb();
void myConnectedCb();
#define CLIENT_ID "client3"
#define TOPIC "/client1/value"
// create MQTT
MQTT myMqtt(CLIENT_ID, "192.168.0.1", 1883);
const char* ssid = "ssid";
const char* password = "ssid_password";
//
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Connecting to MQTT server");
// setup callbacks
myMqtt.onConnected(myConnectedCb);
myMqtt.onDisconnected(myDisconnectedCb);
myMqtt.onPublished(myPublishedCb);
myMqtt.onData(myDataCb);
Serial.println("connect mqtt...");
myMqtt.connect();
Serial.println("subscribe to topic...");
myMqtt.subscribe(TOPIC);
delay(10);
}
//
void loop() {
}
/*
*
*/
void myConnectedCb()
{
Serial.println("connected to MQTT server");
}
void myDisconnectedCb()
{
Serial.println("disconnected. try to reconnect...");
delay(500);
myMqtt.connect();
}
void myPublishedCb()
{
//Serial.println("published.");
}
void myDataCb(String& topic, String& data)
{
Serial.print(topic);
Serial.print(": ");
Serial.println(data);
}

View File

@ -0,0 +1,43 @@
#######################################
# Syntax Coloring Map For Test
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
MQTT.h KEYWORD1
MQTT KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
setClientId KEYWORD2
setUserPwd KEYWORD2
connect KEYWORD2
disconnect KEYWORD2
isConnected KEYWORD2
publish KEYWORD2
subscribe KEYWORD2
getState KEYWORD2
#general
onConnected KEYWORD2
onDisconnected KEYWORD2
onPublished KEYWORD2
onData KEYWORD2
#######################################
# Instances (KEYWORD2)
#######################################
#######################################
# Constants (LITERAL1)
#######################################

View File

@ -0,0 +1,9 @@
name=ESP MQTT
version=1.0.1
author=Ingo Randolf
maintainer=Ingo Randolf
sentence=A Wrapper around mqtt for Arduino to be used with esp8266 modules.
paragraph=It wraps a slightly modified version of mqtt for esp8266 ported by Tuan PM. Original code for esp: https://github.com/tuanpmt/esp_mqtt (7ec2ef8e1df0422b77348fe1da7885568e0c9d01) Original code for contiki: https://github.com/esar/contiki-mqtt
category=Communication
url=https://github.com/i-n-g-o/esp-mqtt-arduino
architectures=esp8266

View File

@ -0,0 +1,269 @@
/*//-------------------------------------------------------------------------------
* MQTT.cpp
*
* Implementation file for MQTT Wrapper
*
* Wrapper for Arduino written by Ingo Randolf during
* eTextiles Summercamp 2015.
*
* This library is intended to be used with esp8266 modules.
*
*
* This class wraps a slightly modified version of mqtt
* for esp8266 written by Tuan PM.
* Original code: https://github.com/tuanpmt/esp_mqtt
*
*
* 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.
//-------------------------------------------------------------------------------*/
#include "MQTT.h"
#include "user_interface.h"
#include "osapi.h"
#include "os_type.h"
#include "mqtt/debug.h"
//------------------------------------------------------------------------------------
// mqtt internal callbacks
//------------------------------------------------------------------------------------
static void mqttConnectedCb(uint32_t *args)
{
MQTT_Client* client = (MQTT_Client*)args;
MQTT* _this = (MQTT*)client->user_data;
if (_this && _this->onMqttConnectedCb) {
_this->onMqttConnectedCb();
}
}
static void mqttDisconnectedCb(uint32_t *args)
{
MQTT_Client* client = (MQTT_Client*)args;
MQTT* _this = (MQTT*)client->user_data;
if (_this && _this->onMqttDisconnectedCb) {
_this->onMqttDisconnectedCb();
}
}
static void mqttPublishedCb(uint32_t *args)
{
MQTT_Client* client = (MQTT_Client*)args;
MQTT* _this = (MQTT*)client->user_data;
if (_this && _this->onMqttPublishedCb) {
_this->onMqttPublishedCb();
}
}
static void mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len)
{
MQTT_Client* client = (MQTT_Client*)args;
MQTT* _this = (MQTT*)client->user_data;
if (_this) {
_this->_onMqttDataCb(topic, topic_len, data, data_len);
}
}
static void mqttTimeoutCb(uint32_t *args)
{
MQTT_Client* client = (MQTT_Client*)args;
MQTT* _this = (MQTT*)client->user_data;
// if (_this && _this->onMqttTimeoutCb) {
// _this->onMqttTimeoutCb();
// }
}
//------------------------------------------------------------------------------------
// MQTT class implementation
//------------------------------------------------------------------------------------
//MQTT::MQTT(const char* client_id, const char* host, uint32_t port) :
MQTT::MQTT(const char* client_id, const char* host, uint32_t port, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage) :
onMqttConnectedCb(0)
,onMqttDisconnectedCb(0)
,onMqttPublishedCb(0)
,onMqttDataCb(0)
,onMqttDataRawCb(0)
{
// init connections
MQTT_InitConnection(&mqttClient, (uint8_t*)host, port, 0);
// init client
if ( !MQTT_InitClient(&mqttClient, (uint8_t*)client_id, (uint8_t*)"", (uint8_t*)"", 15, 1) ) {
MQTT_INFO("Failed to initialize properly. Check MQTT version.\r\n");
}
// init LWT
// MQTT_InitLWT(&mqttClient, (uint8_t*)"/lwt", (uint8_t*)"offline", 0, 0);
MQTT_InitLWT(&mqttClient, (uint8_t*)willTopic, (uint8_t*)willMessage, willQos, (uint8_t)willRetain);
// set user data
mqttClient.user_data = (void*)this;
// setup callbacks
MQTT_OnConnected(&mqttClient, mqttConnectedCb);
MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb);
MQTT_OnPublished(&mqttClient, mqttPublishedCb);
MQTT_OnData(&mqttClient, mqttDataCb);
MQTT_OnTimeout(&mqttClient, mqttTimeoutCb);
}
MQTT::~MQTT()
{
MQTT_DeleteClient(&mqttClient);
}
/*
*/
void MQTT::setClientId(const char* client_id)
{
MQTT_SetUserId(&mqttClient, client_id);
}
void MQTT::setUserPwd(const char* user, const char* pwd)
{
MQTT_SetUserPwd(&mqttClient, user, pwd);
}
/*
*/
void MQTT::connect()
{
MQTT_Connect(&mqttClient);
}
void MQTT::disconnect()
{
MQTT_Disconnect(&mqttClient);
}
bool MQTT::isConnected()
{
return (mqttClient.connState >= TCP_CONNECTED);
}
/*
*/
bool MQTT::publish(const char* topic, const char* buf, uint32_t buf_len, int qos, int retain)
{
return MQTT_Publish(&mqttClient, topic, buf, buf_len, qos, retain);
}
bool MQTT::publish(String& topic, String& data, int qos, int retain)
{
return publish(topic.c_str(), data.c_str(), data.length(), qos, retain);
}
bool MQTT::publish(String& topic, const char* buf, uint32_t buf_len, int qos, int retain)
{
return publish(topic.c_str(), buf, buf_len, qos, retain);
}
bool MQTT::publish(const char* topic, String& data, int qos, int retain)
{
return publish(topic, data.c_str(), data.length(), qos, retain);
}
/*
*/
bool MQTT::subscribe(const char* topic, uint8_t qos)
{
return MQTT_Subscribe(&mqttClient, (char*)topic, qos);
}
bool MQTT::subscribe(const String& topic, uint8_t qos)
{
return MQTT_Subscribe(&mqttClient, (char*)topic.c_str(), qos);
}
//-------------------------------------------------------------------------------
// set user callback functions
//-------------------------------------------------------------------------------
void MQTT::onConnected( void (*function)(void) )
{
onMqttConnectedCb = function;
}
void MQTT::onDisconnected( void (*function)(void) )
{
onMqttDisconnectedCb = function;
}
void MQTT::onPublished( void (*function)(void) )
{
onMqttPublishedCb = function;
}
void MQTT::onData( void (*function)(String&, String&) )
{
onMqttDataCb = function;
}
void MQTT::onData( void (*function)(const char*, uint32_t, const char*, uint32_t) )
{
onMqttDataRawCb = function;
}
// internal callback, calling user CB
void MQTT::_onMqttDataCb(const char* topic, uint32_t topic_len, const char* buf, uint32_t buf_len)
{
if (onMqttDataRawCb) {
onMqttDataRawCb(topic, topic_len, buf, buf_len);
}
if (onMqttDataCb) {
char* topicCpy = (char*)malloc(topic_len+1);
memcpy(topicCpy, topic, topic_len);
topicCpy[topic_len] = 0;
// string it
String topicStr(topicCpy);
char* bufCpy = (char*)malloc(buf_len+1);
memcpy(bufCpy, buf, buf_len);
bufCpy[buf_len] = 0;
// string it
String bufStr(bufCpy);
onMqttDataCb(topicStr, bufStr);
free(topicCpy);
free(bufCpy);
}
}

View File

@ -0,0 +1,93 @@
/*//-------------------------------------------------------------------------------
* MQTT.h
*
* Header file for MQTT Wrapper
*
* Wrapper for Arduino written by Ingo Randolf during
* eTextiles Summercamp 2015.
*
* This library is intended to be used with esp8266 modules.
*
*
* This class wraps a slightly modified version of mqtt
* for esp8266 written by Tuan PM.
* Original code: https://github.com/tuanpmt/esp_mqtt
*
*
* 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.
//-------------------------------------------------------------------------------*/
#ifndef MQTT_WRAPPER_H
#define MQTT_WRAPPER_H
#include <Arduino.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
extern "C" {
#include <stddef.h>
#include "mqtt/mqtt.h"
}
class MQTT
{
public:
// MQTT(const char* client_id, const char* host, uint32_t port);
MQTT(const char* client_id, const char* host, uint32_t port, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
~MQTT();
void setClientId(const char* client_id);
void setUserPwd(const char* user, const char* pwd);
void connect();
void disconnect();
bool isConnected();
bool publish(const char* topic, const char* buf, uint32_t buf_len, int qos = 0, int retain = 0);
bool publish(String& topic, String& data, int qos = 0, int retain = 0);
bool publish(String& topic, const char* buf, uint32_t buf_len, int qos = 0, int retain = 0);
bool publish(const char* topic, String& data, int qos = 0, int retain = 0);
bool subscribe(const char* topic, uint8_t qos = 0);
bool subscribe(const String& topic, uint8_t qos = 0);
int getState() { return mqttClient.connState; };
// set callbacks
void onConnected( void (*)(void) );
void onDisconnected( void (*)(void) );
void onPublished( void (*)(void) );
void onData( void (*)(String&, String&) );
void onData( void (*)(const char*, uint32_t, const char*, uint32_t) );
// user callbacks
void (*onMqttConnectedCb)(void);
void (*onMqttDisconnectedCb)(void);
void (*onMqttPublishedCb)(void);
void (*onMqttDataCb) (String&, String&);
void (*onMqttDataRawCb) (const char*, uint32_t, const char*, uint32_t);
// internal callback
void _onMqttDataCb(const char*, uint32_t, const char*, uint32_t);
private:
MQTT_Client mqttClient;
};
#endif

View File

@ -0,0 +1,19 @@
/*
* debug.h
*
* Created on: Dec 4, 2014
* Author: Minh
*/
#ifndef USER_DEBUG_H_
#define USER_DEBUG_H_
#if defined(MQTT_DEBUG_ON)
#define MQTT_INFO( format, ... ) os_printf( format, ## __VA_ARGS__ )
#else
#define MQTT_INFO( format, ... )
#endif
#endif /* USER_DEBUG_H_ */

Some files were not shown because too many files have changed in this diff Show More