Add Library

This commit is contained in:
Siwat Sirichai 2019-08-09 09:01:56 +07:00
parent e365b9dbd9
commit 3c47103b39
318 changed files with 56465 additions and 0 deletions

View file

@ -0,0 +1,34 @@
# ESP8266MeshHelloWorld
This is a trivial node that can be used to test the mesh network.
## Configuration
a sample configuration is provided in `src/credentials.h.example`.
1) First copy `src/credentials.h.example` to `src/credentials.h`
2) Edit `credentials.h` and modify the configuration to suit your environment
The following variables should be set:
- *NETWORK_PASSWORD* : Specifies the password of your wireless network
- *NETWORK_LIST* : Specifies the SSIDs of your wireless network
- *MQTT_SERVER* : Specify the IP address of your MQTT broker
- *MQTT_PORT* : Specify the port of your MQTT broker
The following can optionally be changed:
- *MESH_PASSWORD* : A string used by all nodes to prevent unauthorized access to the mesh network
- *MESH_PORT* : The port that the mesh nodes listen on
These options are only relevant if the node is compiled with SSL enabled:
- *MESH_SECURE* : Enable SSL bewteen mesh nodes. This requires that the `ssl_cert.h` file is present (Use [this](https://github.com/marvinroger/async-mqtt-client/blob/master/scripts/gen_server_cert.sh) script to generate this header)
- *MQTT_SECURE* : Enable SSL connection to the MQTT broker.
- *MQTT_FINGERPRINT* : a 20-byte string that uniquely identifies your MQTTbroker. A script to retrieve the fingerprint can be found [here](https://github.com/marvinroger/async-mqtt-client/blob/master/scripts/get-fingerprint/get-fingerprint.py)
## Compiling and uploading
This example has been designed to use platformio for building and install
Assuming you have already setup a platformio environment:
### Non-SSL
`platformio run --target upload`
### SSL (Still experimental)
`platformio run -e ssl --target upload`

View file

@ -0,0 +1 @@
<EFBFBD><03><>Ѝ<EFBFBD><D08D><11><>,WN<57><4E>H,5d

View file

@ -0,0 +1,39 @@
#
# Example PlatformIO configuration file for SSL and non-SSL builds.
#
# Before you will be able to build the SSL version of this project, you will
# need to explicitly install the espressif8266_stage platform.
#
# To perform this installation, refer to step 1 of:
# http://docs.platformio.org/en/latest/platforms/espressif8266.html#using-arduino-framework-with-staging-version
[platformio]
env_default = nossl
[common]
framework = arduino
lib_deps = ESP8266MQTTMesh
[env:nossl]
#platform = https://github.com/platformio/platform-espressif8266.git#feature/stage
platform = espressif8266@~1.6.0
board = esp01_1m
framework = ${common.framework}
lib_deps = ${common.lib_deps}
#build_flags = -DLED_PIN=2 -g
[env:ssl]
platform = espressif8266@~1.6.0
board = esp01_1m
#build_flags = -DASYNC_TCP_SSL_ENABLED=1 -DGATEWAY_ID=10499051 -DLED_PIN=2 -g
build_flags = -DASYNC_TCP_SSL_ENABLED=1
framework = ${common.framework}
lib_deps = ${common.lib_deps}
[env:esp32_nossl]
platform = espressif32
board = esp32dev
framework = ${common.framework}
lib_deps = ${common.lib_deps}
build_flags = -DLED_PIN=2 -g

View file

@ -0,0 +1,98 @@
#include "credentials.h"
#include <ESP8266MQTTMesh.h>
#include <FS.h>
#ifndef LED_PIN
#define LED_PIN LED_BUILTIN
#endif
#define FIRMWARE_ID 0x1337
#define FIRMWARE_VER "0.1"
wifi_conn networks[] = NETWORK_LIST;
const char* mesh_password = MESH_PASSWORD;
const char* mqtt_server = MQTT_SERVER;
const int mqtt_port = MQTT_PORT;
#if ASYNC_TCP_SSL_ENABLED
const uint8_t *mqtt_fingerprint = MQTT_FINGERPRINT;
bool mqtt_secure = MQTT_SECURE;
#if MESH_SECURE
#include "ssl_cert.h"
#endif
#endif
#ifdef ESP32
String ID = String((unsigned long)ESP.getEfuseMac());
#else
String ID = String(ESP.getChipId());
#endif
unsigned long previousMillis = 0;
const long interval = 5000;
int cnt = 0;
// Note: All of the '.set' options below are optional. The default values can be
// found in ESP8266MQTTMeshBuilder.h
ESP8266MQTTMesh mesh = ESP8266MQTTMesh::Builder(networks, mqtt_server, mqtt_port)
.setVersion(FIRMWARE_VER, FIRMWARE_ID)
.setMeshPassword(mesh_password)
#if ASYNC_TCP_SSL_ENABLED
.setMqttSSL(mqtt_secure, mqtt_fingerprint)
#if MESH_SECURE
.setMeshSSL(ssl_cert, ssl_cert_len, ssl_key, ssl_key_len, ssl_fingerprint)
#endif //MESH_SECURE
#endif //ASYNC_TCP_SSL_ENABLED
.build();
void callback(const char *topic, const char *msg);
void setup() {
Serial.begin(115200);
delay(1000); //This is only here to make it easier to catch the startup messages. It isn't required
mesh.setCallback(callback);
mesh.begin();
pinMode(LED_PIN, OUTPUT);
}
void loop() {
if (! mesh.connected())
return;
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
String cntStr = String(cnt);
String msg = "hello from " + ID + " cnt: " + cntStr;
mesh.publish(ID.c_str(), msg.c_str());
previousMillis = currentMillis;
cnt++;
}
}
void callback(const char *topic, const char *msg) {
if (0 == strcmp(topic, (const char*) ID.c_str())) {
if(String(msg) == "0") {
digitalWrite(LED_PIN, HIGH);
}else{
digitalWrite(LED_PIN, LOW);
}
}
}

View file

@ -0,0 +1,16 @@
#define NETWORK_PASSWORD "network password"
#define NETWORK_LIST { \
WIFI_CONN("ssid 1", NETWORK_PASSWORD, NULL, 0), \
WIFI_CONN("ssid 2", NETWORK_PASSWORD, NULL, 0), \
NULL, \
}
#define MESH_PASSWORD "esp8266_sensor_mesh"
#define MQTT_SERVER "MQTT Server IP Address"
#define MQTT_PORT 1883
/* Only used if SSL is enabled */
#define MESH_SECURE true
#define MQTT_SECURE false
#define MQTT_FINGERPRINT NULL
//const uint8_t MQTT_FINGERPRINT[] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff,0x00,0x11,0x22,0x33};

View file

@ -0,0 +1,87 @@
const uint8_t ssl_key[] =
"\x30\x82\x02\x5D\x02\x01\x00\x02\x81\x81\x00\xA6\xE5\xE8\x1A\xFB"
"\xF8\x1A\xB7\x34\xCF\x98\x90\x10\x7A\x80\x1D\x1C\x3F\xA7\x9A\xC0"
"\x97\x5D\xC2\xCF\xD0\xD6\xCE\x65\x11\x57\xB5\x4A\x21\x81\x5E\x66"
"\xBE\x05\x70\xDC\xF3\x5C\x8D\x40\x12\x03\x22\xAC\x75\x26\x92\x04"
"\x1F\xC1\x9D\x6F\x68\x4E\x70\xE9\x43\xF1\xD0\xF2\x2F\x68\xDE\xA5"
"\x9A\xBA\xF6\xCA\x53\xA4\x89\x49\xD8\x9C\x65\x7C\x02\x7B\xBF\xFC"
"\x66\x56\xA6\x55\x45\x71\x8B\x31\x3F\xEC\xA0\x65\x0B\x76\x6F\xE5"
"\x08\x67\xDF\x8A\x9E\x8B\x46\x29\x63\x71\x84\xED\x57\xC2\xBC\x37"
"\x79\xA2\x3F\xFA\x39\xD3\xEA\xBF\x7A\xCB\x83\x02\x03\x01\x00\x01"
"\x02\x81\x80\x21\xCB\x2F\xA2\x37\x1E\xD7\x99\xFD\x11\x83\xDC\xB7"
"\xD9\x76\x13\x6E\xE2\xDC\xB7\x13\x04\x13\x32\x1D\x0E\x36\x50\x78"
"\x5A\x78\x9D\xF6\xB2\xAE\x15\x45\x4C\x78\xA1\x8F\xBB\x9F\x23\xE2"
"\xB3\x42\xFB\x44\x5C\x3C\x41\x18\xA0\xAD\x7D\x89\x4F\x5F\x82\xB1"
"\x58\xD6\x9F\x9A\x8F\x3A\x2C\x5C\xE4\xED\xEC\x5E\x95\xDB\x59\x66"
"\xEE\xF3\xAB\x95\x3E\x3D\xF6\xC0\xFD\x13\x38\x78\x1D\xC8\xE2\x08"
"\xAC\x3B\xA5\x1F\xC8\x64\xD2\xD2\xC4\x3E\xD1\xC0\x4B\xC2\xC8\x56"
"\x94\xC1\xE5\xA1\x5C\x57\x7E\x56\x5E\xC1\x33\x80\x7F\x07\x33\xD8"
"\x0B\xD5\xC1\x02\x41\x00\xD3\x95\x14\xE1\xC1\xAB\xEF\x19\x66\x6C"
"\xFE\xDB\xB3\x75\xD0\xEA\x1C\x2C\x17\x2A\x3F\x6D\x79\xCA\xA9\x82"
"\x7F\x19\x98\xC0\x1F\x96\x0A\x6B\x86\x01\xAE\x4E\xEA\x99\x48\x65"
"\x61\xC8\xB1\xC1\xDC\x20\xFF\xEE\x3A\xB3\x10\xCE\x4B\xEF\x6C\xD0"
"\x60\x44\x68\x33\x45\x13\x02\x41\x00\xC9\xEF\x63\xDA\x7D\xF8\x8A"
"\xC9\xD1\x96\xBE\x13\xB6\x3F\xB6\x04\xF1\xD7\x06\x89\xCC\x2D\x5E"
"\xDA\x9A\x78\xA7\xAC\x40\x37\x2E\x5C\x1F\x7C\x64\x6D\x4B\xB1\x78"
"\xD6\x62\x5F\x60\x95\xC9\x7B\xD7\x03\x54\x46\x98\xD8\x4E\xA8\xB8"
"\xC6\x32\xD8\xC5\x32\xAE\xCA\xDD\xD1\x02\x40\x57\x37\x61\xF7\x39"
"\x85\x6D\x37\x14\x30\xA3\xD1\xDE\xA5\x17\x2C\x19\xD6\xD6\xE9\xB4"
"\x61\xA5\x4D\xB4\x18\x35\xDA\x50\x4C\x09\xF9\x28\x6C\x70\x3D\xEB"
"\x23\x5E\xB3\x36\xD3\x8B\xBE\x55\xFF\xEA\x84\xB3\xDA\xF8\xD9\x6D"
"\x79\x0C\x76\x32\x6D\xA6\xF1\x2B\xDE\xCE\x7F\x02\x41\x00\x89\xD6"
"\x0B\xB4\x92\x13\xDA\xB8\x53\x85\xAF\x8C\xC8\xF3\xC8\x0C\xAB\xFE"
"\xF8\x09\x8B\x02\xD5\x22\x26\x1A\x81\x69\x04\x14\x26\x62\xDF\x63"
"\x0B\x31\xC7\x5F\x06\x7A\x5F\x7F\x76\xF0\x07\x2D\xAE\xE0\x28\xE0"
"\x5F\x68\x16\x98\xF8\x36\xE1\x72\x31\x78\x9C\xF3\x00\x61\x02\x41"
"\x00\xB5\x07\xCF\xC3\x62\x65\xD3\xD4\x97\x2B\xCA\x6B\x66\x75\x5C"
"\xE1\x38\xFD\xAF\xC2\xA9\xCE\x21\x3F\x09\xDC\xEA\xEE\xD2\x09\xF8"
"\xCF\xF6\x8D\xEC\x95\xF2\x12\xAC\xE7\x11\x30\xE3\xC6\xDB\x26\x17"
"\x64\xB1\xC2\x78\xF0\x47\x75\x11\xA9\x69\x52\x23\xC3\x2B\x37\x4B"
"\xBB"
;
const uint32_t ssl_key_len = 609;
const uint8_t ssl_cert[] =
"\x30\x82\x02\x47\x30\x82\x01\x2F\x02\x09\x00\xD2\x15\x44\x99\x56"
"\xC9\xF0\xD1\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x05"
"\x05\x00\x30\x1C\x31\x1A\x30\x18\x06\x03\x55\x04\x0A\x0C\x11\x45"
"\x73\x70\x72\x65\x73\x73\x69\x66\x20\x53\x79\x73\x74\x65\x6D\x73"
"\x30\x1E\x17\x0D\x31\x37\x30\x37\x31\x31\x30\x33\x30\x33\x31\x32"
"\x5A\x17\x0D\x33\x31\x30\x33\x32\x30\x30\x33\x30\x33\x31\x32\x5A"
"\x30\x33\x31\x19\x30\x17\x06\x03\x55\x04\x0A\x0C\x10\x61\x78\x54"
"\x4C\x53\x20\x6F\x6E\x20\x45\x53\x50\x38\x32\x36\x36\x31\x16\x30"
"\x14\x06\x03\x55\x04\x03\x0C\x0D\x65\x73\x70\x38\x32\x36\x36\x2E"
"\x6C\x6F\x63\x61\x6C\x30\x81\x9F\x30\x0D\x06\x09\x2A\x86\x48\x86"
"\xF7\x0D\x01\x01\x01\x05\x00\x03\x81\x8D\x00\x30\x81\x89\x02\x81"
"\x81\x00\xA6\xE5\xE8\x1A\xFB\xF8\x1A\xB7\x34\xCF\x98\x90\x10\x7A"
"\x80\x1D\x1C\x3F\xA7\x9A\xC0\x97\x5D\xC2\xCF\xD0\xD6\xCE\x65\x11"
"\x57\xB5\x4A\x21\x81\x5E\x66\xBE\x05\x70\xDC\xF3\x5C\x8D\x40\x12"
"\x03\x22\xAC\x75\x26\x92\x04\x1F\xC1\x9D\x6F\x68\x4E\x70\xE9\x43"
"\xF1\xD0\xF2\x2F\x68\xDE\xA5\x9A\xBA\xF6\xCA\x53\xA4\x89\x49\xD8"
"\x9C\x65\x7C\x02\x7B\xBF\xFC\x66\x56\xA6\x55\x45\x71\x8B\x31\x3F"
"\xEC\xA0\x65\x0B\x76\x6F\xE5\x08\x67\xDF\x8A\x9E\x8B\x46\x29\x63"
"\x71\x84\xED\x57\xC2\xBC\x37\x79\xA2\x3F\xFA\x39\xD3\xEA\xBF\x7A"
"\xCB\x83\x02\x03\x01\x00\x01\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7"
"\x0D\x01\x01\x05\x05\x00\x03\x82\x01\x01\x00\x5F\x4F\xA6\x53\x1D"
"\xC2\x7C\x2C\x0D\xDE\x54\x05\xAD\x61\xDE\x39\xE2\x8B\xA9\x47\x0D"
"\x57\xC3\xC0\x15\x18\x0C\xBF\x71\x32\x5A\x8E\x68\x64\x7A\xA2\xE3"
"\x27\x76\xC4\x22\x16\x31\x7A\x14\xD7\x2B\x16\x1E\x94\x2F\x69\x51"
"\xFF\xE0\xBC\x84\xD7\x6B\x51\xC1\xA7\x45\x1E\x6E\xB4\x86\x4F\xDD"
"\x07\x15\x72\x4B\x12\x79\xEF\x31\xDE\xE4\x9E\xC6\x6F\xDA\x36\xC8"
"\x59\x1B\x6A\x3E\xF0\xDE\xD7\x84\xCE\xE7\xAE\x59\xBE\xB6\x2D\xB0"
"\xD3\x84\x8F\xD6\xA2\x6F\x2F\x9E\x22\x5B\x1D\x61\xCF\x96\xB3\x62"
"\x16\x63\xC7\x8A\xA8\xC8\x7C\xE0\xB5\x98\xAE\x12\xB1\xAE\xE5\xFF"
"\x1F\x1A\x0D\x15\x7C\x26\xF0\x19\xBF\x12\x70\xB3\x29\xF1\xA0\x14"
"\x64\x52\x08\x56\x88\xBF\x54\xCF\x5C\x44\x50\x25\xB9\xF4\xC3\x29"
"\x3B\xB2\x98\xC8\xE2\xB9\x76\x78\x0E\xDB\x8E\x52\x8B\x4D\x7B\x95"
"\xDB\xCB\xE8\x68\x67\x3B\x6F\x99\x0E\xDC\x4D\x81\x93\xB2\xA3\x99"
"\xD2\xBC\x1E\xB4\x4F\x9D\xC0\x11\xEF\x10\xD4\xA8\x32\xEC\xE3\xFE"
"\xA8\x52\x57\x4F\x04\x3D\x17\x9B\xF1\x3C\x19\xAB\x17\x03\x66\x69"
"\x90\x8A\x7B\x09\xDF\xF9\x78\xE6\xC6\xED\x04\x19\x2B\x88\xD4\xE1"
"\x80\x88\x1A\x98\x6F\x9C\x6D\x37\x18\x55\x36"
;
const uint32_t ssl_cert_len = 587;
const uint8_t ssl_fingerprint[] =
"\xC8\x03\xFF\xF8\xD0\x8D\xB8\xE7\x11\xF0\x87\x2C\x57\x4E\xDD\xD3"
"\x48\x2C\x35\x64"
;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,441 @@
#====================================================================================
# makeESPArduino
#
# A makefile for ESP8286 and ESP32 Arduino projects.
# Edit the contents of this file to suit your project
# or just include it and override the applicable macros.
#
# License: GPL 2.1
# General and full license information is available at:
# https://github.com/plerup/makeEspArduino
#
# Copyright (c) 2016-2017 Peter Lerup. All rights reserved.
#
#====================================================================================
#====================================================================================
# Project specfic values
#====================================================================================
# Include possible project makefile. This can be used to override the defaults below
-include $(firstword $(PROJ_CONF) $(dir $(SKETCH))config.mk)
#=== Default values not available in the Arduino configuration files
CHIP ?= esp8266
# Set chip specific default board unless specified
BOARD ?= $(if $(filter $(CHIP), esp32),esp32,generic)
# Serial flashing parameters
UPLOAD_PORT ?= $(shell ls -1tr /dev/ttyUSB* | tail -1)
UPLOAD_VERB ?= -v
# OTA parameters
ESP_ADDR ?= ESP_123456
ESP_PORT ?= 8266
ESP_PWD ?= 123
# HTTP update parameters
HTTP_ADDR ?= ESP_123456
HTTP_URI ?= /update
HTTP_PWD ?= user
HTTP_USR ?= password
# Output directory
BUILD_DIR ?= /tmp/mkESP/$(MAIN_NAME)_$(BOARD)
# File system source directory
FS_DIR ?= $(dir $(SKETCH))data
# Bootloader
BOOT_LOADER ?= $(ESP_ROOT)/bootloaders/eboot/eboot.elf
#====================================================================================
# Standard build logic and values
#====================================================================================
START_TIME := $(shell perl -e "print time();")
# Utility functions
git_description = $(shell git -C $(1) describe --tags --always --dirty 2>/dev/null || echo Unknown)
time_string = $(shell date +$(1))
# ESP Arduino directories
ifndef ESP_ROOT
# Location not defined, find and use possible version in the Arduino IDE installation
OS ?= $(shell uname -s)
ifeq ($(OS), Windows_NT)
ARDUINO_DIR = $(shell cygpath -m $(LOCALAPPDATA)/Arduino15/packages/$(CHIP))
else ifeq ($(OS), Darwin)
ARDUINO_DIR = $(HOME)/Library/Arduino15/packages/$(CHIP)
else
ARDUINO_DIR = $(HOME)/.arduino15/packages/$(CHIP)
endif
ESP_ROOT := $(lastword $(wildcard $(ARDUINO_DIR)/hardware/$(CHIP)/*))
ifeq ($(ESP_ROOT),)
$(error No installed version of $(CHIP) Arduino found)
endif
ESP_ARDUINO_VERSION := $(notdir $(ESP_ROOT))
# Find used version of compiler and tools
COMP_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/xtensa-lx106-elf-gcc/*))
ESPTOOL_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/esptool/*))
MKSPIFFS_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/mkspiffs/*))
else
# Location defined, assume it is a git clone
ESP_ARDUINO_VERSION = $(call git_description,$(ESP_ROOT))
endif
ESP_LIBS = $(ESP_ROOT)/libraries
SDK_ROOT = $(ESP_ROOT)/tools/sdk
TOOLS_ROOT = $(ESP_ROOT)/tools
ifeq ($(wildcard $(ESP_ROOT)/cores/$(CHIP)),)
$(error $(ESP_ROOT) is not a vaild directory for $(CHIP))
endif
ESPTOOL_PY = esptool.py --baud=$(UPLOAD_SPEED) --port $(UPLOAD_PORT)
# Search for sketch if not defined
SKETCH := $(realpath $(firstword \
$(SKETCH) \
$(wildcard *.ino) \
$(if $(filter $(CHIP), esp32),$(ESP_LIBS)/WiFi/examples/WiFiScan/WiFiScan.ino,$(ESP_LIBS)/ESP8266WebServer/examples/HelloServer/HelloServer.ino) \
) \
)
ifeq ($(wildcard $(SKETCH)),)
$(error Sketch $(SKETCH) not found)
endif
# Main output definitions
MAIN_NAME := $(basename $(notdir $(SKETCH)))
MAIN_EXE = $(BUILD_DIR)/$(MAIN_NAME).bin
FS_IMAGE = $(BUILD_DIR)/FS.spiffs
ifeq ($(OS), Windows_NT)
# Adjust critical paths
BUILD_DIR := $(shell cygpath -m $(BUILD_DIR))
SKETCH := $(shell cygpath -m $(SKETCH))
endif
# Build file extensions
OBJ_EXT = .o
DEP_EXT = .d
# Special tool definitions
OTA_TOOL ?= $(TOOLS_ROOT)/espota.py
HTTP_TOOL ?= curl
# Core source files
CORE_DIR = $(ESP_ROOT)/cores/$(CHIP)
CORE_SRC := $(shell find $(CORE_DIR) -name "*.S" -o -name "*.c" -o -name "*.cpp")
CORE_OBJ := $(patsubst %,$(BUILD_DIR)/%$(OBJ_EXT),$(notdir $(CORE_SRC)))
CORE_LIB = $(BUILD_DIR)/arduino.ar
# User defined compilation units and directories
ifeq ($(LIBS),)
# Automatically find directories with header files used by the sketch
FINDCMD := perl -e 'use File::Find;@d = split(" ", shift);while (<>) {$$f{"$$1"} = 1 if /^\s*\#include\s+[<"]([^>"]+)/;}find({follow => 1, wanted => sub {return if($$File::Find::dir =~ /examples|tests/);print $$File::Find::dir," " if $$f{$$_}}}, @d);'
LIBS := $(shell $(FINDCMD) "$(ESP_LIBS) $(HOME)/Arduino/libraries" $(SKETCH) ../../src/*.cpp ../../src/*.h)
ifeq ($(LIBS),)
# No dependencies found
LIBS = /dev/null
endif
endif
IGNORE_PATTERN := $(foreach dir,$(EXCLUDE_DIRS),$(dir)/%)
SKETCH_DIR = $(dir $(SKETCH))
USER_INC := $(filter-out $(IGNORE_PATTERN),$(shell find -L $(SKETCH_DIR) $(LIBS) -name "*.h"))
USER_SRC := $(SKETCH) $(filter-out $(IGNORE_PATTERN),$(shell find -L $(SKETCH_DIR) $(LIBS) -name "*.S" -o -name "*.c" -o -name "*.cpp"))
# Object file suffix seems to be significant for the linker...
USER_OBJ := $(subst .ino,_.cpp,$(patsubst %,$(BUILD_DIR)/%$(OBJ_EXT),$(notdir $(USER_SRC))))
USER_DIRS := $(sort $(dir $(USER_SRC)))
USER_INC_DIRS := $(sort $(dir $(USER_INC)))
# Use first flash definition for the board as default
FLASH_DEF ?= $(shell cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) {if (/^$(BOARD)\.menu\.FlashSize\.([^\.]+)=/){ print "$$1"; exit;}} print "NA";')
# The actual build commands are to be extracted from the Arduino description files
ARDUINO_MK = $(BUILD_DIR)/arduino.mk
ARDUINO_DESC := $(shell find $(ESP_ROOT) -maxdepth 1 -name "*.txt" | sort)
$(ARDUINO_MK): $(ARDUINO_DESC) $(MAKEFILE_LIST) | $(BUILD_DIR)
perl -e "$$PARSE_ARDUINO" $(BOARD) $(FLASH_DEF) $(ARDUINO_EXTRA_DESC) $(ARDUINO_DESC) >$(ARDUINO_MK)
-include $(ARDUINO_MK)
# Compilation directories and path
INCLUDE_DIRS += $(CORE_DIR) $(ESP_ROOT)/variants/$(INCLUDE_VARIANT) $(BUILD_DIR)
C_INCLUDES := $(foreach dir,$(INCLUDE_DIRS) $(USER_INC_DIRS),-I$(dir))
VPATH += $(shell find $(CORE_DIR) -type d) $(USER_DIRS)
# Automatically generated build information data
# Makes the build date and git descriptions at the actual build event available as string constants in the program
BUILD_INFO_H = $(BUILD_DIR)/buildinfo.h
BUILD_INFO_CPP = $(BUILD_DIR)/buildinfo.c++
BUILD_INFO_OBJ = $(BUILD_INFO_CPP)$(OBJ_EXT)
$(BUILD_INFO_H): | $(BUILD_DIR)
echo "typedef struct { const char *date, *time, *src_version, *env_version;} _tBuildInfo; extern _tBuildInfo _BuildInfo;" >$@
# Build rules for the different source file types
$(BUILD_DIR)/%.cpp$(OBJ_EXT): %.cpp $(BUILD_INFO_H) $(ARDUINO_MK)
echo $(<F)
$(CPP_COM) $(CPP_EXTRA) $< -o $@
$(BUILD_DIR)/%_.cpp$(OBJ_EXT): %.ino $(BUILD_INFO_H) $(ARDUINO_MK)
echo $(<F)
$(CPP_COM) $(CPP_EXTRA) -x c++ -include $(CORE_DIR)/Arduino.h $< -o $@
$(BUILD_DIR)/%.c$(OBJ_EXT): %.c $(ARDUINO_MK)
echo $(<F)
$(C_COM) $(C_EXTRA) $< -o $@
$(BUILD_DIR)/%.S$(OBJ_EXT): %.S $(ARDUINO_MK)
echo $(<F)
$(S_COM) $(S_EXTRA) $< -o $@
$(CORE_LIB): $(CORE_OBJ)
echo Creating core archive
rm -f $@
$(AR_COM) $^
BUILD_DATE = $(call time_string,"%Y-%m-%d")
BUILD_TIME = $(call time_string,"%H:%M:%S")
SRC_GIT_VERSION := $(call git_description,$(dir $(SKETCH)))
$(MAIN_EXE): $(CORE_LIB) $(USER_OBJ)
echo Linking $(MAIN_EXE)
echo " Versions: $(SRC_GIT_VERSION), $(ESP_ARDUINO_VERSION)"
echo '#include <buildinfo.h>' >$(BUILD_INFO_CPP)
echo '_tBuildInfo _BuildInfo = {"$(BUILD_DATE)","$(BUILD_TIME)","$(SRC_GIT_VERSION)","$(ESP_ARDUINO_VERSION)"};' >>$(BUILD_INFO_CPP)
$(CPP_COM) $(BUILD_INFO_CPP) -o $(BUILD_INFO_OBJ)
$(LD_COM)
$(GEN_PART_COM)
$(ELF2BIN_COM)
$(SIZE_COM) | perl -e "$$MEM_USAGE" "$(MEM_FLASH)" "$(MEM_RAM)"
ifneq ($(FLASH_INFO),)
printf "Flash size: $(FLASH_INFO)\n\n"
endif
perl -e 'print "Build complete. Elapsed time: ", time()-$(START_TIME), " seconds\n\n"'
upload flash: all
$(UPLOAD_COM)
ota: all
$(OTA_TOOL) -i $(ESP_ADDR) -p $(ESP_PORT) -a $(ESP_PWD) -f $(MAIN_EXE)
http: all
$(HTTP_TOOL) --verbose -F image=@$(MAIN_EXE) --user $(HTTP_USR):$(HTTP_PWD) http://$(HTTP_ADDR)$(HTTP_URI)
echo "\n"
$(FS_IMAGE): $(wildcard $(FS_DIR)/*)
ifneq ($(CHIP),esp32)
echo Generating filesystem image: $(FS_IMAGE)
$(MKSPIFFS_COM)
else
echo No SPIFFS function available for $(CHIP)
exit 1
endif
fs: $(FS_IMAGE)
upload_fs flash_fs: $(FS_IMAGE)
$(FS_UPLOAD_COM)
FLASH_FILE ?= esp_flash.bin
dump_flash:
echo Dumping flash memory to file: $(FLASH_FILE)
$(ESPTOOL_PY) read_flash 0 $(shell perl -e 'shift =~ /(\d+)([MK])/ || die "Invalid memory size\n";$$mem_size=$$1*1024;$$mem_size*=1024 if $$2 eq "M";print $$mem_size;' $(FLASH_DEF)) $(FLASH_FILE)
restore_flash:
echo Restoring flash memory from file: $(FLASH_FILE)
$(ESPTOOL_PY) write_flash -fs $(shell perl -e 'shift =~ /(\d+)([MK])/ || die "Invalid memory size\n";print ($$2 eq "K" ? 2 : $$1*8);' $(FLASH_DEF))m -fm $(FLASH_MODE) -ff $(FLASH_SPEED)m 0 $(FLASH_FILE)
clean:
echo Removing all build files
rm -rf $(BUILD_DIR)/*
list_boards:
echo === Available boards ===
cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) { if (/^(\w+)\.name=(.+)/){ print sprintf("%-20s %s\n", $$1,$$2);} }'
list_lib:
echo === User specific libraries ===
perl -e 'foreach (@ARGV) {print "$$_\n"}' "* Include directories:" $(USER_INC_DIRS) "* Library source files:" $(USER_SRC) "Foo" $(IGNORE_PATTERN)
list_flash_defs:
echo === Memory configurations for board: $(BOARD) ===
cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) { if (/^$(BOARD)\.menu\.FlashSize.([^\.]+)=(.+)/){ print sprintf("%-10s %s\n", $$1,$$2);} }'
help:
echo
echo "Generic makefile for building Arduino esp8266 and esp32 projects"
echo "This file can either be used directly or included from another makefile"
echo ""
echo "The following targets are available:"
echo " all (default) Build the project application"
echo " clean Remove all intermediate build files"
echo " flash Build and and flash the project application"
echo " flash_fs Build and and flash file system (when applicable)"
echo " ota Build and and flash via OTA"
echo " Params: ESP_ADDR, ESP_PORT and ESP_PWD"
echo " http Build and and flash via http (curl)"
echo " Params: HTTP_ADDR, HTTP_URI, HTTP_PWD and HTTP_USR"
echo " dump_flash Dump the whole board flash memory to a file"
echo " restore_flash Restore flash memory from a previously dumped file"
echo " list_lib Show a list of used library files and include paths"
echo "Configurable parameters:"
echo " SKETCH Main source file"
echo " If not specified the first sketch in current"
echo " directory will be used. If none is found there,"
echo " a demo example will be used instead."
echo " LIBS Includes in the sketch file of libraries from within"
echo " the ESP Arduino directories are automatically"
echo " detected. If this is not enough, define this"
echo " variable with all libraries or directories needed."
echo " USER_LIBS Path to user installed Arduino libraries"
echo " CHIP Set to esp8266 or esp32. Default: '$(CHIP)'"
echo " BOARD Name of the target board. Default: '$(BOARD)'"
echo " Use 'list_boards' to get list of available ones"
echo " FLASH_DEF Flash partitioning info. Default '$(FLASH_DEF)'"
echo " Use 'list_flash_defs' to get list of available ones"
echo " BUILD_DIR Directory for intermediate build files."
echo " Default '$(BUILD_DIR)'"
echo " BUILD_EXTRA_FLAGS Additional parameters for the compilation commands"
echo " FS_DIR File system root directory"
echo " UPLOAD_PORT Serial flashing port name. Default: '$(UPLOAD_PORT)'"
echo " UPLOAD_SPEED Serial flashing baud rate. Default: '$(UPLOAD_SPEED)'"
echo " FLASH_FILE File name for dump and restore flash operations"
echo " Default: '$(FLASH_FILE)'"
echo " VERBOSE Set to 1 to get full printout of the build"
echo " SINGLE_THREAD Use only one build thread"
echo
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
.PHONY: all
all: $(BUILD_DIR) $(ARDUINO_MK) $(BUILD_INFO_H) prebuild $(MAIN_EXE)
prebuild:
ifdef USE_PREBUILD
$(PREBUILD_COM)
endif
# Include all available dependencies
-include $(wildcard $(BUILD_DIR)/*$(DEP_EXT))
.DEFAULT_GOAL = all
ifndef SINGLE_THREAD
# Use multithreaded builds by default
MAKEFLAGS += -j
endif
ifndef VERBOSE
# Set silent mode as default
MAKEFLAGS += --silent
endif
# Inline Perl scripts
# Parse Arduino definitions and build commands from the descriptions
define PARSE_ARDUINO
my $$board = shift;
my $$flashSize = shift;
my %v;
sub def_var {
my ($$name, $$var) = @_;
print "$$var ?= $$v{$$name}\n";
$$v{$$name} = "\$$($$var)";
}
$$v{'runtime.platform.path'} = '$$(ESP_ROOT)';
$$v{'includes'} = '$$(C_INCLUDES)';
$$v{'runtime.ide.version'} = '10605';
$$v{'build.arch'} = '$$(CHIP)';
$$v{'build.project_name'} = '$$(MAIN_NAME)';
$$v{'build.path'} = '$$(BUILD_DIR)';
$$v{'object_files'} = '$$^ $$(BUILD_INFO_OBJ)';
foreach my $$fn (@ARGV) {
open($$f, $$fn) || die "Failed to open: $$fn\n";
while (<$$f>) {
next unless /^(\w[\w\-\.]+)=(.*)/;
my ($$key, $$val) =($$1, $$2);
$$board_defined = 1 if $$key eq "$$board.name";
$$key =~ s/$$board\.menu\.FlashSize\.$$flashSize\.//;
$$key =~ s/$$board\.menu\.FlashFreq\.[^\.]+\.//;
$$key =~ s/$$board\.menu\.UploadSpeed\.[^\.]+\.//;
$$key =~ s/^$$board\.//;
$$v{$$key} ||= $$val;
}
close($$f);
}
$$v{'runtime.tools.xtensa-lx106-elf-gcc.path'} ||= '$$(COMP_PATH)';
$$v{'runtime.tools.esptool.path'} ||= '$$(ESPTOOL_PATH)';
$$v{'runtime.tools.mkspiffs.path'} ||= '$$(MKSPIFFS_PATH)';
die "* Uknown board $$board\n" unless $$board_defined;
print "# Board definitions\n";
def_var('build.f_cpu', 'F_CPU');
def_var('build.flash_mode', 'FLASH_MODE');
def_var('build.flash_freq', 'FLASH_SPEED');
def_var('upload.resetmethod', 'UPLOAD_RESET');
def_var('upload.speed', 'UPLOAD_SPEED');
def_var('compiler.warning_flags', 'COMP_WARNINGS');
$$v{'upload.verbose'} = '$$(UPLOAD_VERB)';
$$v{'serial.port'} = '$$(UPLOAD_PORT)';
$$v{'recipe.objcopy.hex.pattern'} =~ s/[^"]+\/bootloaders\/eboot\/eboot.elf/\$$(BOOT_LOADER)/;
$$v{'tools.esptool.upload.pattern'} =~ s/\{(cmd|path)\}/\{tools.esptool.$$1\}/g;
$$v{'compiler.cpreprocessor.flags'} .= " \$$(C_PRE_PROC_FLAGS)";
$$v{'build.extra_flags'} .= " \$$(BUILD_EXTRA_FLAGS)";
foreach my $$key (sort keys %v) {
while ($$v{$$key} =~/\{/) {
$$v{$$key} =~ s/\{([\w\-\.]+)\}/$$v{$$1}/;
$$v{$$key} =~ s/""//;
}
$$v{$$key} =~ s/ -o $$//;
$$v{$$key} =~ s/(-D\w+=)"([^"]+)"/$$1\\"$$2\\"/g;
}
print "INCLUDE_VARIANT = $$v{'build.variant'}\n";
print "# Commands\n";
print "C_COM=$$v{'recipe.c.o.pattern'}\n";
print "CPP_COM=$$v{'recipe.cpp.o.pattern'}\n";
print "S_COM=$$v{'recipe.S.o.pattern'}\n";
print "AR_COM=$$v{'recipe.ar.pattern'}\n";
print "LD_COM=$$v{'recipe.c.combine.pattern'}\n";
print "GEN_PART_COM=$$v{'recipe.objcopy.eep.pattern'}\n";
print "ELF2BIN_COM=$$v{'recipe.objcopy.hex.pattern'}\n";
print "SIZE_COM=$$v{'recipe.size.pattern'}\n";
my $$flash_size = sprintf("0x%X", hex($$v{'build.spiffs_end'})-hex($$v{'build.spiffs_start'}));
print "MKSPIFFS_COM=$$v{'tools.mkspiffs.path'}/$$v{'tools.mkspiffs.cmd'} -b $$v{'build.spiffs_blocksize'} -s $$flash_size -c \$$(FS_DIR) \$$(FS_IMAGE)\n";
print "UPLOAD_COM=$$v{'tools.esptool.upload.pattern'}\n";
my $$fs_upload_com = $$v{'tools.esptool.upload.pattern'};
$$fs_upload_com =~ s/(.+ -ca) .+/$$1 $$v{'build.spiffs_start'} -cf \$$(FS_IMAGE)/;
print "FS_UPLOAD_COM=$$fs_upload_com\n";
my $$val = $$v{'recipe.hooks.core.prebuild.1.pattern'};
$$val =~ s/bash -c "(.+)"/$$1/;
$$val =~ s/(#define .+0x)(\`)/"\\$$1\"$$2/;
$$val =~ s/(\\)//;
print "PREBUILD_COM=$$val\n";
print "MEM_FLASH=$$v{'recipe.size.regex'}\n";
print "MEM_RAM=$$v{'recipe.size.regex.data'}\n";
print "FLASH_INFO=$$v{'menu.FlashSize.' . $$flashSize}\n"
endef
export PARSE_ARDUINO
# Convert memory information
define MEM_USAGE
$$fp = shift;
$$rp = shift;
while (<>) {
$$r += $$1 if /$$rp/;
$$f += $$1 if /$$fp/;
}
print "\nMemory usage\n";
print sprintf(" %-6s %6d bytes\n" x 2 ."\n", "Ram:", $$r, "Flash:", $$f);
endef
export MEM_USAGE

View file

@ -0,0 +1,34 @@
# ESP8266MeshIRRemote
This is an example of an IR Blaster controlled via MQTT commands
The blaster uses Pronto codes (though it should be easy to add support for all protocols handled by the IRRemote library).
The Pronto protocol is very flexible, and should be able to handle virtually all IR codes.
Codes can be saved in a file on the device to make it easy to send frequently used codes
## Hardware
The IRBlaster directory contains the Eagle libraries for the IRBlaster used in this example.
The board is quite basic. It uses an ESP01 module along with a 2n7000 to drive an IR LED. A LM1117-3.3 module is connected
to a mini-usb to provide power.
This was built before Eagle
was moved to a subscription plan. I have since moved to using KiCad, but there was no reason to redesign the schematics.
A PDF of the schematic is provided. Boards can be ordered from OshPark here:
<a href="https://oshpark.com/shared_projects/EaJlztYI"><img src="https://oshpark.com/assets/badge-5b7ec47045b78aef6eb9d83b3bac6b1920de805e9a0c227658eac6e19a045b9c.png" alt="Order from OSH Park"></img></a>
## MQTT Commands
| Topic | Message | Description |
|-------|---------|-------------|
| \<topic>/send | code=\<pronto code> | send specified code one time |
| \<topic>/send | repeat=5,code=\<pronto code> | send specified code 5 times |
| \<topic>/send | repeat=5,code=\<pronto code1>,repeat=3,pronto=\<pronto code2> | send code1 5 times followed by sending code2 3 times |
| \<topic>/send | repeat=5,file=\<filename1>,file=\<filename2>,... | send pronto code previously saved in 'filename1' 5 times, followed by the contents of 'filename2' |
| \<topic>/list | "" | returns a list of all saved files |
| \<topic>/debug | \<1|0> | enable/disable debugging messages over MQTT |
| \<topic>/save/\<filename> | code=\<pronto code> | save specified pronto code to 'filename' on esp8266 device |
| \<topic>/read/\<filename> | "" | return contents of 'flename' via MQTT |

View file

@ -0,0 +1,4 @@
FLASH_DEF = 1M256
USER_LIBS = ${HOME}/Arduino/libraries/
CPP_EXTRA = -Wall
BUILD_EXTRA_FLAGS = "-DMQTT_MAX_PACKET_SIZE=1152"

View file

@ -0,0 +1,20 @@
## Contributors of this project
- [Mark Szabo](https://github.com/markszabo/) : IR sending on ESP8266
- [Sébastien Warin](https://github.com/sebastienwarin/) (http://sebastien.warin.fr) : IR receiving on ESP8266
## Contributors of the original project (https://github.com/shirriff/Arduino-IRremote/)
These are the active contributors of this project that you may contact if there is anything you need help with or if you have suggestions.
- [z3t0](https://github.com/z3t0) : Active Contributor and currently also the main contributor.
* Email: zetoslab@gmail.com
* Skype: polarised16
- [shirriff](https://github.com/shirriff) : Owner of repository and creator of library.
- [Informatic](https://github.com/Informatic) : Active contributor
- [fmeschia](https://github.com/fmeschia) : Active contributor
- [PaulStoffregen](https://github.com/paulstroffregen) : Active contributor
- [crash7](https://github.com/crash7) : Active contributor
- [Neco777](https://github.com/neco777) : Active contributor
Note: This list is being updated constantly so please let [z3t0](https://github.com/z3t0) know if you have been missed.

View file

@ -0,0 +1,160 @@
/***************************************************
* IRremote for ESP8266
*
* Based on the IRremote library for Arduino by Ken Shirriff
* Version 0.11 August, 2009
* Copyright 2009 Ken Shirriff
* For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html
*
* Edited by Mitra to add new controller SANYO
*
* Interrupt code based on NECIRrcv by Joe Knapp
* http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556
* Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/
*
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
* LG added by Darryl Smith (based on the JVC protocol)
* Whynter A/C ARC-110WD added by Francesco Meschia
*
* Updated by markszabo (https://github.com/markszabo/IRremoteESP8266) for sending IR code on ESP8266
* Updated by Sebastien Warin (http://sebastien.warin.fr) for receiving IR code on ESP8266
*
* GPL license, all text above must be included in any redistribution
****************************************************/
#ifndef IRremote_h
#define IRremote_h
// The following are compile-time library options.
// If you change them, recompile the library.
// If DEBUG is defined, a lot of debugging output will be printed during decoding.
// TEST must be defined for the IRtest unittests to work. It will make some
// methods virtual, which will be slightly slower, which is why it is optional.
//#define DEBUG
//#define TEST
enum decode_type_t {
NEC = 1,
SONY = 2,
RC5 = 3,
RC6 = 4,
DISH = 5,
SHARP = 6,
PANASONIC = 7,
JVC = 8,
SANYO = 9,
MITSUBISHI = 10,
SAMSUNG = 11,
LG = 12,
WHYNTER = 13,
AIWA_RC_T501 = 14,
UNKNOWN = -1
};
// Results returned from the decoder
class decode_results {
public:
int decode_type; // NEC, SONY, RC5, UNKNOWN
union { // This is used for decoding Panasonic and Sharp data
unsigned int panasonicAddress;
unsigned int sharpAddress;
};
unsigned long value; // Decoded value
int bits; // Number of bits in decoded value
volatile unsigned int *rawbuf; // Raw intervals in .5 us ticks
int rawlen; // Number of records in rawbuf.
};
// Values for decode_type
#define NEC 1
#define SONY 2
#define RC5 3
#define RC6 4
#define DISH 5
#define SHARP 6
#define PANASONIC 7
#define JVC 8
#define SANYO 9
#define MITSUBISHI 10
#define SAMSUNG 11
#define LG 12
#define WHYNTER 13
#define UNKNOWN -1
// Decoded value for NEC when a repeat code is received
#define REPEAT 0xffffffff
// main class for receiving IR
class IRrecv
{
public:
IRrecv(int recvpin);
int decode(decode_results *results);
void enableIRIn();
void disableIRIn();
void resume();
private:
// These are called by decode
int getRClevel(decode_results *results, int *offset, int *used, int t1);
long decodeNEC(decode_results *results);
long decodeSony(decode_results *results);
long decodeSanyo(decode_results *results);
long decodeMitsubishi(decode_results *results);
long decodeRC5(decode_results *results);
long decodeRC6(decode_results *results);
long decodePanasonic(decode_results *results);
long decodeLG(decode_results *results);
long decodeJVC(decode_results *results);
long decodeSAMSUNG(decode_results *results);
long decodeWhynter(decode_results *results);
long decodeHash(decode_results *results);
int compare(unsigned int oldval, unsigned int newval);
};
// Only used for testing; can remove virtual for shorter code
#ifdef TEST
#define VIRTUAL virtual
#else
#define VIRTUAL
#endif
class IRsend
{
public:
IRsend(int IRsendPin);
void begin();
void sendWhynter(unsigned long data, int nbits);
void sendNEC(unsigned long data, int nbits);
void sendLG(unsigned long data, int nbits);
void sendSony(unsigned long data, int nbits);
// Neither Sanyo nor Mitsubishi send is implemented yet
// void sendSanyo(unsigned long data, int nbits);
// void sendMitsubishi(unsigned long data, int nbits);
void sendRaw(unsigned int buf[], int len, int hz);
void sendRC5(unsigned long data, int nbits);
void sendRC6(unsigned long data, int nbits);
void sendDISH(unsigned long data, int nbits);
void sendSharp(unsigned int address, unsigned int command);
void sendSharpRaw(unsigned long data, int nbits);
void sendPanasonic(unsigned int address, unsigned long data);
void sendJVC(unsigned long data, int nbits, int repeat); // *Note instead of sending the REPEAT constant if you want the JVC repeat signal sent, send the original code value and change the repeat argument from 0 to 1. JVC protocol repeats by skipping the header NOT by sending a separate code value like NEC does.
void sendSAMSUNG(unsigned long data, int nbits);
void sendDenon (unsigned long data, int nbits);
bool sendPronto (const char* s, bool repeat, bool fallback);
void enableIROut(int khz);
VIRTUAL void mark(int usec);
VIRTUAL void space(int usec);
private:
int halfPeriodicTime;
int IRpin;
} ;
// Some useful constants
#define USECPERTICK 50 // microseconds per clock interrupt tick
#define RAWBUF 100 // Length of raw duration buffer
// Marks tend to be 100us too long, and spaces 100us too short
// when received due to sensor lag.
#define MARK_EXCESS 100
#endif

View file

@ -0,0 +1,198 @@
/***************************************************
* IRremote for ESP8266
*
* Based on the IRremote library for Arduino by Ken Shirriff
* Version 0.11 August, 2009
* Copyright 2009 Ken Shirriff
* For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html
*
* Modified by Paul Stoffregen <paul@pjrc.com> to support other boards and timers
*
* Interrupt code based on NECIRrcv by Joe Knapp
* http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556
* Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/
*
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
* Whynter A/C ARC-110WD added by Francesco Meschia
*
* 09/23/2015 : Samsung pulse parameters updated by Sebastien Warin to be compatible with EUxxD6200
*
* GPL license, all text above must be included in any redistribution
****************************************************/
#ifndef IRremoteint_h
#define IRremoteint_h
#if defined(ARDUINO) && ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
// Pulse parms are *50-100 for the Mark and *50+100 for the space
// First MARK is the one after the long gap
// pulse parameters in usec
#define WHYNTER_HDR_MARK 2850
#define WHYNTER_HDR_SPACE 2850
#define WHYNTER_BIT_MARK 750
#define WHYNTER_ONE_MARK 750
#define WHYNTER_ONE_SPACE 2150
#define WHYNTER_ZERO_MARK 750
#define WHYNTER_ZERO_SPACE 750
#define NEC_HDR_MARK 9000
#define NEC_HDR_SPACE 4500
#define NEC_BIT_MARK 560
#define NEC_ONE_SPACE 1690
#define NEC_ZERO_SPACE 560
#define NEC_RPT_SPACE 2250
#define SONY_HDR_MARK 2400
#define SONY_HDR_SPACE 600
#define SONY_ONE_MARK 1200
#define SONY_ZERO_MARK 600
#define SONY_RPT_LENGTH 45000
#define SONY_DOUBLE_SPACE_USECS 500 // usually ssee 713 - not using ticks as get number wrapround
// SA 8650B
#define SANYO_HDR_MARK 3500 // seen range 3500
#define SANYO_HDR_SPACE 950 // seen 950
#define SANYO_ONE_MARK 2400 // seen 2400
#define SANYO_ZERO_MARK 700 // seen 700
#define SANYO_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround
#define SANYO_RPT_LENGTH 45000
// Mitsubishi RM 75501
// 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7
// #define MITSUBISHI_HDR_MARK 250 // seen range 3500
#define MITSUBISHI_HDR_SPACE 350 // 7*50+100
#define MITSUBISHI_ONE_MARK 1950 // 41*50-100
#define MITSUBISHI_ZERO_MARK 750 // 17*50-100
// #define MITSUBISHI_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround
// #define MITSUBISHI_RPT_LENGTH 45000
#define RC5_T1 889
#define RC5_RPT_LENGTH 46000
#define RC6_HDR_MARK 2666
#define RC6_HDR_SPACE 889
#define RC6_T1 444
#define RC6_RPT_LENGTH 46000
#define SHARP_BIT_MARK 245
#define SHARP_ONE_SPACE 1805
#define SHARP_ZERO_SPACE 795
#define SHARP_GAP 600000
#define SHARP_TOGGLE_MASK 0x3FF
#define SHARP_RPT_SPACE 3000
#define DISH_HDR_MARK 400
#define DISH_HDR_SPACE 6100
#define DISH_BIT_MARK 400
#define DISH_ONE_SPACE 1700
#define DISH_ZERO_SPACE 2800
#define DISH_RPT_SPACE 6200
#define DISH_TOP_BIT 0x8000
#define PANASONIC_HDR_MARK 3502
#define PANASONIC_HDR_SPACE 1750
#define PANASONIC_BIT_MARK 502
#define PANASONIC_ONE_SPACE 1244
#define PANASONIC_ZERO_SPACE 400
#define JVC_HDR_MARK 8000
#define JVC_HDR_SPACE 4000
#define JVC_BIT_MARK 600
#define JVC_ONE_SPACE 1600
#define JVC_ZERO_SPACE 550
#define JVC_RPT_LENGTH 60000
#define LG_HDR_MARK 8000
#define LG_HDR_SPACE 4000
#define LG_BIT_MARK 600
#define LG_ONE_SPACE 1600
#define LG_ZERO_SPACE 550
#define LG_RPT_LENGTH 60000
/*
#define SAMSUNG_HDR_MARK 5000
#define SAMSUNG_HDR_SPACE 5000
#define SAMSUNG_BIT_MARK 560
#define SAMSUNG_ONE_SPACE 1600
#define SAMSUNG_ZERO_SPACE 560
#define SAMSUNG_RPT_SPACE 2250
*/
// Update by Sebastien Warin for my EU46D6200
#define SAMSUNG_HDR_MARK 4500
#define SAMSUNG_HDR_SPACE 4500
#define SAMSUNG_BIT_MARK 590
#define SAMSUNG_ONE_SPACE 1690
#define SAMSUNG_ZERO_SPACE 590
#define SAMSUNG_RPT_SPACE 2250
#define SHARP_BITS 15
#define DISH_BITS 16
#define DENON_BITS 14 // The number of bits in the command
#define DENON_HDR_MARK 300 // The length of the Header:Mark
#define DENON_HDR_SPACE 750 // The lenght of the Header:Space
#define DENON_BIT_MARK 300 // The length of a Bit:Mark
#define DENON_ONE_SPACE 1800 // The length of a Bit:Space for 1's
#define DENON_ZERO_SPACE 750 // The length of a Bit:Space for 0's
#define TOLERANCE 25 // percent tolerance in measurements
#define LTOL (1.0 - TOLERANCE/100.)
#define UTOL (1.0 + TOLERANCE/100.)
#define _GAP 5000 // Minimum map between transmissions
#define GAP_TICKS (_GAP/USECPERTICK)
#define TICKS_LOW(us) (int) (((us)*LTOL/USECPERTICK))
#define TICKS_HIGH(us) (int) (((us)*UTOL/USECPERTICK + 1))
// receiver states
#define STATE_IDLE 2
#define STATE_MARK 3
#define STATE_SPACE 4
#define STATE_STOP 5
#define ERR 0
#define DECODED 1
// information for the interrupt handler
typedef struct {
uint8_t recvpin; // pin for IR data from detector
uint8_t rcvstate; // state machine
unsigned int timer; // state timer, counts 50uS ticks.
unsigned int rawbuf[RAWBUF]; // raw data
uint8_t rawlen; // counter of entries in rawbuf
}
irparams_t;
// Defined in IRremote.cpp
extern volatile irparams_t irparams;
// IR detector output is active low
#define MARK 0
#define SPACE 1
#define TOPBIT 0x80000000
#define NEC_BITS 32
#define SONY_BITS 12
#define SANYO_BITS 12
#define MITSUBISHI_BITS 16
#define MIN_RC5_SAMPLES 11
#define MIN_RC6_SAMPLES 1
#define PANASONIC_BITS 48
#define JVC_BITS 16
#define LG_BITS 28
#define SAMSUNG_BITS 32
#define WHYNTER_BITS 32
#endif

View file

@ -0,0 +1,458 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 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.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, 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 library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete 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 distribute a copy of this License along with the
Library.
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 Library or any portion
of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
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 Library, 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 Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you 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.
If distribution of 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 satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be 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.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. 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 not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library 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.
9. 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 Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
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 with
this License.
11. 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 Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library 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 Library.
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.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library 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.
13. The Free Software Foundation may publish revised and/or new
versions of the 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
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 Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
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
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. 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 LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

View file

@ -0,0 +1,27 @@
# IRremote ESP8266 Library
This library enables you to **send and receive** infra-red signals on an ESP8266 using Arduino framework (https://github.com/esp8266/Arduino)
This library is based on Ken Shirriff's work (https://github.com/shirriff/Arduino-IRremote/)
[Mark Szabo](https://github.com/markszabo/IRremoteESP8266) has updated the IRsend class to work on ESP8266 and [Sebastien Warin](https://github.com/sebastienwarin/IRremoteESP8266) the receiving & decoding part (IRrecv class).
Seb's notes : I also changed the pulse parameters for Samsung, update the Panasonic and Samsung decoders and remove the SANYO decoders. The IR decoder was successfully tested with Panasonic and Samsung remote controls.
## Installation
1. Click "Download ZIP"
2. Extract the downloaded zip file
3. Rename the extracted folder to "IRremoteESP8266"
4. Move this folder to your libraries directory (under windows: C:\Users\YOURNAME\Documents\Arduino\libraries\)
5. Restart your Arduino ide
6. Check out the examples
## Contributing
If you want to contribute to this project:
- Report bugs and errors
- Ask for enhancements
- Create issues and pull requests
- Tell other people about this library
## Contributors
Check [here](Contributors.md)

View file

@ -0,0 +1,88 @@
/*
* IRremoteESP8266: IRServer - demonstrates sending IR codes controlled from a webserver
* An IR LED must be connected to ESP8266 pin 0.
* Version 0.1 June, 2015
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <IRremoteESP8266.h>
const char* ssid = ".....";
const char* password = ".....";
MDNSResponder mdns;
ESP8266WebServer server(80);
IRsend irsend(0);
void handleRoot() {
server.send(200, "text/html", "<html><head> <title>ESP8266 Demo</title></head><body><h1>Hello from ESP8266, you can send NEC encoded IR signals from here!</h1><p><a href=\"ir?code=16769055\">Send 0xFFE01F</a></p><p><a href=\"ir?code=16429347\">Send 0xFAB123</a></p><p><a href=\"ir?code=16771222\">Send 0xFFE896</a></p></body></html>");
}
void handleIr(){
for (uint8_t i=0; i<server.args(); i++){
if(server.argName(i) == "code")
{
unsigned long code = server.arg(i).toInt();
irsend.sendNEC(code, 36);
}
}
handleRoot();
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
irsend.begin();
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (mdns.begin("esp8266", WiFi.localIP())) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/ir", handleIr);
server.on("/inline", [](){
server.send(200, "text/plain", "this works as well");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}

View file

@ -0,0 +1,28 @@
/*
* IRremoteESP8266: IRrecvDemo - demonstrates receiving IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 Sept, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
*/
#include <IRremoteESP8266.h>
int RECV_PIN = 2; //an IR detector/demodulatord is connected to GPIO pin 2
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
}
delay(100);
}

View file

@ -0,0 +1,89 @@
/*
* IRremoteESP8266: IRrecvDump - dump details of IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 Sept, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
* LG added by Darryl Smith (based on the JVC protocol)
*/
#include <IRremoteESP8266.h>
int RECV_PIN = 2; //an IR detector/demodulatord is connected to GPIO pin 2
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void dump(decode_results *results) {
// Dumps out the decode_results structure.
// Call this after IRrecv::decode()
int count = results->rawlen;
if (results->decode_type == UNKNOWN) {
Serial.print("Unknown encoding: ");
}
else if (results->decode_type == NEC) {
Serial.print("Decoded NEC: ");
}
else if (results->decode_type == SONY) {
Serial.print("Decoded SONY: ");
}
else if (results->decode_type == RC5) {
Serial.print("Decoded RC5: ");
}
else if (results->decode_type == RC6) {
Serial.print("Decoded RC6: ");
}
else if (results->decode_type == PANASONIC) {
Serial.print("Decoded PANASONIC - Address: ");
Serial.print(results->panasonicAddress, HEX);
Serial.print(" Value: ");
}
else if (results->decode_type == LG) {
Serial.print("Decoded LG: ");
}
else if (results->decode_type == JVC) {
Serial.print("Decoded JVC: ");
}
else if (results->decode_type == AIWA_RC_T501) {
Serial.print("Decoded AIWA RC T501: ");
}
else if (results->decode_type == WHYNTER) {
Serial.print("Decoded Whynter: ");
}
Serial.print(results->value, HEX);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
Serial.print("Raw (");
Serial.print(count, DEC);
Serial.print("): ");
for (int i = 1; i < count; i++) {
if (i & 1) {
Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
}
else {
Serial.write('-');
Serial.print((unsigned long) results->rawbuf[i]*USECPERTICK, DEC);
}
Serial.print(" ");
}
Serial.println();
}
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
dump(&results);
irrecv.resume(); // Receive the next value
}
}

View file

@ -0,0 +1,169 @@
/*
* IRremoteESP8266: IRrecvDumpV2 - dump details of IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 Sept, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
*/
#include <IRremoteESP8266.h>
int RECV_PIN = 2; //an IR detector/demodulator is connected to GPIO pin 2
IRrecv irrecv(RECV_PIN);
void setup ( )
{
Serial.begin(9600); // Status message will be sent to PC at 9600 baud
irrecv.enableIRIn(); // Start the receiver
}
//+=============================================================================
// Display IR code
//
void ircode (decode_results *results)
{
// Panasonic has an Address
if (results->decode_type == PANASONIC) {
Serial.print(results->panasonicAddress, HEX);
Serial.print(":");
}
// Print Code
Serial.print(results->value, HEX);
}
//+=============================================================================
// Display encoding type
//
void encoding (decode_results *results)
{
switch (results->decode_type) {
default:
case UNKNOWN: Serial.print("UNKNOWN"); break ;
case NEC: Serial.print("NEC"); break ;
case SONY: Serial.print("SONY"); break ;
case RC5: Serial.print("RC5"); break ;
case RC6: Serial.print("RC6"); break ;
case DISH: Serial.print("DISH"); break ;
case SHARP: Serial.print("SHARP"); break ;
case JVC: Serial.print("JVC"); break ;
case SANYO: Serial.print("SANYO"); break ;
case MITSUBISHI: Serial.print("MITSUBISHI"); break ;
case SAMSUNG: Serial.print("SAMSUNG"); break ;
case LG: Serial.print("LG"); break ;
case WHYNTER: Serial.print("WHYNTER"); break ;
case AIWA_RC_T501: Serial.print("AIWA_RC_T501"); break ;
case PANASONIC: Serial.print("PANASONIC"); break ;
}
}
//+=============================================================================
// Dump out the decode_results structure.
//
void dumpInfo (decode_results *results)
{
// Show Encoding standard
Serial.print("Encoding : ");
encoding(results);
Serial.println("");
// Show Code & length
Serial.print("Code : ");
ircode(results);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
}
//+=============================================================================
// Dump out the decode_results structure.
//
void dumpRaw (decode_results *results)
{
// Print Raw data
Serial.print("Timing[");
Serial.print(results->rawlen-1, DEC);
Serial.println("]: ");
for (int i = 1; i < results->rawlen; i++) {
unsigned long x = results->rawbuf[i] * USECPERTICK;
if (!(i & 1)) { // even
Serial.print("-");
if (x < 1000) Serial.print(" ") ;
if (x < 100) Serial.print(" ") ;
Serial.print(x, DEC);
} else { // odd
Serial.print(" ");
Serial.print("+");
if (x < 1000) Serial.print(" ") ;
if (x < 100) Serial.print(" ") ;
Serial.print(x, DEC);
if (i < results->rawlen-1) Serial.print(", "); //',' not needed for last one
}
if (!(i % 8)) Serial.println("");
}
Serial.println(""); // Newline
}
//+=============================================================================
// Dump out the decode_results structure.
//
void dumpCode (decode_results *results)
{
// Start declaration
Serial.print("unsigned int "); // variable type
Serial.print("rawData["); // array name
Serial.print(results->rawlen - 1, DEC); // array size
Serial.print("] = {"); // Start declaration
// Dump data
for (int i = 1; i < results->rawlen; i++) {
Serial.print(results->rawbuf[i] * USECPERTICK, DEC);
if ( i < results->rawlen-1 ) Serial.print(","); // ',' not needed on last one
if (!(i & 1)) Serial.print(" ");
}
// End declaration
Serial.print("};"); //
// Comment
Serial.print(" // ");
encoding(results);
Serial.print(" ");
ircode(results);
// Newline
Serial.println("");
// Now dump "known" codes
if (results->decode_type != UNKNOWN) {
// Some protocols have an address
if (results->decode_type == PANASONIC) {
Serial.print("unsigned int addr = 0x");
Serial.print(results->panasonicAddress, HEX);
Serial.println(";");
}
// All protocols have data
Serial.print("unsigned int data = 0x");
Serial.print(results->value, HEX);
Serial.println(";");
}
}
//+=============================================================================
// The repeating section of the code
//
void loop ( )
{
decode_results results; // Somewhere to store the results
if (irrecv.decode(&results)) { // Grab an IR code
dumpInfo(&results); // Output the results
dumpRaw(&results); // Output the results in RAW format
dumpCode(&results); // Output the results as source code
Serial.println(""); // Blank line between entries
irrecv.resume(); // Prepare for the next value
}
}

View file

@ -0,0 +1,25 @@
/*
* IRremoteESP8266: IRsendDemo - demonstrates sending IR codes with IRsend
* An IR LED must be connected to ESP8266 pin 0.
* Version 0.1 June, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
*/
#include <IRremoteESP8266.h>
IRsend irsend(0); //an IR led is connected to GPIO pin 0
void setup()
{
irsend.begin();
Serial.begin(9600);
}
void loop() {
Serial.println("NEC");
irsend.sendNEC(0x00FFE01F, 36);
delay(2000);
Serial.println("Sony");
irsend.sendSony(0xa90, 12);
delay(2000);
}

View file

@ -0,0 +1,29 @@
/*
* IRremoteESP8266: IRsendDemo - demonstrates sending IR codes with IRsend
* An IR LED must be connected to ESP8266 pin 0.
* Version 0.1 June, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
*/
#include <IRremoteESP8266.h>
#define PanasonicAddress 0x4004 // Panasonic address (Pre data)
#define PanasonicPower 0x100BCBD // Panasonic Power button
#define JVCPower 0xC5E8
IRsend irsend(0); //an IR led is connected to GPIO pin 0
void setup()
{
irsend.begin();
}
void loop() {
irsend.sendPanasonic(PanasonicAddress,PanasonicPower); // This should turn your TV on and off
irsend.sendJVC(JVCPower, 16,0); // hex value, 16 bits, no repeat
delayMicroseconds(50); // see http://www.sbprojects.com/knowledge/ir/jvc.php for information
irsend.sendJVC(JVCPower, 16,1); // hex value, 16 bits, repeat
delayMicroseconds(50);
}

View file

@ -0,0 +1,57 @@
#######################################
# Syntax Coloring Map For IRremote
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
decode_results KEYWORD1
IRrecv KEYWORD1
IRsend KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
decode KEYWORD2
enableIRIn KEYWORD2
disableIRIn KEYWORD2
resume KEYWORD2
begin KEYWORD2
enableIROut KEYWORD2
sendNEC KEYWORD2
sendSony KEYWORD2
sendSanyo KEYWORD2
sendMitsubishi KEYWORD2
sendRaw KEYWORD2
sendRC5 KEYWORD2
sendRC6 KEYWORD2
sendDISH KEYWORD2
sendSharp KEYWORD2
sendSharpRaw KEYWORD2
sendPanasonic KEYWORD2
sendJVC KEYWORD2
sendWhynter KEYWORD2
sendSAMSUNG KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
NEC LITERAL1
SONY LITERAL1
SANYO LITERAL1
MITSUBISHI LITERAL1
RC5 LITERAL1
RC6 LITERAL1
DISH LITERAL1
SHARP LITERAL1
PANASONIC LITERAL1
JVC LITERAL1
LG LITERAL1
SAMSUNG LITERAL1
WHYNTER LITERAL1
AIWA_RC_T501 LITERAL1
UNKNOWN LITERAL1
REPEAT LITERAL1

View file

@ -0,0 +1,12 @@
{
"name": "IRremoteESP8266",
"keywords": "infrared, ir, remote",
"description": "Send and receive infrared signals with multiple protocols",
"repository":
{
"type": "git",
"url": "https://github.com/sebastienwarin/IRremoteESP8266.git"
},
"frameworks": "arduino",
"platforms": "esp8266"
}

View file

@ -0,0 +1,9 @@
name=IRremoteESP8266
version=1.0.0
author=Sebastien Warin, Mark Szabo, Ken Shirriff
maintainer=Sebastien Warin
sentence=Send and receive infrared signals with multiple protocols.
paragraph=This library enables you to send and receive infra-red signals on an ESP8266.
category=Device Control
url=https://github.com/sebastienwarin/IRremoteESP8266
architectures=esp8266

View file

@ -0,0 +1,21 @@
#
# Example PlatformIO configuration file for SSL and non-SSL builds.
#
# Before you will be able to build the SSL version of this project, you will
# need to explicitly install the espressif8266_stage platform.
#
# To perform this installation, refer to step 1 of:
# http://docs.platformio.org/en/latest/platforms/espressif8266.html#using-arduino-framework-with-staging-version
[platformio]
env_default = nossl
[common]
framework = arduino
lib_deps = ESP8266MQTTMesh
[env:nossl]
platform = espressif8266
framework = arduino
board = esp01_1m
lib_deps = ${common.lib_deps}

View file

@ -0,0 +1,240 @@
/*
* Copyright (C) 2016 PhracturedBlue
*
* 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 <http://www.gnu.org/licenses/>.
*
* Based on IRremoteESP8266: IRServer - demonstrates sending IR codes controlled from a webserver
*
* esp8266IR Remote allows Pronto IR codes to be sent via an IR LED connected on GPIO2 via http
* It is recommended to drive an n-fet transistor connected to a resistor and diode, since the
* esp8266 can only supply 12mA on its GPIO pin.
*
* Known commands:
* NOTE: The maximum length of topic + payload is ~1156 bytes
* <topic>/send : code=<pronto code> : send specified code one time
* <topic>/send : repeat=5,code=<pronto code> : send specified code 5 times
* <topic>/send : repeat=5,code=<pronto code1>,repeat=3,pronto=<pronto code2> : send code1 5 times followed by sending code2 3 times
* <topic>/send : repeat=5,file=<filename> : send pronto code previously saved in 'filename' 5 times
* <topic>/list : "" : returns a list of all saved files
* <topic>/debug: <1|0> : enable/disable debugging messages over MQTT
* <topic>/save/<filename> : code=<pronto code> : save specified pronto code to 'filename' on esp8266 device
* <topic>/read/<filename> : "" : return contents of 'flename' via MQTT
*
* <topic> will generally be something like: 'esp8266-in/mesh_esp8266-7'
* Version 0.2 2017-04-16
*/
/* See credentials.h.examle for contents of credentials.h */
#include "credentials.h"
#include <ESP8266WiFi.h>
#include <FS.h>
#include <ESP8266MQTTMesh.h>
#include <IRremoteESP8266.h>
#include "QueueArray.h"
#define FIRMWARE_ID 0x2222
#define FIRMWARE_VER "0.2"
const wifi_conn networks[] = NETWORK_LIST;
const char* mqtt_server = MQTT_SERVER;
const char* mesh_password = MESH_PASSWORD;
ESP8266MQTTMesh mesh = ESP8266MQTTMesh::Builder(networks, mqtt_server)
.setVersion(FIRMWARE_VER, FIRMWARE_ID)
.setMeshPassword(mesh_password)
.build();
#define ESP8266_LED 2
bool debug = false;
class Cmd {
public:
Cmd(String _c, int _r, String _p, String _d = "") {
code = _c;
repeat = _r;
protocol = _p;
description = _d;
}
String code;
String protocol;
String description;
int repeat;
};
QueueArray<struct Cmd *> cmdQueue(10);
IRsend irsend(ESP8266_LED);
void handleList() {
String message = "{ \"Commands\": {";
Dir dir = SPIFFS.openDir("/ir/");
bool first = true;
while(dir.next()) {
if (! first) {
message += ",";
}
File f = dir.openFile("r");
int size = f.size();
f.close();
message += " \"" + dir.fileName().substring(4) + "\": " + String(size);
first = false;
}
FSInfo fs_info;
SPIFFS.info(fs_info);
message += " }, \"Free\": " + String(fs_info.totalBytes - fs_info.usedBytes) + "}";
mesh.publish("list", message.c_str());
}
Cmd *parse_code(const char *msg, bool queue = false) {
String code = "";
String protocol = "pronto";
int repeat = 0;
bool debug = false;
bool seen_repeat = false;
while (msg) {
char kv[1024];
char key[16];
const char *value;
ESP8266MQTTMesh::keyValue(msg, ',', kv, sizeof(kv), &msg);
if (! ESP8266MQTTMesh::keyValue(kv, '=', key, sizeof(key), &value)) {
continue;
};
if (0 == strcmp(key, "repeat")) {
repeat = atoi(value);
seen_repeat = true;
}
else if (0 == strcmp(key, "protocol")) {
protocol = value;
}
else if(0 == strcmp(key, "code")) {
code = value;
if (queue) {
cmdQueue.push(new Cmd(code, repeat, protocol, "Code len: " + String(code.length())));
}
}
else if(0 == strcmp(key, "file")) {
File f = SPIFFS.open("/ir/" + String(value), "r");
if (! f) {
Serial.println("Failed to read file: " + String(value));
continue;
}
protocol = f.readStringUntil('\n');
code = f.readStringUntil('\n');
String repeat_str = f.readStringUntil('\n');
if (repeat_str != "" && !seen_repeat) {
repeat = repeat_str.toInt();
}
if (queue) {
cmdQueue.push(new Cmd(code, repeat, protocol, "File: " + String(value)));
}
f.close();
}
}
if (queue) {
return NULL;
}
Cmd *cmd = new Cmd(code, repeat, protocol);
return cmd;
}
void callback(const char *topic, const char *msg)
{
char *endStr;
if (0 == strcmp(topic, "list")) {
handleList();
}
if (0 == strcmp(topic, "debug")) {
debug = atoi(msg);
}
else if (0 == strcmp(topic, "send")) {
parse_code(msg, true);
}
else if (strstr(topic, "read/") == topic) {
const char *filename = topic + 5;
File f = SPIFFS.open("/ir/" + String(filename), "r");
if (! f) {
Serial.println("Failed to read file: " + String(filename));
mesh.publish(topic, "{ \"Failed\": 1 }");
return;
}
String json = "{";
json += " \"protocol\": \"" + f.readStringUntil('\n') + "\"";
json += " \"code\": \"" + f.readStringUntil('\n') + "\"";
json += " \"repeat\": \"" + f.readStringUntil('\n') + "\"";
json += " }";
mesh.publish(topic, json.c_str());
}
else if (strstr(topic, "save/") == topic) {
const char *filename = topic + 5;
Cmd *cmd = parse_code(msg);
File f = SPIFFS.open("/ir/" + String(filename), "w");
if (! f) {
Serial.println("Failed to create file: " + String(filename));
mesh.publish(topic, "{ \"Failed\": 1 }");
} else {
f.print(cmd->protocol + "\n");
f.print(cmd->code + "\n");
f.print(String(cmd->repeat) + "\n");
f.close();
}
delete cmd;
}
}
void setup(void){
irsend.begin();
Serial.begin(115200);
mesh.setCallback(callback);
mesh.begin();
Serial.println("");
if (1) {
FSInfo fs_info;
SPIFFS.info(fs_info);
Serial.print("FS Used: ");
Serial.print(fs_info.usedBytes);
Serial.print(" Free: ");
Serial.print(fs_info.totalBytes - fs_info.usedBytes);
Serial.print(" Blocksize: ");
Serial.println(fs_info.blockSize);
Dir dir = SPIFFS.openDir("/ir/");
while(dir.next()) {
Serial.println("File: " + dir.fileName());
}
}
}
void loop(void){
if (! cmdQueue.isEmpty()) {
Cmd *nextCmd = cmdQueue.peek();
Serial.println("Sendng code: Repeat=" + String(nextCmd->repeat) + " queue size= " + cmdQueue.count());
if (debug) {
mesh.publish("tx", String("Queue Len: " + String(cmdQueue.count()) + " Repeat: " + String(nextCmd->repeat) + " Desc: " + nextCmd->description).c_str());
}
while (1) {
irsend.sendPronto(nextCmd->code.c_str(), nextCmd->repeat ? true : false, true);
if (nextCmd->repeat >= -1) {
break;
}
nextCmd->repeat++;
}
//irsend.sendPronto(nextCmd->code.c_str(), nextCmd->repeat ? true : false, true);
if (nextCmd->repeat <= 1) {
nextCmd = cmdQueue.pop();
delete nextCmd;
} else {
nextCmd->repeat--;
}
}
}

View file

@ -0,0 +1,242 @@
/*
* QueueArray.h
*
* Library implementing a generic, dynamic queue (array version).
*
* ---
*
* Copyright (C) 2010 Efstathios Chatzikyriakidis (contact@efxa.org)
*
* 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 <http://www.gnu.org/licenses/>.
*
* ---
*
* 2013-11-07 Marcus Nowotny <interactive-matter.eu>
* - pushing to a full array does not crash but returns false
*
* 2013-11-05 Marcus Nowotny <interactive-matter.eu>
* - rewritten to use a default size
* - texts are now in flash
*
* Version 1.0
*
* 2010-09-29 Efstathios Chatzikyriakidis <contact@efxa.org>
*
* - added resize(): for growing, shrinking the array size.
*
* 2010-09-25 Efstathios Chatzikyriakidis <contact@efxa.org>
*
* - added exit(), blink(): error reporting and handling methods.
*
* 2010-09-24 Alexander Brevig <alexanderbrevig@gmail.com>
*
* - added setPrinter(): indirectly reference a Serial object.
*
* 2010-09-20 Efstathios Chatzikyriakidis <contact@efxa.org>
*
* - initial release of the library.
*
* ---
*
* For the latest version see: http://www.arduino.cc/
*/
// header defining the interface of the source.
#ifndef _QUEUEARRAY_H
#define _QUEUEARRAY_H
// include Arduino basic header.
#include <Arduino.h>
// the definition of the queue class.
template<typename T>
class QueueArray {
public:
// init the queue (constructor).
QueueArray (const uint16_t initialSize);
// clear the queue (destructor).
~QueueArray ();
// push an item to the queue.
bool push (const T i);
// pop an item from the queue.
T pop ();
// get an item from the queue.
T peek () const;
// check if the queue is empty.
bool isEmpty () const;
// get the number of items in the queue.
uint16_t count () const;
// check if the queue is full.
bool isFull () const;
// set the printer of the queue.
void setStream (Stream & s);
private:
// exit report method in case of error.
void exit(const __FlashStringHelper*) const;
// led blinking method in case of error.
void blink () const;
Stream * stream; // the printer of the queue.
T * contents; // the array of the queue.
uint16_t size; // the size of the queue.
uint16_t items; // the number of items of the queue.
uint16_t head; // the head of the queue.
uint16_t tail; // the tail of the queue.
};
// init the queue (constructor).
template<typename T>
QueueArray<T>::QueueArray (const uint16_t initialSize) {
size = 0; // set the size of queue to zero.
items = 0; // set the number of items of queue to zero.
head = 0; // set the head of the queue to zero.
tail = 0; // set the tail of the queue to zero.
stream = NULL; // set the printer of queue to point nowhere.
// allocate enough memory for the array.
contents = (T *) malloc (sizeof (T) * initialSize);
// if there is a memory allocation error.
if (contents == NULL)
exit (F("QUEUE: insufficient memory to initialize queue."));
// set the initial size of the queue.
size = initialSize;
}
// clear the queue (destructor).
template<typename T>
QueueArray<T>::~QueueArray () {
free (contents); // deallocate the array of the queue.
contents = NULL; // set queue's array pointer to nowhere.
stream = NULL; // set the printer of queue to point nowhere.
size = 0; // set the size of queue to zero.
items = 0; // set the number of items of queue to zero.
head = 0; // set the head of the queue to zero.
tail = 0; // set the tail of the queue to zero.
}
// push an item to the queue.
template<typename T>
bool QueueArray<T>::push (const T i) {
// check if the queue is full.
if (isFull ())
// we cannot add anythif - just return false
return false;
// store the item to the array.
contents[tail++] = i;
// wrap-around index.
if (tail == size) tail = 0;
// increase the items.
items++;
//ok everything was fin
return true;
}
// pop an item from the queue.
template<typename T>
T QueueArray<T>::pop () {
// check if the queue is empty.
if (isEmpty ())
exit (F("QUEUE: can't pop item from queue: queue is empty."));
// fetch the item from the array.
T item = contents[head++];
// decrease the items.
items--;
// wrap-around index.
if (head == size) head = 0;
// return the item from the array.
return item;
}
// get an item from the queue.
template<typename T>
T QueueArray<T>::peek () const {
// check if the queue is empty.
if (isEmpty ())
exit (F("QUEUE: can't peek item from queue: queue is empty."));
// get the item from the array.
return contents[head];
}
// check if the queue is empty.
template<typename T>
bool QueueArray<T>::isEmpty () const {
return items == 0;
}
// check if the queue is full.
template<typename T>
bool QueueArray<T>::isFull () const {
return items == size;
}
// get the number of items in the queue.
template<typename T>
uint16_t QueueArray<T>::count () const {
return items;
}
// set the printer of the queue.
template<typename T>
void QueueArray<T>::setStream (Stream & s) {
stream = &s;
}
// exit report method in case of error.
template<typename T>
void QueueArray<T>::exit (const __FlashStringHelper * m) const {
// print the message if there is a printer.
if (stream)
stream->println (m);
// loop blinking until hardware reset.
blink ();
}
// led blinking method in case of error.
template<typename T>
void QueueArray<T>::blink () const {
while(1);
// solution selected due to lack of exit() and assert().
}
#endif // _QUEUEARRAY_H

View file

@ -0,0 +1,441 @@
#====================================================================================
# makeESPArduino
#
# A makefile for ESP8286 and ESP32 Arduino projects.
# Edit the contents of this file to suit your project
# or just include it and override the applicable macros.
#
# License: GPL 2.1
# General and full license information is available at:
# https://github.com/plerup/makeEspArduino
#
# Copyright (c) 2016-2017 Peter Lerup. All rights reserved.
#
#====================================================================================
#====================================================================================
# Project specfic values
#====================================================================================
# Include possible project makefile. This can be used to override the defaults below
-include $(firstword $(PROJ_CONF) $(dir $(SKETCH))config.mk)
#=== Default values not available in the Arduino configuration files
CHIP ?= esp8266
# Set chip specific default board unless specified
BOARD ?= $(if $(filter $(CHIP), esp32),esp32,generic)
# Serial flashing parameters
UPLOAD_PORT ?= $(shell ls -1tr /dev/ttyUSB* | tail -1)
UPLOAD_VERB ?= -v
# OTA parameters
ESP_ADDR ?= ESP_123456
ESP_PORT ?= 8266
ESP_PWD ?= 123
# HTTP update parameters
HTTP_ADDR ?= ESP_123456
HTTP_URI ?= /update
HTTP_PWD ?= user
HTTP_USR ?= password
# Output directory
BUILD_DIR ?= /tmp/mkESP/$(MAIN_NAME)_$(BOARD)
# File system source directory
FS_DIR ?= $(dir $(SKETCH))data
# Bootloader
BOOT_LOADER ?= $(ESP_ROOT)/bootloaders/eboot/eboot.elf
#====================================================================================
# Standard build logic and values
#====================================================================================
START_TIME := $(shell perl -e "print time();")
# Utility functions
git_description = $(shell git -C $(1) describe --tags --always --dirty 2>/dev/null || echo Unknown)
time_string = $(shell date +$(1))
# ESP Arduino directories
ifndef ESP_ROOT
# Location not defined, find and use possible version in the Arduino IDE installation
OS ?= $(shell uname -s)
ifeq ($(OS), Windows_NT)
ARDUINO_DIR = $(shell cygpath -m $(LOCALAPPDATA)/Arduino15/packages/$(CHIP))
else ifeq ($(OS), Darwin)
ARDUINO_DIR = $(HOME)/Library/Arduino15/packages/$(CHIP)
else
ARDUINO_DIR = $(HOME)/.arduino15/packages/$(CHIP)
endif
ESP_ROOT := $(lastword $(wildcard $(ARDUINO_DIR)/hardware/$(CHIP)/*))
ifeq ($(ESP_ROOT),)
$(error No installed version of $(CHIP) Arduino found)
endif
ESP_ARDUINO_VERSION := $(notdir $(ESP_ROOT))
# Find used version of compiler and tools
COMP_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/xtensa-lx106-elf-gcc/*))
ESPTOOL_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/esptool/*))
MKSPIFFS_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/mkspiffs/*))
else
# Location defined, assume it is a git clone
ESP_ARDUINO_VERSION = $(call git_description,$(ESP_ROOT))
endif
ESP_LIBS = $(ESP_ROOT)/libraries
SDK_ROOT = $(ESP_ROOT)/tools/sdk
TOOLS_ROOT = $(ESP_ROOT)/tools
ifeq ($(wildcard $(ESP_ROOT)/cores/$(CHIP)),)
$(error $(ESP_ROOT) is not a vaild directory for $(CHIP))
endif
ESPTOOL_PY = esptool.py --baud=$(UPLOAD_SPEED) --port $(UPLOAD_PORT)
# Search for sketch if not defined
SKETCH := $(realpath $(firstword \
$(SKETCH) \
$(wildcard *.ino) \
$(if $(filter $(CHIP), esp32),$(ESP_LIBS)/WiFi/examples/WiFiScan/WiFiScan.ino,$(ESP_LIBS)/ESP8266WebServer/examples/HelloServer/HelloServer.ino) \
) \
)
ifeq ($(wildcard $(SKETCH)),)
$(error Sketch $(SKETCH) not found)
endif
# Main output definitions
MAIN_NAME := $(basename $(notdir $(SKETCH)))
MAIN_EXE = $(BUILD_DIR)/$(MAIN_NAME).bin
FS_IMAGE = $(BUILD_DIR)/FS.spiffs
ifeq ($(OS), Windows_NT)
# Adjust critical paths
BUILD_DIR := $(shell cygpath -m $(BUILD_DIR))
SKETCH := $(shell cygpath -m $(SKETCH))
endif
# Build file extensions
OBJ_EXT = .o
DEP_EXT = .d
# Special tool definitions
OTA_TOOL ?= $(TOOLS_ROOT)/espota.py
HTTP_TOOL ?= curl
# Core source files
CORE_DIR = $(ESP_ROOT)/cores/$(CHIP)
CORE_SRC := $(shell find $(CORE_DIR) -name "*.S" -o -name "*.c" -o -name "*.cpp")
CORE_OBJ := $(patsubst %,$(BUILD_DIR)/%$(OBJ_EXT),$(notdir $(CORE_SRC)))
CORE_LIB = $(BUILD_DIR)/arduino.ar
# User defined compilation units and directories
ifeq ($(LIBS),)
# Automatically find directories with header files used by the sketch
FINDCMD := perl -e 'use File::Find;@d = split(" ", shift);while (<>) {$$f{"$$1"} = 1 if /^\s*\#include\s+[<"]([^>"]+)/;}find({follow => 1, wanted => sub {return if($$File::Find::dir =~ /examples|tests/);print $$File::Find::dir," " if $$f{$$_}}}, @d);'
LIBS := $(shell $(FINDCMD) "$(ESP_LIBS) $(HOME)/Arduino/libraries" $(SKETCH) ../../src/*.cpp ../../src/*.h)
ifeq ($(LIBS),)
# No dependencies found
LIBS = /dev/null
endif
endif
IGNORE_PATTERN := $(foreach dir,$(EXCLUDE_DIRS),$(dir)/%)
SKETCH_DIR = $(dir $(SKETCH))
USER_INC := $(filter-out $(IGNORE_PATTERN),$(shell find -L $(SKETCH_DIR) $(LIBS) -name "*.h"))
USER_SRC := $(SKETCH) $(filter-out $(IGNORE_PATTERN),$(shell find -L $(SKETCH_DIR) $(LIBS) -name "*.S" -o -name "*.c" -o -name "*.cpp"))
# Object file suffix seems to be significant for the linker...
USER_OBJ := $(subst .ino,_.cpp,$(patsubst %,$(BUILD_DIR)/%$(OBJ_EXT),$(notdir $(USER_SRC))))
USER_DIRS := $(sort $(dir $(USER_SRC)))
USER_INC_DIRS := $(sort $(dir $(USER_INC)))
# Use first flash definition for the board as default
FLASH_DEF ?= $(shell cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) {if (/^$(BOARD)\.menu\.FlashSize\.([^\.]+)=/){ print "$$1"; exit;}} print "NA";')
# The actual build commands are to be extracted from the Arduino description files
ARDUINO_MK = $(BUILD_DIR)/arduino.mk
ARDUINO_DESC := $(shell find $(ESP_ROOT) -maxdepth 1 -name "*.txt" | sort)
$(ARDUINO_MK): $(ARDUINO_DESC) $(MAKEFILE_LIST) | $(BUILD_DIR)
perl -e "$$PARSE_ARDUINO" $(BOARD) $(FLASH_DEF) $(ARDUINO_EXTRA_DESC) $(ARDUINO_DESC) >$(ARDUINO_MK)
-include $(ARDUINO_MK)
# Compilation directories and path
INCLUDE_DIRS += $(CORE_DIR) $(ESP_ROOT)/variants/$(INCLUDE_VARIANT) $(BUILD_DIR)
C_INCLUDES := $(foreach dir,$(INCLUDE_DIRS) $(USER_INC_DIRS),-I$(dir))
VPATH += $(shell find $(CORE_DIR) -type d) $(USER_DIRS)
# Automatically generated build information data
# Makes the build date and git descriptions at the actual build event available as string constants in the program
BUILD_INFO_H = $(BUILD_DIR)/buildinfo.h
BUILD_INFO_CPP = $(BUILD_DIR)/buildinfo.c++
BUILD_INFO_OBJ = $(BUILD_INFO_CPP)$(OBJ_EXT)
$(BUILD_INFO_H): | $(BUILD_DIR)
echo "typedef struct { const char *date, *time, *src_version, *env_version;} _tBuildInfo; extern _tBuildInfo _BuildInfo;" >$@
# Build rules for the different source file types
$(BUILD_DIR)/%.cpp$(OBJ_EXT): %.cpp $(BUILD_INFO_H) $(ARDUINO_MK)
echo $(<F)
$(CPP_COM) $(CPP_EXTRA) $< -o $@
$(BUILD_DIR)/%_.cpp$(OBJ_EXT): %.ino $(BUILD_INFO_H) $(ARDUINO_MK)
echo $(<F)
$(CPP_COM) $(CPP_EXTRA) -x c++ -include $(CORE_DIR)/Arduino.h $< -o $@
$(BUILD_DIR)/%.c$(OBJ_EXT): %.c $(ARDUINO_MK)
echo $(<F)
$(C_COM) $(C_EXTRA) $< -o $@
$(BUILD_DIR)/%.S$(OBJ_EXT): %.S $(ARDUINO_MK)
echo $(<F)
$(S_COM) $(S_EXTRA) $< -o $@
$(CORE_LIB): $(CORE_OBJ)
echo Creating core archive
rm -f $@
$(AR_COM) $^
BUILD_DATE = $(call time_string,"%Y-%m-%d")
BUILD_TIME = $(call time_string,"%H:%M:%S")
SRC_GIT_VERSION := $(call git_description,$(dir $(SKETCH)))
$(MAIN_EXE): $(CORE_LIB) $(USER_OBJ)
echo Linking $(MAIN_EXE)
echo " Versions: $(SRC_GIT_VERSION), $(ESP_ARDUINO_VERSION)"
echo '#include <buildinfo.h>' >$(BUILD_INFO_CPP)
echo '_tBuildInfo _BuildInfo = {"$(BUILD_DATE)","$(BUILD_TIME)","$(SRC_GIT_VERSION)","$(ESP_ARDUINO_VERSION)"};' >>$(BUILD_INFO_CPP)
$(CPP_COM) $(BUILD_INFO_CPP) -o $(BUILD_INFO_OBJ)
$(LD_COM)
$(GEN_PART_COM)
$(ELF2BIN_COM)
$(SIZE_COM) | perl -e "$$MEM_USAGE" "$(MEM_FLASH)" "$(MEM_RAM)"
ifneq ($(FLASH_INFO),)
printf "Flash size: $(FLASH_INFO)\n\n"
endif
perl -e 'print "Build complete. Elapsed time: ", time()-$(START_TIME), " seconds\n\n"'
upload flash: all
$(UPLOAD_COM)
ota: all
$(OTA_TOOL) -i $(ESP_ADDR) -p $(ESP_PORT) -a $(ESP_PWD) -f $(MAIN_EXE)
http: all
$(HTTP_TOOL) --verbose -F image=@$(MAIN_EXE) --user $(HTTP_USR):$(HTTP_PWD) http://$(HTTP_ADDR)$(HTTP_URI)
echo "\n"
$(FS_IMAGE): $(wildcard $(FS_DIR)/*)
ifneq ($(CHIP),esp32)
echo Generating filesystem image: $(FS_IMAGE)
$(MKSPIFFS_COM)
else
echo No SPIFFS function available for $(CHIP)
exit 1
endif
fs: $(FS_IMAGE)
upload_fs flash_fs: $(FS_IMAGE)
$(FS_UPLOAD_COM)
FLASH_FILE ?= esp_flash.bin
dump_flash:
echo Dumping flash memory to file: $(FLASH_FILE)
$(ESPTOOL_PY) read_flash 0 $(shell perl -e 'shift =~ /(\d+)([MK])/ || die "Invalid memory size\n";$$mem_size=$$1*1024;$$mem_size*=1024 if $$2 eq "M";print $$mem_size;' $(FLASH_DEF)) $(FLASH_FILE)
restore_flash:
echo Restoring flash memory from file: $(FLASH_FILE)
$(ESPTOOL_PY) write_flash -fs $(shell perl -e 'shift =~ /(\d+)([MK])/ || die "Invalid memory size\n";print ($$2 eq "K" ? 2 : $$1*8);' $(FLASH_DEF))m -fm $(FLASH_MODE) -ff $(FLASH_SPEED)m 0 $(FLASH_FILE)
clean:
echo Removing all build files
rm -rf $(BUILD_DIR)/*
list_boards:
echo === Available boards ===
cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) { if (/^(\w+)\.name=(.+)/){ print sprintf("%-20s %s\n", $$1,$$2);} }'
list_lib:
echo === User specific libraries ===
perl -e 'foreach (@ARGV) {print "$$_\n"}' "* Include directories:" $(USER_INC_DIRS) "* Library source files:" $(USER_SRC) "Foo" $(IGNORE_PATTERN)
list_flash_defs:
echo === Memory configurations for board: $(BOARD) ===
cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) { if (/^$(BOARD)\.menu\.FlashSize.([^\.]+)=(.+)/){ print sprintf("%-10s %s\n", $$1,$$2);} }'
help:
echo
echo "Generic makefile for building Arduino esp8266 and esp32 projects"
echo "This file can either be used directly or included from another makefile"
echo ""
echo "The following targets are available:"
echo " all (default) Build the project application"
echo " clean Remove all intermediate build files"
echo " flash Build and and flash the project application"
echo " flash_fs Build and and flash file system (when applicable)"
echo " ota Build and and flash via OTA"
echo " Params: ESP_ADDR, ESP_PORT and ESP_PWD"
echo " http Build and and flash via http (curl)"
echo " Params: HTTP_ADDR, HTTP_URI, HTTP_PWD and HTTP_USR"
echo " dump_flash Dump the whole board flash memory to a file"
echo " restore_flash Restore flash memory from a previously dumped file"
echo " list_lib Show a list of used library files and include paths"
echo "Configurable parameters:"
echo " SKETCH Main source file"
echo " If not specified the first sketch in current"
echo " directory will be used. If none is found there,"
echo " a demo example will be used instead."
echo " LIBS Includes in the sketch file of libraries from within"
echo " the ESP Arduino directories are automatically"
echo " detected. If this is not enough, define this"
echo " variable with all libraries or directories needed."
echo " USER_LIBS Path to user installed Arduino libraries"
echo " CHIP Set to esp8266 or esp32. Default: '$(CHIP)'"
echo " BOARD Name of the target board. Default: '$(BOARD)'"
echo " Use 'list_boards' to get list of available ones"
echo " FLASH_DEF Flash partitioning info. Default '$(FLASH_DEF)'"
echo " Use 'list_flash_defs' to get list of available ones"
echo " BUILD_DIR Directory for intermediate build files."
echo " Default '$(BUILD_DIR)'"
echo " BUILD_EXTRA_FLAGS Additional parameters for the compilation commands"
echo " FS_DIR File system root directory"
echo " UPLOAD_PORT Serial flashing port name. Default: '$(UPLOAD_PORT)'"
echo " UPLOAD_SPEED Serial flashing baud rate. Default: '$(UPLOAD_SPEED)'"
echo " FLASH_FILE File name for dump and restore flash operations"
echo " Default: '$(FLASH_FILE)'"
echo " VERBOSE Set to 1 to get full printout of the build"
echo " SINGLE_THREAD Use only one build thread"
echo
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
.PHONY: all
all: $(BUILD_DIR) $(ARDUINO_MK) $(BUILD_INFO_H) prebuild $(MAIN_EXE)
prebuild:
ifdef USE_PREBUILD
$(PREBUILD_COM)
endif
# Include all available dependencies
-include $(wildcard $(BUILD_DIR)/*$(DEP_EXT))
.DEFAULT_GOAL = all
ifndef SINGLE_THREAD
# Use multithreaded builds by default
MAKEFLAGS += -j
endif
ifndef VERBOSE
# Set silent mode as default
MAKEFLAGS += --silent
endif
# Inline Perl scripts
# Parse Arduino definitions and build commands from the descriptions
define PARSE_ARDUINO
my $$board = shift;
my $$flashSize = shift;
my %v;
sub def_var {
my ($$name, $$var) = @_;
print "$$var ?= $$v{$$name}\n";
$$v{$$name} = "\$$($$var)";
}
$$v{'runtime.platform.path'} = '$$(ESP_ROOT)';
$$v{'includes'} = '$$(C_INCLUDES)';
$$v{'runtime.ide.version'} = '10605';
$$v{'build.arch'} = '$$(CHIP)';
$$v{'build.project_name'} = '$$(MAIN_NAME)';
$$v{'build.path'} = '$$(BUILD_DIR)';
$$v{'object_files'} = '$$^ $$(BUILD_INFO_OBJ)';
foreach my $$fn (@ARGV) {
open($$f, $$fn) || die "Failed to open: $$fn\n";
while (<$$f>) {
next unless /^(\w[\w\-\.]+)=(.*)/;
my ($$key, $$val) =($$1, $$2);
$$board_defined = 1 if $$key eq "$$board.name";
$$key =~ s/$$board\.menu\.FlashSize\.$$flashSize\.//;
$$key =~ s/$$board\.menu\.FlashFreq\.[^\.]+\.//;
$$key =~ s/$$board\.menu\.UploadSpeed\.[^\.]+\.//;
$$key =~ s/^$$board\.//;
$$v{$$key} ||= $$val;
}
close($$f);
}
$$v{'runtime.tools.xtensa-lx106-elf-gcc.path'} ||= '$$(COMP_PATH)';
$$v{'runtime.tools.esptool.path'} ||= '$$(ESPTOOL_PATH)';
$$v{'runtime.tools.mkspiffs.path'} ||= '$$(MKSPIFFS_PATH)';
die "* Uknown board $$board\n" unless $$board_defined;
print "# Board definitions\n";
def_var('build.f_cpu', 'F_CPU');
def_var('build.flash_mode', 'FLASH_MODE');
def_var('build.flash_freq', 'FLASH_SPEED');
def_var('upload.resetmethod', 'UPLOAD_RESET');
def_var('upload.speed', 'UPLOAD_SPEED');
def_var('compiler.warning_flags', 'COMP_WARNINGS');
$$v{'upload.verbose'} = '$$(UPLOAD_VERB)';
$$v{'serial.port'} = '$$(UPLOAD_PORT)';
$$v{'recipe.objcopy.hex.pattern'} =~ s/[^"]+\/bootloaders\/eboot\/eboot.elf/\$$(BOOT_LOADER)/;
$$v{'tools.esptool.upload.pattern'} =~ s/\{(cmd|path)\}/\{tools.esptool.$$1\}/g;
$$v{'compiler.cpreprocessor.flags'} .= " \$$(C_PRE_PROC_FLAGS)";
$$v{'build.extra_flags'} .= " \$$(BUILD_EXTRA_FLAGS)";
foreach my $$key (sort keys %v) {
while ($$v{$$key} =~/\{/) {
$$v{$$key} =~ s/\{([\w\-\.]+)\}/$$v{$$1}/;
$$v{$$key} =~ s/""//;
}
$$v{$$key} =~ s/ -o $$//;
$$v{$$key} =~ s/(-D\w+=)"([^"]+)"/$$1\\"$$2\\"/g;
}
print "INCLUDE_VARIANT = $$v{'build.variant'}\n";
print "# Commands\n";
print "C_COM=$$v{'recipe.c.o.pattern'}\n";
print "CPP_COM=$$v{'recipe.cpp.o.pattern'}\n";
print "S_COM=$$v{'recipe.S.o.pattern'}\n";
print "AR_COM=$$v{'recipe.ar.pattern'}\n";
print "LD_COM=$$v{'recipe.c.combine.pattern'}\n";
print "GEN_PART_COM=$$v{'recipe.objcopy.eep.pattern'}\n";
print "ELF2BIN_COM=$$v{'recipe.objcopy.hex.pattern'}\n";
print "SIZE_COM=$$v{'recipe.size.pattern'}\n";
my $$flash_size = sprintf("0x%X", hex($$v{'build.spiffs_end'})-hex($$v{'build.spiffs_start'}));
print "MKSPIFFS_COM=$$v{'tools.mkspiffs.path'}/$$v{'tools.mkspiffs.cmd'} -b $$v{'build.spiffs_blocksize'} -s $$flash_size -c \$$(FS_DIR) \$$(FS_IMAGE)\n";
print "UPLOAD_COM=$$v{'tools.esptool.upload.pattern'}\n";
my $$fs_upload_com = $$v{'tools.esptool.upload.pattern'};
$$fs_upload_com =~ s/(.+ -ca) .+/$$1 $$v{'build.spiffs_start'} -cf \$$(FS_IMAGE)/;
print "FS_UPLOAD_COM=$$fs_upload_com\n";
my $$val = $$v{'recipe.hooks.core.prebuild.1.pattern'};
$$val =~ s/bash -c "(.+)"/$$1/;
$$val =~ s/(#define .+0x)(\`)/"\\$$1\"$$2/;
$$val =~ s/(\\)//;
print "PREBUILD_COM=$$val\n";
print "MEM_FLASH=$$v{'recipe.size.regex'}\n";
print "MEM_RAM=$$v{'recipe.size.regex.data'}\n";
print "FLASH_INFO=$$v{'menu.FlashSize.' . $$flashSize}\n"
endef
export PARSE_ARDUINO
# Convert memory information
define MEM_USAGE
$$fp = shift;
$$rp = shift;
while (<>) {
$$r += $$1 if /$$rp/;
$$f += $$1 if /$$fp/;
}
print "\nMemory usage\n";
print sprintf(" %-6s %6d bytes\n" x 2 ."\n", "Ram:", $$r, "Flash:", $$f);
endef
export MEM_USAGE

View file

@ -0,0 +1,27 @@
# ESP8266MeshSensor
This example is designed to use the ESP8266MQTTMesh library with a Sonoff Relay
(it has only been tested with the SonoffPOW, but should work with other variants
with minor changes)
## Required Libraries
The following libraries are required to build ths example
* ESP8266MQTTMesh
* HLW8012 (if using a Sonoff POW)
* OneWire (if using DS18B20)
* DallasTemperature (is using DS18B20)
## Compiling
The collowing configurations are needed before compiling:
* copy credentials.h.example to credentials.h and update as needed
* ensure the relevant pins are defined if you have a DS18B20 or HLW8012
## MQTT Commands
| Topic | Message | Description |
|---------------------|-------------|-------------|
| \<prefix>/heartbeat | \<number> | How often to send current status in millseconds (default 60000) |
| \<prefix>/expectedpower | \<number> | Calculate HLW8012 calibration based on current power |
| \<prefix>/expectedvoltage | \<number> | Calculate HLW8012 calibration based on current voltage |
| \<prefix>/expectedcurrent | \<number> | Calculate HLW8012 calibration based on current current |
| \<prefix>/resetpower | \<number> | Reset all of the HLW8012 calibration values |

View file

@ -0,0 +1,4 @@
FLASH_DEF = 2M
USER_LIBS = ${HOME}/Arduino/libraries/
CPP_EXTRA = -Wall
BUILD_EXTRA_FLAGS = "-DMQTT_MAX_PACKET_SIZE=1152"

View file

@ -0,0 +1,12 @@
#define NETWORK_LIST { \
"ssid 1", \
"ssid 2", \
"", \
}
#define NETWORK_PASSWORD "network password"
#define MESH_PASSWORD "esp8266_sensor_mesh"
#define BASE_SSID "mesh_esp8266-"
#define MQTT_SERVER "MQTT Server IP Address"
#define MQTT_PORT 1883
#define MESH_PORT 1884

View file

@ -0,0 +1,27 @@
#
# Example PlatformIO configuration file for SSL and non-SSL builds.
#
# Before you will be able to build the SSL version of this project, you will
# need to explicitly install the espressif8266_stage platform.
#
# To perform this installation, refer to step 1 of:
# http://docs.platformio.org/en/latest/platforms/espressif8266.html#using-arduino-framework-with-staging-version
[platformio]
env_default = nossl
[common]
framework = arduino
lib_deps = ESP8266MQTTMesh
lib_deps_external =
HLW8012
OneWire
DallasTemperature
[env:nossl]
platform = espressif8266@~1.6.0
framework = arduino
board = esp01_1m
lib_deps =
${common.lib_deps}
${common.lib_deps_external}

View file

@ -0,0 +1,393 @@
/*
* Copyright (C) 2016 PhracturedBlue
*
* 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 <http://www.gnu.org/licenses/>.
*
* HLW8012 code Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
*/
/* Sonoff POW w/ DS18B20 attached to GPIO2(SDA) */
#define GREEN_LED 15 //MTDO
#define RELAY 12 //MTDI
#define BUTTON 0 //GPIO0
#define DS18B20 2 //GPIO2
#define HLW8012_SEL 5 //GPIO5
#define HLW8012_CF 14 //MTMS
#define HLW8012_CF1 13 //MTCK
/* See credentials.h.examle for contents of credentials.h */
#include "credentials.h"
#include "capabilities.h"
#include <ESP8266WiFi.h>
#include <FS.h>
#if HAS_DS18B20
#include <OneWire.h>
#include <DallasTemperature.h>
#endif
#if HAS_HLW8012
#include <HLW8012.h>
#endif
#include <ESP8266MQTTMesh.h>
#if HAS_DS18B20 && HAS_HLW8012
#define FIRMWARE_ID 0x4455
#elif HAS_DS18B20
#define FIRMWARE_ID 0x4454
#elif HAS_HLW8012
#define FIRMWARE_ID 0x4453
#else
#define FIRMWARE_ID 0x4452
#endif
#define FIRMWARE_VER "0.8.1"
//const char* networks[] = NETWORK_LIST;
const wifi_conn networks[] = {
WIFI_CONN("foo", NETWORK_PASSWORD, NULL, false),
WIFI_CONN("bar", NETWORK_PASSWORD, "XX:XX:XX:XX:XX:XX", true),
NULL
};
const char* mesh_password = MESH_PASSWORD;
const char* mqtt_server = MQTT_SERVER;
#if HAS_DS18B20
OneWire oneWire(DS18B20);
DallasTemperature ds18b20(&oneWire);
DeviceAddress ds18b20Address;
#endif
#if HAS_HLW8012
#define HLW8012_CURRENT_R 0.001
#define HLW8012_VOLTAGE_R_UP ( 5 * 470000 ) // Real: 2280k
#define HLW8012_VOLTAGE_R_DOWN ( 1000 ) // Real 1.009k
#define HLW8012_UPDATE_INTERVAL 2000
#define HLW8012_MIN_CURRENT 0.05
#define HLW8012_MIN_POWER 10
HLW8012 hlw8012;
unsigned int power_sum;
unsigned int voltage_sum;
double current_sum;
double energy; //in Watt-Seconds
unsigned long power_sample_count = 0;
bool hlw8012Enabled = false;
void hlw8012_cf1_interrupt();
void hlw8012_cf_interrupt();
void hlw8012_enable_interrupts(bool enabled);
unsigned int hlw8012_getActivePower();
double hlw8012_getCurrent();
unsigned int hlw8012_getVoltage();
#endif
ESP8266MQTTMesh mesh = ESP8266MQTTMesh::Builder(networks, mqtt_server)
.setVersion(FIRMWARE_VER, FIRMWARE_ID)
.setMeshPassword(mesh_password)
.build();
bool relayState = false;
bool stateChanged = false;
int heartbeat = 60000;
float temperature = 0.0;
void read_config();
void save_config();
void callback(const char *topic, const char *msg);
String build_json();
void setup() {
pinMode(GREEN_LED, OUTPUT);
pinMode(RELAY, OUTPUT);
pinMode(BUTTON, INPUT);
Serial.begin(115200);
delay(5000);
mesh.setCallback(callback);
mesh.begin();
#if HAS_DS18B20
ds18b20.begin();
ds18b20.getAddress(ds18b20Address, 0);
ds18b20.setWaitForConversion(false);
ds18b20.requestTemperatures();
#endif
Serial.println("HLW8012 start");
#if HAS_HLW8012
hlw8012.begin(HLW8012_CF, HLW8012_CF1, HLW8012_SEL, HIGH, true);
hlw8012.setResistors(HLW8012_CURRENT_R, HLW8012_VOLTAGE_R_UP, HLW8012_VOLTAGE_R_DOWN);
#endif
Serial.println("HLW8012 end");
//mesh.setup will initialize the filesystem
if (SPIFFS.exists("/config")) {
read_config();
}
Serial.println("config end");
digitalWrite(RELAY, relayState);
}
void loop() {
static unsigned long pressed = 0;
static unsigned long lastSend = 0;
static bool needToSend = false;
unsigned long now = millis();
#if HAS_DS18B20
if (ds18b20.isConversionAvailable(ds18b20Address)) {
temperature = ds18b20.getTempF(ds18b20Address);
ds18b20.requestTemperatures();
}
#endif
#if HAS_HLW8012
if (! hlw8012Enabled && mesh.connected()) {
hlw8012_enable_interrupts(true);
} else if (hlw8012Enabled && ! mesh.connected()) {
hlw8012_enable_interrupts(false);
}
static unsigned long last_hlw8012_update = 0;
if (now - last_hlw8012_update > HLW8012_UPDATE_INTERVAL) {
static unsigned int power[3] = {0};
static unsigned int voltage[3] = {0};
static double current[3] = {0};
for (int i = 0; i < 2; i++) {
power[i] = power[i+1];
voltage[i] = voltage[i+1];
current[i] = current[i+1];
}
power[2] = hlw8012_getActivePower();
voltage[2] = hlw8012_getVoltage();
current[2] = hlw8012_getCurrent();
//Spike removal
if (power[1] > 0 && power[0] == 0 && power[2] == 0) {
power[1] = 0;
}
if (current[1] > 0 && current[0] == 0 && current[2] == 0) {
current[1] = 0;
}
if (voltage[1] > 0 && voltage[0] == 0 && voltage[2] == 0) {
voltage[1] = 0;
}
power_sum += power[0];
current_sum += current[0];
voltage_sum += voltage[0];
energy += 1.0 * power[0] * (now - last_hlw8012_update) / 1000.0;
power_sample_count++;
last_hlw8012_update = now;
}
#endif
if (! digitalRead(BUTTON)) {
if(pressed == 0) {
relayState = ! relayState;
digitalWrite(RELAY, relayState);
stateChanged = true;
}
pressed = now;
} else if (pressed && now - pressed > 100) {
pressed = 0;
}
if (stateChanged) {
save_config();
needToSend = true;
stateChanged = false;
} else if (now - lastSend > heartbeat) {
needToSend = true;
}
if (! mesh.connected()) {
return;
}
if (needToSend) {
lastSend = now;
String data = build_json();
#if HAS_HLW8012
power_sum = 0;
current_sum = 0;
voltage_sum = 0;
power_sample_count = 0;
#endif
mesh.publish("status", data.c_str());
needToSend = false;
}
}
void callback(const char *topic, const char *msg) {
if (0 == strcmp(topic, "heartbeat")) {
unsigned int hb = strtoul(msg, NULL, 10);
if (hb > 10000) {
heartbeat = hb;
save_config();
}
}
else if (0 == strcmp(topic, "state")) {
bool nextState = strtoul(msg, NULL, 10) ? true : false;
if (relayState != nextState) {
relayState = nextState;
digitalWrite(RELAY, relayState);
stateChanged = true;
}
}
#if HAS_HLW8012
else if (0 == strcmp(topic, "expectedpower")) {
int pow = atoi(msg);
if (pow > 0) {
hlw8012.expectedActivePower(pow);
save_config();
}
}
else if (0 == strcmp(topic, "expectedvoltage")) {
int volt = atoi(msg);
if (volt > 0) {
hlw8012.expectedVoltage(volt);
save_config();
}
}
else if (0 == strcmp(topic, "expectedcurrent")) {
double current = atof(msg);
if (current > 0) {
hlw8012.expectedCurrent(current);
save_config();
}
}
else if (0 == strcmp(topic, "resetpower")) {
int state = atoi(msg);
if (state > 0) {
hlw8012.resetMultipliers();
save_config();
}
}
#endif //HAS_HLW8012
}
String build_json() {
String msg = "{";
msg += " \"relay\":\"" + String(relayState ? "ON" : "OFF") + "\"";
#if HAS_DS18B20
msg += ", \"temp\":" + String(temperature, 2);
#endif
#if HAS_HLW8012
double count = power_sample_count ? power_sample_count : 1;
double power = (double)power_sum / count;
double current = (double)current_sum / count;
double voltage = (double)voltage_sum / count;
double apparent= voltage * current;
double pfactor = (apparent > 0) ? 100 * power / apparent : 100;
if (pfactor > 100) {
pfactor = 100;
}
msg += ", \"power\":" + String(power, 3);
msg += ", \"current\":" + String(current, 3);
msg += ", \"voltage\":" + String(voltage, 3);
msg += ", \"pf\":" + String(pfactor, 3);
msg += ", \"energy\":" + String(energy / 3600, 3); //Watt-Hours
#endif
msg += "}";
return msg;
}
void read_config() {
File f = SPIFFS.open("/config", "r");
if (! f) {
Serial.println("Failed to read config");
return;
}
while(f.available()) {
char s[32];
char key[32];
const char *value;
s[f.readBytesUntil('\n', s, sizeof(s)-1)] = 0;
if (! ESP8266MQTTMesh::keyValue(s, '=', key, sizeof(key), &value)) {
continue;
}
if (0 == strcmp(key, "RELAY")) {
relayState = value[0] == '0' ? 0 : 1;
}
else if (0 == strcmp(key, "HEARTBEAT")) {
heartbeat = atoi(value);
if (heartbeat < 1000) {
heartbeat = 1000;
} else if (heartbeat > 60 * 60 * 1000) {
heartbeat = 5 * 60 * 1000;
}
}
#if HAS_HLW8012
else if (0 == strcmp(key, "hlw8012PowerMult")) {
double dbl = atof(value);
if (dbl > 0) hlw8012.setPowerMultiplier(dbl);
}
else if (0 == strcmp(key, "hlw8012CurrentMult")) {
double dbl = atof(value);
if (dbl > 0) hlw8012.setCurrentMultiplier(dbl);
}
else if (0 == strcmp(key, "hlw8012VoltageMult")) {
double dbl = atof(value);
if (dbl > 0) hlw8012.setVoltageMultiplier(dbl);
}
#endif //HAS_HLW8012
}
f.close();
}
void save_config() {
File f = SPIFFS.open("/config", "w");
if (! f) {
Serial.println("Failed to write config");
return;
}
f.print("RELAY=" + String(relayState ? "1" : "0") + "\n");
f.print("HEARTBEAT=" + String(heartbeat) + "\n");
#if HAS_HLW8012
f.print("hlw8012PowerMult=" + String(hlw8012.getPowerMultiplier()));
f.print("hlw8012CurrentMult=" + String(hlw8012.getCurrentMultiplier()));
f.print("hlw8012VoltageMult=" + String(hlw8012.getVoltageMultiplier()));
#endif
f.close();
}
// When using interrupts we have to call the library entry point
// whenever an interrupt is triggered
#if HAS_HLW8012
void hlw8012_cf1_interrupt() {
hlw8012.cf1_interrupt();
}
void hlw8012_cf_interrupt() {
hlw8012.cf_interrupt();
}
void hlw8012_enable_interrupts(bool enabled) {
if (enabled) {
attachInterrupt(HLW8012_CF1, hlw8012_cf1_interrupt, CHANGE);
attachInterrupt(HLW8012_CF, hlw8012_cf_interrupt, CHANGE);
hlw8012Enabled = true;
} else {
detachInterrupt(HLW8012_CF1);
detachInterrupt(HLW8012_CF);
hlw8012Enabled = false;
}
}
unsigned int hlw8012_getActivePower() {
unsigned int power = hlw8012.getActivePower();
if (power < HLW8012_MIN_POWER) power = 0;
return power;
}
double hlw8012_getCurrent() {
double current = hlw8012.getCurrent();
if (current < HLW8012_MIN_CURRENT) current = 0;
return current;
}
unsigned int hlw8012_getVoltage() {
return hlw8012.getVoltage();
}
#endif

View file

@ -0,0 +1,15 @@
#ifndef _CAPABILITIES_H_
#define _CAPABILITIES_H_
#ifdef DS18B20
#define HAS_DS18B20 1
#else
#define HAS_DS18B20 0
#endif
#if defined(HLW8012_SEL) && defined(HLW8012_CF) && defined (HLW8012_CF1)
#define HAS_HLW8012 1
#else
#define HAS_HLW8012 0
#endif
#endif //_CAPABILITIES_H_