diff --git a/.gitea/workflows/build-release.yml b/.gitea/workflows/build-release.yml index 477a43b..b357293 100644 --- a/.gitea/workflows/build-release.yml +++ b/.gitea/workflows/build-release.yml @@ -67,16 +67,13 @@ jobs: echo "tag_name=${TAG_NAME}" >> "$GITHUB_OUTPUT" echo "short_sha=${SHORT_SHA}" >> "$GITHUB_OUTPUT" - - name: Set version tag in sources - env: - TAG_NAME: ${{ steps.prep.outputs.tag_name }} - run: | - sed -i "s/version_tag/${TAG_NAME}/g" main/User_config.h scripts/latest_version.json - - name: Build OpenMQTTGateway Firmware (${{ steps.prep.outputs.pio_env }}) env: PIO_ENV: ${{ steps.prep.outputs.pio_env }} + TAG_NAME: ${{ steps.prep.outputs.tag_name }} run: | + # Inject the firmware version (same mechanism as upstream scripts/ci_build_firmware.sh) + export PLATFORMIO_BUILD_FLAGS="-DOMG_VERSION=\\\"${TAG_NAME}\\\"" mkdir -p ".pio/build/${PIO_ENV}" pio run -e "${PIO_ENV}" diff --git a/.gitignore b/.gitignore index 4887bbf..9185faa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,50 @@ .pio .vscode *_env.ini +*.pem **/.DS_Store node_modules *.ps1 main/certs/private* lib/* !lib/esp32-bt-lib +!lib/TheengsUtils +!lib/LEDManager CMakeLists.txt dependencies.lock sdkconfig.* !sdkconfig.defaults +__pycache__ +*.pem +managed_components + + +.github/chatmodes +.github/prompts +.github/*instructions.md +.github/workflows/_docs +# CI/CD Generated outputs +docs/.vitepress/dist/ +docs/.vitepress/cache/ +docs/.vitepress/public/boards-info.json +docs/.vitepress/public/commonConfig.js +docs/.vitepress/public/firmware_build + +# Generated site/firmware/reports files +generated/ + +# Generated ssl for testing +.ssl + +# Generated JSON files from templates +scripts/latest_version.json +scripts/latest_version_dev.json + +# Generated configuration files +docs/.vitepress/meta.json + +# Generated full documentation pages +docs/prerequisites/board-full.md +docs/upload/web-install-full.md +.superpowers/ +docs/superpowers/ diff --git a/.shellcheckrc b/.shellcheckrc new file mode 100644 index 0000000..db9bb42 --- /dev/null +++ b/.shellcheckrc @@ -0,0 +1 @@ +disable=SC1091 \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..56f138f --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,319 @@ +# OpenMQTTGateway - Claude Code Context + +This document provides essential context about the OpenMQTTGateway project for AI assistants working on the codebase. + +## Project Overview + +OpenMQTTGateway is a unified firmware that bridges various wireless technologies (RF 433MHz, IR, BLE, LoRa, etc.) to MQTT protocol, enabling home automation integration with platforms like Home Assistant, OpenHAB, and Node-RED. + +**Key Features:** +- Multi-protocol gateway (BLE, RF 433MHz, IR, LoRa, RTL_433, Pilight, etc.) +- ESP8266/ESP32 and Arduino support +- MQTT-based communication +- Web UI for configuration +- Home Assistant MQTT Discovery support +- Over 100 supported BLE sensors via Theengs Decoder + +**Main Branch:** `development` (not master/main) + +## Architecture + +### Modular Design + +The firmware uses a modular architecture where each protocol/sensor/actuator is implemented as a separate "gateway" or "sensor" module: + +- **Gateways**: Receive and transmit signals (e.g., `gatewayBT.cpp`, `gatewayRF.cpp`, `gatewayIR.cpp`) +- **Sensors**: Read physical sensor data (e.g., `sensorBME280.cpp`, `sensorDHT.cpp`) +- **Actuators**: Control outputs (e.g., `actuatorONOFF.cpp`, `actuatorPWM.cpp`) + +Each module has: +- A config file (e.g., `config_BT.h`, `config_RF.h`) +- An implementation file (e.g., `gatewayBT.cpp`, `gatewayRF.cpp`) + +### Configuration System + +Configuration is managed through: +1. **User_config.h** - Main configuration file with defaults +2. **config_*.h** - Module-specific configurations +3. **platformio.ini & environments.ini** - Build-time configurations +4. **prod_env.ini** - User-specific environments (gitignored) + +Build flags in `environments.ini` can override User_config.h parameters. + +## Directory Structure + +``` +OpenMQTTGateway/ +├── main/ # Main source code (Arduino convention) +│ ├── main.cpp # Main application entry point +│ ├── User_config.h # Global configuration +│ ├── config_*.h # Module configurations +│ ├── gateway*.cpp # Gateway implementations +│ ├── sensor*.cpp # Sensor implementations +│ ├── actuator*.cpp # Actuator implementations +│ ├── webUI.cpp # Web interface +│ ├── mqttDiscovery.cpp # Home Assistant discovery +│ └── rf/ # RF-specific modules +├── lib/ # Custom libraries +├── scripts/ # Build and automation scripts +├── docs/ # VuePress documentation +├── tests/ # Test configurations +├── environments.ini # PlatformIO environment definitions +├── platformio.ini # PlatformIO configuration +└── prod_env.ini.example # Example production environment + +Note: src_dir is set to "main" in platformio.ini +``` + +## Key Concepts + +### Environment-Based Builds + +The project supports 80+ hardware configurations defined in `environments.ini`. Examples: +- `esp32dev-ble` - ESP32 with BLE gateway +- `esp32dev-pilight` - ESP32 with Pilight RF +- `esp32dev-rtl_433` - ESP32 with RTL_433 decoder +- `nodemcuv2-ir` - NodeMCU with IR +- `rfbridge` - Sonoff RF Bridge + +### MQTT Topics + +Standard topic structure: +- Base: `home/` (configurable via Base_Topic) +- Gateway name: `OpenMQTTGateway` or `OMG` (configurable) +- Example: `home/OpenMQTTGateway/BTtoMQTT` + +### Module Activation + +Modules are activated via build flags in environments.ini: +```ini +build_flags = + '-DZgatewayBT="BT"' # Enable BLE gateway + '-DZgatewayRF="RF"' # Enable RF gateway + '-DZsensorBME280="BME280"' # Enable BME280 sensor +``` + +### Web UI & WiFi Manager + +- ESP32/ESP8266 boards include a WiFiManager for initial setup +- Access point: SSID = `WifiManager_ssid`, Password = `WifiManager_password` +- Web UI provides runtime configuration and control +- Can disable WiFiManager with `ESPWifiManualSetup` flag + +## Important Files + +### Core Files + +- **main/main.cpp** - Main application loop, MQTT handling, module coordination +- **main/User_config.h** - Global configuration defaults +- **main/webUI.cpp** - Web interface implementation +- **main/mqttDiscovery.cpp** - Home Assistant MQTT discovery + +### Gateway Files + +- **main/gatewayBT.cpp** - BLE gateway (uses Theengs Decoder) +- **main/gatewayRF.cpp** - RF 433MHz gateway (RCSwitch library) +- **main/gatewayRF2.cpp** - Alternative RF implementation +- **main/gatewayPilight.cpp** - Pilight protocol gateway +- **main/gatewayRTL_433.cpp** - RTL_433 decoder integration +- **main/gatewayIR.cpp** - Infrared gateway +- **main/gatewayLORA.cpp** - LoRa gateway + +### Configuration Files + +All in `main/` directory: +- **config_RF.h** - RF gateway configuration +- **config_BT.h** - BLE gateway configuration +- **config_IR.h** - IR gateway configuration +- etc. + +### Build System + +- **platformio.ini** - Main PlatformIO config +- **environments.ini** - All environment definitions (~3000+ lines) +- **scripts/** - Python scripts for build automation + +## Common Patterns + +### Adding a New Gateway Module + +1. Create `gateway[NAME].cpp` in `main/` +2. Create `config_[NAME].h` in `main/` +3. Add build flag in `environments.ini`: `-DZgateway[NAME]="[NAME]"` +4. Include conditional compilation: `#ifdef Zgateway[NAME]` +5. Implement setup function: `setup[NAME]()` +6. Implement loop function: `[NAME]toMQTT()` +7. Optionally implement MQTT callback: `MQTTto[NAME]()` + +### Adding a New Sensor Module + +Similar to gateways, but prefix with `sensor` instead of `gateway` and `Z` becomes `Zsensor`. + +### Configuration Override Pattern + +```cpp +#ifndef PARAM_NAME +# define PARAM_NAME default_value +#endif +``` + +This allows platformio.ini build flags to override defaults. + +### MQTT Publishing Pattern + +```cpp +pub(subjectToMQTT, data); // Basic publish +pub_custom_topic(topic, data, retain); // Custom topic with retain +``` + +## Development Workflow + +### Building + +```bash +# List all environments +pio run --list-targets + +# Build specific environment +pio run -e esp32dev-ble + +# Upload to device +pio run -e esp32dev-ble -t upload + +# Monitor serial +pio device monitor +``` + +### Code Formatting + +- Uses clang-format with config in `.clang-format` +- CI checks formatting automatically +- Format before committing + +### Testing + +- Unit tests in `tests/` directory +- CI runs builds for all environments +- Nightly builds test comprehensive environment matrix + +### Documentation + +- Documentation uses VuePress, located in `docs/` +- Hosted at https://docs.openmqttgateway.com + +## CI/CD + +### GitHub Actions Workflows + +Located in `.github/workflows/`: +- **build.yml** - Build validation on PRs +- **nightly.yml** - Nightly builds of all environments +- **format-check.yml** - Code formatting validation + +### Build Matrix + +The nightly build tests configurations: +- ESP32 variants (ESP32, ESP32-S3, ESP32-C3) +- ESP8266 variants (NodeMCU, Sonoff) +- Different gateway combinations +- Board-specific builds (M5Stack, Heltec, TTGO, etc.) + +## Common Issues & Solutions + +### Memory Constraints + +- ESP8266 has limited RAM (~40KB free) +- Use `PROGMEM` for constants +- Minimize module combinations on ESP8266 +- ESP32 has more headroom (~200KB+ free) + +### RF Module Conflicts + +- Some RF implementations (RF, RF2, Pilight, RTL_433) may conflict +- Use separate environments for different RF approaches +- Check GPIO pin assignments in config files + +### BLE on ESP32 + +- BLE stack uses significant RAM +- Limit simultaneous BLE connections + +## Related Projects + +- **Theengs Decoder** - BLE device decoder library +- **Theengs Gateway** - Python version for Raspberry Pi/PC +- **RTL_433_ESP** - ESP32 port of RTL_433 + +## Resources + +- **Documentation**: https://docs.openmqttgateway.com +- **Community Forum**: https://community.openmqttgateway.com +- **GitHub**: https://github.com/1technophile/OpenMQTTGateway +- **Web Installer**: https://docs.openmqttgateway.com/upload/web-install.html + +## Products + +- **Theengs Bridge** - ESP32 BLE gateway with Ethernet +- **Theengs Plug** - Smart plug with BLE gateway + +## Conventions + +### Naming + +- Gateways: `gateway[NAME].cpp` with `Zgateway[NAME]` flag +- Sensors: `sensor[NAME].cpp` with `Zsensor[NAME]` flag +- Actuators: `actuator[NAME].cpp` with `Zactuator[NAME]` flag +- Config files: `config_[NAME].h` + +### Code Style + +- 2-space indentation +- Follow existing patterns in similar modules +- Use preprocessor directives for module isolation +- Comment complex RF protocols or BLE parsing + +### Git Workflow + +- Main branch: `development` +- Feature branches from `development` +- PRs target `development` +- Squash commits when appropriate +- Descriptive commit messages + +## Quick Start for Contributors + +1. Fork the repository +2. Create `prod_env.ini` for your local environments +3. Choose an environment from `environments.ini` +4. Build: `pio run -e [environment-name]` +5. Make changes following existing patterns +6. Test build with your environment +7. Run format check +8. Submit PR to `development` branch + +## Platform-Specific Notes + +### ESP32 +- Preferred platform for new development +- More RAM and Flash +- Supports BLE natively +- Can use Ethernet via add-on boards + +### ESP8266 +- Legacy support +- Memory constrained +- No native BLE +- Good for simple RF/IR gateways + +## Tips for AI Assistants + +1. **Check environments.ini** when modifying build configurations +2. **Follow existing module patterns** when adding new features +3. **Test on relevant environments** - changes may affect multiple boards +4. **Memory is precious** especially on ESP8266 +5. **MQTT topic structure** is critical for Home Assistant integration +6. **Config headers** allow user customization without code changes +7. **Use conditional compilation** to keep builds modular +8. **WebUI changes** need both backend (webUI.cpp) and frontend (config_WebUI.h) +9. **RF protocols** often need precise timing - be careful with changes +10. **The main branch is `development`** - always target PRs there diff --git a/README.md b/README.md index 8ef78d4..c0ac0e9 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,5 @@ [![Community forum](https://img.shields.io/badge/community-forum-brightgreen.svg)](https://community.openmqttgateway.com) -![Build](https://github.com/1technophile/OpenMQTTGateway/workflows/Build/badge.svg?branch=development) -![Check Code Format](https://github.com/1technophile/OpenMQTTGateway/workflows/Check%20Code%20Format/badge.svg?branch=development) - [![OpenMQTTGateway capabilities](https://github.com/1technophile/OpenMQTTGateway/blob/development/docs/img/OpenMQTTGateway.png)](https://community.openmqttgateway.com) OpenMQTTGateway aims to unify various technologies and protocols into a single firmware. This reduces the need for multiple physical bridges and streamlines diverse technologies under the widely-used [MQTT](http://mqtt.org/) protocol. @@ -15,49 +12,39 @@ OpenMQTTGateway aims to unify various technologies and protocols into a single f The documentation is [here](https://docs.openmqttgateway.com) +New to OpenMQTTGateway? Follow the [Getting Started guide](https://docs.openmqttgateway.com/getting-started.html) to flash a board from your browser and see your first sensor data in about 15 minutes. + The reference sheet, with the list of all functions, pinouts is [here](https://docs.google.com/spreadsheets/d/1_5fQjAixzRtepkykmL-3uN3G5bLfQ0zMajM9OBZ1bx0/edit#gid=0) ## Upload -Upload OpenMQTTGateway directly from the [upload page](https://docs.openmqttgateway.com/upload/web-install.html) (no additional software required) or [build your own configuration](https://docs.openmqttgateway.com/upload/builds.html) with [PlatformIO](https://platformio.org/) or [Arduino IDE](https://www.arduino.cc/en/software) +Upload OpenMQTTGateway directly from the [upload page](https://docs.openmqttgateway.com/upload/web-install.html) (no additional software required) or [build your own configuration](https://docs.openmqttgateway.com/upload/builds.html) with [PlatformIO](https://platformio.org/). ## Using OpenMQTTGateway ? -Support open-source development through sponsorship and gain exclusive access to our private forum. Your questions, issues, and feature requests will receive priority attention, plus you'll gain insider access to our roadmap. +Support open-source development through sponsorship, it helps keep the project healthy and evolving. -[![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/theengs) +[![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/1technophile) ## Products powered by OpenMQTTGateway ### Theengs Bridge, Bluetooth gateway (BLE) with external antenna -[Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) is a powerfull BLE to MQTT gateway for over [90 sensors](https://decoder.theengs.io/devices/devices.html). Equipped with an Ethernet port, and external antenna, ensuring an enhanced range for your BLE sensors. It supports also WiFi connectivity. +[Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) is a powerfull BLE to MQTT gateway for over [100 sensors](https://decoder.theengs.io/devices/devices.html). Equipped with an Ethernet port, and external antenna, ensuring an enhanced range for your BLE sensors. It supports also WiFi connectivity. [![Theengs bridge view](./docs/img/Theengs-Bridge-ble-gateway.png)](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) -### Theengs Plug, Bluetooth gateway (BLE) gateway and Smart Plug - -[Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) brings the following features: -* BLE to MQTT gateway, tens of [Bluetooth devices](https://compatible.openmqttgateway.com/index.php/devices/ble-devices/) supported thanks to Theengs Decoder library. The plug uses an ESP32 acting as a BLE to Wifi gateway to scan, decode and forward the data of the nearby sensors, -* Smart plug that can be controlled remotely, -* Energy consumption monitoring, -* Device tracker, -* Presence detection (beta), -* Local connectivity first. - -[![Theengs plug view](./docs/img/Theengs-Plug-OpenMQTTGateway.png)](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) - -Support the project by purchasing the [Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) or the [Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) +Support the project by purchasing the [Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) ## Compatible items -* [List of supported devices](https://compatible.openmqttgateway.com/index.php/devices/), door/window sensors, PIR sensors, smoke detectors, weather stations... +* [List of supported BLE devices](https://decoder.theengs.io/devices/devices.html), thermometers, scales, plant sensors, beacons... -* [List of compatible boards (Off the shelf or DIY) is available](https://compatible.openmqttgateway.com/index.php/boards/), RF Bridge, IR, BLE gateways... +* [Boards guide](https://docs.openmqttgateway.com/prerequisites/board.html), RF Bridge, IR, BLE gateways... *Running on a computer* If you want to use the BLE decoding capabilities of OpenMQTTGateway with a Raspberry Pi, Windows or Unix PC you can now leverage [Theengs Gateway](https://theengs.github.io/gateway/). -* [List of compatible components to build your gateway](https://compatible.openmqttgateway.com/index.php/parts/), DHT, RF, IR emitters and receivers... +* [Parts to build your gateway](https://docs.openmqttgateway.com/prerequisites/parts.html), DHT, RF, IR emitters and receivers... ## Compatible controllers, saas or software @@ -82,7 +69,6 @@ For Questions or Support please don't open an issue, first go to the [docs](http If you like the project and/or used it please consider supporting it! It can be done in different ways: * Helping other users in the [community](https://community.openmqttgateway.com) * [Contribute](development) to the [code](https://github.com/1technophile/OpenMQTTGateway) or the [documentation](https://docs.openmqttgateway.com) -* Buy devices, boards or parts from the [compatible web site](https://compatible.openmqttgateway.com), the devices and parts linked use affiliated links. * Donate or sponsor the project [developers](https://github.com/1technophile/OpenMQTTGateway/graphs/contributors) * Make a video or a blog article about what you have done with [OpenMQTTGateway](https://docs.openmqttgateway.com) and share it to the [community](https://community.openmqttgateway.com) diff --git a/docs/.vitepress/commonConfig.mts b/docs/.vitepress/commonConfig.mts new file mode 100644 index 0000000..fc0bf1d --- /dev/null +++ b/docs/.vitepress/commonConfig.mts @@ -0,0 +1,41 @@ +// docs/.vitepress/commonConfig.mts +// Adapter that loads the shared Theengs commonConfig.js (CommonJS) downloaded +// by CI from https://www.theengs.io/commonConfig.js, and re-exports the nav +// and head arrays in a format VitePress can consume. +// +// This keeps theengs.io as the single source of truth for nav/head until all +// Theengs docs sites are migrated to VitePress. + +import { createRequire } from 'module' +import { existsSync } from 'fs' +import { resolve, dirname } from 'path' +import { fileURLToPath } from 'url' + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const require = createRequire(import.meta.url) + +const commonConfigPath = resolve(__dirname, 'public/commonConfig.js') + +let sharedConfig: any = null + +if (existsSync(commonConfigPath)) { + sharedConfig = require(commonConfigPath) +} else { + console.warn( + 'commonConfig.js not found in .vitepress/public/. ' + + 'Using fallback nav/head. Run CI or download from https://www.theengs.io/commonConfig.js' + ) +} + +// Re-export nav from shared config, or use a minimal fallback +export const commonNav = sharedConfig?.themeConfig?.nav ?? [ + { text: 'Home', link: 'https://www.theengs.io' }, + { text: 'Community', link: 'https://community.openmqttgateway.com' }, + { text: 'Shop', link: 'https://shop.theengs.io/' } +] + +// Re-export head from shared config, or use a minimal fallback +export const commonHead = sharedConfig?.head ?? [ + ['meta', { name: 'viewport', content: 'width=device-width, initial-scale=1' }], + ['meta', { name: 'theme-color', content: '#3eaf7c' }] +] diff --git a/docs/.vitepress/components/BoardEnvironmentTable.vue b/docs/.vitepress/components/BoardEnvironmentTable.vue new file mode 100644 index 0000000..137d727 --- /dev/null +++ b/docs/.vitepress/components/BoardEnvironmentTable.vue @@ -0,0 +1,926 @@ + + + + + diff --git a/docs/.vitepress/components/FlashEnvironmentSelector.vue b/docs/.vitepress/components/FlashEnvironmentSelector.vue new file mode 100644 index 0000000..f8b78a0 --- /dev/null +++ b/docs/.vitepress/components/FlashEnvironmentSelector.vue @@ -0,0 +1,730 @@ + + + + + diff --git a/docs/.vitepress/components/OmgPipeline.vue b/docs/.vitepress/components/OmgPipeline.vue new file mode 100644 index 0000000..6667b91 --- /dev/null +++ b/docs/.vitepress/components/OmgPipeline.vue @@ -0,0 +1,124 @@ + + + diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts new file mode 100644 index 0000000..5191bba --- /dev/null +++ b/docs/.vitepress/config.mts @@ -0,0 +1,147 @@ +// docs/.vitepress/config.mts +import { defineConfig } from 'vitepress' +import { resolve, dirname } from 'path' +import { fileURLToPath } from 'url' +import { commonNav, commonHead } from './commonConfig.mts' + +const __dirname = dirname(fileURLToPath(import.meta.url)) + +// Load metadata with override support +import defaults from './defaults.json' +let meta = { ...defaults } +try { + const overrides = await import('./meta.json') + meta = { ...meta, ...overrides.default } +} catch { + console.warn('meta.json not found or not valid. Using default configuration.') +} + +export default defineConfig({ + title: `${meta.title} - ${meta.version}`, + description: 'One gateway, many technologies: MQTT gateway for ESP8266 or ESP32 with bidirectional 433mhz/315mhz/868mhz/915mhz RF, Infrared communications, BLE, LoRa, beacons detection, mi flora / mi jia / LYWSD02/ Mi Scale compatibility, SMS & LORA.', + base: meta.url_prefix as '/' | `/${string}/`, + outDir: resolve(__dirname, '../../', meta.dest), + // Internal working documents, not part of the published site + srcExclude: ['superpowers/**'], + head: commonHead, + ignoreDeadLinks: [ + /localhost/, + /LoraTemperature/ + ], + lastUpdated: true, + markdown: { + lineNumbers: true + }, + themeConfig: { + siteTitle: 'OpenMQTTGateway', + // @ts-expect-error custom fields consumed by index.md to render the dev-version banner + mode: meta.mode, + // @ts-expect-error + version: meta.version, + // @ts-expect-error + repo: meta.theme_config_repo, + nav: commonNav, + socialLinks: [ + { icon: 'github', link: `https://github.com/${meta.theme_config_repo}` } + ], + editLink: { + pattern: `https://github.com/${meta.theme_config_repo}/edit/development/docs/:path` + }, + sidebar: [ + { text: 'What is it for', link: '/' }, + { text: 'Getting Started', link: '/getting-started' }, + { + text: '1 - Prerequisites', + collapsed: true, + items: [ + { text: 'Devices', link: '/prerequisites/devices' }, + { text: 'Board', link: '/prerequisites/board' }, + { text: 'Parts', link: '/prerequisites/parts' }, + { text: 'Broker', link: '/prerequisites/broker' }, + { text: 'Controller', link: '/prerequisites/controller' } + ] + }, + { + text: '2 - Upload', + collapsed: true, + link: '/upload/', + items: [ + { text: '1. Web installer (easiest)', link: '/upload/web-install' }, + { text: '2. Ready-to-go binaries', link: '/upload/binaries' }, + { text: '3. Build from source', link: '/upload/builds' }, + { text: 'Configuration portal', link: '/upload/portal' }, + { text: 'Portal HTTP API', link: '/upload/portal-api' }, + { text: 'Advanced Configuration', link: '/upload/advanced-configuration' }, + { text: 'Troubleshoot', link: '/upload/troubleshoot' } + ] + }, + { + text: '3 - Hardware setup', + collapsed: true, + items: [ + { text: 'RF', link: '/setitup/rf' }, + { text: 'BLE', link: '/setitup/ble' }, + { text: 'IR', link: '/setitup/ir' }, + { text: 'LoRa', link: '/setitup/lora' }, + { text: 'GSM', link: '/setitup/gsm' }, + { text: 'Serial', link: '/setitup/serial' }, + { text: 'Sensors', link: '/setitup/sensors' }, + { text: 'Actuators', link: '/setitup/actuators' } + ] + }, + { + text: '4 - Use', + collapsed: true, + items: [ + { text: 'RF', link: '/use/rf' }, + { text: 'BLE', link: '/use/ble' }, + { text: 'IR', link: '/use/ir' }, + { text: 'LoRa', link: '/use/lora' }, + { text: 'GSM', link: '/use/gsm' }, + { text: 'Serial', link: '/use/serial' }, + { text: 'RFM69', link: '/use/rfm69' }, + { text: 'Sensors', link: '/use/sensors' }, + { text: 'Actuators', link: '/use/actuators' }, + { text: 'Boards', link: '/use/boards' }, + { text: 'Displays', link: '/use/displays' }, + { text: 'Gateway', link: '/use/gateway' }, + { text: 'WebUI', link: '/use/webui' } + ] + }, + { + text: '5 - Integrate', + collapsed: true, + items: [ + { text: 'OpenHAB 2', link: '/integrate/openhab2' }, + { text: 'OpenHAB 3', link: '/integrate/openhab3' }, + { text: 'Home Assistant', link: '/integrate/home_assistant' }, + { text: 'Node-RED', link: '/integrate/node_red' }, + { text: 'AWS IoT', link: '/integrate/aws_iot' }, + { text: 'Jeedom', link: '/integrate/jeedom' } + ] + }, + { + text: '6 - Participate', + collapsed: true, + link: '/participate/', + items: [ + { text: 'Contributor Quick Start', link: '/participate/quick_start' }, + { text: 'Support', link: '/participate/support' }, + { text: 'Development', link: '/participate/development' }, + { text: 'Adding Protocols', link: '/participate/adding-protocols' }, + { text: 'Community', link: '/participate/community' }, + { text: 'License', link: meta.url_license_file } + ] + } + ], + search: { + provider: 'local' + } + }, + sitemap: { + hostname: meta.hostname + }, + vite: { + publicDir: '.vitepress/public' + } +}) diff --git a/docs/.vitepress/defaults.json b/docs/.vitepress/defaults.json new file mode 100644 index 0000000..2c8ddca --- /dev/null +++ b/docs/.vitepress/defaults.json @@ -0,0 +1,12 @@ +{ + "title": "Theengs OpenMQTTGateway", + "version": "edge", + "url_prefix": "/", + "dest": "generated/site", + "mode": "prod", + "url_license_file": "https://github.com/1technophile/OpenMQTTGateway/blob/development/LICENSE.txt", + "url_community_forum": "https://community.openmqttgateway.com", + "hostname": "https://docs.openmqttgateway.com", + "repo": "1technophile/OpenMQTTGateway", + "theme_config_repo": "1technophile/OpenMQTTGateway" +} \ No newline at end of file diff --git a/docs/.vuepress/public/apple-touch-icon.png b/docs/.vitepress/public/apple-touch-icon.png similarity index 100% rename from docs/.vuepress/public/apple-touch-icon.png rename to docs/.vitepress/public/apple-touch-icon.png diff --git a/docs/.vuepress/public/favicon-144x144.png b/docs/.vitepress/public/favicon-144x144.png similarity index 100% rename from docs/.vuepress/public/favicon-144x144.png rename to docs/.vitepress/public/favicon-144x144.png diff --git a/docs/.vuepress/public/favicon-16x16.png b/docs/.vitepress/public/favicon-16x16.png similarity index 100% rename from docs/.vuepress/public/favicon-16x16.png rename to docs/.vitepress/public/favicon-16x16.png diff --git a/docs/.vuepress/public/favicon-32x32.png b/docs/.vitepress/public/favicon-32x32.png similarity index 100% rename from docs/.vuepress/public/favicon-32x32.png rename to docs/.vitepress/public/favicon-32x32.png diff --git a/docs/.vitepress/public/img/OpenMQTTGateway-sensors-ble.png b/docs/.vitepress/public/img/OpenMQTTGateway-sensors-ble.png new file mode 100644 index 0000000..9ae8daf Binary files /dev/null and b/docs/.vitepress/public/img/OpenMQTTGateway-sensors-ble.png differ diff --git a/docs/.vitepress/public/img/OpenMQTTGateway.png b/docs/.vitepress/public/img/OpenMQTTGateway.png new file mode 100644 index 0000000..e8ce218 Binary files /dev/null and b/docs/.vitepress/public/img/OpenMQTTGateway.png differ diff --git a/docs/.vitepress/public/img/Theengs-Bridge-ble-gateway.png b/docs/.vitepress/public/img/Theengs-Bridge-ble-gateway.png new file mode 100644 index 0000000..a1b166f Binary files /dev/null and b/docs/.vitepress/public/img/Theengs-Bridge-ble-gateway.png differ diff --git a/docs/.vitepress/public/img/Theengs-Plug-OpenMQTTGateway.png b/docs/.vitepress/public/img/Theengs-Plug-OpenMQTTGateway.png new file mode 100644 index 0000000..96e8bda Binary files /dev/null and b/docs/.vitepress/public/img/Theengs-Plug-OpenMQTTGateway.png differ diff --git a/docs/.vitepress/public/img/boards/airm2m.png b/docs/.vitepress/public/img/boards/airm2m.png new file mode 100644 index 0000000..493118c Binary files /dev/null and b/docs/.vitepress/public/img/boards/airm2m.png differ diff --git a/docs/.vitepress/public/img/boards/az-delivery.jpg b/docs/.vitepress/public/img/boards/az-delivery.jpg new file mode 100644 index 0000000..a781f9a Binary files /dev/null and b/docs/.vitepress/public/img/boards/az-delivery.jpg differ diff --git a/docs/.vitepress/public/img/boards/esp32-feather.jpg b/docs/.vitepress/public/img/boards/esp32-feather.jpg new file mode 100644 index 0000000..9a9ea9b Binary files /dev/null and b/docs/.vitepress/public/img/boards/esp32-feather.jpg differ diff --git a/docs/.vitepress/public/img/boards/esp32c3-devkit-c02.png b/docs/.vitepress/public/img/boards/esp32c3-devkit-c02.png new file mode 100644 index 0000000..f6fc7f4 Binary files /dev/null and b/docs/.vitepress/public/img/boards/esp32c3-devkit-c02.png differ diff --git a/docs/.vitepress/public/img/boards/esp32c3-devkit-m1.png b/docs/.vitepress/public/img/boards/esp32c3-devkit-m1.png new file mode 100644 index 0000000..e367e8b Binary files /dev/null and b/docs/.vitepress/public/img/boards/esp32c3-devkit-m1.png differ diff --git a/docs/.vitepress/public/img/boards/esp32dev.jpg b/docs/.vitepress/public/img/boards/esp32dev.jpg new file mode 100644 index 0000000..785e977 Binary files /dev/null and b/docs/.vitepress/public/img/boards/esp32dev.jpg differ diff --git a/docs/.vitepress/public/img/boards/esp32doitv1.jpg b/docs/.vitepress/public/img/boards/esp32doitv1.jpg new file mode 100644 index 0000000..9a256ff Binary files /dev/null and b/docs/.vitepress/public/img/boards/esp32doitv1.jpg differ diff --git a/docs/.vitepress/public/img/boards/esp32s3-devkit-c1.png b/docs/.vitepress/public/img/boards/esp32s3-devkit-c1.png new file mode 100644 index 0000000..2a97806 Binary files /dev/null and b/docs/.vitepress/public/img/boards/esp32s3-devkit-c1.png differ diff --git a/docs/.vitepress/public/img/boards/heltec-wifi-kit-32.png b/docs/.vitepress/public/img/boards/heltec-wifi-kit-32.png new file mode 100644 index 0000000..3cc771f Binary files /dev/null and b/docs/.vitepress/public/img/boards/heltec-wifi-kit-32.png differ diff --git a/docs/.vitepress/public/img/boards/heltec-wifi-lora-32.png b/docs/.vitepress/public/img/boards/heltec-wifi-lora-32.png new file mode 100644 index 0000000..2444d62 Binary files /dev/null and b/docs/.vitepress/public/img/boards/heltec-wifi-lora-32.png differ diff --git a/docs/.vitepress/public/img/boards/lilygo-lora32-v21.jpg b/docs/.vitepress/public/img/boards/lilygo-lora32-v21.jpg new file mode 100644 index 0000000..3cb5928 Binary files /dev/null and b/docs/.vitepress/public/img/boards/lilygo-lora32-v21.jpg differ diff --git a/docs/.vitepress/public/img/boards/lilygo-t3-s3.jpg b/docs/.vitepress/public/img/boards/lilygo-t3-s3.jpg new file mode 100644 index 0000000..7e4429b Binary files /dev/null and b/docs/.vitepress/public/img/boards/lilygo-t3-s3.jpg differ diff --git a/docs/.vitepress/public/img/boards/lolin-c3-mini.jpg b/docs/.vitepress/public/img/boards/lolin-c3-mini.jpg new file mode 100644 index 0000000..6c076de Binary files /dev/null and b/docs/.vitepress/public/img/boards/lolin-c3-mini.jpg differ diff --git a/docs/.vitepress/public/img/boards/lolin32-lite.jpg b/docs/.vitepress/public/img/boards/lolin32-lite.jpg new file mode 100644 index 0000000..dff1e4b Binary files /dev/null and b/docs/.vitepress/public/img/boards/lolin32-lite.jpg differ diff --git a/docs/.vitepress/public/img/boards/m5atom-lite.webp b/docs/.vitepress/public/img/boards/m5atom-lite.webp new file mode 100644 index 0000000..330d4ce Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5atom-lite.webp differ diff --git a/docs/.vitepress/public/img/boards/m5atom-matrix.webp b/docs/.vitepress/public/img/boards/m5atom-matrix.webp new file mode 100644 index 0000000..e1ac7ab Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5atom-matrix.webp differ diff --git a/docs/.vitepress/public/img/boards/m5atoms3u.webp b/docs/.vitepress/public/img/boards/m5atoms3u.webp new file mode 100644 index 0000000..25d21c5 Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5atoms3u.webp differ diff --git a/docs/.vitepress/public/img/boards/m5stack-core.webp b/docs/.vitepress/public/img/boards/m5stack-core.webp new file mode 100644 index 0000000..8903c7e Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5stack-core.webp differ diff --git a/docs/.vitepress/public/img/boards/m5stamp-c3.webp b/docs/.vitepress/public/img/boards/m5stamp-c3.webp new file mode 100644 index 0000000..73c34ff Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5stamp-c3.webp differ diff --git a/docs/.vitepress/public/img/boards/m5stamp-c3u.webp b/docs/.vitepress/public/img/boards/m5stamp-c3u.webp new file mode 100644 index 0000000..84978d8 Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5stamp-c3u.webp differ diff --git a/docs/.vitepress/public/img/boards/m5stamp-s3.webp b/docs/.vitepress/public/img/boards/m5stamp-s3.webp new file mode 100644 index 0000000..9896fb6 Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5stamp-s3.webp differ diff --git a/docs/.vitepress/public/img/boards/m5stick-c-plus.webp b/docs/.vitepress/public/img/boards/m5stick-c-plus.webp new file mode 100644 index 0000000..1ee901b Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5stick-c-plus.webp differ diff --git a/docs/.vitepress/public/img/boards/m5stick-c.webp b/docs/.vitepress/public/img/boards/m5stick-c.webp new file mode 100644 index 0000000..70c56d9 Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5stick-c.webp differ diff --git a/docs/.vitepress/public/img/boards/m5stick.webp b/docs/.vitepress/public/img/boards/m5stick.webp new file mode 100644 index 0000000..d463bdf Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5stick.webp differ diff --git a/docs/.vitepress/public/img/boards/m5tough.webp b/docs/.vitepress/public/img/boards/m5tough.webp new file mode 100644 index 0000000..0dc2d8f Binary files /dev/null and b/docs/.vitepress/public/img/boards/m5tough.webp differ diff --git a/docs/.vitepress/public/img/boards/nodemcuv2.jpg b/docs/.vitepress/public/img/boards/nodemcuv2.jpg new file mode 100644 index 0000000..edd8a25 Binary files /dev/null and b/docs/.vitepress/public/img/boards/nodemcuv2.jpg differ diff --git a/docs/.vitepress/public/img/boards/olimex-esp32-gateway.jpg b/docs/.vitepress/public/img/boards/olimex-esp32-gateway.jpg new file mode 100644 index 0000000..39cd3ac Binary files /dev/null and b/docs/.vitepress/public/img/boards/olimex-esp32-gateway.jpg differ diff --git a/docs/.vitepress/public/img/boards/olimex-esp32-poe-iso.jpg b/docs/.vitepress/public/img/boards/olimex-esp32-poe-iso.jpg new file mode 100644 index 0000000..d345775 Binary files /dev/null and b/docs/.vitepress/public/img/boards/olimex-esp32-poe-iso.jpg differ diff --git a/docs/.vitepress/public/img/boards/olimex-esp32-poe.jpg b/docs/.vitepress/public/img/boards/olimex-esp32-poe.jpg new file mode 100644 index 0000000..a0e4199 Binary files /dev/null and b/docs/.vitepress/public/img/boards/olimex-esp32-poe.jpg differ diff --git a/docs/.vitepress/public/img/boards/shelly-plus1.jpg b/docs/.vitepress/public/img/boards/shelly-plus1.jpg new file mode 100644 index 0000000..4236593 Binary files /dev/null and b/docs/.vitepress/public/img/boards/shelly-plus1.jpg differ diff --git a/docs/.vitepress/public/img/boards/sonoff-basic.jpg b/docs/.vitepress/public/img/boards/sonoff-basic.jpg new file mode 100644 index 0000000..855c64d Binary files /dev/null and b/docs/.vitepress/public/img/boards/sonoff-basic.jpg differ diff --git a/docs/.vitepress/public/img/boards/sonoff-rf-bridge.jpg b/docs/.vitepress/public/img/boards/sonoff-rf-bridge.jpg new file mode 100644 index 0000000..6bd6de3 Binary files /dev/null and b/docs/.vitepress/public/img/boards/sonoff-rf-bridge.jpg differ diff --git a/docs/.vitepress/public/img/boards/sonoff-rfr3.jpg b/docs/.vitepress/public/img/boards/sonoff-rfr3.jpg new file mode 100644 index 0000000..8bfda39 Binary files /dev/null and b/docs/.vitepress/public/img/boards/sonoff-rfr3.jpg differ diff --git a/docs/.vitepress/public/img/boards/thingpulse-espgateway.jpg b/docs/.vitepress/public/img/boards/thingpulse-espgateway.jpg new file mode 100644 index 0000000..b4768c7 Binary files /dev/null and b/docs/.vitepress/public/img/boards/thingpulse-espgateway.jpg differ diff --git a/docs/.vitepress/public/img/boards/tinypico.jpg b/docs/.vitepress/public/img/boards/tinypico.jpg new file mode 100644 index 0000000..c440ab6 Binary files /dev/null and b/docs/.vitepress/public/img/boards/tinypico.jpg differ diff --git a/docs/.vitepress/public/img/boards/ttgo-lora32-v1.jpg b/docs/.vitepress/public/img/boards/ttgo-lora32-v1.jpg new file mode 100644 index 0000000..b9edca1 Binary files /dev/null and b/docs/.vitepress/public/img/boards/ttgo-lora32-v1.jpg differ diff --git a/docs/.vitepress/public/img/boards/ttgo-t-beam.jpg b/docs/.vitepress/public/img/boards/ttgo-t-beam.jpg new file mode 100644 index 0000000..d8efd0f Binary files /dev/null and b/docs/.vitepress/public/img/boards/ttgo-t-beam.jpg differ diff --git a/docs/.vitepress/public/img/boards/wt32-eth01.jpg b/docs/.vitepress/public/img/boards/wt32-eth01.jpg new file mode 100644 index 0000000..c0820f8 Binary files /dev/null and b/docs/.vitepress/public/img/boards/wt32-eth01.jpg differ diff --git a/docs/.vitepress/public/img/microcontroller.gif b/docs/.vitepress/public/img/microcontroller.gif new file mode 100644 index 0000000..40a9bc2 Binary files /dev/null and b/docs/.vitepress/public/img/microcontroller.gif differ diff --git a/docs/.vuepress/public/robots.txt b/docs/.vitepress/public/robots.txt similarity index 100% rename from docs/.vuepress/public/robots.txt rename to docs/.vitepress/public/robots.txt diff --git a/docs/.vitepress/theme/custom.css b/docs/.vitepress/theme/custom.css new file mode 100644 index 0000000..9ee5a75 --- /dev/null +++ b/docs/.vitepress/theme/custom.css @@ -0,0 +1,123 @@ +/* docs/.vitepress/theme/custom.css */ + +/* Prevent long site title from overlapping sidebar/nav */ +.VPNavBarTitle .title { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* The shared Theengs nav has seven top-level entries, and the default theme + switches from the hamburger to the full nav bar at 768px -- far too early for + this menu. Between 768px and ~1180px the entries overflowed: Shop, Sponsor, + the appearance switch and the GitHub link ended up clipped or off-screen, and + the page picked up a horizontal scrollbar. Keep the compact nav (hamburger + + full-screen menu, which already lists every entry plus the appearance switch + and social links) until the full menu genuinely fits. */ +@media (min-width: 768px) and (max-width: 1199px) { + .VPNav .VPNavBar .VPNavBarMenu.menu, + .VPNav .VPNavBar .VPNavBarExtra.extra { + display: none; + } + + .VPNav .VPNavBar .VPNavBarHamburger.hamburger { + display: flex; + } + + header.VPNav .VPNavScreen { + display: block; + } +} + +/* Widen the entire content column on pages without aside (board/flash pages) */ +.VPDoc:not(.has-aside) .content-container, +.VPDoc:not(.has-aside) .container { + max-width: 100% !important; +} + +.VPDoc:not(.has-aside) .vp-doc { + max-width: 100% !important; +} + +/* Enlarge the home hero image beyond the theme's ~320px default cap */ +.VPHome .VPHero .image-container { + transform: none; + width: 100%; + height: auto; + margin: 0 auto; +} + +.VPHome .VPHero .image-bg { + display: none; +} + +.VPHome .VPHero .image-src { + position: static; + transform: none; + width: 100%; + max-width: 420px; + max-height: none; +} + +/* Below the desktop breakpoint the default theme stacks the image on top of the + hero text and pulls it with negative margins (-76px -24px -48px), which only + works because the image is normally absolutely positioned inside a fixed + 320px box. Since we let it flow, those margins made it bleed off-screen and + collide with the hero title -- reset them. */ +@media (max-width: 959px) { + .VPHome .VPHero .image { + margin: 0 0 16px; + } +} + +/* On phones the stacked image is a wall of unreadable logos that pushes the + title, tagline and call-to-action buttons below the fold. Drop it and let the + hero lead with the text. */ +@media (max-width: 639px) { + .VPHome .VPHero .image { + display: none; + } +} + +@media (min-width: 960px) { + .VPHome .VPHero .image-src { + max-width: 520px; + } +} + +/* Indented (non-fenced) markdown code blocks render as a bare
; the default
+   theme only makes code scroll inside its language-* wrapper, so long lines such
+   as the esptool.py commands pushed the whole page sideways on phones. */
+.vp-doc pre {
+  overflow-x: auto;
+}
+
+/* Embeds are written as raw HTML in markdown with fixed width/height attributes
+   (e.g. 
-
-
-## Products powered by OpenMQTTGateway
-
-### Theengs Bridge, BLE gateway with external antenna
-
-[Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) is a powerfull BLE to MQTT gateway for over [90 sensors](https://decoder.theengs.io/devices/devices.html). Equipped with an Ethernet port, and external antenna, ensuring an enhanced range for your BLE sensors. It supports also WiFi connectivity.
-
-[![Theengs bridge view](./img/Theengs-Bridge-ble-gateway.png)](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna)
-
-### Theengs Plug, BLE gateway and Smart Plug
-
-[Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) brings the following features:
-* BLE to MQTT gateway, tens of [Bluetooth devices](https://compatible.openmqttgateway.com/index.php/devices/ble-devices/) supported thanks to Theengs Decoder library. The plug uses an ESP32 acting as a BLE to Wifi gateway to scan, decode and forward the data of the nearby sensors,
-* Smart plug that can be controlled remotely,
-* Energy consumption monitoring,
-* Device tracker,
-* Presence detection (beta),
-* Local connectivity first.
-
-[![Theengs plug view](./img/Theengs-Plug-OpenMQTTGateway.png)](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption)
-
-Support the project by purchasing the [Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) or the [Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption)
-
-## Media
-
-* [Hackaday - ARDUINO LIBRARY BRINGS RTL_433 TO THE ESP32](https://hackaday.com/2023/01/13/arduino-library-brings-rtl_433-to-the-esp32)
-* [CNX Software - 433 MHz is not dead! Using an ESP32 board with LoRa module to talk to 433 MHz sensors](https://www.cnx-software.com/2023/01/14/esp32-board-with-lora-433-mhz-sensors/)
-* [RTL_433 PORTED TO ESP32 MICROCONTROLLERS WITH CC1101 OR SX127X TRANSCEIVER CHIPS](https://www.rtl-sdr.com/rtl_433-ported-to-esp32-microcontrollers-with-cc1101-or-sx127x-transceiver-chips/)
-* [Using low-cost wireless sensors in the unlicensed bands](https://lwn.net/Articles/921497/)
-* [SMART PLUG ESP32 OPENMQTTGATEWAY SERVING AS AN BLE MQTT GATEWAY AND A POWER METER](https://www.electronics-lab.com/smart-plug-esp32-openmqttgateway-serving-as-an-ble-mqtt-gateway-and-a-power-meter/)
-
-### Theengs Plug
-[![Theengs Plug video ElektroMaker](https://img.youtube.com/vi/nUwMt9p2U7o/0.jpg)](https://www.youtube.com/watch?v=nUwMt9p2U7o&t=427s)
-
-### 433Mhz and BLE
-[![433Mhz and BLE gateway video by Andreas Spiess](https://img.youtube.com/vi/_gdXR1uklaY/0.jpg)](https://www.youtube.com/watch?v=_gdXR1uklaY)
-
-### BLE
-[![BLE gateway video by Andreas Spiess](https://img.youtube.com/vi/noUROhtf0E0/0.jpg)](https://www.youtube.com/watch?v=noUROhtf0E0)
-
-### 433Mhz
-[![RTL_433 video by TECH MIND](https://img.youtube.com/vi/H-JXWbWjJYE/0.jpg)](https://www.youtube.com/watch?v=H-JXWbWjJYE)
-
-### LORA
-[![LORA video by Priceless Toolkit](https://img.youtube.com/vi/6DftaHxDawM/0.jpg)](https://www.youtube.com/watch?v=6DftaHxDawM)
-
-::: warning Note
-The material and information contained in this documentation is for general information purposes only. You should not rely upon the material or information on this documentation as a basis for making any business, legal or any other decisions. There is no warranty given on this documentation content. If you decide to follow the information and materials given it is at your own risk. I will not be liable for any false, inaccurate, inappropriate or incomplete information presented on this website.
-:::
diff --git a/docs/getting-started.md b/docs/getting-started.md
new file mode 100644
index 0000000..c7b9736
--- /dev/null
+++ b/docs/getting-started.md
@@ -0,0 +1,73 @@
+# Getting Started
+
+This guide walks you through the two most popular setups from start to finish, flashed **from your browser** and integrated with **Home Assistant**. No soldering, no development environment, about 15 minutes:
+
+* **Bluetooth sensors** — any ESP32 board reading thermometers, plant sensors, scales...
+* **RF devices (433/315/868/915MHz)** — a LILYGO LoRa32 board receiving weather stations, door sensors, PIR sensors...
+
+Using another controller (OpenHAB, Node-RED...) or another technology (IR, LoRa)? Follow the same steps and take the detours linked along the way.
+
+## How the pieces fit together
+
+OpenMQTTGateway (OMG) is a firmware for your board that translates signals from your devices (Bluetooth sensors, RF remotes, weather stations...) into MQTT messages, and the other way around:
+
+
+
+The **broker** is the message hub; the **controller** is the home automation software where you see and use the data.
+
+## What you need
+
+* **A board** — for **Bluetooth**, any ESP32 development board. For **RF**, a LILYGO® LoRa32 V2.1 or a Heltec LoRa V2 matching your devices' frequency — 433MHz for most European devices, 915MHz in North America (no soldering needed). See the [board guide](prerequisites/board.md) for other cases, or get a pre-flashed [Theengs Bridge](https://shop.theengs.io/) and skip the flashing step.
+* **A data USB cable** — some cables are charge-only and won't work.
+* **An MQTT broker** — see Step 1.
+* **A device to observe** — e.g. a [compatible Bluetooth sensor](https://decoder.theengs.io/devices/devices.html) such as a Mi Flora, LYWSD03MMC, Govee or Inkbird thermometer, or any RF sensor around you (weather station, door or PIR sensor...).
+
+## Step 1 — Set up the MQTT broker
+
+If you use **Home Assistant**, the simplest option is the Mosquitto add-on:
+
+1. In Home Assistant go to **Settings → Add-ons → Add-on store**, install **Mosquitto broker** and start it.
+2. Install the **MQTT integration** (**Settings → Devices & services → Add integration → MQTT**) if it isn't set up already.
+3. Create a dedicated user for the gateway in **Settings → People → Users** (e.g. `omg` — it doesn't need to be an administrator). The gateway will log in with it.
+
+No Home Assistant? Install [Mosquitto](https://mosquitto.org/) on any always-on machine, or see the [broker page](prerequisites/broker.md) for alternatives.
+
+## Step 2 — Flash the firmware from your browser
+
+1. Open the [web installer](upload/web-install.md) in **Chrome, Edge or Opera** (Firefox and Safari don't support web flashing).
+2. Connect the board to your computer with the USB cable.
+3. Pick the firmware matching your board and use case — the two most flashed:
+   * **Bluetooth** on a generic ESP32: esp32dev-ble
+   * **RF** on a LILYGO LoRa32: lilygo-rtl_433 (the radio frequency is configurable afterwards)
+4. Click **Connect**, select the board's USB port, and let the installer finish.
+
+Prefer a desktop tool, or need a custom configuration? See the other [upload options](upload/index.md).
+
+## Step 3 — Connect the gateway to your WiFi and broker
+
+After flashing, the gateway starts its own WiFi access point:
+
+1. From your phone or computer, connect to the WiFi network named **OpenMQTTGateway** or starting with **OMG_** (no password, except for Theengs devices — see the [portal page](upload/portal.md)).
+2. A configuration page opens (on Android, accept "stay connected without internet"). Click **Configure WiFi**.
+3. Select your WiFi network and enter its password.
+4. Enter your broker's address as MQTT server (for the Home Assistant add-on, `homeassistant.local` or the server IP), keep port `1883`, and fill in the MQTT username and password from Step 1.
+5. Click **Save**. The gateway restarts and joins your network.
+
+The full list of portal fields is described on the [configuration portal page](upload/portal.md).
+
+## Step 4 — Check that it works
+
+* In Home Assistant, go to **Settings → Devices & services → MQTT**: after a minute you should see a device named **OpenMQTTGateway**, created automatically through MQTT discovery.
+* **Bluetooth**: bring a compatible sensor nearby — it appears as its own device with its measurements as entities. Some devices only advertise on an event: press a button or trigger a reading if nothing shows up.
+* **RF**: supported devices appear automatically as soon as they transmit — weather stations send every minute or two, door and PIR sensors on an event, so trigger one to see it arrive.
+* You can also watch the raw messages with [MQTT Explorer](https://mqtt-explorer.com/): connect to your broker and look for `home/OpenMQTTGateway/LWT` = `online` and messages under `home/OpenMQTTGateway/`.
+
+Something not right? Head to the [troubleshooting page](upload/troubleshoot.md) or ask on the [community forum](https://community.openmqttgateway.com).
+
+## Where to go next
+
+* **More RF options** — other compatible boards and firmwares, transmitting, frequency tuning, and protocol details in [RF hardware setup](setitup/rf.md) and [RF usage](use/rf.md).
+* **Infrared** — wire an IR emitter/receiver following the [IR hardware setup](setitup/ir.md).
+* **Tune the gateway** — the [WebUI](use/webui.md) and [gateway commands](use/gateway.md) let you configure it at runtime over MQTT.
+* **Other controllers** — [OpenHAB](integrate/openhab3.md), [Node-RED](integrate/node_red.md), [Jeedom](integrate/jeedom.md), [AWS IoT](integrate/aws_iot.md).
+* **Full Home Assistant details** — [Home Assistant integration](integrate/home_assistant.md).
diff --git a/docs/img/EMQ.png b/docs/img/EMQ.png
index 669f9be..fcd09d3 100644
Binary files a/docs/img/EMQ.png and b/docs/img/EMQ.png differ
diff --git a/docs/img/HASS-RF-DeviceTrigger.png b/docs/img/HASS-RF-DeviceTrigger.png
new file mode 100644
index 0000000..de349eb
Binary files /dev/null and b/docs/img/HASS-RF-DeviceTrigger.png differ
diff --git a/docs/img/HASS-RF-MQTTSensor.png b/docs/img/HASS-RF-MQTTSensor.png
new file mode 100644
index 0000000..eb1f80c
Binary files /dev/null and b/docs/img/HASS-RF-MQTTSensor.png differ
diff --git a/docs/img/HASS-RF-Sensor-example.png b/docs/img/HASS-RF-Sensor-example.png
new file mode 100644
index 0000000..51a5f00
Binary files /dev/null and b/docs/img/HASS-RF-Sensor-example.png differ
diff --git a/docs/img/HASS-RF-Trigger-example.png b/docs/img/HASS-RF-Trigger-example.png
new file mode 100644
index 0000000..8e97609
Binary files /dev/null and b/docs/img/HASS-RF-Trigger-example.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Attach_Policy.png b/docs/img/Integrate_AWS_IOT_Attach_Policy.png
index a973a75..9c75f40 100644
Binary files a/docs/img/Integrate_AWS_IOT_Attach_Policy.png and b/docs/img/Integrate_AWS_IOT_Attach_Policy.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Attach_Policy2.png b/docs/img/Integrate_AWS_IOT_Attach_Policy2.png
index e932525..9b10625 100644
Binary files a/docs/img/Integrate_AWS_IOT_Attach_Policy2.png and b/docs/img/Integrate_AWS_IOT_Attach_Policy2.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Attach_Thing.png b/docs/img/Integrate_AWS_IOT_Attach_Thing.png
index 3e71cbb..75e9ad5 100644
Binary files a/docs/img/Integrate_AWS_IOT_Attach_Thing.png and b/docs/img/Integrate_AWS_IOT_Attach_Thing.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Attach_Thing2.png b/docs/img/Integrate_AWS_IOT_Attach_Thing2.png
index 0a3a8e3..13d87cd 100644
Binary files a/docs/img/Integrate_AWS_IOT_Attach_Thing2.png and b/docs/img/Integrate_AWS_IOT_Attach_Thing2.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Certificate.png b/docs/img/Integrate_AWS_IOT_Create_Certificate.png
index 6663614..2e50478 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Certificate.png and b/docs/img/Integrate_AWS_IOT_Create_Certificate.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Certificate2.png b/docs/img/Integrate_AWS_IOT_Create_Certificate2.png
index c59a538..ccb8510 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Certificate2.png and b/docs/img/Integrate_AWS_IOT_Create_Certificate2.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Certificate3.png b/docs/img/Integrate_AWS_IOT_Create_Certificate3.png
index 40cfb45..2a1d2df 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Certificate3.png and b/docs/img/Integrate_AWS_IOT_Create_Certificate3.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Policy.png b/docs/img/Integrate_AWS_IOT_Create_Policy.png
index 19e9f81..c0bfc43 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Policy.png and b/docs/img/Integrate_AWS_IOT_Create_Policy.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Policy2.png b/docs/img/Integrate_AWS_IOT_Create_Policy2.png
index fa8b161..f89a5f6 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Policy2.png and b/docs/img/Integrate_AWS_IOT_Create_Policy2.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Policy3.png b/docs/img/Integrate_AWS_IOT_Create_Policy3.png
index 813bc77..04b6624 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Policy3.png and b/docs/img/Integrate_AWS_IOT_Create_Policy3.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Thing.png b/docs/img/Integrate_AWS_IOT_Create_Thing.png
index 8e977e9..ce74d2a 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Thing.png and b/docs/img/Integrate_AWS_IOT_Create_Thing.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Thing2.png b/docs/img/Integrate_AWS_IOT_Create_Thing2.png
index edd5172..3b9af6f 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Thing2.png and b/docs/img/Integrate_AWS_IOT_Create_Thing2.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Thing3.png b/docs/img/Integrate_AWS_IOT_Create_Thing3.png
index 0f890aa..fae243f 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Thing3.png and b/docs/img/Integrate_AWS_IOT_Create_Thing3.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Create_Thing4.png b/docs/img/Integrate_AWS_IOT_Create_Thing4.png
index 5d70be0..a522bc4 100644
Binary files a/docs/img/Integrate_AWS_IOT_Create_Thing4.png and b/docs/img/Integrate_AWS_IOT_Create_Thing4.png differ
diff --git a/docs/img/Integrate_AWS_IOT_Find_Endpoint.png b/docs/img/Integrate_AWS_IOT_Find_Endpoint.png
index 184d17a..1c51388 100644
Binary files a/docs/img/Integrate_AWS_IOT_Find_Endpoint.png and b/docs/img/Integrate_AWS_IOT_Find_Endpoint.png differ
diff --git a/docs/img/Integrate_AWS_IOT_result_MQTT.png b/docs/img/Integrate_AWS_IOT_result_MQTT.png
index b0b1a6a..6f434c1 100644
Binary files a/docs/img/Integrate_AWS_IOT_result_MQTT.png and b/docs/img/Integrate_AWS_IOT_result_MQTT.png differ
diff --git a/docs/img/Integrate_Jeedom_Broker-brkTab.png b/docs/img/Integrate_Jeedom_Broker-brkTab.png
index de153c0..9e6d6fd 100644
Binary files a/docs/img/Integrate_Jeedom_Broker-brkTab.png and b/docs/img/Integrate_Jeedom_Broker-brkTab.png differ
diff --git a/docs/img/Integrate_Jeedom_Broker-eqTab.png b/docs/img/Integrate_Jeedom_Broker-eqTab.png
index 5fcc935..19202dd 100644
Binary files a/docs/img/Integrate_Jeedom_Broker-eqTab.png and b/docs/img/Integrate_Jeedom_Broker-eqTab.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-Add.png b/docs/img/Integrate_Jeedom_Eq-Add.png
index 4cf9b83..b13f17e 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-Add.png and b/docs/img/Integrate_Jeedom_Eq-Add.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-Mijia-Cmds.png b/docs/img/Integrate_Jeedom_Eq-Mijia-Cmds.png
index f613087..ac28f29 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-Mijia-Cmds.png and b/docs/img/Integrate_Jeedom_Eq-Mijia-Cmds.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-Mijia-Create.png b/docs/img/Integrate_Jeedom_Eq-Mijia-Create.png
index bb5af97..b309f38 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-Mijia-Create.png and b/docs/img/Integrate_Jeedom_Eq-Mijia-Create.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-Mijia-Dashboard-pimped.png b/docs/img/Integrate_Jeedom_Eq-Mijia-Dashboard-pimped.png
index 0aba143..efb4531 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-Mijia-Dashboard-pimped.png and b/docs/img/Integrate_Jeedom_Eq-Mijia-Dashboard-pimped.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-Mijia-Dashboard.png b/docs/img/Integrate_Jeedom_Eq-Mijia-Dashboard.png
index ebd4d67..2bae5b3 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-Mijia-Dashboard.png and b/docs/img/Integrate_Jeedom_Eq-Mijia-Dashboard.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-Mijia-tmp-Cmd-Json.png b/docs/img/Integrate_Jeedom_Eq-Mijia-tmp-Cmd-Json.png
index 5f5dfac..71be026 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-Mijia-tmp-Cmd-Json.png and b/docs/img/Integrate_Jeedom_Eq-Mijia-tmp-Cmd-Json.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-Mijia-tmp-Cmd.png b/docs/img/Integrate_Jeedom_Eq-Mijia-tmp-Cmd.png
index 228622c..a3335b8 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-Mijia-tmp-Cmd.png and b/docs/img/Integrate_Jeedom_Eq-Mijia-tmp-Cmd.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-BTtoMQTT-mijia.png b/docs/img/Integrate_Jeedom_Eq-OMG-BTtoMQTT-mijia.png
index 772e04f..6fa5a1e 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-BTtoMQTT-mijia.png and b/docs/img/Integrate_Jeedom_Eq-OMG-BTtoMQTT-mijia.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-BTtoMQTT.png b/docs/img/Integrate_Jeedom_Eq-OMG-BTtoMQTT.png
index aa83384..33cd391 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-BTtoMQTT.png and b/docs/img/Integrate_Jeedom_Eq-OMG-BTtoMQTT.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT-json.png b/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT-json.png
index 786f0ed..02da12c 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT-json.png and b/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT-json.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT-restart.png b/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT-restart.png
index 0110592..684ad17 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT-restart.png and b/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT-restart.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT.png b/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT.png
index f57f812..b16f152 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT.png and b/docs/img/Integrate_Jeedom_Eq-OMG-SYStoMQTT.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-cmd-added.png b/docs/img/Integrate_Jeedom_Eq-OMG-cmd-added.png
index 45636c2..a662f3a 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-cmd-added.png and b/docs/img/Integrate_Jeedom_Eq-OMG-cmd-added.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-cmds.png b/docs/img/Integrate_Jeedom_Eq-OMG-cmds.png
index 3f8d829..04f50c3 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-cmds.png and b/docs/img/Integrate_Jeedom_Eq-OMG-cmds.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-config.png b/docs/img/Integrate_Jeedom_Eq-OMG-config.png
index 525a722..ef00e26 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-config.png and b/docs/img/Integrate_Jeedom_Eq-OMG-config.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-lwt-formula.png b/docs/img/Integrate_Jeedom_Eq-OMG-lwt-formula.png
index 08d3727..cad2d86 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-lwt-formula.png and b/docs/img/Integrate_Jeedom_Eq-OMG-lwt-formula.png differ
diff --git a/docs/img/Integrate_Jeedom_Eq-OMG-lwt.png b/docs/img/Integrate_Jeedom_Eq-OMG-lwt.png
index 19e2808..3e80446 100644
Binary files a/docs/img/Integrate_Jeedom_Eq-OMG-lwt.png and b/docs/img/Integrate_Jeedom_Eq-OMG-lwt.png differ
diff --git a/docs/img/Integrate_Jeedom_Install-Activate.png b/docs/img/Integrate_Jeedom_Install-Activate.png
index d62667f..09eb433 100644
Binary files a/docs/img/Integrate_Jeedom_Install-Activate.png and b/docs/img/Integrate_Jeedom_Install-Activate.png differ
diff --git a/docs/img/Integrate_Jeedom_Install-Daemon-OK.png b/docs/img/Integrate_Jeedom_Install-Daemon-OK.png
index c277d18..27042a7 100644
Binary files a/docs/img/Integrate_Jeedom_Install-Daemon-OK.png and b/docs/img/Integrate_Jeedom_Install-Daemon-OK.png differ
diff --git a/docs/img/Integrate_Jeedom_Install-Deps-OK.png b/docs/img/Integrate_Jeedom_Install-Deps-OK.png
index aa72410..5b3e549 100644
Binary files a/docs/img/Integrate_Jeedom_Install-Deps-OK.png and b/docs/img/Integrate_Jeedom_Install-Deps-OK.png differ
diff --git a/docs/img/Integrate_Jeedom_Install-Deps.png b/docs/img/Integrate_Jeedom_Install-Deps.png
index c2bdc37..27c3022 100644
Binary files a/docs/img/Integrate_Jeedom_Install-Deps.png and b/docs/img/Integrate_Jeedom_Install-Deps.png differ
diff --git a/docs/img/Integrate_Jeedom_Install-Mosquitto.png b/docs/img/Integrate_Jeedom_Install-Mosquitto.png
index 3d1dcd4..f76bc2b 100644
Binary files a/docs/img/Integrate_Jeedom_Install-Mosquitto.png and b/docs/img/Integrate_Jeedom_Install-Mosquitto.png differ
diff --git a/docs/img/Integrate_Jeedom_Install-jMQTT.png b/docs/img/Integrate_Jeedom_Install-jMQTT.png
index c18d7c8..51c8bb4 100644
Binary files a/docs/img/Integrate_Jeedom_Install-jMQTT.png and b/docs/img/Integrate_Jeedom_Install-jMQTT.png differ
diff --git a/docs/img/KBeacon-app-configuration-moving.jpg b/docs/img/KBeacon-app-configuration-moving.jpg
index 8343c47..56e40a1 100644
Binary files a/docs/img/KBeacon-app-configuration-moving.jpg and b/docs/img/KBeacon-app-configuration-moving.jpg differ
diff --git a/docs/img/KBeacon-app-configuration-moving2.jpg b/docs/img/KBeacon-app-configuration-moving2.jpg
index e6da91d..e125d50 100644
Binary files a/docs/img/KBeacon-app-configuration-moving2.jpg and b/docs/img/KBeacon-app-configuration-moving2.jpg differ
diff --git a/docs/img/OMQTTG_8207.JPG b/docs/img/OMQTTG_8207.JPG
index a4cc953..2e54e33 100644
Binary files a/docs/img/OMQTTG_8207.JPG and b/docs/img/OMQTTG_8207.JPG differ
diff --git a/docs/img/OMQTTG_8211.JPG b/docs/img/OMQTTG_8211.JPG
index 3b3faed..11067c7 100644
Binary files a/docs/img/OMQTTG_8211.JPG and b/docs/img/OMQTTG_8211.JPG differ
diff --git a/docs/img/OMQTTG_8217.JPG b/docs/img/OMQTTG_8217.JPG
index d87b8f6..007e291 100644
Binary files a/docs/img/OMQTTG_8217.JPG and b/docs/img/OMQTTG_8217.JPG differ
diff --git a/docs/img/OpenMQTTGateway-BLE-tracker-Home-Assistant.png b/docs/img/OpenMQTTGateway-BLE-tracker-Home-Assistant.png
index b97125b..840b7d5 100644
Binary files a/docs/img/OpenMQTTGateway-BLE-tracker-Home-Assistant.png and b/docs/img/OpenMQTTGateway-BLE-tracker-Home-Assistant.png differ
diff --git a/docs/img/OpenMQTTGateway-Build-gitpod-env.png b/docs/img/OpenMQTTGateway-Build-gitpod-env.png
deleted file mode 100644
index 5079879..0000000
Binary files a/docs/img/OpenMQTTGateway-Build-gitpod-env.png and /dev/null differ
diff --git a/docs/img/OpenMQTTGateway-Build-gitpod.png b/docs/img/OpenMQTTGateway-Build-gitpod.png
deleted file mode 100644
index 775dc2d..0000000
Binary files a/docs/img/OpenMQTTGateway-Build-gitpod.png and /dev/null differ
diff --git a/docs/img/OpenMQTTGateway-Configuration-Home-Assistant-Discovery-Integration.png b/docs/img/OpenMQTTGateway-Configuration-Home-Assistant-Discovery-Integration.png
index 5a72a38..ae0b6d2 100644
Binary files a/docs/img/OpenMQTTGateway-Configuration-Home-Assistant-Discovery-Integration.png and b/docs/img/OpenMQTTGateway-Configuration-Home-Assistant-Discovery-Integration.png differ
diff --git a/docs/img/OpenMQTTGateway-Configuration-Home-Assistant.png b/docs/img/OpenMQTTGateway-Configuration-Home-Assistant.png
index 1e06506..448cc1e 100644
Binary files a/docs/img/OpenMQTTGateway-Configuration-Home-Assistant.png and b/docs/img/OpenMQTTGateway-Configuration-Home-Assistant.png differ
diff --git a/docs/img/OpenMQTTGateway-OTA-Update-Home-Assistant.png b/docs/img/OpenMQTTGateway-OTA-Update-Home-Assistant.png
index dbf77a0..56fc46f 100644
Binary files a/docs/img/OpenMQTTGateway-OTA-Update-Home-Assistant.png and b/docs/img/OpenMQTTGateway-OTA-Update-Home-Assistant.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding.png
index 11be6a0..293c552 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding2.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding2.png
index 7ae56c0..188d7dd 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding2.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding2.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding3.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding3.png
index 14c8b3f..a3f4b6c 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding3.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding3.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding4.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding4.png
index 5036002..818685a 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding4.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding4.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding5.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding5.png
index 5ae2f37..865fe65 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding5.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding5.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding6.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding6.png
index b46175c..6cc42bf 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding6.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-binding6.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-ip.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-ip.png
index 4d9e75c..7e4a664 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-ip.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-ip.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-jinja.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-jinja.png
index 1908e0a..72b4dba 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-jinja.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-jinja.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things.png
index 45e0712..0c2fa12 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things2.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things2.png
index 0646b34..94f5779 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things2.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things2.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things3.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things3.png
index f3db3cd..4022b6b 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things3.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things3.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things4.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things4.png
index 52caaf2..1dcb16e 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things4.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things4.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things5.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things5.png
index 1c8d176..5439eb7 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things5.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt-things5.png differ
diff --git a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt.png b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt.png
index 3ff5f1f..c6d4bc5 100644
Binary files a/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt.png and b/docs/img/OpenMQTTGateway-OpenHAB-Theengs-mqtt.png differ
diff --git a/docs/img/OpenMQTTGateway-home-assistant-chart.png b/docs/img/OpenMQTTGateway-home-assistant-chart.png
index f2ec402..adc94ea 100644
Binary files a/docs/img/OpenMQTTGateway-home-assistant-chart.png and b/docs/img/OpenMQTTGateway-home-assistant-chart.png differ
diff --git a/docs/img/OpenMQTTGateway-mqtt-explorer-lywsd03mmc-atc.png b/docs/img/OpenMQTTGateway-mqtt-explorer-lywsd03mmc-atc.png
index 373eb72..879acce 100644
Binary files a/docs/img/OpenMQTTGateway-mqtt-explorer-lywsd03mmc-atc.png and b/docs/img/OpenMQTTGateway-mqtt-explorer-lywsd03mmc-atc.png differ
diff --git a/docs/img/OpenMQTTGateway-sensors-ble.png b/docs/img/OpenMQTTGateway-sensors-ble.png
index de03925..c32dd17 100644
Binary files a/docs/img/OpenMQTTGateway-sensors-ble.png and b/docs/img/OpenMQTTGateway-sensors-ble.png differ
diff --git a/docs/img/OpenMQTTGateway.jpg b/docs/img/OpenMQTTGateway.jpg
index c9b41a6..523a5c6 100644
Binary files a/docs/img/OpenMQTTGateway.jpg and b/docs/img/OpenMQTTGateway.jpg differ
diff --git a/docs/img/OpenMQTTGateway.png b/docs/img/OpenMQTTGateway.png
index 937d1a2..e8ce218 100644
Binary files a/docs/img/OpenMQTTGateway.png and b/docs/img/OpenMQTTGateway.png differ
diff --git a/docs/img/OpenMQTTGateway_ESP32_breadboard.jpg b/docs/img/OpenMQTTGateway_ESP32_breadboard.jpg
index 712bf60..50ee257 100644
Binary files a/docs/img/OpenMQTTGateway_ESP32_breadboard.jpg and b/docs/img/OpenMQTTGateway_ESP32_breadboard.jpg differ
diff --git a/docs/img/OpenMQTTGateway_Home_Assistant_MQTT_discovery.png b/docs/img/OpenMQTTGateway_Home_Assistant_MQTT_discovery.png
index 29e4495..850e0a9 100644
Binary files a/docs/img/OpenMQTTGateway_Home_Assistant_MQTT_discovery.png and b/docs/img/OpenMQTTGateway_Home_Assistant_MQTT_discovery.png differ
diff --git a/docs/img/OpenMQTTGateway_IR_AVATTO_TYWE3S.png b/docs/img/OpenMQTTGateway_IR_AVATTO_TYWE3S.png
index abbdcc6..ec453db 100644
Binary files a/docs/img/OpenMQTTGateway_IR_AVATTO_TYWE3S.png and b/docs/img/OpenMQTTGateway_IR_AVATTO_TYWE3S.png differ
diff --git a/docs/img/OpenMQTTGateway_LORA_Configuration.png b/docs/img/OpenMQTTGateway_LORA_Configuration.png
index 03c43e4..be01292 100644
Binary files a/docs/img/OpenMQTTGateway_LORA_Configuration.png and b/docs/img/OpenMQTTGateway_LORA_Configuration.png differ
diff --git a/docs/img/OpenMQTTGateway_Pilight_Digoo-DG-R8S.png b/docs/img/OpenMQTTGateway_Pilight_Digoo-DG-R8S.png
index ae9bbbf..425b8d4 100644
Binary files a/docs/img/OpenMQTTGateway_Pilight_Digoo-DG-R8S.png and b/docs/img/OpenMQTTGateway_Pilight_Digoo-DG-R8S.png differ
diff --git a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_FTDI.jpg b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_FTDI.jpg
index 52b64b5..90d751b 100644
Binary files a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_FTDI.jpg and b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_FTDI.jpg differ
diff --git a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_OTA.png b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_OTA.png
index 96f45ab..b67bc83 100644
Binary files a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_OTA.png and b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_OTA.png differ
diff --git a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_disassembly.jpg b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_disassembly.jpg
index 8be4f40..604d034 100644
Binary files a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_disassembly.jpg and b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_disassembly.jpg differ
diff --git a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_green_led.jpg b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_green_led.jpg
index 8091fad..4cb973a 100644
Binary files a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_green_led.jpg and b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_green_led.jpg differ
diff --git a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_serial_and_broker.png b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_serial_and_broker.png
index 75b7ecf..c56f6a0 100644
Binary files a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_serial_and_broker.png and b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_serial_and_broker.png differ
diff --git a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_user_config.png b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_user_config.png
index 3faa9d4..662f483 100644
Binary files a/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_user_config.png and b/docs/img/OpenMQTTGateway_SONOFF_RF_Bridge_user_config.png differ
diff --git a/docs/img/OpenMQTTGateway_TTGO32_LORA_Receive.jpg b/docs/img/OpenMQTTGateway_TTGO32_LORA_Receive.jpg
index 5d353f6..65d4638 100644
Binary files a/docs/img/OpenMQTTGateway_TTGO32_LORA_Receive.jpg and b/docs/img/OpenMQTTGateway_TTGO32_LORA_Receive.jpg differ
diff --git a/docs/img/OpenMQTTGateway_TTGO32_LORA_Send.jpg b/docs/img/OpenMQTTGateway_TTGO32_LORA_Send.jpg
index b1c92a2..5c2778d 100644
Binary files a/docs/img/OpenMQTTGateway_TTGO32_LORA_Send.jpg and b/docs/img/OpenMQTTGateway_TTGO32_LORA_Send.jpg differ
diff --git a/docs/img/OpenMQTTGateway_Wifi_Manager_enter_parameters.png b/docs/img/OpenMQTTGateway_Wifi_Manager_enter_parameters.png
index 74cf7d7..2e9d978 100644
Binary files a/docs/img/OpenMQTTGateway_Wifi_Manager_enter_parameters.png and b/docs/img/OpenMQTTGateway_Wifi_Manager_enter_parameters.png differ
diff --git a/docs/img/OpenMQTTGateway_Wifi_Manager_menu.png b/docs/img/OpenMQTTGateway_Wifi_Manager_menu.png
index cc0ec33..205f68b 100644
Binary files a/docs/img/OpenMQTTGateway_Wifi_Manager_menu.png and b/docs/img/OpenMQTTGateway_Wifi_Manager_menu.png differ
diff --git a/docs/img/OpenMQTTGateway_Wifi_Manager_save.png b/docs/img/OpenMQTTGateway_Wifi_Manager_save.png
index 6078983..9b9a664 100644
Binary files a/docs/img/OpenMQTTGateway_Wifi_Manager_save.png and b/docs/img/OpenMQTTGateway_Wifi_Manager_save.png differ
diff --git a/docs/img/OpenMQTTGateway_arduino_esp32_sketchbook_folder.png b/docs/img/OpenMQTTGateway_arduino_esp32_sketchbook_folder.png
index 976a008..aa4f262 100644
Binary files a/docs/img/OpenMQTTGateway_arduino_esp32_sketchbook_folder.png and b/docs/img/OpenMQTTGateway_arduino_esp32_sketchbook_folder.png differ
diff --git a/docs/img/OpenMQTTGateway_auto_discovery_BLE_Sensor_Home_Assistant.gif b/docs/img/OpenMQTTGateway_auto_discovery_BLE_Sensor_Home_Assistant.gif
index 1cfe3d2..1851556 100644
Binary files a/docs/img/OpenMQTTGateway_auto_discovery_BLE_Sensor_Home_Assistant.gif and b/docs/img/OpenMQTTGateway_auto_discovery_BLE_Sensor_Home_Assistant.gif differ
diff --git a/docs/img/OpenMQTTGateway_auto_discovery_Gateway_Home_Assistant.gif b/docs/img/OpenMQTTGateway_auto_discovery_Gateway_Home_Assistant.gif
index b2cda02..4b4edba 100644
Binary files a/docs/img/OpenMQTTGateway_auto_discovery_Gateway_Home_Assistant.gif and b/docs/img/OpenMQTTGateway_auto_discovery_Gateway_Home_Assistant.gif differ
diff --git a/docs/img/OpenMQTTGateway_board_wifi_rf_gateway.png b/docs/img/OpenMQTTGateway_board_wifi_rf_gateway.png
index a7e8064..73918ea 100644
Binary files a/docs/img/OpenMQTTGateway_board_wifi_rf_gateway.png and b/docs/img/OpenMQTTGateway_board_wifi_rf_gateway.png differ
diff --git a/docs/img/OpenMQTTGateway_boards-removebg-preview.png b/docs/img/OpenMQTTGateway_boards-removebg-preview.png
index a59c03a..ebc1689 100644
Binary files a/docs/img/OpenMQTTGateway_boards-removebg-preview.png and b/docs/img/OpenMQTTGateway_boards-removebg-preview.png differ
diff --git a/docs/img/OpenMQTTGateway_boards.png b/docs/img/OpenMQTTGateway_boards.png
index ad51fb4..1209d33 100644
Binary files a/docs/img/OpenMQTTGateway_boards.png and b/docs/img/OpenMQTTGateway_boards.png differ
diff --git a/docs/img/OpenMQTTGateway_boards_avatto_s06.png b/docs/img/OpenMQTTGateway_boards_avatto_s06.png
index 3ed2886..20323a0 100644
Binary files a/docs/img/OpenMQTTGateway_boards_avatto_s06.png and b/docs/img/OpenMQTTGateway_boards_avatto_s06.png differ
diff --git a/docs/img/OpenMQTTGateway_boards_sonoff-removebg-preview.png b/docs/img/OpenMQTTGateway_boards_sonoff-removebg-preview.png
index d066ee1..22a6952 100644
Binary files a/docs/img/OpenMQTTGateway_boards_sonoff-removebg-preview.png and b/docs/img/OpenMQTTGateway_boards_sonoff-removebg-preview.png differ
diff --git a/docs/img/OpenMQTTGateway_boards_sonoff.png b/docs/img/OpenMQTTGateway_boards_sonoff.png
index a50e2ac..857def0 100644
Binary files a/docs/img/OpenMQTTGateway_boards_sonoff.png and b/docs/img/OpenMQTTGateway_boards_sonoff.png differ
diff --git a/docs/img/OpenMQTTGateway_boards_sonoff_rfbridge.png b/docs/img/OpenMQTTGateway_boards_sonoff_rfbridge.png
index 5df6e4b..81842ae 100644
Binary files a/docs/img/OpenMQTTGateway_boards_sonoff_rfbridge.png and b/docs/img/OpenMQTTGateway_boards_sonoff_rfbridge.png differ
diff --git a/docs/img/OpenMQTTGateway_boards_sonoff_rfr3.png b/docs/img/OpenMQTTGateway_boards_sonoff_rfr3.png
index c62c33b..921d324 100644
Binary files a/docs/img/OpenMQTTGateway_boards_sonoff_rfr3.png and b/docs/img/OpenMQTTGateway_boards_sonoff_rfr3.png differ
diff --git a/docs/img/OpenMQTTGateway_breadboard.jpg b/docs/img/OpenMQTTGateway_breadboard.jpg
index a16b79d..c128c13 100644
Binary files a/docs/img/OpenMQTTGateway_breadboard.jpg and b/docs/img/OpenMQTTGateway_breadboard.jpg differ
diff --git a/docs/img/OpenMQTTGateway_controllers.png b/docs/img/OpenMQTTGateway_controllers.png
index 81f5d5d..59c08ec 100644
Binary files a/docs/img/OpenMQTTGateway_controllers.png and b/docs/img/OpenMQTTGateway_controllers.png differ
diff --git a/docs/img/OpenMQTTGateway_devices_ble.png b/docs/img/OpenMQTTGateway_devices_ble.png
index 77a5c59..08353fd 100644
Binary files a/docs/img/OpenMQTTGateway_devices_ble.png and b/docs/img/OpenMQTTGateway_devices_ble.png differ
diff --git a/docs/img/OpenMQTTGateway_devices_rf1.png b/docs/img/OpenMQTTGateway_devices_rf1.png
index 4666e0b..f01489f 100644
Binary files a/docs/img/OpenMQTTGateway_devices_rf1.png and b/docs/img/OpenMQTTGateway_devices_rf1.png differ
diff --git a/docs/img/OpenMQTTGateway_devices_rf2.png b/docs/img/OpenMQTTGateway_devices_rf2.png
index 4dae908..c9dad90 100644
Binary files a/docs/img/OpenMQTTGateway_devices_rf2.png and b/docs/img/OpenMQTTGateway_devices_rf2.png differ
diff --git a/docs/img/OpenMQTTGateway_devices_rf3.png b/docs/img/OpenMQTTGateway_devices_rf3.png
index 0e920db..de4b354 100644
Binary files a/docs/img/OpenMQTTGateway_devices_rf3.png and b/docs/img/OpenMQTTGateway_devices_rf3.png differ
diff --git a/docs/img/OpenMQTTGateway_multiple_install.png b/docs/img/OpenMQTTGateway_multiple_install.png
index d4f0903..d557adb 100644
Binary files a/docs/img/OpenMQTTGateway_multiple_install.png and b/docs/img/OpenMQTTGateway_multiple_install.png differ
diff --git a/docs/img/OpenMQTTGateway_serial1.jpg b/docs/img/OpenMQTTGateway_serial1.jpg
index dddd741..4b40218 100644
Binary files a/docs/img/OpenMQTTGateway_serial1.jpg and b/docs/img/OpenMQTTGateway_serial1.jpg differ
diff --git a/docs/img/OpenMQTTGateway_serial2.jpg b/docs/img/OpenMQTTGateway_serial2.jpg
index a333be8..3d9a3dd 100644
Binary files a/docs/img/OpenMQTTGateway_serial2.jpg and b/docs/img/OpenMQTTGateway_serial2.jpg differ
diff --git a/docs/img/OpenMQTTGateway_serial3.jpg b/docs/img/OpenMQTTGateway_serial3.jpg
index a2d9d4d..773f627 100644
Binary files a/docs/img/OpenMQTTGateway_serial3.jpg and b/docs/img/OpenMQTTGateway_serial3.jpg differ
diff --git a/docs/img/OpenMQTTGateway_serial_2G_1.jpg b/docs/img/OpenMQTTGateway_serial_2G_1.jpg
index 01caecd..d997b08 100644
Binary files a/docs/img/OpenMQTTGateway_serial_2G_1.jpg and b/docs/img/OpenMQTTGateway_serial_2G_1.jpg differ
diff --git a/docs/img/OpenMQTTGateway_serial_2G_2.jpg b/docs/img/OpenMQTTGateway_serial_2G_2.jpg
index 05a77af..6c13f07 100644
Binary files a/docs/img/OpenMQTTGateway_serial_2G_2.jpg and b/docs/img/OpenMQTTGateway_serial_2G_2.jpg differ
diff --git a/docs/img/OpenMQTTgateway_Arduino_Addon_BT.png b/docs/img/OpenMQTTgateway_Arduino_Addon_BT.png
index 8b31cc5..ff22249 100644
Binary files a/docs/img/OpenMQTTgateway_Arduino_Addon_BT.png and b/docs/img/OpenMQTTgateway_Arduino_Addon_BT.png differ
diff --git a/docs/img/OpenMQTTgateway_Arduino_Addon_DHT.png b/docs/img/OpenMQTTgateway_Arduino_Addon_DHT.png
index b1efbe7..71c1e42 100644
Binary files a/docs/img/OpenMQTTgateway_Arduino_Addon_DHT.png and b/docs/img/OpenMQTTgateway_Arduino_Addon_DHT.png differ
diff --git a/docs/img/OpenMQTTgateway_Arduino_Addon_IR.png b/docs/img/OpenMQTTgateway_Arduino_Addon_IR.png
index 14eb193..2650dae 100644
Binary files a/docs/img/OpenMQTTgateway_Arduino_Addon_IR.png and b/docs/img/OpenMQTTgateway_Arduino_Addon_IR.png differ
diff --git a/docs/img/OpenMQTTgateway_Arduino_Addon_RF.png b/docs/img/OpenMQTTgateway_Arduino_Addon_RF.png
index e8e7dc9..0b852ed 100644
Binary files a/docs/img/OpenMQTTgateway_Arduino_Addon_RF.png and b/docs/img/OpenMQTTgateway_Arduino_Addon_RF.png differ
diff --git a/docs/img/OpenMQTTgateway_Arduino_Addon_RS232.png b/docs/img/OpenMQTTgateway_Arduino_Addon_RS232.png
index 64765d1..be426b5 100644
Binary files a/docs/img/OpenMQTTgateway_Arduino_Addon_RS232.png and b/docs/img/OpenMQTTgateway_Arduino_Addon_RS232.png differ
diff --git a/docs/img/OpenMQTTgateway_Arduino_AllInOne_IR-RF-BT-DHT.png b/docs/img/OpenMQTTgateway_Arduino_AllInOne_IR-RF-BT-DHT.png
index c1fad43..8418fb6 100644
Binary files a/docs/img/OpenMQTTgateway_Arduino_AllInOne_IR-RF-BT-DHT.png and b/docs/img/OpenMQTTgateway_Arduino_AllInOne_IR-RF-BT-DHT.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP32_Addon_IR.png b/docs/img/OpenMQTTgateway_ESP32_Addon_IR.png
index 9d94465..20c07c0 100644
Binary files a/docs/img/OpenMQTTgateway_ESP32_Addon_IR.png and b/docs/img/OpenMQTTgateway_ESP32_Addon_IR.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP32_Addon_RF.png b/docs/img/OpenMQTTgateway_ESP32_Addon_RF.png
index f27052e..929a16c 100644
Binary files a/docs/img/OpenMQTTgateway_ESP32_Addon_RF.png and b/docs/img/OpenMQTTgateway_ESP32_Addon_RF.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP32_Addon_RS232.png b/docs/img/OpenMQTTgateway_ESP32_Addon_RS232.png
index 345e94f..8d46477 100644
Binary files a/docs/img/OpenMQTTgateway_ESP32_Addon_RS232.png and b/docs/img/OpenMQTTgateway_ESP32_Addon_RS232.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP32_LORA_MSG.png b/docs/img/OpenMQTTgateway_ESP32_LORA_MSG.png
index 0eb0865..3fd309f 100644
Binary files a/docs/img/OpenMQTTgateway_ESP32_LORA_MSG.png and b/docs/img/OpenMQTTgateway_ESP32_LORA_MSG.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP32_binary_flash.png b/docs/img/OpenMQTTgateway_ESP32_binary_flash.png
index a3288a0..ab36cc1 100644
Binary files a/docs/img/OpenMQTTgateway_ESP32_binary_flash.png and b/docs/img/OpenMQTTgateway_ESP32_binary_flash.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP32_binary_flash2.png b/docs/img/OpenMQTTgateway_ESP32_binary_flash2.png
index 83ab713..abeb7ad 100644
Binary files a/docs/img/OpenMQTTgateway_ESP32_binary_flash2.png and b/docs/img/OpenMQTTgateway_ESP32_binary_flash2.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP8266_Addon_2G.png b/docs/img/OpenMQTTgateway_ESP8266_Addon_2G.png
index f324209..616bff8 100644
Binary files a/docs/img/OpenMQTTgateway_ESP8266_Addon_2G.png and b/docs/img/OpenMQTTgateway_ESP8266_Addon_2G.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP8266_Addon_DHT.png b/docs/img/OpenMQTTgateway_ESP8266_Addon_DHT.png
index 6b86d58..7b35028 100644
Binary files a/docs/img/OpenMQTTgateway_ESP8266_Addon_DHT.png and b/docs/img/OpenMQTTgateway_ESP8266_Addon_DHT.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP8266_Addon_I2C.png b/docs/img/OpenMQTTgateway_ESP8266_Addon_I2C.png
index 5d53b0d..7992ddd 100644
Binary files a/docs/img/OpenMQTTgateway_ESP8266_Addon_I2C.png and b/docs/img/OpenMQTTgateway_ESP8266_Addon_I2C.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP8266_Addon_IR.png b/docs/img/OpenMQTTgateway_ESP8266_Addon_IR.png
index 2870ed8..9d17c81 100644
Binary files a/docs/img/OpenMQTTgateway_ESP8266_Addon_IR.png and b/docs/img/OpenMQTTgateway_ESP8266_Addon_IR.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP8266_Addon_RF.png b/docs/img/OpenMQTTgateway_ESP8266_Addon_RF.png
index 38e09d9..23eb774 100644
Binary files a/docs/img/OpenMQTTgateway_ESP8266_Addon_RF.png and b/docs/img/OpenMQTTgateway_ESP8266_Addon_RF.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP8266_Addon_RFM69.png b/docs/img/OpenMQTTgateway_ESP8266_Addon_RFM69.png
index cf9c5c1..ac3a088 100644
Binary files a/docs/img/OpenMQTTgateway_ESP8266_Addon_RFM69.png and b/docs/img/OpenMQTTgateway_ESP8266_Addon_RFM69.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP8266_Addon_RS232.png b/docs/img/OpenMQTTgateway_ESP8266_Addon_RS232.png
index 84c95b3..99985cd 100644
Binary files a/docs/img/OpenMQTTgateway_ESP8266_Addon_RS232.png and b/docs/img/OpenMQTTgateway_ESP8266_Addon_RS232.png differ
diff --git a/docs/img/OpenMQTTgateway_ESP8285_Addon_IR.png b/docs/img/OpenMQTTgateway_ESP8285_Addon_IR.png
index 061ed9a..72e182d 100644
Binary files a/docs/img/OpenMQTTgateway_ESP8285_Addon_IR.png and b/docs/img/OpenMQTTgateway_ESP8285_Addon_IR.png differ
diff --git a/docs/img/OpenMQTTgateway_M5_Atom_Board.png b/docs/img/OpenMQTTgateway_M5_Atom_Board.png
index cea6bea..b982388 100644
Binary files a/docs/img/OpenMQTTgateway_M5_Atom_Board.png and b/docs/img/OpenMQTTgateway_M5_Atom_Board.png differ
diff --git a/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Logo.png b/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Logo.png
index 0a82ee1..56d8f0f 100644
Binary files a/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Logo.png and b/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Logo.png differ
diff --git a/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Text.png b/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Text.png
index ba8bc50..ee575db 100644
Binary files a/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Text.png and b/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Text.png differ
diff --git a/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Warning.png b/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Warning.png
index 4324c9e..7cec62f 100644
Binary files a/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Warning.png and b/docs/img/OpenMQTTgateway_M5_Stack_Board_Display_Warning.png differ
diff --git a/docs/img/OpenMQTTgateway_M5_StickC_Board_Display_Text.png b/docs/img/OpenMQTTgateway_M5_StickC_Board_Display_Text.png
index 349b661..cdd8f74 100644
Binary files a/docs/img/OpenMQTTgateway_M5_StickC_Board_Display_Text.png and b/docs/img/OpenMQTTgateway_M5_StickC_Board_Display_Text.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-chart-dashboard.png b/docs/img/OpenMQTTgateway_NODERED-chart-dashboard.png
index d7aa864..cb7caf7 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-chart-dashboard.png and b/docs/img/OpenMQTTgateway_NODERED-chart-dashboard.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-chart.png b/docs/img/OpenMQTTgateway_NODERED-chart.png
index 0d6df20..9fa8d42 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-chart.png and b/docs/img/OpenMQTTgateway_NODERED-chart.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-flow-BLE-temperature.png b/docs/img/OpenMQTTgateway_NODERED-flow-BLE-temperature.png
index c3cb2fa..f3564cd 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-flow-BLE-temperature.png and b/docs/img/OpenMQTTgateway_NODERED-flow-BLE-temperature.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-gauge-dashboard.png b/docs/img/OpenMQTTgateway_NODERED-gauge-dashboard.png
index 22b519b..856c370 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-gauge-dashboard.png and b/docs/img/OpenMQTTgateway_NODERED-gauge-dashboard.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-gauge.png b/docs/img/OpenMQTTgateway_NODERED-gauge.png
index 2cf0b53..b8e98a2 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-gauge.png and b/docs/img/OpenMQTTgateway_NODERED-gauge.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-integration-debug.png b/docs/img/OpenMQTTgateway_NODERED-integration-debug.png
index c1df1c9..5e2099e 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-integration-debug.png and b/docs/img/OpenMQTTgateway_NODERED-integration-debug.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-integration-debug2.png b/docs/img/OpenMQTTgateway_NODERED-integration-debug2.png
index 43cc447..fd00572 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-integration-debug2.png and b/docs/img/OpenMQTTgateway_NODERED-integration-debug2.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-integration-debug3.png b/docs/img/OpenMQTTgateway_NODERED-integration-debug3.png
index 5e235a0..62da36c 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-integration-debug3.png and b/docs/img/OpenMQTTgateway_NODERED-integration-debug3.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-integration-process.png b/docs/img/OpenMQTTgateway_NODERED-integration-process.png
index e96bae4..8bf6f09 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-integration-process.png and b/docs/img/OpenMQTTgateway_NODERED-integration-process.png differ
diff --git a/docs/img/OpenMQTTgateway_NODERED-integration.png b/docs/img/OpenMQTTgateway_NODERED-integration.png
index 4cae338..03c0be3 100644
Binary files a/docs/img/OpenMQTTgateway_NODERED-integration.png and b/docs/img/OpenMQTTgateway_NODERED-integration.png differ
diff --git a/docs/img/OpenMQTTgateway_NodeMCU_PyFlasher.png b/docs/img/OpenMQTTgateway_NodeMCU_PyFlasher.png
index 9029c36..483b5f9 100644
Binary files a/docs/img/OpenMQTTgateway_NodeMCU_PyFlasher.png and b/docs/img/OpenMQTTgateway_NodeMCU_PyFlasher.png differ
diff --git a/docs/img/OpenMQTTgateway_OpenHAB_Control.png b/docs/img/OpenMQTTgateway_OpenHAB_Control.png
index 50a2a79..b24f223 100644
Binary files a/docs/img/OpenMQTTgateway_OpenHAB_Control.png and b/docs/img/OpenMQTTgateway_OpenHAB_Control.png differ
diff --git a/docs/img/OpenMQTTgateway_SONOFF_RFBRIDGE_Upload_Parameters.png b/docs/img/OpenMQTTgateway_SONOFF_RFBRIDGE_Upload_Parameters.png
index b466a9c..5aa636e 100644
Binary files a/docs/img/OpenMQTTgateway_SONOFF_RFBRIDGE_Upload_Parameters.png and b/docs/img/OpenMQTTgateway_SONOFF_RFBRIDGE_Upload_Parameters.png differ
diff --git a/docs/img/OpenMQTTgateway_SONOFF_RFBRIDGE_results.png b/docs/img/OpenMQTTgateway_SONOFF_RFBRIDGE_results.png
index be6f4c8..9e12b6b 100644
Binary files a/docs/img/OpenMQTTgateway_SONOFF_RFBRIDGE_results.png and b/docs/img/OpenMQTTgateway_SONOFF_RFBRIDGE_results.png differ
diff --git a/docs/img/OpenMQTTgateway_miflora_results.png b/docs/img/OpenMQTTgateway_miflora_results.png
index 16952a7..7713e8d 100644
Binary files a/docs/img/OpenMQTTgateway_miflora_results.png and b/docs/img/OpenMQTTgateway_miflora_results.png differ
diff --git a/docs/img/Openmqttgateway_logo.png b/docs/img/Openmqttgateway_logo.png
index c4b043a..ad145be 100644
Binary files a/docs/img/Openmqttgateway_logo.png and b/docs/img/Openmqttgateway_logo.png differ
diff --git a/docs/img/Openmqttgateway_logo_micro.png b/docs/img/Openmqttgateway_logo_micro.png
index 0fd082c..71c6cd0 100644
Binary files a/docs/img/Openmqttgateway_logo_micro.png and b/docs/img/Openmqttgateway_logo_micro.png differ
diff --git a/docs/img/Openmqttgateway_logo_mini.png b/docs/img/Openmqttgateway_logo_mini.png
index 9674455..88d62c8 100644
Binary files a/docs/img/Openmqttgateway_logo_mini.png and b/docs/img/Openmqttgateway_logo_mini.png differ
diff --git a/docs/img/Openmqttgateway_logo_mini_512.png b/docs/img/Openmqttgateway_logo_mini_512.png
index 7a3a182..b788e96 100644
Binary files a/docs/img/Openmqttgateway_logo_mini_512.png and b/docs/img/Openmqttgateway_logo_mini_512.png differ
diff --git a/docs/img/Openmqttgateway_logo_mini_margins.png b/docs/img/Openmqttgateway_logo_mini_margins.png
index 6b8a761..6412d8a 100644
Binary files a/docs/img/Openmqttgateway_logo_mini_margins.png and b/docs/img/Openmqttgateway_logo_mini_margins.png differ
diff --git a/docs/img/Theengs-Bridge-ble-gateway.png b/docs/img/Theengs-Bridge-ble-gateway.png
index a1b166f..681f58b 100644
Binary files a/docs/img/Theengs-Bridge-ble-gateway.png and b/docs/img/Theengs-Bridge-ble-gateway.png differ
diff --git a/docs/img/Theengs-Plug-OpenMQTTGateway.png b/docs/img/Theengs-Plug-OpenMQTTGateway.png
index 96e8bda..cb6f3bc 100644
Binary files a/docs/img/Theengs-Plug-OpenMQTTGateway.png and b/docs/img/Theengs-Plug-OpenMQTTGateway.png differ
diff --git a/docs/img/Wiki_module_BT.png b/docs/img/Wiki_module_BT.png
index 9f5b473..fece17b 100644
Binary files a/docs/img/Wiki_module_BT.png and b/docs/img/Wiki_module_BT.png differ
diff --git a/docs/img/Wiki_module_DHT.png b/docs/img/Wiki_module_DHT.png
index 2c6c0e2..38b1c69 100644
Binary files a/docs/img/Wiki_module_DHT.png and b/docs/img/Wiki_module_DHT.png differ
diff --git a/docs/img/Wiki_module_I2C.png b/docs/img/Wiki_module_I2C.png
index f81f68b..9c72489 100644
Binary files a/docs/img/Wiki_module_I2C.png and b/docs/img/Wiki_module_I2C.png differ
diff --git a/docs/img/Wiki_module_IR.png b/docs/img/Wiki_module_IR.png
index 860fdd2..638a7b7 100644
Binary files a/docs/img/Wiki_module_IR.png and b/docs/img/Wiki_module_IR.png differ
diff --git a/docs/img/Wiki_module_RF.png b/docs/img/Wiki_module_RF.png
index fc3b1b8..2ce546d 100644
Binary files a/docs/img/Wiki_module_RF.png and b/docs/img/Wiki_module_RF.png differ
diff --git a/docs/img/Wiki_module_RFM69.png b/docs/img/Wiki_module_RFM69.png
index 7e010a5..be05750 100644
Binary files a/docs/img/Wiki_module_RFM69.png and b/docs/img/Wiki_module_RFM69.png differ
diff --git a/docs/img/arduino-esp32-sketchbook.png b/docs/img/arduino-esp32-sketchbook.png
index c7f982f..2cce5e7 100644
Binary files a/docs/img/arduino-esp32-sketchbook.png and b/docs/img/arduino-esp32-sketchbook.png differ
diff --git a/docs/img/digoo-pir-DG-HOSA.png b/docs/img/digoo-pir-DG-HOSA.png
new file mode 100644
index 0000000..f168713
Binary files /dev/null and b/docs/img/digoo-pir-DG-HOSA.png differ
diff --git a/docs/img/domoticz-logo.jpg b/docs/img/domoticz-logo.jpg
index 1607411..8fc9d28 100644
Binary files a/docs/img/domoticz-logo.jpg and b/docs/img/domoticz-logo.jpg differ
diff --git a/docs/img/fhem_logo.png b/docs/img/fhem_logo.png
index e9ba39d..8e9e64c 100644
Binary files a/docs/img/fhem_logo.png and b/docs/img/fhem_logo.png differ
diff --git a/docs/img/home-assistant-logo.png b/docs/img/home-assistant-logo.png
index ba31199..2e6e621 100644
Binary files a/docs/img/home-assistant-logo.png and b/docs/img/home-assistant-logo.png differ
diff --git a/docs/img/jeedom-logo.png b/docs/img/jeedom-logo.png
index dcb9720..c0f601a 100644
Binary files a/docs/img/jeedom-logo.png and b/docs/img/jeedom-logo.png differ
diff --git a/docs/img/node-red-logo.png b/docs/img/node-red-logo.png
index 898c242..9d9123d 100644
Binary files a/docs/img/node-red-logo.png and b/docs/img/node-red-logo.png differ
diff --git a/docs/img/openhab-logo.png b/docs/img/openhab-logo.png
index cd63463..c661d99 100644
Binary files a/docs/img/openhab-logo.png and b/docs/img/openhab-logo.png differ
diff --git a/docs/img/upload.png b/docs/img/upload.png
new file mode 100644
index 0000000..9ea6616
Binary files /dev/null and b/docs/img/upload.png differ
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..5562b2f
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,286 @@
+---
+layout: home
+
+hero:
+  name: OpenMQTTGateway
+  text: One gateway, many technologies
+  tagline: Bridge RF, Infrared, Bluetooth LE, LoRa and more to MQTT, and to your home automation platform.
+  image:
+    src: /img/OpenMQTTGateway.png
+    alt: Overview of the protocols and compatible controllers
+  actions:
+    - theme: brand
+      text: Get started
+      link: /getting-started
+    - theme: alt
+      text: Flash from your browser
+      link: /upload/web-install
+    - theme: alt
+      text: Supported BLE devices
+      link: https://decoder.theengs.io/devices/devices.html
+
+features:
+  - icon: 📶
+    title: Bluetooth Low Energy
+    details: Decodes more than 100 BLE sensors out of the box thanks to Theengs Decoder — Mi Flora, Xiaomi, Govee, Inkbird, SwitchBot and more.
+  - icon: 📡
+    title: RF 433/315/868/915MHz
+    details: Receive and transmit RF signals with RTL_433, RCSwitch, KaKu or Pilight — weather stations, door sensors, remotes, PIR sensors.
+  - icon: 🔴
+    title: Infrared & LoRa
+    details: Make your old TV or AC smart through IR, or reach far-away sensors with LoRa.
+  - icon: 🏠
+    title: Home automation ready
+    details: Home Assistant MQTT auto-discovery enabled by default. Works with OpenHAB, Domoticz, Jeedom, Node-RED, FHEM and any MQTT-capable software.
+  - icon: ⚡
+    title: Easy to install
+    details: Flash an ESP32 or ESP8266 directly from your browser, then configure WiFi and MQTT through a web portal. No development tools required.
+  - icon: 🔧
+    title: Extensible
+    details: Add sensors (BME280, DHT, INA226...) and actuators (relays, PWM, LED), secure connections with TLS, and update over the air.
+---
+
+
+
+
+

Development Version

+

This is the edge version of the documentation, built from commit {{ version }}{{ version }}. It is under active development and may contain bugs, incomplete features, or breaking changes. Use it at your own risk.

+
+ +
+

How it works

+

OpenMQTTGateway is a firmware for ESP32 and ESP8266 boards that translates your devices' signals into MQTT messages — and back. One board replaces a drawer full of proprietary bridges.

+ +

Decodes more than 100 BLE devices and many RF protocols (433/315/868/915MHz) through RTL_433 decoders — and the BLE decoding also runs on Raspberry Pi, Windows or Linux with Theengs Gateway.

+
+ +
+

What will you automate?

+
+
+ {{ uc.icon }} + {{ uc.text }} +
+
+

The limit is your imagination 😀

+
+ +
+

See it in action

+ +

In the press: + +

+
+ +
+

Under the hood

+
+ {{ f }} +
+
+ +
+

Support the project

+
+ + Theengs Bridge, BLE to MQTT gateway with Ethernet and external antenna + +
+

Theengs Bridge — ready-to-use BLE gateway

+

Pre-flashed with OpenMQTTGateway, with an Ethernet port and an external antenna for enhanced BLE range. Every purchase directly funds the project.

+ Get the Theengs Bridge +
+
+

You can also sponsor the development to help keep the project healthy and evolving.

+
+ +
+
+ +
+

The material and information contained in this documentation is for general information purposes only. You should not rely upon it as a basis for making any business, legal or any other decisions. There is no warranty given on this documentation content; if you decide to follow the information and materials given it is at your own risk.

+
+ + diff --git a/docs/integrate/aws_iot.md b/docs/integrate/aws_iot.md index 0885cda..b77c318 100644 --- a/docs/integrate/aws_iot.md +++ b/docs/integrate/aws_iot.md @@ -78,18 +78,7 @@ Now you should have the following information for the OpenMQTTGateway configurat ## Modify OpenMQTTGateway configuration -With Arduino IDE, you can update the following field into User_config.h with the information gathered: -* Gateway_Name -* `MQTT_SERVER "xxxxxx.iot-eu-amazonaws.com"` -* `MQTT_PORT "8883"` -* `AWS_IOT true` -* ss_server_cert with the root certificate -* ss_client_cert with the client certificate -* ss_client_key with the Client key -* `MQTT_SECURE_SELF_SIGNED 1` -* `MQTT_SECURE_DEFAULT true` - -With PlatformIO you can directly leverage the environment `esp32dev-ble-aws` +With PlatformIO you can directly leverage the environment `esp32dev-ble-aws` as an example and modify it following your needs. ## Build and upload diff --git a/docs/integrate/home_assistant.md b/docs/integrate/home_assistant.md index 2ea7993..29deb8f 100644 --- a/docs/integrate/home_assistant.md +++ b/docs/integrate/home_assistant.md @@ -5,13 +5,13 @@ Home Assistant provide the [MQTT integration](https://www.home-assistant.io/inte Once this integration on home assistant is configured with the same MQTT broker, it is possible to create devices manually or through the autodiscovery function. -## Auto discovery +## Automatic integration with Auto discovery From Home Assistant site > The discovery of MQTT devices will enable one to use MQTT devices with only minimal configuration effort on the side of Home Assistant. The configuration is done on the device itself and the topic used by the device. -On OpenMQTTGateway the Home Assistant discovery is enabled by default on all binaries and platformio configurations except for UNO. With Arduino IDE please read the [advanced configuration section](../upload/advanced-configuration#auto-discovery) of the documentation. Here are a few tips for activating discovery on Home Assistant, but for detailed configuration please refer to the Home Assistant website. +On OpenMQTTGateway the Home Assistant discovery is enabled by default on all binaries and platformio configurations. Here are a few tips for activating discovery on Home Assistant, but for detailed configuration please refer to the Home Assistant website. Enable discovery on your MQTT integration in HASS (activated per default). @@ -37,12 +37,12 @@ OMG will use the auto discovery functionality of home assistant to create gatewa The Bluetooth and the RTL_433 gateway will automatically create devices and entities, the RF gateway will create DeviceTrigger. The OpenMQTTGateway will also be available as a device to monitor its parameters and control it. The sensors (DHT for example) and actuators (relays) are attached to the gateway. -On first and subsequent startups, auto discovery will start. If you want to prevent this from happening, be sure to manually turn off auto discovery, either by using the UI in Home Assistant, or by publishing to the home//commands/MQTTtoSYS/config topic. +On first and subsequent startups, auto discovery will start. If you want to prevent this from happening, be sure to manually turn off auto discovery, either by using the UI in Home Assistant, or by publishing to the `home//commands/MQTTtoSYS/config` topic. 30 minutes after its activation the auto discovery will be automatically deactivated, you can reactivate it from the gateway controls. Some devices may require a button push or motion/contact event to trigger a message and generate the auto discovery. ::: -## RTL_433 auto discovery specificity +### RTL_433 auto discovery specificity Even if the RTL_433 gateway will create automatically the devices and entities, you may lose the link to them when you change the batteries. This is proper to the RF devices. In this case new device and entities will be created. You may bypass this by creating entities through manual configuration that filter following the device model and other parameters and don't take into account the id. Example: @@ -74,16 +74,119 @@ mqtt: Alternatively the rssi signal could be used also. -## MQTT Device Trigger and RF +### RF (RCSwitch based gateway) Auto discovery specificity +With OpenMQTTGateway [configured to receive RF signals](../setitup/rf.html) messages are transmitted accordingly. -With OpenMQTTGateway [configured to receive RF signals](../setitup/rf.html) the messages are transmitted as indicated by [RCSwitch based gateway](../use/rf.html#rcswitch-based-gateway), so it is possible to receive a pulse every time the sensor discover a signal. +As indicated in the [RCSwitch based gateway](../use/rf.html#rcswitch-based-gateway), it is possible to receive a pulse each time the sensor detects a signal. With auto-discovery enabled, you can configure two types of entities in Home Assistant to handle RF signals: -With autodiscovery enabled, HomeAssistant will discover a [MQTT Device Trigger](https://www.home-assistant.io/integrations/device_trigger.mqtt/) identified by the value field given in the mqtt argument. -## Manual integration examples -From @123, @finity, @denniz03, @jrockstad, @anarchking, @dkluivingh +1. An [MQTT Device Trigger](https://www.home-assistant.io/integrations/device_trigger.mqtt/) which allows actions to be triggered when a specific RF signal is received. +2. An [MQTT Sensor](https://www.home-assistant.io/integrations/sensor.mqtt/) +which stores the received RF data as a sensor value. + +Below are some examples of both configurations. + +#### Example A - RF as MQTT Device Trigger +If the following parameters are enabled in OpenMQTTGateway: +- ZgatewayRF="RF" +- valueAsATopic=true +- HADiscovery=true +- RF_on_HAS_as_DeviceTrigger=true +- RF_on_HAS_as_MQTTSensor=false + +Then, each time an RF signal is received by OpenMQTTGateway, two messages are sent to the MQTT broker: + +1. A device trigger announcement (used by Home Assistant to recognize the trigger). +2. The RF signal data on the corresponding MQTT topic. + +``` +... +N: [ OMG->MQTT ] topic: homeassistant/device_automation/246F287AF0C4/15524904/config msg: {"automation_type":"trigger","platform ":"device_automation","type":"Received","subtype":"RF-15524904","device":{"configuration_url":"http://192.168.2.150/","connections":[["mac","246F287AF0C4"]],"identifiers":["246F287AF0C4"],"mf":"OMG_community","mdl":"[\"WebUI\",\"RF\"]","name":"OMG_DEVELOPMENT","sw":"1.8.0-o"},"value_template":"{{trigger.value.raw}}","topic":"home/OMG_DEVELOPMENT/433toMQTT/15524904"} +T: Dequeue JSON +N: [ OMG->MQTT ] topic: home/OMG_DEVELOPMENT/433toMQTT/15524904 msg: {"value":15524904,"protocol":1,"length":24,"delay":368,"tre_state":"-","binary":"111011001110010000101000","raw":"11427,1042,407,1039,417,1027,430,302,1148,1019,438,1015,440,295,1152,301,1153,1014,442,1012,441,1008,445,291,1160,293,1158,1011,444,292,1156,296,1157,296,1157,298,1154,1011,442,295,1153,1013,443,293,1157,295,1154,300"} +... +``` + +These messages allow Home Assistant to recognize and integrate the RF signal as a device trigger. +![MQTTExplorer Show Topic](../img/HASS-RF-DeviceTrigger.png) +*Example of a detected RF device trigger in Home Assistant: Green shows the real message, Yellow shows the device trigger configuration* + +Once this process is completed, Home Assistant detects a new trigger associated with the OpenMQTTGateway device and linked to the received RF signal value. +This means that Home Assistant can now react to the received RF signal as an automation trigger. + +Example of a detected RF trigger in Home Assistant: + +![MQTTExplorer Show Topic](../img/HASS-RF-Trigger-example.png) +*Example of a detected RF trigger in Home Assistant* + + + +#### Example B - RF As MQTT Sensor +If the following parameters are enabled in OpenMQTTGateway: +- ZgatewayRF="RF" +- HADiscovery=true +- RF_on_HAS_as_DeviceTrigger=false +- RF_on_HAS_as_MQTTSensor=true + +During any discovery round, a SYS message is sent, setting the MQTT Sensor as a sensor of the OpenMQTTGateway device. + +``` +... +N: [ OMG->MQTT ] topic: homeassistant/sensor/246F287AF0C4-gatewayRF/config msg: {"stat_t":"home/OMG_DEVELOPMENT/433toMQTT/#","avty_t":"home/OMG_DEVELOPMENT/LWT","name":"gatewayRF","uniq_id":"246F287AF0C4-gatewayRF","val_tpl":"{{ value_json.value | is_defined }}","pl_avail":"online","pl_not_avail":"offline","device":{"ids":["246F287AF0C4"],"name":"OMG_DEVELOPMENT","mdl":"[\"WebUI\",\"RF\"]","mf":"OMG_community","cu":"http://192.168.2.150/","sw":"1.8.0-o"}} +T: Dequeue JSON +``` + +Then, each time an RF signal is received by OpenMQTTGateway, the content of messages are sent to the MQTT broker on classic topic: + +``` +T: Dequeue JSON +N: [ OMG->MQTT ] topic: home/OMG_DEVELOPMENT/433toMQTT/15524904 msg: {"value":15524904,"protocol":1,"length":24,"delay":368,"tre_state":"-","binary":"111011001110010000101000","raw":"11404,1045,414,1034,424,1024,430,305,1146,1022,431,1019,436,299,1150,304,1145,1021,432,1017,438,1013,441,295,1156,299,1149,1018,436,300,1149,304,1146,307,1143,310,1141,1025,430,306,1143,1021,432,305,1145,310,1140,309"} + +``` + +These messages enable Home Assistant to recognize and integrate the RF signal as a sensor. + +![MQTTExplorer Show Topic](../img/HASS-RF-MQTTSensor.png) +*Example of a detected RF sensor in Home Assistant: Yellow the configuration of sensor, Green the real message* + +Once this process is completed, Home Assistant detects a device with the new sensor and linked to the received RF signal value. +This means that Home Assistant can now react to the received RF signal as an sensor event. + +Example of a detected RF trigger in Home Assistant: + +![MQTTExplorer Show Topic](../img/HASS-RF-Sensor-example.png) +*Example of a detected RF sensor in Home Assistant: Yellow the real message* + + + +## Manual integration +If you prefer not to use MQTT auto-discovery, you can manually configure Home Assistant to manage MQTT topics. This approach gives you full control over the structure and behavior of your MQTT entities. Below are some examples of how to define your devices, sensors, and switches manually using YAML configuration. + +From @123, @finity, @denniz03, @jrockstad, @anarchking, @dkluivingh, @Odyno + + +### Pir Sensor +This is an example of how to configure a PIR (Passive Infrared) sensor in Home Assistant using MQTT. + +![Pir Sensor](../img/digoo-pir-DG-HOSA.png) + +The configuration below sets up a binary sensor that detects motion and sends the state to Home Assistant. + +```yaml +mqtt: + binary_sensor: + - unique_id: pir.15484294 + name: "Pir.Mansarda" + device_class: motion + state_topic: "home/+/433toMQTT/15484294" + value_template: "{{ value_json.value }}" + payload_on: "15484294" + off_delay: 3 +``` + ### Door sensor + ```yaml mqtt: binary_sensor: @@ -166,6 +269,45 @@ mqtt: qos: "0" retain: true ``` +### RF gateway mode - Pilight, RF, kaku +insert an include statement in HA configuration.yaml +```bash +grep homed ./configuration.yaml +mqtt: !include homed-mqtt.yaml +``` +In the example, the included file is homed-mqtt.yaml. It provides an mqtt select entity with the ability to show and also change via dropdown - the desired mode of the RF receiver gateway. In the homed-mqtt.yaml snippet, the device section (as it is optional) is ommited, +```yaml +select: + - name: 'RF: Mode receive' + unique_id: espdevcho-rf-mode + #platform: mqtt + availability_topic: home/espdevcho/LWT # espdevcho is a particular name of the gateway, instead of the default OpenMQTTGateway + payload_available: online + payload_not_available: offline + options: + - "Pilight" + - "RF classic" + - "RF2 kaku" + state_topic: home/espdevcho/RFtoMQTT # espdevcho is a particular name of the gateway, instead of the default OpenMQTTGateway + value_template: > + {% if value_json.active == 1 %} Pilight + {% elif value_json.active == 2 %} RF classic + {% elif value_json.active == 4 %} RF2 kaku + {% endif %} + #unit_of_measurement: s + command_topic: home/espdevcho/commands/MQTTtoRF/config # espdevcho is a particular name of the gateway, instead of the default OpenMQTTGateway + command_template: > + {% set value_map = { + "Pilight": 1, + "RF classic": 2, + "RF2 kaku": 4, + } + %} + {"active":{{ value_map[value] }}} + device: + configuration_url: http://192.168.1.11/ # device section is optional. It is almost ommited in this example. Values here will update the corresponding device, if it already exist + +``` ### Mijia Thermometer BLE diff --git a/docs/integrate/openhab3.md b/docs/integrate/openhab3.md index 1bc5f1b..af6949a 100644 --- a/docs/integrate/openhab3.md +++ b/docs/integrate/openhab3.md @@ -76,13 +76,6 @@ Or use another upload method from the Upload section that requires credentials b You should see the gateway connected to your broker by checking with an MQTT client like MQTT Explorer. -To make the auto discovery compatible with OpenHAB you have to send the following command with a retain flag. - -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"ohdisc":true}'` - -You can also activate OpenHAB auto discovery by adding the gateway as a Thing, Model, and switching the button to ON. The name of the channel to add is "SYS: OpenHAB discovery". -Once activated restart OpenMQTTGateway. - ## Adding the things 1. From the Administration click on "Things" under "Settings", you should see a number in the INBOX button diff --git a/docs/participate/adding-protocols.md b/docs/participate/adding-protocols.md index 88b174c..5a19e99 100644 --- a/docs/participate/adding-protocols.md +++ b/docs/participate/adding-protocols.md @@ -1,12 +1,22 @@ # Adding protocols -Adding your device protocol to OpenMQTTGateway enables it to increase interoperability and to create new use cases with your device. Below you will find some guidance to do that. +Adding your device protocol to OpenMQTTGateway increases interoperability and creates new use cases. Use the steps below to pick the right path and upstream your changes. + +::: tip Before you open a PR +Read the [Development contributions guide](./development.md) for naming rules, QA, and PR steps. It keeps your protocol addition reviewable. +::: ## RF or IR -For adding RF and IR protocols to OpenMQTTGateway the best way is to do a pull request to [RCSwitch](https://github.com/1technophile/rc-switch), [Pilight](https://github.com/pilight/pilight) for RF, and [IRRemoteESP8266](https://github.com/crankyoldgit/IRremoteESP8266) for IR. +1. Implement or extend the protocol in the upstream libs first: [RCSwitch](https://github.com/1technophile/rc-switch) or [Pilight](https://github.com/pilight/pilight) for RF, and [IRRemoteESP8266](https://github.com/crankyoldgit/IRremoteESP8266) for IR. +2. Once merged (or while your PR is pending), wire it in OMG as a new decoder/mapping. +3. Add a short test sniff/build locally with the relevant environment (for example `esp32dev-all-test`). ## BLE -For BLE message decoding OpenMQTTGateway uses the [Theengs Decoder](https://decoder.theengs.io/) library. New device decoder pull requests can be submitted directly to the [GitHub repository](https://github.com/theengs/decoder). +1. For BLE message decoding, OpenMQTTGateway uses [Theengs Decoder](https://decoder.theengs.io/). Submit new device decoders directly to the [GitHub repository](https://github.com/theengs/decoder). +2. After the decoder exists, ensure the device is reported correctly through OMG (advertising devices are supported without connection). +3. Build locally for a BLE-enabled environment and validate the payload. -Currently we support the reading of advertizing BLE devices, advertizing means that the BLE device broadcasts regularly its sensor data without the need of a BLE connection. +Notes: +- We support reading **advertising** BLE devices (they broadcast regularly without a connection). +- Keep payloads compact and follow existing JSON fields for consistency. diff --git a/docs/participate/community.md b/docs/participate/community.md index d8494b6..ded39a8 100644 --- a/docs/participate/community.md +++ b/docs/participate/community.md @@ -1,4 +1,9 @@ # Community participation -The first entry step for participating to OMG is sharing and discussing with the [community](https://community.openmqttgateway.com), by sharing your experiences and answering to other questions you are giving back what the others gave to you. +The first entry step for participating to OMG is sharing and discussing with the [community](https://community.openmqttgateway.com). By sharing your experiences and answering questions you give back what others gave to you. -You can use the forum to ask questions, post answers, suggest features and discuss about home automation or Internet of things in a more general way. \ No newline at end of file +Use the forum to: +- Ask questions about hardware, builds, MQTT, BLE/RF/IR, or docs. +- Share projects, logs, and payload samples that help others. +- Suggest features or confirm if something already exists. + +When you have a change to contribute, follow the [Development contributions guide](./development.md) for the PR flow. \ No newline at end of file diff --git a/docs/participate/development.md b/docs/participate/development.md index 471a811..f67a235 100644 --- a/docs/participate/development.md +++ b/docs/participate/development.md @@ -1,30 +1,37 @@ # Development contributions -We like pull requests from everyone. By participating in this project, you -agree to follow the code of conduct below +We like pull requests from everyone and ask you to follow the code of conduct below. -[code of conduct](https://github.com/1technophile/OpenMQTTGateway/blob/master/CODE_OF_CONDUCT.md) +* [Code of conduct](https://github.com/1technophile/OpenMQTTGateway/blob/master/CODE_OF_CONDUCT.md) -[code style guide](https://google.github.io/styleguide/cppguide.html#Formatting) +* [Code style guide](https://google.github.io/styleguide/cppguide.html#Formatting) -So as to format automatically your document you have to add the "clang-Format" extension to VSCode, once done, you can format the code by doing a right click into the code file window and clicking "Format document". +If you need a step-by-step install and build guide, read the [Quick Start to Develop OpenMQTTGateway](./quick_start.md). It explains the tools, PlatformIO, and docs workflow. Use this page as a fast checklist once you know the flow. -Fork the [development branch](https://github.com/1technophile/OpenMQTTGateway/tree/development), then clone the repo +**Quick checklist** +1. Fork the [development branch](https://github.com/1technophile/OpenMQTTGateway/tree/development) and clone the repo. +2. Make your changes and follow the naming rules: + * New gateway: `ZgatewayXXX` where `XXX` is the protocol name. + * New sensor: `ZsensorYYY` where `YYY` is the sensor type. + * New actuator: `ZactuatorZZZ` where `ZZZ` is the actuator type. +3. Review your code and compile for ESP32 and ESP8266. +4. Test on your hardware. +5. Open a pull request, verify the GitHub Actions CI build, and request a review. -Make your modification, -* If you want to add a new gateway, name it `ZgatewayXXX`, `XXX` replaced by your gateway communication type, can be more than three letters -* If you want to add a new sensor, name it `ZsensorYYY`, `YYY` replaced by your sensor type, can be more than three letters -* If you want to add a new actuator, name it `ZactuatorZZZ`, `ZZZ` replaced by your actuator type, can be more than three letters +## Automated Testing and CI -Review your code, compile it for Arduino Uno, ESP32 and ESP8266 +Your pull request will be automatically tested by GitHub Actions. If you want to run the same checks locally before pushing, you can use the `ci.sh` script in the scripts folder. -Test it locally on your hardware config +**Need help with the ci.sh commands?** See [section 5 in Quick Start](./quick_start.md#5-firmware-development-from-the-terminal-with-cish) for detailed examples of running QA checks and builds from the terminal. -Emit a pull request +For more details on how CI works and available scripts, see the [CI documentation](https://github.com/1technophile/OpenMQTTGateway/blob/development/scripts) in the scripts folder. -Verify the GitHub Actions CI compilation results +For a comprehensive overview of all GitHub Actions workflows used in this project, check the [Workflows README](https://github.com/1technophile/OpenMQTTGateway/tree/development/.github/workflows). + +## Code Quality + +To format your code automatically, add the "clang-Format" extension to VSCode, then right click in the file and choose "Format document". -Request for review We may suggest some changes, improvements or alternatives. @@ -73,3 +80,5 @@ This Developer Certificate Of Origin (DCO) was adopted on June 7, 2021. The text of this license is available under the [Creative Commons Attribution-ShareAlike 3.0 Unported License](http://creativecommons.org/licenses/by-sa/3.0/). It is based on the Linux [Developer Certificate Of Origin](http://elinux.org/Developer_Certificate_Of_Origin). To accept the DCO it is required to put a x between [ ] on `[ ] I accept the DCO` in the PR template when submitting it. The [ ] is an opt-in box, so you have to manually accept it. + + diff --git a/docs/participate/index.md b/docs/participate/index.md new file mode 100644 index 0000000..34618ee --- /dev/null +++ b/docs/participate/index.md @@ -0,0 +1,46 @@ +# Participate in OpenMQTTGateway + +OpenMQTTGateway is community-driven: every feature, bug fix, and doc improvement comes from contributors like you. Whether you want to add support for a new sensor, fix a bug, improve documentation, or just help others—there's a place for you here. + +## Choose your path + +### 🚀 New to the project? Start here +[**Quick Start Guide**](./quick_start.md) walks you through setting up your development environment, building firmware, and previewing the docs. It covers PlatformIO, VS Code, terminal workflows, and troubleshooting. Perfect if you're new to ESP32/ESP8266 development or just want to get your hands dirty quickly. + +**What you'll learn:** Installing tools · Building firmware · Flashing boards · Running tests · Working with the docs + +--- + +### 💻 Ready to contribute code? +[**Development Contributions**](./development.md) covers the contribution workflow: naming conventions, code quality checks, testing on multiple boards, and opening pull requests. This is your checklist before submitting code. + +**What you'll find:** PR workflow · Naming rules (ZgatewayXXX, ZsensorYYY) · QA automation · DCO · CI/CD integration + +--- + +### 🔌 Adding a new protocol or device? +[**Adding Protocols**](./adding-protocols.md) explains how to integrate RF, IR, or BLE devices. Most protocol work happens upstream (RCSwitch, Pilight, IRRemoteESP8266, Theengs Decoder), and this guide shows you how to wire it into OMG. + +**What you'll learn:** Upstream contribution · Protocol integration · Testing decoders · Payload validation + +--- + +### 💬 Join the community +[**Community Participation**](./community.md) is where you ask questions, share your projects, and help others. The forum is the first stop for feature requests, debugging help, and general IoT/home automation discussion. + +**What you can do:** Ask questions · Share builds · Propose features · Help newcomers + +--- + +### ❤️ Support the project +[**Supporting the Project**](./support.md) lists all the ways you can help beyond code: answering forum questions, improving docs, purchasing Theengs products, sponsoring developers, or creating content about your OMG setup. + +**How you can help:** Forum support · Documentation · Sponsorship · Content creation + +--- + +::: tip Not sure where to start? +- **First time here?** → [Quick Start](./quick_start.md) +- **Have a fix or feature ready?** → [Development contributions](./development.md) +- **Need help or want to discuss?** → [Community](./community.md) +::: diff --git a/docs/participate/quick_start.md b/docs/participate/quick_start.md new file mode 100644 index 0000000..ea96b94 --- /dev/null +++ b/docs/participate/quick_start.md @@ -0,0 +1,842 @@ +--- +title: Contributor Quick Start +permalink: /participate/quick_start.html +sidebarDepth: 2 +lang: en-US +--- + +# Contributor Quick Start + +Looking to **use** OpenMQTTGateway rather than develop it? Head to the [Getting Started guide](../getting-started.md) instead. + +This document helps a new contributor. Maybe this is your first time with: + +- Git +- PlatformIO +- ESP32 or ESP8266 + +It is normal to feel a bit lost at the beginning. This guide walks with you, step by step. + +::: tip Already experienced? +If you only need the contribution rules and PR flow, jump to [Development contributions](./development.md). For community help or non-code support, see [Community participation](./community.md) and [Supporting the project](./support.md). +::: + + + +In this document you will learn how to: + +- Prepare the development environment on Windows or Linux. +- Build and flash the firmware (ESP32 / ESP8266 and other boards). +- Build and preview the documentation website in the docs folder. + +At the end of each step you see a **Check**. Use it to confirm that the previous step is correct before you go to the next one. If a check fails, do not worry: read the step again, fix it, and try one more time. + + + +## 1. Understand this project + +OpenMQTTGateway is a firmware project. It runs on ESP32, ESP8266 and other boards. It connects many protocols (Bluetooth, RF, IR, LoRa, sensors) to MQTT. + +The repository also contains the documentation website. The docs use VuePress and live in the docs folder. + +Very simple view of the repository: + +- main: C++ source code for the firmware. +- lib: reusable libraries. +- scripts: helper scripts for build, test, CI. +- docs: documentation website. + +You will mainly work on: + +- Firmware code: files under main and sometimes lib. +- Docs site: files under docs and docs/.vuepress. + +**Check:** open the repository in a file explorer and confirm you see at least main, lib, scripts and docs folders. If not, read section 3 again. + + + +## 2. Prepare your computer + +You can use Windows or Linux. The steps are very similar. The examples use a terminal. On Windows you can use **Git Bash** or **WSL**; on Linux you can use your normal shell. + +Not everybody needs to install the same tools. It depends on what you want to do: + +- **Only firmware (with VS Code or terminal):** you mainly need Git, PlatformIO, VS Code (if you like GUI) and a bash shell. +- **Only documentation website:** you mainly need Git, Node.js and npm. +- **Both firmware and docs:** you need everything. + +The next subsections explain this. + +### 2.1 Common tools (for everyone) + +Install these tools first. They are useful for **all** types of work: + +- Git +- Visual Studio Code (recommended, but you can also use another editor) +- A bash shell + - On Windows: Git Bash or WSL (Ubuntu is a good choice). + +On Windows you can download: + +- Git from the official site: https://git-scm.com/downloads +- Visual Studio Code from https://code.visualstudio.com/ +- Git Bash comes with "Git for Windows". + +On Linux you can install these with your package manager (for example apt on Ubuntu). For more help you can read the Git book: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git. + +**Check (common tools):** open a terminal (Git Bash, WSL, or Linux shell) and run: + +```bash +git --version +``` + +If this command fails, install Git again and then close and reopen the terminal. + +### 2.2 Tools for firmware development + +For firmware builds you need **PlatformIO**. PlatformIO itself will install the right compiler and frameworks for your boards. + +You have two main options: + +1. Use **PlatformIO inside VS Code** (recommended for most users). +2. Use **PlatformIO CLI in the terminal** (good for advanced or CI usage). + +#### 2.2.1 PlatformIO inside VS Code (recommended) + +If you only plan to build firmware from VS Code, you usually do **not** need to install Python or PlatformIO CLI manually. The PlatformIO extension will download what it needs. + +- Just install VS Code and the PlatformIO extension (see section 2.3). +- When you first open the project, PlatformIO will set up its own tools. + +**Check:** after installing the extension and opening the project, the VS Code status bar shows something like "PlatformIO: Ready". + +#### 2.2.2 PlatformIO command line (CLI) with Python (for terminal builds) + +If you want to use the bash scripts (ci.sh, ci_build_firmware.sh, etc.) or build from a plain terminal, you need Python and PlatformIO CLI. + +Install these extra tools: + +- Python 3.10 or newer +- PlatformIO CLI (pip package) + +PlatformIO is the main build system for this project. We will use it from VS Code and from the terminal. If you want to read more, the official docs are here: https://docs.platformio.org/. + +On Windows you can download Python from: https://www.python.org/downloads/ + +On Linux you can install Python with your package manager. + +Then install PlatformIO CLI globally with Python: + +```bash +python3 -m pip install -U platformio +``` + +**Check (firmware tools):** + +```bash +python3 --version +platformio --version +``` + +If you see version numbers, the install is good. If the platformio command is not found, check that Python added the scripts folder (for example ~/.local/bin on Linux) to your PATH, then open a new terminal and try again. + +### 2.3 Tools for documentation website (Node.js and npm) +::: warning Note +This section is **only needed** if you want to **build or preview the site on your own computer**. +::: + +If you want to build or edit the **documentation website**, you also need Node.js and npm. You do **not** need these tools just to build firmware. + +Install: + +- Node.js 18 or newer +- npm (usually comes with Node.js) + +On Windows you can get Node.js from: https://nodejs.org/en/download + +On Linux you can install Node.js with your package manager or by following the docs: https://nodejs.org/en/download/package-manager. + +**Check (docs tools):** + +```bash +node --version +npm --version +``` + +If one of these commands fails, reinstall Node.js, close the terminal, and try again. + +### 2.4 PlatformIO extension in Visual Studio Code +Now add PlatformIO inside VS Code. You can also see pictures of these steps in many ESP32 + PlatformIO tutorials, for example on the PlatformIO site: https://platformio.org/install/ide?install=vscode. + +Steps (based on common PlatformIO + VS Code ESP32 guides, adapted for this project): + +1. Open Visual Studio Code. +2. Click the Extensions icon on the left. +3. In the search box, type "PlatformIO IDE". +4. Click **Install** on the "PlatformIO IDE" extension. + +When the install finishes, a new icon appears on the left sidebar. It looks like an ant or an alien head. This opens the PlatformIO view. + +**Check:** + +- In VS Code, you see the PlatformIO icon on the left. +- If you click it, PlatformIO opens without errors. + +If you do not see the icon, restart VS Code and wait a few seconds. + +**Friendly tip:** the first install can take several minutes because PlatformIO downloads tools for many boards. It happens only once. You can get a coffee while it works. + + + +## 3. Get the source code + +Now download this repository to your computer from GitHub. + +1. Open a terminal (Git Bash, WSL or Linux shell). +2. Choose a parent folder where you want to keep your projects. +3. Run: + +```bash +git clone https://github.com/1technophile/OpenMQTTGateway.git +cd OpenMQTTGateway +``` + +**Check:** + +- Run: + + ```bash + git status + ``` + +- The output should say "On branch" and "nothing to commit". +- In your file explorer or with: + + ```bash + ls + ``` + + you should see main, lib, scripts, docs and other files. + +If the clone fails, check your internet connection or a possible proxy. Then try again. If you are new to Git, the GitHub "Hello World" guide can also help: https://docs.github.com/en/get-started/start-your-journey/hello-world. + + + +## 4. Firmware development with Visual Studio Code and PlatformIO + +This section explains how to build and flash the firmware using Visual Studio Code with the PlatformIO extension. + +If you know the classic Arduino IDE, you can think of PlatformIO as a more powerful alternative. It manages many boards, libraries, and environments for you. The official introduction is here: https://docs.platformio.org/en/latest/what-is-platformio.html. + +You do **not** create a new PlatformIO project. This repository is already a PlatformIO project. You just open it. + +### 4.1 Open the project in VS Code + +1. Start Visual Studio Code. +2. Click **File → Open Folder…**. +3. Select the OpenMQTTGateway folder you cloned in section 3. +4. Click **Open**. + +VS Code will load the folder. PlatformIO will detect the platformio.ini file and start to prepare its toolchain (compiler, libraries, board support). You do not need to install these by hand. + +**Check:** + +- In the bottom status bar you see messages like "PlatformIO: Installing" and then "PlatformIO: Ready". +- You can also open a terminal inside VS Code (View → Terminal) and run: + + ```bash + pio --version + ``` + + You should see the PlatformIO version. + +If PlatformIO stays stuck on "Installing" for a long time, close VS Code, reopen it and wait again. Check that your internet connection is working. + +### 4.2 Look at the PlatformIO project structure + +PlatformIO projects usually have folders like (you will see similar names in many tutorials): + +- src: main source code. +- lib: libraries. +- include: headers. +- platformio.ini: configuration for boards and environments. + +In OpenMQTTGateway the structure is a bit different, because it is a large project: + +- main: main C++ files for the firmware. +- lib: libraries used by the firmware. +- platformio.ini and environments.ini: list many PlatformIO environments. +- test: tests for PlatformIO unit test framework. + +**Check:** open platformio.ini in VS Code and scroll. You should see several [env:...] sections. This means PlatformIO understands the project. + +If you want to know more about this file, see the PlatformIO docs about configuration: https://docs.platformio.org/en/latest/projectconf/index.html. + +### 4.3 Choose a PlatformIO environment + +An "environment" in PlatformIO is a build target. It defines the board, framework and options. You can think of it as a named profile for a specific device. + +To select the environment for your board: + +1. Press Ctrl+Shift+P (on macOS use Cmd+Shift+P). +2. Type "PlatformIO: Switch Project Environment" and press Enter. +3. A list of environments appears (for example esp32dev-all-test, theengs-bridge and many others). +4. Choose an environment that matches your board. For a generic ESP32 DevKit you can start with **esp32dev-all-test**. + +**Check:** + +- Look at the bottom blue bar. You should see the selected environment name. + +If you chose the wrong environment, repeat the steps and pick another one. + +### 4.4 Build the firmware in VS Code + +Now compile the firmware. + +1. In VS Code, open the PlatformIO view (left sidebar icon). +2. In the PlatformIO toolbar (bottom of the window), click the **check** (✓) icon. This runs the "Build" task. + +PlatformIO now compiles the code for the selected environment. This can take several minutes the first time. + +**Check:** + +- In the Terminal panel, the build ends with the word "SUCCESS". +- On disk, a file like: + + ``` + .pio/build//firmware.bin + ``` + + exists. + +If the build fails, read the error at the end of the log. Take your time; errors are part of the normal developer life. + +Common problems: + +- Missing tools: check that platformio works from the terminal (section 2.2). +- Wrong environment: try with esp32dev-all-test first. + +Fix the problem, then run the build again. + +### 4.5 Upload the firmware to the board + +After a successful build you can flash the firmware (upload the program to the board). + +1. Connect your ESP board to the computer with a good USB cable. +2. In the PlatformIO toolbar click the **right arrow** (→) icon. This runs the "Upload" task. + +PlatformIO selects a serial port automatically in many cases. + +**Check:** + +- The upload log ends with success, and no "Failed to connect" error. +- The board reboots after upload. + +If the upload fails: + +- Check the USB cable (some cables are power-only and do not carry data). +- On some boards you must press and hold the BOOT button during upload. +- Make sure no other program is using the same serial port (for example another serial monitor). +- You can set the serial port manually in platformio.ini with the upload_port option. + +### 4.6 Open the Serial Monitor + +The Serial Monitor lets you see log messages from the firmware. + +1. In the PlatformIO toolbar click the **plug** icon. This opens the Serial Monitor. +2. Set the baud rate to 115200 if it is not already set. + +**Check:** + +- After reset, you see text from the board, for example boot messages and MQTT logs. + +If the text is unreadable, check that the baud rate matches the value in platformio.ini (monitor_speed). In this project the default is usually 115200. + +If you want to learn more about Serial Monitor problems, the PlatformIO docs have a short page: https://docs.platformio.org/en/latest/core/userguide/device/cmd_monitor.html. + +### 4.7 Run PlatformIO tests (optional) + +You can run unit tests for the project. + +1. Open a terminal inside VS Code (View → Terminal). +2. In the project root, run: + +```bash +pio test -e test +``` + +**Check:** + +- The output ends with "SUCCESS". If tests fail, read which test failed and open the file under test to understand why. + + +## 5. Firmware development from the terminal with ci.sh + +You can also work only from the terminal. This is useful if you prefer command line, use remote development, or want to reproduce the same steps as the CI (Continuous Integration, the automatic build that runs on GitHub). + +All helper scripts live in the scripts folder. The main entry point is: + +- scripts/ci.sh + +This script calls other scripts: + +- scripts/ci_build.sh +- scripts/ci_build_firmware.sh +- scripts/ci_prepare_artifacts.sh +- scripts/ci_site.sh +- scripts/ci_qa.sh +- scripts/ci_list-env.sh + +The scripts are written for bash. On Windows always use **Git Bash** or **WSL** for them, not plain PowerShell or cmd. + +If you are new to bash, a gentle introduction is here: https://ubuntu.com/tutorials/command-line-for-beginners. + +### 5.1 Check that you are in the right place + +1. Open a bash terminal. +2. Go to your clone: + +```bash +cd path/to/OpenMQTTGateway +``` + +**Check:** run: + +```bash +ls scripts main docs +``` + +You should see these folders listed. If not, you are in the wrong directory. + +### 5.2 List available firmware environments + +You can ask the helper scripts which PlatformIO environments exist. + +```bash +./scripts/ci.sh list-env +``` + +**Check:** + +- The command prints many names in columns (for example esp32dev-all-test, theengs-bridge, rfbridge-direct, and so on). + +If the command fails with "command not found" or similar, confirm that bash is used and that the file has execute permission (on Linux you may need chmod +x scripts/ci.sh). + +### 5.3 Quick build of one firmware (simple mode) + +Use ci.sh with the build command to build one firmware from the terminal. + +Example for a development build on esp32dev-all-test: + +```bash +./scripts/ci.sh build esp32dev-all-test --mode dev --verbose +``` + +What this does: + +- Checks that Python, PlatformIO and git are installed. +- Calls ci_build_firmware.sh to run platformio run -e esp32dev-all-test. +- Optionally prepares artifacts if you add deployment options. + +Useful flags: + +- --mode dev or --mode prod: choose development or production mode. For local work, **dev** is usually enough. +- --clean: remove old build files before building. +- --verbose: show more logs from PlatformIO. + +**Check:** + +- The command ends with a "Build Summary" block and "Status: SUCCESS". +- The folder .pio/build/esp32dev-all-test contains firmware.bin. + +If the build fails, read the error line near the bottom. Fix missing tools (see section 2) or wrong environment name, then run the command again. + +### 5.4 Use ci_build_firmware.sh directly (advanced control) + +Sometimes you want to work closer to PlatformIO. + +You can call scripts/ci_build.sh directly when you want more control or when you debug a CI issue: + +```bash +./scripts/ci_build.sh esp32dev-all-test --dev-ota --clean --verbose +``` + +This script: + +- Validates the environment name. +- Sets environment variables for the build (for example OMG_VERSION, OTA flags). +- Runs platformio run for the chosen environment. +- Verifies that firmware.bin and other files exist. + +**Check:** + +- At the end you see a "Build Summary" for that environment. +- The directory .pio/build/esp32dev-all-test contains .bin and .elf files. + +If there are no artifacts, check that PlatformIO is installed and that the environment name matches one from ci_list-env.sh. + +### 5.5 Prepare artifacts for sharing or flashing tools + +After a successful build, you can create a clean set of files ready for release or for use with external flashing tools (for example esptool.py or web uploaders). + +Use scripts/ci_prepare_artifacts.sh through ci_build.sh, or call it directly. + +Example (after a build) with ci_build.sh wrapper: + +```bash +./scripts/ci_build.sh esp32dev-all-test --mode prod --deploy-ready +``` + +Example direct call to ci_prepare_artifacts.sh: + +```bash +./scripts/ci_prepare_artifacts.sh esp32dev-all-test --clean +``` + +This script: + +- Copies firmware.bin, partitions.bin, bootloader.bin and other files from `.pio/build/` into the output folder. +- Renames them with the environment name, for example esp32dev-all-test-firmware.bin. +- Creates archives for the libraries used by that environment. + +**Check:** + +- The folder generated/toDeploy (or your custom output) exists. +- It contains files like `-firmware.bin` and one or more `*-libraries.tgz` archives. + +If the script says the build directory is missing, run a firmware build first (section 5.3 or 5.4). + +### 5.6 Run QA checks from the terminal + +Before you send a pull request, it is good to check the code style. + +Run: + +```bash +./scripts/ci.sh qa --check +``` + +This uses scripts/ci_qa.sh to run clang-format checks on files under main by default. + +**Check:** + +- The summary says "Status: SUCCESS". + +If there are formatting problems, you can auto-fix them: + +```bash +./scripts/ci.sh qa --fix +``` + +After this, review the changes with git diff, then commit them. + +### 5.7 Run the full pipeline (QA + firmware build + docs) + +For a full local run, similar to CI, use: + +```bash +./scripts/ci.sh all esp32dev-all-test --mode prod +``` + +This will: + +- Run QA checks. +- Build the firmware. +- Build the documentation site in production mode (unless you add --no-site). + +**Check:** + +- At the end you see a "Complete Pipeline Summary" with "Status: SUCCESS". + +If QA fails, fix style issues first. If the build fails, fix code or environment problems, then run again. + +::: tip Next Steps +Once your code builds successfully, check the [Development contributions guide](./development.md) for: +- Code naming rules (ZgatewayXXX, ZsensorYYY, etc.) +- Code style and quality requirements +- How to open a pull request +- Contributing workflow +::: + + + +## 6. Work on the documentation website (from the terminal) + +The documentation website uses VuePress and Node.js. The site source is in the docs folder. + +::: warning Note +This section is **only needed** if you want to **build or preview the site on your own computer**. +If you make a **very small change** in a markdown (.md) file (for example fix a typo or add one sentence), you can: + +- Edit the file in VS Code. +- Push your change and open a pull request. + +In that case it is **not mandatory** to install Node.js, npm, or to run `./scripts/ci.sh site`. The CI on GitHub will build the site for you and show problems if there are any. + +If you want to see your doc changes locally before you push (recommended for bigger edits), then follow the steps below. +::: + +### 6.1 Install Node dependencies + +From the project root: + +```bash +cd OpenMQTTGateway # only if you are not already inside +npm install +``` + +This command reads package.json and installs all Node modules needed for the docs. + +**Check:** + +- The command finishes without error. +- A node_modules folder exists in the project root. + +If install is slow, your internet may be the reason. If it fails, try again later or clear the npm cache with: + +```bash +npm cache clean --force +``` + +### 6.2 Build the docs site with ci.sh + +If you want to check that everything still builds well after bigger doc changes, you can build the site locally. + +The recommended way is: + +```bash +./scripts/ci.sh site --mode prod --url-prefix / --version 1.8.0 +``` + +Important options: + +- `--mode dev` or `--mode prod`: development or production build (default: dev). +- `--url-prefix PATH`: base URL path for links, e.g. `/` for root or `/dev/` for dev (default: /dev/). +- `--version TAG`: version string written into docs/.vuepress/meta.json (default: edge). +- `--preview`: if added, starts a local HTTPS preview server after build. +- `--clean`: remove generated/site folder before build. +- `--insecure-curl`: allow curl to skip TLS verification if needed. + +The script (scripts/ci_site.sh) will: + +- Check that node, npm and openssl are available. +- Download a shared configuration file for the site. +- Create docs/.vuepress/meta.json with site info. +- Run npm run docs:build to build the site. + +**Check:** + +- The summary at the end says "Site Build Summary" and "Status: SUCCESS". +- The folder docs/.vuepress/dist exists and contains HTML files. + +If openssl or node is missing, go back to section 2 and install them. + +### 6.3 Preview the docs site locally + +To preview the site in your browser: + +```bash +./scripts/ci.sh site --mode dev --url-prefix /dev/ --version edge --preview +``` + +The script will start a local HTTPS server. + +**Check:** + +- The log prints a line similar to: "Preview server running at https://localhost:8443/dev/". +- Open that URL in your browser. You should see the OpenMQTTGateway documentation. + +To stop the preview, go back to the terminal and press Ctrl+C. + +### 6.4 Work on docs with plain npm commands + +If you prefer not to use the ci.sh wrapper, you can work directly with npm and VuePress. + +From the project root: + +```bash +npm run docs:dev +``` + +This runs VuePress in development mode with hot reload. When you change a .md file under docs, the browser reloads. + +For a production build: + +```bash +npm run docs:build +``` + +**Check:** + +- For docs:dev, the terminal prints a local URL like http://localhost:8080. Open it in the browser and see the docs. +- For docs:build, the folder docs/.vuepress/dist is created. + +If docs:build fails with an OpenSSL error on new Node versions, set: + +```bash +export NODE_OPTIONS="--openssl-legacy-provider" +``` + +then run the command again. The ci_site.sh script already does this for you. + +### 6.5 Where to edit docs + +- All documentation pages are markdown (.md) files under docs. +- This file itself is in docs/participate/quick_start.md. + +To add or edit docs: + +1. Open the docs folder in VS Code. +2. Change or create markdown files. +3. Run npm run docs:dev to check how the page looks. + +**Check:** after a change and a page refresh, your new text appears on the site. + + + +## 7. Typical workflows for contributors + +This section gives some example "day to day" flows. + +### 7.1 Quick firmware change with VS Code + +1. Open the project folder in VS Code. +2. Choose the right environment (section 4.3). +3. Edit code in main or lib. +4. Build (section 4.4). +5. Upload (section 4.5). +6. Watch logs in Serial Monitor (section 4.6). + +**Check:** your change has the expected effect on the real device. + +### 7.2 Firmware change using terminal only + +1. Open a bash terminal. +2. Go to the project root. +3. Build firmware with: + + ```bash + ./scripts/ci.sh build --mode dev --verbose + ``` + +4. Flash firmware using PlatformIO CLI or another flash tool with the generated firmware file. + +**Check:** the device boots with your new firmware and behaves as expected. + +### 7.3 Change documentation and preview + +1. Edit markdown files under docs. +2. In a terminal, run npm run docs:dev or ./scripts/ci.sh site --mode dev --preview. +3. Open the local URL in your browser. + +**Check:** your text appears on the page and looks correct. + + + +## 8. Troubleshooting + +This list gives quick help for common problems. + +- **Problem:** platformio command not found. + - **Fix:** install it with python3 -m pip install -U platformio and open a new terminal. + +- **Problem:** Build fails for all environments. + - **Fix:** run ./scripts/ci.sh list-env to confirm you use a valid env. Check that you did not change platformio.ini or environments.ini in a wrong way. + +- **Problem:** Build fails with missing libraries. + - **Fix:** run a clean build (add --clean). If you work only with VS Code, press the trash icon or use the clean target from PlatformIO. + +- **Problem:** Upload fails ("Failed to connect to ESP32"). + - **Fix:** choose the right serial port, check the cable, try holding BOOT during upload. + +- **Problem:** Serial output is garbled. + - **Fix:** set Serial Monitor baud to 115200 and confirm monitor_speed in platformio.ini is the same. + +- **Problem:** npm install is very slow or fails. + - **Fix:** check your internet connection. If needed run npm cache clean --force and try again. + +- **Problem:** Site build fails with an OpenSSL error. + - **Fix:** export NODE_OPTIONS="--openssl-legacy-provider" before running npm run docs:build, or use ./scripts/ci.sh site which already sets this. + +If you still have problems after these steps, you can open an issue on the project GitHub page. Include: + +- Your operating system (Windows or Linux, version). +- What you tried to do. +- The exact command you ran. +- The error message from the end of the log. + +This information helps maintainers reproduce and fix the problem. + + + +## 9. Glossary (simple words) + +This glossary explains some words used in this guide. + +- **Firmware**: the program that runs inside your ESP32 or ESP8266 board. +- **Repository (repo)**: the project folder stored on GitHub and on your computer. +- **Commit**: a saved set of changes in Git, with a message. +- **Branch**: a line of development in Git, like a separate copy where you work. +- **Pull Request (PR)**: a request to merge your branch into the main project on GitHub. +- **Environment (env)**: a PlatformIO configuration for a specific board and options. +- **CI (Continuous Integration)**: automatic scripts that build and test the project on every change. +- **Serial Monitor**: a window that shows text messages sent by your board over USB. +- **MQTT**: a lightweight network protocol used to send messages between devices. +- **VuePress**: a static site generator used to build this documentation. + +If any word in this guide is not clear, you can search it on the web or ask in the project community. Many people had the same question before you. + + + +## 10. External links and further reading + +Here is a list of useful links related to tools used in this project: + +- **OpenMQTTGateway project**: https://github.com/1technophile/OpenMQTTGateway +- **PlatformIO main site**: https://platformio.org/ +- **PlatformIO installation for VS Code**: https://platformio.org/install/ide?install=vscode +- **PlatformIO documentation**: https://docs.platformio.org/ +- **Visual Studio Code documentation**: https://code.visualstudio.com/docs +- **Git official site**: https://git-scm.com/ +- **Pro Git book (free)**: https://git-scm.com/book/en/v2 +- **GitHub getting started**: https://docs.github.com/en/get-started +- **Node.js documentation**: https://nodejs.org/en/docs +- **npm documentation**: https://docs.npmjs.com/ +- **VuePress documentation** (v1, similar to what this project uses): https://v1.vuepress.vuejs.org/ +- **MQTT introduction (HiveMQ)**: https://www.hivemq.com/mqtt-essentials/ + +You do **not** need to read all of them now. Keep this list as a bookmark and come back when you are curious or stuck. + + +## 11. Final words and friendly advice + +Contributing to an open source project is a journey. The first steps (install tools, learn Git, learn PlatformIO) can feel slow. This is normal. + +Some final tips: + +- Change one thing at a time and test often. +- Keep your changes small; they are easier to review. +- Write clear commit messages. +- When something breaks, read the last 10–20 lines of the log first. +- Do not be afraid to ask questions; everyone started as a beginner. + +You are now ready to work on both firmware and documentation for OpenMQTTGateway. Take your time, follow the checks after each step, and you will build confidence with the toolchain and the project. Step by step, you will become faster and more comfortable. + + +If you are new and want to "play" a bit before you change real logic, here are some safe exercises: + +1. **Practice the build chain only.** + - Clone the repo, open it in VS Code, select `esp32dev-all-test`, build, and upload to your board. + - Check that you can see logs in the Serial Monitor. +2. **Make a tiny log change.** + - Find a `LOG` or `Serial` message in a gateway or sensor file under `main`. + - Change the text slightly (for example add a word), rebuild, upload, and verify you see the new message. +3. **Edit a small doc page.** + - Fix a typo or add one sentence of clarification in a markdown file under `docs`. + - Run `./scripts/ci.sh site --mode prod --preview` and confirm your change appears in the browser. +4. **Run QA locally.** + - Run `./scripts/ci.sh qa --check`. If there are issues, run `./scripts/ci.sh qa --fix` and see how files are changed. +5. **Open a small PR.** + - For example, only the doc change or a very small code improvement. This lets you learn the review process without much stress. + +These small steps build confidence. After that you can move to bigger things: adding new sensors, improving MQTT payloads, or extending the web documentation. diff --git a/docs/participate/support.md b/docs/participate/support.md index 16c718b..f6501f6 100644 --- a/docs/participate/support.md +++ b/docs/participate/support.md @@ -1,16 +1,22 @@ # Supporting the project -If you like the project and/or used it please consider supporting it! It can be done in different ways: -* Purchase the [Theengs mobile application](https://app.theengs.io) -* Purchase the [Theengs plug](https://shop.theengs.io) -* Helping other users in the [community](https://community.openmqttgateway.com) -* [Contribute](development) to the [code](https://github.com/1technophile/OpenMQTTGateway) or the [documentation](https://docs.openmqttgateway.com) -* Buy devices, boards or parts from the [compatible web site](https://compatible.openmqttgateway.com), the devices and parts linked use affiliated links. -* Donate or sponsor the project [developers](https://github.com/1technophile/OpenMQTTGateway/graphs/contributors) -* Make a video or a blog article about what you have done with [OpenMQTTGateway](https://docs.openmqttgateway.com) and share it. +If you like the project, you can help in different ways. Choose what fits you best. -Support open-source development through sponsorship and gain exclusive access to our private forum. Your questions, issues, and feature requests will receive priority attention, plus you'll gain insider access to our roadmap. +## Give time and knowledge +- Help other users in the [community](https://community.openmqttgateway.com). +- Share logs, payload samples, or how-to posts that unblock others. + +## Contribute code or docs +- Follow the [Development contributions guide](./development.md) to open a PR. +- Improve docs or examples if you spot unclear steps. + +## Financial support +- Purchase the [Theengs mobile application](https://app.theengs.io) or the [Theengs Bridge](https://shop.theengs.io). +- Sponsor the project [developers](https://github.com/1technophile/OpenMQTTGateway/graphs/contributors). +- Make a video or blog article about what you built with [OpenMQTTGateway](https://docs.openmqttgateway.com) and share it. + +Support open-source development through sponsorship, it helps keep the project healthy and evolving.
- +
diff --git a/docs/prerequisites/board.md b/docs/prerequisites/board.md index 874fbca..9fa7305 100644 --- a/docs/prerequisites/board.md +++ b/docs/prerequisites/board.md @@ -1,38 +1,37 @@ +--- +aside: false +--- + # Boards -OpenMQTTGateway is not closed to one board or type of board, by using the power of the Arduino framework and libraries that are cross compatibles it let you many choice of hardware, from an Arduino UNO to an ESP32. +OpenMQTTGateway is not closed to one board or type of board, by using the power of the Arduino framework and libraries that are cross compatibles it let you many choice of hardware, from an ESP8266 to an ESP32. -You can take a look to the [OpenMQTTGateway compatible website](https://compatible.openmqttgateway.com) to have a view of the [supported boards](https://compatible.openmqttgateway.com/index.php/boards/). +## Which board do I need? + +For the most common use cases, the choice is simple: + +|I want to...|Recommended board|Extra hardware| +|-|-|:-:| +|Bring Bluetooth sensors into my home automation|Any ESP32 development board|None| +|Receive RF devices — 433/315/868/915MHz (weather stations, door/PIR sensors...)|LILYGO® LoRa32 V2.1 or Heltec LoRa V2, matching your devices' frequency|None| +|Send and receive RF remotes and switches (433/315MHz)|ESP32 + SRX882/STX882 or CC1101 modules|[Wiring](../setitup/rf.md)| +|Control my TV or AC through infrared|ESP32 + IR emitter/receiver|[Wiring](../setitup/ir.md)| +|Reach far-away sensors with LoRa|LILYGO® LoRa32 or Heltec LoRa board|None| +|Skip flashing and wiring entirely|[Theengs Bridge](https://shop.theengs.io/), a pre-flashed BLE gateway|None| + +::: tip Running on a computer +If you want to use the BLE decoding capabilities of OpenMQTTGateway with a Raspberry Pi, Windows or Unix PC you can use [Theengs Gateway](https://gateway.theengs.io/), and on a tablet or smartphone the [Theengs App](https://app.theengs.io/). +::: + +## Exploring further Moreover the gateways capacities can be extended with sensors; DHT, HC SR501, ADC, I2C bus, INA226, MQ2, TEMT6000, TSL2561, BME280/BMP280, HTU21D, AHTx0, DS1820 or actuators; LED, relays, PWM. -::: tip Running on a computer -If you want to use the BLE decoding capabilities of OpenMQTTGateway with a Raspberry Pi, Windows or Unix PC you can use [Theengs Gateway](https://gateway.theengs.io/). -::: - -::: tip Running on a tablet or phone -If you want to use the BLE decoding capabilities of OpenMQTTGateway with a tablet or smartphone you can use [Theengs App](https://app.theengs.io/). -::: - -[Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) is a powerful BLE to MQTT gateway for over [90 sensors](https://decoder.theengs.io/devices/devices.html). Equipped with an Ethernet port, and external antenna, ensuring an enhanced range for your BLE sensors. It supports also WiFi connectivity. - -[![Theengs bridge view](../img/Theengs-Bridge-ble-gateway.png)](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) - -[Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) is available flashed with OpenMQTTGateway, and brings the functions below: -* BLE to MQTT gateway, tens of Bluetooth devices supported thanks to Theengs Decoder library. The plug uses an ESP32 acting as a BLE to Wifi gateway to scan, decode and forward the data of the nearby sensors, -* Smart plug that can be controlled remotely, -* Energy consumption monitoring, -* Device tracker, -* Presence detection (beta), -* Local connectivity first. - -[![Theengs plug view](../img/Theengs-Plug-OpenMQTTGateway.png)](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) - -Support the project by purchasing the [Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) or the [Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) -The plug is available in North America only, other regions are planned. - Choosing your board depends heavily on the technologies you want to use with it. -To have a good overview of the compatibilities per board you can refer to the compatible modules attributes of each [board](https://compatible.openmqttgateway.com/index.php/boards/). +The choice between these boards will depend on your knowledge and your requirements in terms of reliability, situation, modules wanted and devices you already have. Use the table below to explore the latest environments. -The choice between these boards will depend on your knowledge and your requirements in terms of reliability, situation, modules wanted and devices you already have. The table below present those (auto-generated) + diff --git a/docs/prerequisites/boards/.gitignore b/docs/prerequisites/boards/.gitignore deleted file mode 100644 index 86d0cb2..0000000 --- a/docs/prerequisites/boards/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Ignore everything in this directory -* -# Except this file -!.gitignore \ No newline at end of file diff --git a/docs/prerequisites/broker.md b/docs/prerequisites/broker.md index 3d10d9b..3f8c9d9 100644 --- a/docs/prerequisites/broker.md +++ b/docs/prerequisites/broker.md @@ -3,6 +3,11 @@ The broker will act as an intermediary between OpenMQTTGateway and your [control All the events or commands could pass by the broker. +::: tip Recommended setup +* **You use Home Assistant**: install the **Mosquitto broker add-on** (Settings → Add-ons → Add-on store), enable the MQTT integration, and create a dedicated user for the gateway. This is the path followed by the [Getting Started guide](../getting-started.md). +* **You don't**: install [Mosquitto](https://mosquitto.org/) on any always-on machine (Raspberry Pi, NAS, server), it is lightweight, open source and well documented. +::: + There are many choices of brokers, here are some of the most popular: * [Mosquitto](https://mosquitto.org/) (Open source) * [Moquette](https://moquette-io.github.io/moquette/) (Open source) diff --git a/docs/prerequisites/devices.md b/docs/prerequisites/devices.md index f1dbbbe..222ccb9 100644 --- a/docs/prerequisites/devices.md +++ b/docs/prerequisites/devices.md @@ -1,129 +1,24 @@ # Devices -You can take a look to the [OpenMQTTGateway compatible website](https://compatible.openmqttgateway.com) to have a view of the [supported devices](https://compatible.openmqttgateway.com/index.php/devices/). - -Added to that is an overview of devices supported by OpenMQTTGateway: +For Bluetooth, the maintained list of supported devices is the [Theengs Decoder compatible devices list](https://decoder.theengs.io/devices/devices.html). For the other technologies, the sections below give an overview of what is supported: ## For radio frequency devices OpenMQTTGateway can support a wide range of 433mhz/315mhz devices, all the ones with SC5262 / SC5272, HX2262 / HX2272, PT2262 / PT2272, EV1527, RT1527, FP1527, HS1527 chipsets are supported by the RF gateway. Added to that RF2 support Kaku and Pilight an [huge list](https://wiki.pilight.org/devices). Note that for the moment RF, RF2 and Pilight can not be activated on the same boards together. -![boards](../img/OpenMQTTGateway_devices_rf1.png ':size=250%') -![boards](../img/OpenMQTTGateway_devices_rf2.png ':size=250%') -![boards](../img/OpenMQTTGateway_devices_rf3.png ':size=250%') + ## For BLE devices OpenMQTTGateway is able to scan all the BLE devices that advertise their data so as to do presence detection. -Added to that it retrieves the measures from the devices below. By default the data are read from the advertisements (no impact on device battery life). When a (c) is present after the model name, this means that the gateway connects to it so as to retrieve data or control the device. For some devices we may connect only to retrieve one or several parameters (the rest being advertised), in this case the (c) is placed with the parameter. +Added to that it retrieves the measures from the devices mentioned and linked to below. By default the data are read from the advertisements (no or very little impact on device battery life). For some devices we may connect briefly only to retrieve one or several parameters. -|Devices|Model|Measurements| -|-|:-:|:-:| -| Amazfit|Smart Watch, Band|steps, activity heart rate (when activated in the Zepp Life settings)| -| April Brother|ABTemp|uuid, mfid, major, txpower @ 1 m, temperature, battery| -| April Brother|N03|temperature, humidity, luminance, battery| -| April Brother|N07|temperature, humidity, battery, packet ID| -| ATorch Battery Capacity Monitor (c)|DT24|voltage, amp, watt| -| BLE watches with fixed MAC||rssi for presence detection| -| BLE beacons keychains||rssi for presence detection| -| BlueCharm|BC08|acceleration x, y, z-axis, voltage, temperature| -| BlueCharm|BC04P|acceleration x, y, z-axis, voltage, temperature| -| BlueCharm|BC021|acceleration x, y, z-axis, voltage, temperature| -| BlueMaestro|TempoDisc 1 in 1|temperature, battery| -| BlueMaestro|TempoDisc 3 in 1|temperature, humidity, dew point, battery| -| BlueMaestro|TempoDisc 4 in 1|temperature, humidity, pressure, battery| -| BM2 Battery Monitor|BM2|battery, volt(c)| -| BM6 Battery Monitor|BM6|battery| -| ClearGrass|CGG1|temperature, humidity, battery, voltage (depending on which CGG1 firmware is installed)| -| ClearGrass alarm clock|CGD1|temperature, humidity, battery| -| ClearGrass alarm clock|CGC1|temperature, humidity, battery| -| ClearGrass with atmospheric pressure|CGP1W|temperature, humidity, air pressure| -| ClearGrass Clock|LYWSD02|temperature, humidity, battery| -| GOVEE|H5055|temperature1, temperature2, temperature3, temperature4, temperature5, temperature6, battery| -| GOVEE|H5074|temperature, humidity, battery| -| GOVEE|H5075|temperature, humidity, battery| -| GOVEE|H5072|temperature, humidity, battery| -| GOVEE|H5100|temperature, humidity, battery| -| GOVEE|H5101|temperature, humidity, battery| -| GOVEE|H5102|temperature, humidity, battery| -| GOVEE|H5104|temperature, humidity, battery| -| GOVEE|H5106|PM2.5, temperature, humidity, battery| -| GOVEE|H5174|temperature, humidity, battery| -| GOVEE|H5177|temperature, humidity, battery| -| GOVEE|H5179|temperature, humidity, battery| -| HONEYWELL|JQJCY01YM|formaldehyde, temperature, humidity, battery| -| Hydractiva Digital | Amphiro, Oras|sessions, time, litres, temperature, energy| -| iBeacon|protocol|uuid, mfid, major, minor, txpower @ 1 m, voltage| -| Jaalee|JHT F525|temperature, humidity, battery| -| INKBIRD|IBS-TH1|temperature, humidity, battery| -| INKBIRD|IBS-TH12S|temperature, humidity, battery| -| INKBIRD|IBS-TH2, P01B|temperature, battery| -| INKBIRD|IBT-2X|temperature1, temperature2| -| INKBIRD|IBT-4X(S, C)|temperature1, temperature2, temperature3, temperature4| -| INKBIRD|IBT-6XS|temperature1, temperature2, temperature3, temperature4, temperature5, temperature6| -| iNode|Energy Meter|Current average and aggregate kW(h), m³, battery| -| KKM |K6P|temperature, humidity, voltage| -| KKM |K9|temperature, humidity, voltage, acceleration x, y, z-axis (optional - without recognised as K6P)| -| Oral B| Toothbrush| state, mode, sector, pressure, time| -| Oria, Brifit, SigmaWit, SensorPro|TH Sensor T201|temperature, humidity, battery| -| Oria, Brifit, SigmaWit, SensorPro|TH Sensor T301|temperature, humidity, battery| -| Mokosmart|M1|acceleration x, y, z-axis, battery| -| Mokosmart|H4|temperature, humidity, voltage| -| Mopeka|Pro|temperature, level, sync status, voltage, battery, reading quality, acceleration x, y-axis| -| Lippert|BottleCheck|temperature, level, sync status, voltage, battery, reading quality, acceleration x, y-axis| -| Otio, BeeWi|Door & Window Sensor|contact, battery| -| Polar|H10 Chest strap|activity heart rate| -| Qingping|CGDK2|temperature, humidity| -| Qingping|CGH1|open| -| Qingping|CGPR1|presence, luminance, battery| -| Qingping|CGDN1|temperature, humidity, PM2.5, PM10, carbon dioxide| -| RDL52832||mfid, uuid, minor, major, txpower @ 1 m, temperature, humidity, acceleration x, y, z-axis| -| RBaron|b-parasite|moisture, temperature, humidity, luminance (v1.1.0+), voltage| -| RuuviTag Raw V1|RuuviTag|temperature, humidity, pressure, acceleration x, y, z-axis, voltage| -| RuuviTag Raw V2|RuuviTag|temperature, humidity, pressure, acceleration x, y, z-axis, voltage, TX power, movement, counter, sequence number| -| SmartDry|Laundry Sensor|temperature, humidity, shake, voltage, wake| -| Sensirion|MyCO₂, CO₂ Gadget|temperature, humidity, carbon dioxide| -| Sensirion|SHT4X TH sensor|temperature, humidity| -| ShellyBlu|Button1|button press type, battery, packet ID| -| ShellyBlu|Door, Window|contact, rotation, battery, packet ID| -| ShellyBlu|Motion|motion, illuminance, battery, packet ID| -| Switchbot|Bot (c)|mode, state, battery| -| Switchbot|Motion Sensor|movement, light level, sensing distance, led, scope tested, battery| -| Switchbot|Contact Sensor|contact, movement, scope tested, light level, in count, out count, push count, battery| -| Switchbot|Curtain|motion state, position, light level, battery, calibration state| -| Switchbot|Meter (Plus)|temperature, humidity, battery| -| Switchbot|Outdoor Meter|temperature, humidity, battery| -| Thermobeacon|WS02|temperature, humidity, voltage, timestamp, maximum temperature, maximum temperature timestamp, minimum temperature, minimum temperature timestamp| -| Thermobeacon|WS08|temperature, humidity, voltage, timestamp, maximum temperature, maximum temperature timestamp, minimum temperature, minimum temperature timestamp| -| ThermoPro|TP357|temperature, humidity| -| ThermoPro|TP357s|temperature, humidity| -| ThermoPro|TP358|temperature, humidity| -| ThermoPro|TP359|temperature, humidity| -| ThermoPro|TP393|temperature, humidity| -| TPMS|TPMS|temperature, pressure, battery, alarm, count| -| Vegtrug||temperature, moisture, luminance, fertility| -| XIAOMI Mi Flora|HHCCJCY01HHCC|temperature, moisture, luminance, fertility, battery(c) firmware >3.1.8| -| XIAOMI Ropot|HHCCPOT002|temperature, moisture, fertility| -| XIAOMI Mi Jia|LYWSDCGO|temperature, humidity, battery| -| XIAOMI Mi Jia|LYWSD02|temperature, humidity, battery| -| XIAOMI Mi Jia 2(c)|LYWSD03MMC|temperature, humidity, battery, voltage| -| XIAOMI Mi Jia 2 custom firmware (2)|LYWSD03MMC ATC|temperature, humidity, battery, voltage| -| XIAOMI Mi Jia 2 custom firmware (3)|LYWSD03MMC PVVX (encrypted or not)|temperature, humidity, battery, voltage| -| XIAOMI Mi Lamp|MUE4094RT|presence| -| XIAOMI Mi Smart Scale|XMTZC01HM, XMTZC04HM|weighing mode, unit, weight| -| XIAOMI Mi Body Composition Scale|XMTZC02HM, XMTZC05HM|weighing mode, unit, weight, impedance| -| XIAOMI Mi Temp, Humidity v1(c)|MHO-C401|temperature, humidity, battery, voltage| -| XIAOMI Mi Temp, Humidity v2(c)|XMWSDJ04MMC|temperature, humidity, battery, voltage| -| XIAOMI|Mi band|steps, activity heart rate (when activated in the Zepp Life settings)| - -Exhaustive list [here](https://compatible.openmqttgateway.com/index.php/devices/ble-devices/) +OpenMQTTGateway currently supports the decoding of [more than 100 Bluetooth devices](https://decoder.theengs.io/devices/devices.html), which include popular devices like Mi Flora, Xiaomi scales, Inkbird, Govee and ThermoPro thermo-hygrometers and BBQ thermometers, SwitchBot devices status and many more. ::: tip - (2) See https://github.com/atc1441/ATC_MiThermometer - (3) See https://github.com/pvvx/ATC_MiThermometer ::: -![devices](../img/OpenMQTTGateway_devices_ble.png ':size=250%') - ## For infrared IR devices The list of supported devices for ESP is [here](https://github.com/crankyoldgit/IRremoteESP8266/blob/master/SupportedProtocols.md), and [here](https://github.com/1technophile/OpenMQTTGateway/blob/6f73160d1421bebf2c1bbc9b8017978ff5b16520/main/config_IR.h#L123) for Arduino boards, as there is also the possibility of using raw and global cache (ESP) sending possibilities of this gateway is huge! diff --git a/docs/prerequisites/parts.md b/docs/prerequisites/parts.md index ecfafd4..354bb21 100644 --- a/docs/prerequisites/parts.md +++ b/docs/prerequisites/parts.md @@ -1,8 +1,6 @@ # Parts Depending on the gateway you would like to setup and your board, you may need extra parts/module to add. -You can take a look to the [OpenMQTTGateway compatible website](https://compatible.openmqttgateway.com) to have a view of the [supported parts](https://compatible.openmqttgateway.com/index.php/parts/). - Here is below the main parts reference. ## Main parts @@ -15,5 +13,5 @@ Here is below the main parts reference. |A6/A7|-|-|-|-|X| ::: tip -There is a wide range of parts available that may be compatible with OpenMQTTGateway, the ones [listed](https://compatible.openmqttgateway.com/index.php/parts/) are the ones tested and for which you can ask for support. Indeed for other parts we may not have it so as to reproduce the issue, or in the worst case they may not be compatible. +There is a wide range of parts available that may be compatible with OpenMQTTGateway, the ones listed above are the ones tested and for which you can ask for support. Indeed for other parts we may not have it so as to reproduce the issue, or in the worst case they may not be compatible. ::: diff --git a/docs/setitup/actuators.md b/docs/setitup/actuators.md index f4e47fb..87a33a5 100644 --- a/docs/setitup/actuators.md +++ b/docs/setitup/actuators.md @@ -1,11 +1,11 @@ # Actuators ## Compatible parts -|Module|Purpose|Where to Buy| -|-|-|-| -|LED|Basic led|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|FASTLED|RGB Leds management|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|BUZZER|-|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|RELAY|Switch power circuit|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| +|Module|Purpose| +|-|-| +|LED|Basic led| +|FASTLED|RGB Leds management| +|BUZZER|-| +|RELAY|Switch power circuit| ## Pinout |Module| Boards| diff --git a/docs/setitup/gsm.md b/docs/setitup/gsm.md index 67676bf..f472fed 100644 --- a/docs/setitup/gsm.md +++ b/docs/setitup/gsm.md @@ -1,10 +1,10 @@ # GSM 2G gateway ## Compatible parts -|Module|Purpose|Where to Buy| -|-|-|-| -|A6|GSM GPRS module|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|A7|GSM GPRS module with GPS|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| +|Module|Purpose| +|-|-| +|A6|GSM GPRS module| +|A7|GSM GPRS module with GPS| ## Hardware setup diff --git a/docs/setitup/ir.md b/docs/setitup/ir.md index 3f7ecca..ee9f865 100644 --- a/docs/setitup/ir.md +++ b/docs/setitup/ir.md @@ -1,27 +1,23 @@ # IR gateway ## Compatible parts -|Module|Purpose|Where to Buy| -|-|-|-| -|IR diode|Emitting|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|IR receiver|Receiving|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|transistor 2N2222|Amplify uC signal for the IR diode|-| -|330 ohms resistor|-|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|220 ohms resistor|limit current to LED|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| +|Module|Purpose| +|-|-| +|IR diode|Emitting| +|IR receiver|Receiving| +|transistor 2N2222|Amplify uC signal for the IR diode| +|330 ohms resistor|-| +|220 ohms resistor|limit current to LED| The IR setup can work with bc547 and a 4x3 LED-Matrix. ## Pinout |Board| Receiver Pin| Emitter Pin| |-|:-:|:-:| -|Arduino UNO|D2|D9| |ESP8266|D4|D0| |ESP32|27/**26**|14| Connect the Emitter and Receiver to a 5V supply source, and the ground of your supply source to the ground of your board. -## Arduino Hardware setup -![IR](../img/OpenMQTTgateway_Arduino_Addon_IR.png) - ## ESP8266 Hardware setup ![IR](../img/OpenMQTTgateway_ESP8266_Addon_IR.png) diff --git a/docs/setitup/lora.md b/docs/setitup/lora.md index ac1d6a3..f67b146 100644 --- a/docs/setitup/lora.md +++ b/docs/setitup/lora.md @@ -1,6 +1,6 @@ # LoRa gateway ## Compatible parts An ESP32 board with a LoRa module. -Ideally a TTGO board with LoRa module included see [compatible parts list](https://compatible.openmqttgateway.com/index.php/parts) +Ideally a TTGO board with LoRa module included. With this kind of board there is no hardware modification needed. diff --git a/docs/setitup/rf.md b/docs/setitup/rf.md index 18bdb70..e4f41b3 100644 --- a/docs/setitup/rf.md +++ b/docs/setitup/rf.md @@ -1,4 +1,4 @@ -# RF gateway (433mhz/315mhz) +# RF gateway (433/315/868/915MHz) ## Protocols, modules and library @@ -21,19 +21,18 @@ If you want to try the RTL_433 module with a combination or a board outside of t Heltec LORA V3 is not compatible with RTL_433 library as it is based on an SX1262 module. ## Assembly/soldering required parts -|Module|Purpose|Compatible modules|Receiver Switching|Where to Buy| -|-|-|-|-|-| -|SRX882 or SRX882S (recommended)|433Mhz Receiver|RF(RCSwitch), RF2(KaKu), Pilight|Supported|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|STX882 (recommended)|433Mhz Transmitter|RF(RCSwitch), RF2(KaKu), Pilight|Supported|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|CC1101|433Mhz Transceiver|[RTL_433](../use/rf#supported-decoders), RF(RCSwitch), RF2(KaKu), Pilight|Supported|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|SX1276/SX1278|433Mhz Transceiver|[RTL_433](../use/rf#supported-decoders)|Not Supported|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|LilyGo/Heltec|433Mhz Transceiver|[RTL_433](../use/rf#supported-decoders)|Not Supported|[compatible parts list](https://compatible.openmqttgateway.com/index.php/parts)| +|Module|Purpose|Compatible modules|Receiver Switching| +|-|-|-|-| +|SRX882 or SRX882S (recommended)|433Mhz Receiver|RF(RCSwitch), RF2(KaKu), Pilight|Supported| +|STX882 (recommended)|433Mhz Transmitter|RF(RCSwitch), RF2(KaKu), Pilight|Supported| +|CC1101|433Mhz Transceiver|[RTL_433](../use/rf#supported-decoders), RF(RCSwitch), RF2(KaKu), Pilight|Supported| +|SX1276/SX1278|433Mhz Transceiver|[RTL_433](../use/rf#supported-decoders)|Not Supported| +|LilyGo/Heltec|433Mhz Transceiver|[RTL_433](../use/rf#supported-decoders)|Not Supported| ### SRX STX Pinout |Board| Receiver Pin| Emitter Pin| |-|:-:|:-:| -|Arduino UNO|D3|D4| -|ESP8266|D2/**D3**/D1/D8|**RX**/D2| +|ESP8266|**D2**/D1/D8|**RX**/D2| |ESP32|**27**/26|12| |RF BRIDGE|-|-| |RF BRIDGE [DIRECT HACK](https://github.com/xoseperez/espurna/wiki/Hardware-Itead-Sonoff-RF-Bridge---Direct-Hack)|4|5| @@ -49,11 +48,25 @@ With SRX882S receiver connect the CS pin to 3.3V ### CC1101 Pinout |Board|Receiver Pin(GDO2)|Emitter Pin(GDO0)|SCK|VCC|MOSI|MISO|CSN|GND |-|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:| -|ESP8266|D2/**D3**/D1/D8|**RX**/D2|D5|**3V3**|D7|D6|D8|GND +|ESP8266|**D2**/D1/D8|**RX**/D2|D5|**3V3**|D7|D6|D8|GND |ESP32|**D27**|D12|D18|**3V3**|D23|D19|D5|GND -To use the CC1101 module, `ZradioCC1101` must be uncomment in the `User_config.h` or added to the `build_flags`. -More information about the [CC1101 wiring](https://github.com/LSatan/SmartRC-CC1101-Driver-Lib#wiring). ( Please note that with OMG we are recommending CC1101 GDO2 to be connected to ESP32 D27 and GDO0 to be connected to D12, this is different than the LSatan diagram. This is due to the ESP32 using D2 as part of the boot process. ) +To use the CC1101 module, `ZradioCC1101` must be uncomment in the `User_config.h` or added to the `build_flags`. + +More information about the [CC1101 wiring](https://github.com/LSatan/SmartRC-CC1101-Driver-Lib#wiring). + + +:::tip Please note that with OMG we are recommending CC1101 GDO2 to be connected to ESP32 D27 and GDO0 to be connected to D12, this is different than the LSatan diagram. This is due to the ESP32 using D2 as part of the boot process. + +If you want to use custom SPI pins for the CC1101 module, you can define the following variables in your `User_config.h` or as `build_flags` in `platformio.ini`: + - `RF_CC1101_SCK`: SPI clock pin (SCK) + - `RF_CC1101_SCK`: SPI clock pin (SCK) + - `RF_CC1101_MISO`: SPI MISO pin (Master In Slave Out) + - `RF_CC1101_MOSI`: SPI MOSI pin (Master Out Slave In) + - `RF_CC1101_CS`: SPI chip select pin (CSN) + +When **all** these variables are defined, OpenMQTTGateway will use your custom pinout for the CC1101 connection. This is useful if your board does not use the default pins or if you want to avoid conflicts with other devices. +::: ## ESP32 Hardware setup ![Addon_RF](../img/OpenMQTTgateway_ESP32_Addon_RF.png) @@ -65,9 +78,6 @@ With SRX882 some users reported that D3 is not working use D1 instead in this ca ![Addon_RF](../img/OpenMQTTgateway_ESP8266_Addon_RF.png) -## Arduino Hardware setup -![RF](../img/OpenMQTTgateway_Arduino_Addon_RF.png) - ## SONOFF RF Bridge Hardware setup Per default there is no need on modifying the RF Bridge hardware, unless you don't want to use the provided RF controller (EFM8BB1). Indeed if you want to extend the protocols supported by the bridge you can [bypass this controller](https://github.com/xoseperez/espurna/wiki/Hardware-Itead-Sonoff-RF-Bridge---Direct-Hack) and use the ESP8255 capacities to decode RF Signal. The RF processing can be achieved after the modification by either RF, RF2 or Pilight gateways. @@ -77,3 +87,5 @@ The RF processing can be achieved after the modification by either RF, RF2 or Pi ## WIFI RF GATEWAY Hardware setup This board doesn't require any hardware modifications. + + diff --git a/docs/setitup/sensors.md b/docs/setitup/sensors.md index 12548cc..3fc55d0 100644 --- a/docs/setitup/sensors.md +++ b/docs/setitup/sensors.md @@ -1,21 +1,21 @@ # Sensors ## Compatible sensors -|Module|Purpose|Where to Buy| -|-|-|-| -|DHT11|Temperature, Humidity|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|DHT22|Temperature, Humidity|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|HCSR501|PIR|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|BH1750|Digital light|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|BME280|Temperature, Humidity, Pressure|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|BMP280|Temperature, Pressure|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|C-37, YL-83, HM-RD|Leak, Water|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|HTU21|Temperature, Humidity|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|GPIO Input|Inputs|-| -|GPIO KeyCode|Keycode|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|INA226|Current, Voltage|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|MQ2|Gas (flammable)|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|TEMT6000|Luminosity|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| -|TSL2561|Luminosity|[parts list](https://compatible.openmqttgateway.com/index.php/parts)| +|Module|Purpose| +|-|-| +|DHT11|Temperature, Humidity| +|DHT22|Temperature, Humidity| +|HCSR501|PIR| +|BH1750|Digital light| +|BME280|Temperature, Humidity, Pressure| +|BMP280|Temperature, Pressure| +|C-37, YL-83, HM-RD|Leak, Water| +|HTU21|Temperature, Humidity| +|GPIO Input|Inputs| +|GPIO KeyCode|Keycode| +|INA226|Current, Voltage| +|MQ2|Gas (flammable)| +|TEMT6000|Luminosity| +|TSL2561|Luminosity| ## Pinout |Module|Arduino Pin| ESP8266 Pin|ESP32 Pin| diff --git a/docs/setitup/rs232.md b/docs/setitup/serial.md similarity index 86% rename from docs/setitup/rs232.md rename to docs/setitup/serial.md index 5206662..4a88127 100644 --- a/docs/setitup/rs232.md +++ b/docs/setitup/serial.md @@ -1,4 +1,4 @@ -# RS232 gateway +# Serial/RS232 gateway ## Compatible parts |Module|Purpose|Where to Buy| |-|-|-| @@ -10,15 +10,11 @@ Any module using a MAX232 chip will work. Don't pay extra to get all the signals ## Pinout |Board| Receiver Pin| Emitter Pin| |-|:-:|:-:| -|Arduino UNO|D2|D9| |ESP8266|D2|D4| |ESP32|27/**26**|14| Connect VCC on the module to 5V of your board, and the ground on the module to the ground of your board. your Transmit pin goes to TX and your Receive pin goes to RX. This may seem backwards, but the module is labeled as where it will be connected on the RS232 side of the module. -## Arduino Hardware setup -![RS232](../img/OpenMQTTgateway_Arduino_Addon_RS232.png) - ## ESP8266 Hardware setup ![RS232](../img/OpenMQTTgateway_ESP8266_Addon_RS232.png) diff --git a/docs/upload/advanced-configuration.md b/docs/upload/advanced-configuration.md index 2368d6c..fee36a7 100644 --- a/docs/upload/advanced-configuration.md +++ b/docs/upload/advanced-configuration.md @@ -10,16 +10,17 @@ The configuration of the broker is not covered here, you should look into the do ### Prerequisites The MQTT broker is configured for TLS and you have access to the CA certificate which was used to sign the MQTT broker certificate. -You are using ESP8266 or ESP32, for other boards TLS is not supported. +You are using ESP8266 or ESP32. ### Configure secure connection in the gateway -To enable the secure connection and use TLS set the `#define MQTT_DEFAULT_SECURE` to true. +To enable the secure connection and use TLS set the `#define MQTT_DEFAULT_SECURE` to true at build time, or the `mqtt secure` parameter with WiFi Manager or `mqtt_secure` with MQTT. Set `MQTT_SERVER` to the Common Name (CN) of the certificate of the broker. -This can be the hostname or the IP of the broker. + +The server identity can be verified against a certificate or not, if you don't want to use a certicate to verify the server you can uncheck the option `validate cert` with WiFi Manager or set `mqtt_validate` to `false` with MQTT The CA certificate should be in PEM ascii format. If your CA certificate is not in the correct format or you don't know the format, use `openssl` to convert the certificate to the correct format. -In `User_config.h` replace the `...` with the content of your certificate which is between the `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` lines: +At build time, in `main/certs/default_server_cert.h` replace the `...` with the content of your certificate which is between the `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` lines: ```cpp const char* certificate CERT_ATTRIBUTE = R"EOF(" -----BEGIN CERTIFICATE----- @@ -28,7 +29,14 @@ const char* certificate CERT_ATTRIBUTE = R"EOF(" ")EOF"; ``` -You can know compile and upload to your board and the gateway should connect with TLS to your broker. +With WiFi Manager copy your certificate from `-----BEGIN CERTIFICATE-----` to `-----END CERTIFICATE-----` (included) and paste it into the input field: +``` +-----BEGIN CERTIFICATE----- +... +-----END CERTIFICATE----- +``` + +This process can also be used for the other certificates, OTA, client key, client certificate if necessary. ## Add the received "value" at the end of the topic For the gateways that publish a "value" parameter on the json (RF, IR...), it is possible to concatenate this parameter at the end of the topic. @@ -53,7 +61,7 @@ home/OpenMQTTGateway/SRFBtoMQTT/59365 {"raw":"2B660186042E00E7E5","value":"59365 It can be useful to avoid warning or errors on certain controllers. ## Auto discovery -Home Assistant discovery is enabled by default on all binaries and platformio configurations except for UNO. With Arduino IDE you have to uncomment [ZmqttDiscovery](https://github.com/1technophile/OpenMQTTGateway/blob/0180a0dbd55ed8e0799e30ee84f68070a6f478fa/User_config.h#L99) in User_config.h. +Home Assistant discovery is enabled by default on all binaries and platformio configurations. To have a working discovery setup you need to enable it on your MQTT integration definition in HASS. diff --git a/docs/upload/binaries.md b/docs/upload/binaries.md index 2348ff7..182f43b 100644 --- a/docs/upload/binaries.md +++ b/docs/upload/binaries.md @@ -15,7 +15,6 @@ https://www.espressif.com/en/products/hardware/esp32/resources * Choose ESP32 DownloadTool * Set the files and the address as below: ![Flash download tool](../img/OpenMQTTgateway_ESP32_binary_flash.png) -And set the parameters used by Arduino IDE, we are able to upload to ESP32 a binary file containing OpenMQTTGateway. * Set the config as above * Connect your ESP32 board and select the COM port * Click on erase if it is your first upload @@ -68,6 +67,19 @@ If you want to upload the ready-to-go binary from Linux (or any other OS where y Hard resetting via RTS pin... * The board resets after the upload and boots the gateway firmware +### Mac - esptool.py +The approach for Mac is similiar to Linux. You need to install [Brew](https://brew.sh) for Mac to use [pip](https://docs.brew.sh/Homebrew-and-Python). +The esptool.py tool needs to be adressed explicitly with .py at the end. +If you do fail with the command, run `esptool.py chip_id` to let your Mac check for the ESP32 on your serial ports. A common failure for this looks like this: + + A fatal error occurred: Unable to verify flash chip connection (Invalid head of packet (0xE0): Possible serial noise or corruption.). + +If you receive this error + + A fatal error occurred: Unable to verify flash chip connection (Packet content transfer stopped (received 7 bytes)). + +while flashing, try to reduce the baud rate to `--baud 115200`, as this seems to help in most cases. + ## ESP8266 * Download the NodeMCU Py Flasher tool : https://github.com/marcelstoer/nodemcu-pyflasher/releases diff --git a/docs/upload/board-selector.md b/docs/upload/board-selector.md new file mode 100644 index 0000000..e31a913 --- /dev/null +++ b/docs/upload/board-selector.md @@ -0,0 +1,5 @@ + + +Board photos courtesy of their manufacturers. ESP32 Feather photo © Adafruit Industries, CC BY-SA. diff --git a/docs/upload/builds.md b/docs/upload/builds.md index e2c9f64..8d2ffa7 100644 --- a/docs/upload/builds.md +++ b/docs/upload/builds.md @@ -2,16 +2,10 @@ ## Introduction -This section is useful if you want to do advanced configuration of your project or if you choose an Arduino. Indeed the ESP hardware family can be loaded directly without any configuration from your desktop. +This section is useful if you want to make an advanced project configuration not supported by the pre-built binaries. Advanced configuration means changing the default pins, the MQTT topics, and all the expert parameters that you can find in [`User_config.h`](https://github.com/1technophile/OpenMQTTGateway/blob/development/main/User_config.h) and in all [`config_XX.h`](https://github.com/1technophile/OpenMQTTGateway/tree/development/main) files. If you don't have to change the default parameters except Wi-Fi and MQTT broker settings, you don't need advanced configuration; you can go directly to the [Upload Binaries](binaries.md) section instead. -To make advanced configurations to OpenMQTTGateway, you have the choice between two development environments: -* [PlatformIO](https://platformio.org/) -* [Arduino IDE](https://www.arduino.cc/en/Main/Software) - -I recommend using PlatformIO; this way you will not have to search for all the necessary libraries and adequate forks/revisions. If you really want to use Arduino IDE, you need to download the libraries listed [here](https://github.com/1technophile/OpenMQTTGateway/blob/d2dd6138558909b71cc44f69665340247bd5f356/platformio.ini#L55) at the version or revision specified. - ## Configure & Upload with PlatformIO * Download the [CODE](https://github.com/1technophile/OpenMQTTGateway/releases) from github. @@ -24,7 +18,7 @@ PlatformIO config files work on the concept of overriding. At first, a very simp [env] framework = arduino lib_deps = - ${libraries.pubsubclient} + ${libraries.picomqtt} ${libraries.arduinojson} ${libraries.arduinolog} build_flags = @@ -157,6 +151,7 @@ Example to add IR to `esp32dev-rf` add the `build_flags` below to the env defini ``` ini [env:esp32dev-rf] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev lib_deps = ${com-esp.lib_deps} @@ -193,6 +188,7 @@ With PIO you can also upload the firmware through Over the Air, so as to do that ``` ini [env:esp32-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev board_build.partitions = min_spiffs.csv lib_deps = @@ -209,38 +205,6 @@ upload_flags = --port=8266 ``` -## Configure & Upload with Arduino IDE - -* Download the [CODE](https://github.com/1technophile/OpenMQTTGateway/releases) from github -* First download the last version of the Arduino IDE from the Arduino [website](https://www.arduino.cc/en/Main/Software) -* Add ESP32 boards by following this [tutorial](https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html#installing-using-arduino-ide) -* Add ESP8266 boards by following this [tutorial](https://github.com/esp8266/Arduino#installing-with-boards-manager) -* Download the libraries package corresponding to your board and module wished into the same page (example esp32-m5stick-c-ble-libraries.zip) -* Unzip the libraries into your Arduino libraries folder (example D:/Users/XXXX/Documents/Arduino/libraries) -* If necessary replace the spaces into each library folder by _: example rename “ESP32 BLE Arduino” folder to “ESP32_BLE_Arduino” -* Open the file main.ino from OpenMQTTGateway/main folder with the Arduino IDE -* Change the settings and the desired gateways into `User_config.h` (uncomment the modules you want) - -*Example for the use of RF gateway:* - -```cpp -#define ZgatewayRF "RF" //ESP8266, Arduino, ESP32 -//#define ZgatewayIR "IR" //ESP8266, Arduino, Sonoff RF Bridge -//#define ZgatewayLORA "LORA" //ESP8266, Arduino, ESP32 -//#define ZgatewayPilight "Pilight" //ESP8266, Arduino, ESP32 -//#define ZgatewayBT "BT" //ESP8266, ESP32 -``` - -* Change the pins or parameters corresponding to the modules chosen, for RF you can change the pins in config_RF.h -* Choose the board on the Arduino IDE -* Select the port corresponding to the board -* Note that for using BLE on ESP32 you will need to select *Minimal SPIFFS* into Tools->Partition Scheme -* Open the serial monitor and set 115200 baud -* Upload ➡️ -* You should see the logs in the serial monitor - -With an ESP if you did not set your network and MQTT parameters manually you can now open the [web portal configuration](portal.md). - ## API With the V0.9 we added the support of json for receiving and publishing. Per default Json reception and Json publication is activated, the previous simple reception mode is also activated to avoid regression on commands. diff --git a/docs/upload/gitpod.md b/docs/upload/gitpod.md deleted file mode 100644 index 4cc9a8a..0000000 --- a/docs/upload/gitpod.md +++ /dev/null @@ -1,18 +0,0 @@ -# (Option 4) Build from the web - -To build OpenMQTTGateway from the web and download the binary, follow these steps: - -1. Use Gitpod by clicking on the link below: -[https://gitpod.io#https://github.com/1technophile/OpenMQTTGateway/tree/development](https://gitpod.io#https://github.com/1technophile/OpenMQTTGateway/tree/development) - -2. This will generate a development environment in your browser and install [platformio](https://platformio.org/) as a build environment. - -3. A first build for `esp32dev-ble` will be launched automatically. To modify the environment configuration, go to the environments.ini file in the root folder and launch the command like the one shown at the bottom of the image below: -`platformio run -e ` - -![Gitpod build success](../img/OpenMQTTGateway-Build-gitpod-env.png) - -4. Wait for the server to build the binary. Once you see [SUCCESS], you can go to `.pio/build/` and download `firmware.bin` and `partitions.bin` by right-clicking on each and selecting "Download." -![Gitpod build download](../img/OpenMQTTGateway-Build-gitpod.png) - -5. Finally, follow [Option 2](binaries.md) to upload the binary. diff --git a/docs/upload/index.md b/docs/upload/index.md new file mode 100644 index 0000000..f7b0586 --- /dev/null +++ b/docs/upload/index.md @@ -0,0 +1,159 @@ +# Upload + +Getting OpenMQTTGateway onto your board takes three steps, whichever method you pick: + +
+
+ 1 + Flash the firmware + pick a method below +
+ → +
+ 2 + Configure WiFi & MQTT + through the portal +
+ → +
+ 3 + Verify + gateway appears on your broker & controller +
+
+ +## Choose your installation method + + + +| | Web installer | Binaries | From source | +|--------------------------|:---:|:---:|:---:| +| No software to install | ✅ | ❌ | ❌ | +| Custom configuration | ❌ | ❌ | ✅ | +| Difficulty | Easiest | Easy | Advanced | + +## After flashing: configure your gateway + +However you flashed, a freshly installed gateway starts its own WiFi access point (named `OpenMQTTGateway` or starting with `OMG_`). Connect to it and the [configuration portal](portal.md) lets you set your WiFi network, MQTT broker, and optional security settings — no rebuild needed. + +If you build from source you can alternatively [embed the network and MQTT settings at build time](builds.md), so the gateway connects automatically on first boot. + +## Going further + +* [Advanced configuration](advanced-configuration.md) — TLS-secured MQTT connections, certificates, OTA updates. +* [Home Assistant integration](../integrate/home_assistant.md) — auto-discovery is enabled by default; your gateway and sensors appear automatically. +* [Gateway configuration](../use/gateway.md) — MQTT topic structure and runtime commands per module. + +Stuck? Check the [troubleshooting page](troubleshoot.md), or ask on the [community forum](https://community.openmqttgateway.com). + + diff --git a/docs/upload/portal-api.md b/docs/upload/portal-api.md new file mode 100644 index 0000000..5a27fb5 --- /dev/null +++ b/docs/upload/portal-api.md @@ -0,0 +1,61 @@ +# Configuration portal HTTP API + +This page documents the HTTP form fields accepted by the on-device WiFi configuration portal so that companion apps, provisioning scripts, and Home Assistant flows can integrate without reading firmware source. + +The portal is implemented on top of [h2zero's WiFiManager fork](https://github.com/h2zero/WiFiManager) and the field declarations live in `main/main.cpp` (see `setup_wifimanager`). + +## Endpoint + +``` +POST http:///wifisave +Content-Type: application/x-www-form-urlencoded +``` + +When the portal is active (no saved credentials, or trigger pressed at boot) the device exposes a soft-AP — see [Portal](portal.md) for SSID/password rules. + +## Form fields + +| Field | Type | Source declaration | Persisted? | +|--------------|------------------|---------------------------------|------------| +| `s` | SSID | WiFiManager built-in | yes | +| `p` | WiFi PSK | WiFiManager built-in | yes | +| `server` | MQTT host (≤ 64) | `custom_mqtt_server` | yes, if non-empty | +| `port` | MQTT port | `custom_mqtt_port` | yes, if non-empty | +| `user` | MQTT username | `custom_mqtt_user` | yes, if non-empty | +| `pass` | MQTT password | `custom_mqtt_pass` | yes, if non-empty *and* value differs from the compile-time `MQTT_PASS` sentinel | +| `secure` | `0` / `1` | `custom_mqtt_secure` | yes (always) | +| `validate` | `0` / `1` | `custom_validate_cert` | yes (always) | +| `cert` | PEM (≤ 4096 B) | `custom_mqtt_cert` | yes, if length > `MIN_CERT_LENGTH` | +| `ota_cert` | PEM (≤ 4096 B) | `custom_ota_server_cert` | yes, if length > `MIN_CERT_LENGTH` | +| `client_cert`| PEM | `custom_client_cert` (signed-client builds only) | yes, if length > `MIN_CERT_LENGTH` | +| `client_key` | PEM | `custom_client_key` (signed-client builds only) | yes, if length > `MIN_CERT_LENGTH` | +| `topic` | MQTT base topic | `custom_mqtt_topic` | yes, if non-empty (trailing `/` added if missing) | +| `name` | Gateway name | `custom_gateway_name` | yes, if non-empty | +| `ota` | OTA / WebUI password | `custom_ota_pass` | yes, if non-empty | + +## Empty-field semantics + +Empty `server` / `port` / `user` / `topic` / `name` / `ota` values are **ignored** rather than persisted. This means a partial POST (e.g. WiFi-only) preserves any pre-flashed defaults instead of clearing them. To intentionally clear a field, this portal API does not currently support it — re-flash with new build defaults or use the WebUI. + +The `pass` field combines the empty-check with a sentinel guard: the firmware persists the form value only when it is non-empty *and* differs from the compile-time `MQTT_PASS` sentinel. The sentinel branch prevents an unmodified form (which echoes back the default) from overwriting a stored password; the non-empty branch prevents a partial POST from wiping it. + +## Response and AP teardown + +After processing the POST, WiFiManager returns a small success page and then tears down the soft-AP to attempt joining the configured station network. The teardown happens quickly enough that the TCP socket may be reset before the HTTP response is fully flushed to the client. Companion apps should: + +- Treat a connection reset immediately after the POST as a likely-success signal, not a failure. +- Verify provisioning by checking for the device on the target network or for its first MQTT LWT message rather than relying on the HTTP response. + +## Example + +```bash +curl -X POST \ + --data-urlencode 's=my-ssid' \ + --data-urlencode 'p=my-psk' \ + --data-urlencode 'server=192.168.1.10' \ + --data-urlencode 'port=1883' \ + --data-urlencode 'name=kitchen-omg' \ + --data-urlencode 'ota=mySecret123' \ + --data-urlencode 'topic=home/' \ + http://192.168.4.1/wifisave +``` diff --git a/docs/upload/portal.md b/docs/upload/portal.md index 2e20d6c..d9b3100 100644 --- a/docs/upload/portal.md +++ b/docs/upload/portal.md @@ -29,8 +29,6 @@ If the board is connected by ethernet, the Wifi and password can be empty. If yo * Set your MQTT Server IP or domain name (for Home Assistant you can enter `homeassistant.local` if your server is configured with mDNS) * Set your MQTT Server Port (default: 1883) -* Set the MQTT secure connection box to select whether or not the connection should be secure -* Copy/paste the MQTT server certificate in the MQTT server cert box (only required if using a secure connection), be sure to include the `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` markers * Set your MQTT Server username (optional, 64 characters maximum) * Set your MQTT Server password (optional, 64 characters maximum) * Set your MQTT base topic if you need to change it (you must keep the / at the end) (default: home/, 64 characters maximum) @@ -39,6 +37,10 @@ If the board is connected by ethernet, the Wifi and password can be empty. If yo * Local and remote OTA * WebUI login (login:"admin", password: "") * WiFi Manager Access Point password after initial config +* Set the MQTT secure connection box to select whether or not the connection should be secure +* Set the certificate validation to select wether or not you want to validate the server identity with a certificate +* Copy/paste the MQTT server certificate in the MQTT server cert box (only required if using a secure connection), be sure to include the `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` markers +* Add your certificates * Click on save ![WiFi manager save](../img/OpenMQTTGateway_Wifi_Manager_save.png) @@ -59,6 +61,7 @@ You can configure your MQTT server credentials and network configuration before ``` ini [env:esp32-olimex-gtw-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-gateway board_build.partitions = min_spiffs.csv lib_deps = diff --git a/docs/upload/troubleshoot.md b/docs/upload/troubleshoot.md index 97a31b7..6911009 100644 --- a/docs/upload/troubleshoot.md +++ b/docs/upload/troubleshoot.md @@ -1,10 +1,9 @@ # Troubleshooting ## Compilation/build error -This badge [![Build Status](https://github.com/1technophile/OpenMQTTGateway/workflows/Build/badge.svg?branch=master)](https://github.com/1technophile/OpenMQTTGateway/actions?query=branch%3Amaster+workflow%3ABuild) show you the state of the compilation of the master and this one [![Build Status](https://github.com/1technophile/OpenMQTTGateway/workflows/Build/badge.svg?branch=development)](https://github.com/1technophile/OpenMQTTGateway/actions?query=branch%3Adevelopment+workflow%3ABuild) for the development branch. +This badge [![Build Status](https://github.com/1technophile/OpenMQTTGateway/workflows/Build/badge.svg?branch=development)](https://github.com/1technophile/OpenMQTTGateway/actions?query=branch%3Adevelopment+workflow%3ABuild) show you the state of the compilation of the development branch, from which the releases are made. If you see a green badge this means that the code compilation is OK with the configuration given in the `docs/platformio.ini`. -Check your IDE environment version, boards version, libraries version before submitting an issue or a question. -Verify especially that the libraries provided into the [release page](https://github.com/1technophile/OpenMQTTGateway/releases) are located into your "sketchbook folder"/libraries if your are using the Arduino IDE. +Check your environment, boards , libraries before submitting an issue or a question. ## ESP32 compilation errors related to WiFi If you get one or several of the following errors: @@ -36,26 +35,12 @@ in config_rf.h instead of `#define RF_RECEIVER_GPIO 0 // D3 on nodemcu` -## Exception seen on serial monitor: -Hey I got a callback -malloc -memcpy -7 -Exception (2): - -→ You are not using the last update of ESP8266 into board manager, go to your Arduino IDE and update it, should be at least 2.3.0 - ## Repetitive MQTT disconnections or/and commands sent to the gateway not taken into account Most probably a network issue, don't use a guest network and if going through a firewall check its rules. To put aside gateway issue, try to connect to a local broker on the same network. -## You don't see the messages appearing on your broker but they appears on the serial monitor -This is due to a too small MQTT packet size, open User_config.h and set: -`#define mqtt_max_packet_size 1024` - -## Your Arduino with w5100 Ethernet shield does not connect to network until you press Reset button -If you notice that your Arduino with w5100 Ethernet shield does not connect to network until you press its Reset button, but connects fine if you connect the Arduino with a USB cable to a computer/laptop with Arduino IDE running and open Serial Monitor, the problem is most likely the Ethernet shield and/or the power supply you're using. -According to this [video](https://www.youtube.com/watch?v=9ZBeprOqC3w&feature=youtu.be), w5100 clones sometimes struggle to initialise because the reset pin wasn't held low long enough. The solution is simple - add a 0.1uF (100nF) capacitor between the pins on the reset switch. You can get more details [here](http://forum.arduino.cc/index.php?topic=28175.15). -But even with this fix your board might not work well with a specific PSU. I would recommend try at least one different one and also try bigger capacitor (some report using 47uF) +## OMG ignores messages sent to it via MQTT +This can happen if the messages are too big and exceed the internal buffer size limit. To fix this, check the size of the message you're sending (in bytes). Next, open `User_config.h` and set `mqtt_max_payload_size` to be greater than that size, e.g.: +`#define mqtt_max_payload_size 1024` ## ESP Continuous restart or strange behaviour: This can be due to corruption of the ESP flash memory, try to erase flash and upload OMG on it again. diff --git a/docs/upload/web-install.md b/docs/upload/web-install.md index bc9d5b0..56a28d6 100644 --- a/docs/upload/web-install.md +++ b/docs/upload/web-install.md @@ -1,39 +1,45 @@ ---- -pageClass: table-generated-page +--- +aside: false --- # (Option 1) Upload from the web -[![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fdocs.openmqttgateway.com%2Fupload%2Fweb-install.html&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=hits&edge_flat=false)](https://hits.seeyoufarm.com) +This is the easiest way to install OpenMQTTGateway: no software to download, no development environment. + +## Before you flash + +* Use a **data** USB cable — many cables are charge-only and the board won't show up with one. +* Use **Chrome, Edge or Opera** — Firefox and Safari don't support web flashing. +* Most boards need a **USB serial driver**. Recent operating systems often include it; if your board doesn't appear in the port list, see below. + +::: details My board doesn't show up in the port list +1. Try another USB cable (data, not charge-only) and another USB port. +2. Install the driver matching your board's USB chip (check the board's product page if unsure): + * **CP210x** (Silicon Labs): [driver download](https://www.silabs.com/developer-tools/usb-to-uart-bridge-vcp-drivers) + * **CH340 / CH341** (WCH): [driver download](https://www.wch-ic.com/downloads/CH341SER_ZIP.html) + * **CH9102** (WCH): [macOS driver](https://github.com/WCHSoftGroup/ch34xser_macos), [Windows driver](https://www.wch-ic.com/downloads/CH343SER_ZIP.html) +3. On macOS, complete the driver installation by confirming it in the **Security** section of **System Preferences**, then restart. For a LilyGo LoRa32 V2.1 board, the correct port to select is `/dev/cu.wchusbserialXXXXXXXXXXX`. +4. Some boards need the **BOOT** button held down while plugging in the cable to enter flash mode. +5. On Linux, add your user to the `dialout` group (`sudo usermod -a -G dialout $USER`) and log in again. +::: + +## Select your firmware +To upload firmware to your ESP device directly from this page, first connect your ESP device to a USB port on your computer. Then, choose the appropriate firmware from the available options. Next, click the **Connect** button and select the USB port where your ESP is plugged in. Wait for the upload process to finish. After the upload completes, you can set up your [WiFi and MQTT credentials](portal.md). + + + +Board photos courtesy of their manufacturers. ESP32 Feather photo © Adafruit Industries, CC BY-SA. + ::: tip Running on a tablet or phone If you want to use the BLE decoding capabilities of OpenMQTTGateway with a tablet or smartphone you can use [Theengs App](https://app.theengs.io/). ::: -::: warning Note -If you are on macOS and have a LilyGo LoRa32 V2.1 board, make sure you have the [correct driver for the CH9102 Serial Chip](https://github.com/WCHSoftGroup/ch34xser_macos) installed and selected in the popup when initiating the web install. -To finalise the driver installation don't forget the confirmation in the **Security** section of **System Preferences** after the restart. -The correct driver to then select in the popup of this web install is -`/dev/cu.wchusbserialXXXXXXXXXXX` -::: -You can upload the firmware to your ESP device directly from here. -1. Plug in your ESP to a USB port. -2. Select the firmware in the box below. -3. Click the install button and choose the port that the ESP is connected to. -4. Wait until the process is complete. -5. Once completed you can configure your [WiFi and MQTT credentials](portal.md) +## Next step - +Once the upload is complete, connect the gateway to your WiFi network and MQTT broker through the [configuration portal](portal.md). -Upload powered by [ESP Web Tools](https://esphome.github.io/esp-web-tools/) - -## Using OpenMQTTGateway ? -Support open-source development through sponsorship and gain exclusive access to our private forum. Your questions, issues, and feature requests will receive priority attention, plus you'll gain insider access to our roadmap. - -
- -
- -## Environments characteristics -The auto-generated table below describes the libraries and the modules of each board configuration. diff --git a/docs/use/ble.md b/docs/use/ble.md index 15776a1..c3e6670 100644 --- a/docs/use/ble.md +++ b/docs/use/ble.md @@ -4,29 +4,46 @@ description: Versatile Bluetooth gateway that scans and decodes data from variou --- # Bluetooth gateway -The manufacturer agnostic Bluetooth Low Energy (BLE) gateway acts as a powerful BLE scanner and decoder of [Bluetooth devices](https://compatible.openmqttgateway.com/index.php/devices/ble-devices/), allowing you to visualize and analyze information from a wide range of sensors. +The manufacturer agnostic Bluetooth Low Energy (BLE) gateway acts as a powerful BLE scanner and decoder of [Bluetooth devices](https://decoder.theengs.io/devices/devices.html), allowing you to visualize and analyze information from a wide range of sensors. It can also act as a device tracker and presence detection gateway by receiving nearby BLE devices and trackers. Data are transmitted to an MQTT broker, where it can be used to trigger events and rules, as well as displayed, stored and processed in your favorite controller (Home Assistant, OpenHAB, Jeedom, Domoticz, ioBroker or any MQTT compatible software). With the ability to monitor and analyze data such as temperature, humidity, moisture, luminance, weight, pressure, fine particles, and more, the BLE gateway provides a flexible and customizable solution for integrating BLE technology into your control and monitoring systems. -![BLE sensors and devices](../img/OpenMQTTGateway-sensors-ble.png) +
+ BLE sensors and devices +
-## The first plug-and-play OpenMQTTGateway BLE gateway and Smart Plug! +## Products powered by OpenMQTTGateway -[Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) is available flashed with OpenMQTTGateway, and brings the functions below: -* BLE to MQTT gateway, tens of [Bluetooth devices](https://compatible.openmqttgateway.com/index.php/devices/ble-devices/) supported thanks to Theengs Decoder library. The plug uses an ESP32 acting as a BLE to Wifi gateway to scan, decode and forward the data of the nearby sensors, +### Theengs Bridge, BLE gateway with external antenna + +[Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) is a powerfull BLE to MQTT gateway for over [100 sensors](https://decoder.theengs.io/devices/devices.html). Equipped with an Ethernet port, and external antenna, ensuring an enhanced range for your BLE sensors. It supports also WiFi connectivity. + + + +### Theengs Plug, BLE gateway and Smart Plug + +[Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) brings the following features: +* BLE to MQTT gateway, tens of [Bluetooth devices](https://decoder.theengs.io/devices/devices.html) supported thanks to Theengs Decoder library. The plug uses an ESP32 acting as a BLE to Wifi gateway to scan, decode and forward the data of the nearby sensors, * Smart plug that can be controlled remotely, * Energy consumption monitoring, * Device tracker, * Presence detection (beta), * Local connectivity first. -[![Theengs plug view](../img/Theengs-Plug-OpenMQTTGateway.png)](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) + -Support the project by purchasing the [Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) -The plug is available in North America only, other regions are planned. +Support the project by purchasing the [Theengs bridge](https://shop.theengs.io/products/theengs-bridge-esp32-ble-mqtt-gateway-with-ethernet-and-external-antenna) or the [Theengs plug](https://shop.theengs.io/products/theengs-plug-smart-plug-ble-gateway-and-energy-consumption) ## Disable or enable the BLE gateway (default: true, available with HA discovery) @@ -55,17 +72,15 @@ Once the data has been transmitted to the MQTT broker, it can be easily integrat ![Home Assistant chart](../img/OpenMQTTGateway-home-assistant-chart.png) -Examples of compatible sensors among [our list](https://decoder.theengs.io/devices/devices_by_brand.html: Mi Flora, Mi jia, LYWDS02, LYWSD03MMC, ClearGrass, Mi scale, iBBQ, TPMS +Examples of compatible sensors among [our list](https://decoder.theengs.io/devices/devices_by_brand.html): Mi Flora, Mi jia, LYWDS02, LYWSD03MMC, ClearGrass, Mi scale, iBBQ, TPMS ## Receiving signals from BLE devices for Device Tracker detection -The gateway will detect BLE trackers from Tile, Nut, TagIt and iTag, as well as other devices with additional properties decoding like Mi Band, Amazfit, RuuviTag and others indicated as Device Trackers in the [compatible BLE devices list](https://decoder.theengs.io/devices/devices.html), and automatically create a device tracker entity following the Home Assistant discovery convention (if auto discovery is activated). +The gateway will detect BLE trackers from Tile, Nut, TagIt, iTAG, Gigaset G-Tag, TicWatch GTH (Pro), Teltonika FMT100 vehicle tracker and Bosch Nyon eBike computers, as well as other devices with additional properties decoding like Mi Band, Amazfit, RuuviTag and others indicated as Device Trackers in the [compatible BLE devices list](https://decoder.theengs.io/devices/devices.html), and automatically create a device tracker entity following the Home Assistant discovery convention (if auto discovery is activated). The devicen tracker entity created can be attached to a person to leverage presence detection. The `away` or `not home` state is triggered if the BLE tracker is not detected during the timer defined by `presenceawaytimer`. ![Away home Home assistant view](../img/OpenMQTTGateway-BLE-tracker-Home-Assistant.png) -If you have multiple gateways, your BLE trackers may not be detected temporary by one gateway but still by the others. In this case you will see the tracker appears offline briefly and online again once it is detected by the others gateways. - By default `presenceawaytimer` is set to 120s, you can change it from the slider in your controller or with the following command (ms) `mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"presenceawaytimer":66000}'` @@ -109,8 +124,6 @@ A white list is a list of MAC addresses permitted to be published by OMG to set white list `mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"white-list":["01:23:14:55:16:15","4C:65:77:88:9C:79","4C:65:A6:66:3C:79"]}'` -Note: if you want to filter (white or black list) on BLE sensors that are auto discovered, you need to wait for the discovery before applying the white or black list, or temporarily disable it: - to temporarily disable white/black list `mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"ignoreWBlist":true}'` @@ -120,12 +133,13 @@ to enable white/black list back ::: tip So as to keep your white/black list persistent you can publish it with the retain option of MQTT (-r with mosquitto_pub or retain check box of MQTT Explorer) `mosquitto_pub -r -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"white-list":["01:23:14:55:16:15","4C:65:77:88:9C:79","4C:65:A6:66:3C:79"]}'` + +**NOTE**: Only when sending a white/black list should the retain option be set. All other commands to any OpenMQTTGateway gateway **must not** have the retain option set. To persist such other command settings, read [the following section](https://docs.openmqttgateway.com/use/ble.html#store-ble-configuration-into-the-gateway) ::: ## Setting the time between BLE scans and force a scan (available with HA discovery) -If you want to change the time between readings you can change the interval by MQTT. -For example, if you want the BLE to scan every 66 seconds: +Example if you want the BLE to scan every 66 seconds: `mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"interval":66000}'` @@ -133,6 +147,8 @@ you can also force a scan to be done by the following command: `mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"interval":0}'` +Changing the interval between scans will deactivate adaptive scanning. + ::: tip With Home Assistant, this command is directly available through MQTT auto discovery as a switch into the HASS OpenMQTTGateway device entities list. ::: @@ -141,9 +157,9 @@ Once the forced scan has completed, the previous scan interval value will be res The default value `TimeBtwRead` is set into config_BT.h or into your .ini file for platformio users. -If you want to scan continuously for BLE devices, for example for beacon location you can set the interval to 1ms: +If you want to scan continuously for BLE devices, for example for beacon location you can set the interval to 100ms: -`mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"interval":1}'` +`mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"interval":100}'` In this case you should deactivate the BLE connection mechanism to avoid concurrency between scan and connections (see chapter below, bleconnect). @@ -191,7 +207,7 @@ An overview with background information to better understand the different setti **Active scanning:** With this scanning mode the gateway sends out requests for sensor broadcasts first, before then picking up the broadcast advertisement data. Some devices require this request before they send out all data in their broadcasts. The interval for this active scanning with request first is set by [{"intervalacts":300000}](#setting-the-time-between-active-scanning) -If adaptive scanning is set to false and you want to manually set these intervals, setting [Publishing advertisement and advanced data](#advanced-publishing-advertisement-and-advanced-data-default-false) to true will show you additional data about which of your devices require active scanning and/or continuous scanning, so that you can tune these setting to your devices and your individual requirements of their data. +Setting [Publishing advertisement and advanced data](#advanced-publishing-advertisement-and-advanced-data-default-false) to true will show you additional data about which of your devices require active scanning and/or continuous scanning, so that you can tune these setting to your devices and your individual requirements of their data. **"cont":true** - the device requires continuous scanning. If passive ({"interval":100}) or active ({"intervalacts":100}) depends on the additional device specification. @@ -201,10 +217,16 @@ If adaptive scanning is set to false and you want to manually set these interval If you have passive scanning activated, but also have some devices which require active scanning, this defines the time interval between two intermittent active scans. -If you want to change the time between active scans you can change it by MQTT. For setting the active scan interval time to every 5 minutes: +Example for setting the active scan interval time to every 5 minutes: `mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"intervalacts":300000}'` +Changing the active scan interval will deactivate adaptive scanning. + +::: warning Note +The active scan interval `intervalacts` can only bet set equal to or higher than the passive scan interval `interval`, as any lower value would not make any sense. +::: + ## Setting the duration of a scan (available with HA discovery) If you want to change the default duration of each scan cycle to 5 seconds @@ -293,6 +315,11 @@ By the way, if you want to load the default built-in configuration (on any board `mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT/config -m '{"init":true}'` Note that it will not change the stored configuration, `erase` or `save` is still needed to overwrite the saved configuration. +## Controlling devices +::: tip +To control devices reliably, set the interval between scans to at least 5 seconds and the scan duration to 1 second to ensure commands are successfully transmitted to your devices. +::: + ## Read/write BLE characteristics over MQTT The gateway can read and write BLE characteristics from devices and provide the results in an MQTT message. @@ -348,10 +375,16 @@ Response: ::: tip The `ttl` parameter is the number of attempts to connect (defaults to 1), which occur after the BLE scan completes. `value_type` can be one of: STRING, HEX, INT, FLOAT. Default is STRING if omitted in the message. +::: ## SwitchBot Bot control (available with HA discovery) -SwitchBot Bot devices are automatically discovered and available as a device in the configuration menu of home assistant. +SwitchBot Bot devices are automatically discovered and available as a device in the Home Assistant Settings menu. The following commands are supported: +* Press +* On +* Off +* Up +* Down ::: tip If the SwitchBot mode is changed the ESP32 must be restarted. @@ -359,13 +392,51 @@ If the SwitchBot mode is changed the ESP32 must be restarted. The device can also be controlled over MQTT with a simplified BLE write command. -### Example command to set the SwitchBot state to ON: +### Set the SwitchBot Bot state to ON: ``` mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ - "SBS1":"on", - "mac":"AA:BB:CC:DD:EE:FF" + "model_id":"X1", + "cmd":"on", + "id":"AA:BB:CC:DD:EE:FF" }' ``` + +### Set the SwitchBot Bot state to OFF: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"X1", + "cmd":"off", + "id":"AA:BB:CC:DD:EE:FF" +}' +``` + +### Set the SwitchBot Bot to PRESS: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"X1", + "cmd":"press", + "id":"AA:BB:CC:DD:EE:FF" +}' +``` + +### Set the SwitchBot Bot to go UP: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"X1", + "cmd":"up", + "id":"AA:BB:CC:DD:EE:FF" +}' +``` + +### Set the SwitchBot Bot to go DOWN: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"X1", + "cmd":"down", + "id":"AA:BB:CC:DD:EE:FF" +}' +``` + Response (assuming success): ``` { @@ -374,6 +445,123 @@ Response (assuming success): } ``` +## SwitchBot Blind Tilt control (available with HA discovery) + +SwitchBot Blind Tilt devices are automatically discovered and available as a device in the settings Home Assistant Settings menu. The following commands are supported: +* Open +* Close down +* Set a percentage + +The device can also be controlled over MQTT with a simplified BLE write command. + +### Set the SwitchBot Blind Tilt state to OPEN: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"W270160X", + "tilt":"open", + "id":"AA:BB:CC:DD:EE:FF" + }' +``` + +### Set the SwitchBot Blind Tilt state to CLOSE_DOWN: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"W270160X", + "tilt":"close_down", + "id":"AA:BB:CC:DD:EE:FF" + }' +``` + +### Set the SwitchBot Blind Tilt state to CLOSE_UP: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"W270160X", + "tilt":"close_up", + "id":"AA:BB:CC:DD:EE:FF" + }' +``` + +### Set the SwitchBot Blind Tilt state to a percentage (0-100): +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"W270160X", + "tilt":55, + "id":"AA:BB:CC:DD:EE:FF" + }' +``` + +### Set the SwitchBot Blind Tilt to Stop: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"W270160X", + "tilt":"stop", + "id":"AA:BB:CC:DD:EE:FF" + }' +``` + +### Response (assuming success): +The Switchbot Blind Tilt response : +``` +{ + "id":"AA:BB:CC:DD:EE:FF", + "tilt":55, + "open":90, + "direction":"up" +} +``` + +## SwitchBot Curtain (2/3) control (available with HA discovery) + +SwitchBot Curtain (2/3) devices are automatically discovered and available as a device in the settings Home Assistant Settings menu. The following commands are supported: +* Set a percentage + +The device can also be controlled over MQTT with a simplified BLE write command. + +### Set the SwitchBot Curtain state to OPEN: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"W070160X", + "position":"open", + "id":"AA:BB:CC:DD:EE:FF" + }' +``` + +### Set the SwitchBot Curtain state to CLOSE: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"W070160X", + "position":"close", + "id":"AA:BB:CC:DD:EE:FF" + }' +``` + +### Set the SwitchBot Curtain to a percentage (0-100): +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"W070160X", + "position":55, + "id":"AA:BB:CC:DD:EE:FF" + }' +``` + +### Set the SwitchBot Curtain to Stop: +``` +mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoBT -m '{ + "model_id":"W070160X", + "position":"stop", + "id":"AA:BB:CC:DD:EE:FF" + }' +``` + +### Response (assuming success): +The Switchbot Curtain response : +``` +{ + "id":"AA:BB:CC:DD:EE:FF", + "position":55, +} +``` + ## ADVANCED: Setting up an external decoder This advanced option is used to publish raw radio frames on a specific topic to be decoded by an external decoder instead of the integrated one. diff --git a/docs/use/boards.md b/docs/use/boards.md index 9f226dd..8563786 100644 --- a/docs/use/boards.md +++ b/docs/use/boards.md @@ -21,33 +21,33 @@ This can be achieved with the following macro, `WifiGMode` defined true and `Wif Since the WiFi protocol is persisted in the flash of the ESP you have to run at least once with `WiFiGMode` defined **false** to get Band N back. ### Low power mode for ESP32 -OpenMQTTGateway support a low power mode for ESP32, this mode is available per default on boards with batteries. The other boards needs to have the macro `DEFAULT_LOW_POWER_MODE` defined at 0, 1 or 2 to use it. More information about the modes is available into User_config.h. +OpenMQTTGateway support a low power mode for ESP32, the boards needs to have the macro `DEFAULT_LOW_POWER_MODE` defined at `ALWAYS_ON`, `INTERVAL` or `ACTION` to use it. More information about the modes is available into User_config.h. When available this mode can be set by MQTT: * Normal mode (per default) -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoBT/config" -m '{"lowpowermode":0}'` +`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"powermode":0, "save":true}'` -* Low Power mode +* Low Power mode wake up from interval defined by DEEP_SLEEP_IN_US and pins defined by ESP32_EXT0_WAKE_PIN and/or ESP32_EXT1_WAKE_PIN -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoBT/config" -m '{"lowpowermode":2}'` +`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"powermode":1, "save":true}'` -The interval between the ESP32 wake up is defined at build time by the macro `TimeBtwRead`, a change of the `interval` through MQTT will not impact the time between wake up. +* Low Power mode wake up from pins defined by ESP32_EXT0_WAKE_PIN and/or ESP32_EXT1_WAKE_PIN + +`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"powermode":2, "save":true}'` ::: tip -When coming back from mode 2 to mode 0 you may publish the command with a retain flag so as to enable the gateway to retrieve it when reconnecting. A low power mode switch is automatically created by discovery with Home Assistant, you may experience a delay between the command and the state update due to the fact that the update will be received and acknowledged when the device woke up. -In low power mode you should use ESPWifiManualSetup so as to rely on the credentials entered into User_config.h. -So as to do that uncomment the line below in User_config.h -``` c -//# define ESPWifiManualSetup true -``` -For platformio and example of environment is available into [prod_env.ini.example](https://github.com/1technophile/OpenMQTTGateway/blob/development/prod_env.ini.example) +If you are publishing the state change while the device is asleep use the retain flag. This way the device will retrieve the powermode command at wake up. ::: +The default sleep time is defined by the macro `DEEP_SLEEP_IN_US` (default 60s) + +We can also use an external sensor state to wake-up the ESP, this is defined by macro `ESP32_EXT0_WAKE_PIN/ESP32_EXT1_WAKE_PIN`, the level is defined by the macro `ESP32_EXT0_WAKE_PIN_STATE/ESP32_EXT0_WAKE_PIN_STATE` (default to HIGH). + ::: warning -If you change the default low power mode in config_BT.h to 2 and your credential are not set or not correct, the ESP32 will not connect to the broker and the only way to change the low power mode will be a new erase/upload. +If you change the default low power mode to INTERVAL or ACTION and your credential are not set or not correct, the ESP32 will not connect to the broker and the only way to change the low power mode will be a new erase/upload. ::: ## M5StickC, M5StickC Plus or M5Stack @@ -73,41 +73,3 @@ You can also change it by MQTT. For example if you want to set to LCD you can also revert it to the serial monitor: `mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoM5/config -m '{"log-display":false}'` - -### Low power mode for M5 boards -OpenMQTTGateway support a low power mode for ESP32, this mode can be set by MQTT or a button on M5 boards: - -* Normal mode (per default), screen ON - -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoBT/config" -m '{"lowpowermode":0}'` - -* Low Power mode, screen ON when processing only - -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoBT/config" -m '{"lowpowermode":1}'` - -* Low Power mode, screen OFF, LED ON when processing on M5StickC or M5stickC Plus - -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoBT/config" -m '{"lowpowermode":2}'` - -The low power mode can be changed also with a push to button B when the board is processing (top button on M5stickC, M5stickC Plus and middle button of M5stack). -If you are already in low power mode 1 or 2 with M5Stack you can wake up the board by pressing the red button. - -### Low power mode (deepSleep) for ESP8266 & ESP32 boards -In certain use cases where power is severely limited you can use the ESP8266 or ESP32 deep sleep capability. - -* e.g. measuring a pool temperature every 5 minutes using an ESP8266 and DS18B20 probe where the ESP8266 is powered by very limited battery backed solar power. -* e.g. as a water/leak detector which wake-up based on sensor state an ESP32 and C-37 YL-83 HM-RD sensor where the ESP32 is powered by very limited battery power. - -During deep sleep everything is off and (almost) all execution state is lost. - -Consumption is about 20 µA on an ESP8266. - -Use this when you want the device to sleep for minutes, hours woken by external sensor state. - -You only have to define the macro `DEEP_SLEEP_IN_US` with the number of microseconds, this works for both ESP8266 and ESP32. - -For an ESP8266 a hardware jumper is required connecting RST to a GPIO (not to CH_PD) defined by the macro `ESP8266_DEEP_SLEEP_WAKE_PIN` and defaulted to D0. - -On an ESP32 we can also use an external sensor state to wake-up the ESP and this is defined by macro `ESP32_EXT0_WAKE_PIN` and which state it must toggle to by macro `ESP32_EXT0_WAKE_PIN_STATE` defaulted to 1 (high). - -And the sensor code must set variable `ready_to_sleep` to true after publishing the measurement to MQTT and the main loop will then enter deep sleep. diff --git a/docs/use/displays.md b/docs/use/displays.md index e382050..572a565 100644 --- a/docs/use/displays.md +++ b/docs/use/displays.md @@ -20,6 +20,20 @@ MQTT Display ON command: `mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoSSD1306/config -m {"onstate":true}` +#### Usage of a touch GPIO display blanking + +Support can be enabled to use a GPIO pin as a simple touch sensor to enable the display. When enabled, the display will blank after 30 seconds, and when GPIO 2 is touched, the display will enable for 30 seconds. For testing a wire was connected to the GPIO pin. + +This can be enabled with the compiler directive `-DDISPLAY_BLANKING=true` + +Blanking Compiler Directives + +| Directive | Default | Description | +| - | - | - | +| DISPLAY_BLANKING | false | Enables touch based display blanking | +| DISPLAY_BLANKING_TOUCH_GPIO | 2 | GPIO pin to use the touch. Must be a touch supported GPIO pin | +| DISPLAY_BLANKING_START | 30 | Seconds to wait before disabling the display | + ### Brightness The display brightness can be set between 0-100%. diff --git a/docs/use/gateway.md b/docs/use/gateway.md index 8f5abcb..bf30579 100644 --- a/docs/use/gateway.md +++ b/docs/use/gateway.md @@ -32,20 +32,12 @@ If you want the settings to be kept upon gateway restart, you can save the state `mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"disc":false, "save":true}'` ::: tip -Auto discovery is enabled by default on release binaries and platformio (except for UNO). With Arduino IDE, please read the [advanced configuration section](../upload/advanced-configuration#auto-discovery) of the documentation. +Auto discovery is enabled by default on release binaries and platformio. ::: -## AutoDiscovery compatible with OpenHAB (default: false) -OpenHAB does not support the key `is_defined` in the json template, to remove it at runtime and make the auto discovery compatible you can use the following command with a retain flag. +## Activate Offline mode -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"ohdisc":true}'` - -If you want the settings to be kept upon gateway restart, you can save the state by adding `"save":true` (ESP32 only). -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"ohdisc":true, "save":true}'` - -::: tip -This command can also be used with other controllers that does not support the is_defined key. -::: +`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"offline":true,"save":true}'` ## Change the WiFi credentials @@ -69,30 +61,28 @@ mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m "mqtt_pass": "password", "mqtt_server": "host", "mqtt_port": "port", - "mqtt_secure": "false" + "mqtt_validate": false, + "mqtt_secure": false }' ``` + ::: tip INFO By default this function is not available on the pre built binary of RFBridge, in order to have less code size and enable to have OTA update working properly. So as to enable it remove from the rf bridge env: ``` build_flags = '-UMQTTsetMQTT' ``` -Arduino boards does not have this function per default also, to add it: -``` -build_flags = '-DMQTTsetMQTT' -``` ::: ::: tip -Server, port, and secure_flag are only required if changing connection to another broker. If the new connection fails the gateway will fallback to the previous connection. ::: -## Change the MQTT main topic and or gateway name +## Change the MQTT main topic, discovery prefix, and or gateway name ``` mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{ "mqtt_topic": "topic/", + "discovery_prefix": "prefix", "gateway_name": "name" }' ``` @@ -100,13 +90,13 @@ mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m This will change the subscribed and published mqtt_topic/gateway_name that the gateway uses. No parameters are mandatory, the current topic or gateway name will be used if not supplied. ::: -## Switching brokers and using self signed and client certificates +## Switching brokers and using signed and client certificates -In the `user_config.h` file it is possible to specify multiple MQTT brokers and client certificates. These are commonly self signed and are supported by defining `MQTT_SECURE_SELF_SIGNED` as true or 1. +In the `user_config.h` file it is possible to specify multiple MQTT brokers and client certificates. Additionally, support for multiple brokers and client certificates has been added. To use this, it is required that the server certificate, client certificate, and client key are provided as their own constant string value as demonstrated in the file. -To add more than one broker and switch between them it is necessary to provide all of the relevant certificates/keys and add their respective variable names in the `certs_array` structure, as shown in `user_config.h`, and changing the array size to the number of different connections -1. +To add more than one broker and switch between them it is necessary to provide all of the relevant certificates/keys and add their respective variable names in the `cnt_parameters_array` structure, as shown in `user_config.h`.. -To switch between these servers with an MQTT command message, the format is as follows: +To switch between these connections with an MQTT command message, the format is as follows: ``` mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{ @@ -114,14 +104,93 @@ mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m "mqtt_pass": "password", "mqtt_server": "host", "mqtt_port": "port", - "mqtt_secure": "true", - "mqtt_cert_index":0 + "mqtt_secure": true, + "mqtt_validate": true, + "cnt_index":1, + "save_cnt": true }' ``` ::: tip -The `mqtt_cert_index` value corresponds to the 0 to X index of the `certs_array` in `user_config.h`. +The `cnt_index` value corresponds to the 0 to 2 index of the `cnt_parameters_array` in `user_config.h`. +0 being the default index, containing the onboarding parameters. ::: +To read the connection parameters: +``` +mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m +'{ + "cnt_index":1, + "read_cnt": true + }' + ``` + + To test a connection change without saving: + ``` +mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m +'{ + "cnt_index":1, + "test_cnt": true + }' + ``` + +::: tip +If the client can't connect to the MQTT broker corresponding to the current `cnt_index`, it will increment the index to the next valid connection set and restart with it. +::: + +## Saving/Loading connection parameters/certificates at runtime +This chapter details the process for managing certificates/connections parameters used for secure MQTT communication with OpenMQTTGateway + +### Storing and Loading Certificates +* Flash Memory Storage: +Certificates can be saved to the flash memory using specific indices. Valid indices for storing certificates are 1 and 2, as 0 is reserved for the default certificate. +* RAM Memory Loading: +Certificates can be loaded from RAM, where valid indices range from 0 to 2. The device publishes a hash of the certificate to the broker to verify its identity. If the connection using the current certificate fails, the device will revert to the previous certificate. + +### Use Case: Changing a Group of Certificates +When updating certificates, follow these steps to ensure that the new certificates are correctly loaded and used: + +1. Push Certificates via MQTT: +Send the new certificates one by one through MQTT, using indices 1 or 2. Replace newline characters (\n) in the certificates with spaces. +```json +{ + "cnt_index": 1, + "mqtt_server_cert": "-----BEGIN CERTIFICATE----- MIIDQTCC----END CERTIFICATE-----" +} +``` + +Accepted certificates are: +* `mqtt_server_cert` +* `mqtt_client_cert` +* `mqtt_client_key` +* `ota_server_cert` + +2. Verify Certificates in RAM: +After pushing the certificates, verify that they have been correctly loaded into RAM. +```json +{ + "cnt_index": 1, + "read_cnt": true +} +``` + +3. Test and Save Certificates: +Once verification is complete, test the connection using the new certificates. If the connection is successful, send the command to save the certificates to flash. +```json +{ + "cnt_index": 1, + "save_cnt": true +} +``` + +4. Broker Connection: +The broker will attempt to use the newly received certificates for the connection. + +5. Successful Connection Handling: +If the connection is successful, the certificates are permanently stored in the flash memory at the specified index. + +6. Handling Connection Failures: +If the connection fails, the device will revert to the previously used certificate index, and the new certificates will not be saved. + # Firmware update from MQTT (ESP only) When the gateway used is from a standard ESP32 environment [listed and defined here](https://github.com/1technophile/OpenMQTTGateway/blob/development/environments.ini), it can be updated through a simple MQTT command: @@ -148,7 +217,7 @@ OpenMQTTGateway checks at start and every hour if an update is available. Alternatively if you want to choose the update URL you can use the command below (ESP32 and ESP8266): -Without certificate, in this case we will use the root certificate defined in User_config.h +Without certificate, in this case the gateway will use the ota_server_cert certificate defined in default_ota_cert.h ``` mosquitto_pub -t "home/OpenMQTTGateway_ESP32_BLE/commands/MQTTtoSYS/firmware_update" -m '{ "version": "test", @@ -157,39 +226,29 @@ mosquitto_pub -t "home/OpenMQTTGateway_ESP32_BLE/commands/MQTTtoSYS/firmware_upd }' ``` -With certificate: +With certificate (replace the \n in the certificate by spaces to publish it easily): ``` mosquitto_pub -t "home/OpenMQTTGateway_ESP32_BLE/commands/MQTTtoSYS/firmware_update" -m '{ "version": "test", "password": "OTAPASSWORD", "url": "https://github.com/1technophile/OpenMQTTGateway/releases/download/v0.9.12/esp32dev-ble-firmware.bin", - "server_cert": "-----BEGIN CERTIFICATE----- -MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD -QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT -MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j -b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB -CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 -nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt -43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P -T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 -gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO -BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR -TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw -DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr -hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg -06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF -PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls -YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk -CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= ------END CERTIFICATE-----"}' + "ota_server_cert": "-----BEGIN CERTIFICATE----- MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= -----END CERTIFICATE-----"}' ``` -A bash script is available [here](ota_command_cert.zip) to simplify the use of the `server_cert` parameter. +A bash script is available [here also](ota_command_cert.zip) to simplify the use of the `server_cert` parameter. +Alternatively the OTA certificate can also be saved with the cnt_index for future use: + +``` +mosquitto_pub -t "home/OpenMQTTGateway_ESP32_BLE/commands/MQTTtoSYS/config" -m '{ + "cnt_index": 1, + "save_cnt":true, + "ota_server_cert": "-----BEGIN CERTIFICATE----- MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= -----END CERTIFICATE-----" +}' +``` +The other connection parameters corresponding to the index need to be valid for the save function to work. This command will switch to connection parameters of index 1. + To enable this functionality, `MQTT_HTTPS_FW_UPDATE` will need to be defined or the line that defines in in user_config.h will need to be uncommented. ::: tip @@ -202,23 +261,124 @@ The `server_cert` parameter is optional. If the update server has changed or cer The pre-built binaries for **rfbridge** and **avatto-bakeey-ir** have the above WiFi and MQTT broker credentials and the Firmware update via MQTT options disabled. This is due to the restricted available flash, so as to still be able to use OTA firmware updates for these boards. ::: +# Communication layers + +## MQTT +OpenMQTTGateway uses per default MQTT on top of Ethernet or WiFi for communicating (default: true). +The MQTT communication can be deactivated with the following command: +`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"mqtt":false}'` +Once activated the MQTT API is no longer accessible + +## Serial +Added to MQTT, OpenMQTTGateway cans use Serial to transmit or receive json data (default: false): +`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"serial":true}'` + +The build need to have the following macro: +``` + '-DZgatewaySERIAL="SERIAL"' +``` + +An example scenario is a slave offline ESP32 dedicated to RF decoding connected to another online ESP32 through Serial. + +# Indicators + ## Change the LED indicator brightness Minimum: 0, Maximum: 255, Default defined by DEFAULT_ADJ_BRIGHTNESS `mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoSYS/config" -m '{"brightness":200}'` -# State LED usage +## Understanding LED Indicators in OpenMQTTGateway +With boards having one or several RGB Led, OpenMQTTGateway uses them to provide visual feedback about its current state. This guide will help you interpret these LED signals to understand what's happening with your gateway. -The gateway can support up to 3 LED to display its operating state: -* LED_INFO -switched ON when network and MQTT connection are OK -5s ON, 5s OFF when MQTT is disconnected -2s ON, 2s OFF when NETWORK is disconnected +## LED Color Guide +OpenMQTTGateway uses a variety of colors to indicate different states: -* LED_RECEIVE -Blink for `TimeLedON` 1s when the gateway receive a signal from one of its module so as to send to MQTT +Green (0x00FF00): Indicates normal operation or successful connections +Blue (0x0000FF): Shows processing or offline status +Orange (0xFFA500): Indicates waiting states or minor issues +Yellow (0xFFFF00): Used during the onboarding process +Red (0xFF0000): Signals an error state +Magenta (0xFF00FF): Indicates local Over-The-Air (OTA) updates +Purple (0x8000FF): Shows remote OTA updates are in progress -* LED_SEND -Blink for `TimeLedON` 1s when the gateway send a signal with one of its module from an MQTT command +## Understanding Gateway States +Here's what different LED behaviors mean: +### Power On + +Color: Green +Behavior: Solid light +Meaning: The gateway is powered and operational + +### Processing + +Color: Blue +Behavior: Blinking (3 times) +Meaning: The gateway is processing data + +### Waiting for Onboarding + +Color: Orange +Behavior: Solid light +Meaning: The gateway is ready to be set up + +### Onboarding in Progress + +Color: Yellow +Behavior: Solid light +Meaning: The gateway is being configured + +### Network Connected + +Color: Green +Behavior: Solid light +Meaning: Successfully connected to the network + +### Network Disconnected + +Color: Orange +Behavior: Blinking +Meaning: Lost connection to the network + +### MQTT Broker Connected + +Color: Green +Behavior: Solid light +Meaning: Successfully connected to the MQTT broker + +### MQTT Broker Disconnected + +Color: Orange +Behavior: Blinking +Meaning: Lost connection to the MQTT broker + +### Offline + +Color: Blue +Behavior: Blinking +Meaning: The gateway is offline + +### Local OTA Update + +Color: Magenta +Behavior: Blinking +Meaning: A local Over-The-Air update is in progress + +### Remote OTA Update + +Color: Purple +Behavior: Blinking +Meaning: A remote Over-The-Air update is in progress + +### Error + +Color: Red +Behavior: Blinking (3 times) +Meaning: An error has occurred + +### Actuator On/Off + +Color: Green +Behavior: Depends on actuator state +Meaning: Indicates the state of a connected actuator \ No newline at end of file diff --git a/docs/use/ir.md b/docs/use/ir.md index 89cb45d..35121aa 100644 --- a/docs/use/ir.md +++ b/docs/use/ir.md @@ -97,11 +97,7 @@ mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoIR -m '{"value":551489775," ## Send raw IR data by MQTT -2) If you use an Arduino UNO enable `IR_Raw` by uncommenting the line 129 in User_config.h -`#define IR_Raw` -If you are using the uno you will have to comment other gateway like ZgatewayRF, ZgatewayBT and ZgatewayIR to keep enough memory - -3) publish your code like below +Publish your code like below ``` mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoIR -m '{"raw":"8850,4450,600,550,550,550,600,1600,600,550,600,500,600,500,600,550,600,500,600,1650,600,1600,600,550,600,1600,600,1650,600,1600,600,1650,600,1600,600,550,600,500,600,550,550,1650,600,500,600,550,600,500,600,550,550,1650,600,1650,550,1650,600,550,550,1650,600,1650,550,1650,600,1650,600","protocol_name":"Raw"}' ``` @@ -111,12 +107,10 @@ In this case the best way is to use hex values instead, but if you can't you may In User_config.h replace: ```cpp # define JSON_MSG_BUFFER 512 -# define mqtt_max_packet_size 1024 ``` by ```cpp # define JSON_MSG_BUFFER 1280 -# define mqtt_max_packet_size 1280 ``` ## Repeat the IR signal OpenMQTTGateway receive diff --git a/docs/use/rf.md b/docs/use/rf.md index e52065d..560a3a4 100644 --- a/docs/use/rf.md +++ b/docs/use/rf.md @@ -39,19 +39,23 @@ Note that with CC1101 this frequency will be used as the default sending frequen Switching of the active transceiver (RTL_433 receiver only) module is available between the RF, RF2, and (RTL_433 or Pilight) gateway modules, allowing for changing of signal decoders without redeploying the OpenMQTTGateway package. Sending a JSON message to the command topic will change the active transceiver module. -To enable the RF gateway module send a json message to the RF gateway module command subject with the key being 'active', and any value. The value at this time is ignored. +To change the RF gateway module, which will receive, send a json message to the RF gateway module command subject (home/OpenMQTTGateway/commands/MQTTtoRF/config) with the corresponding value of the key "active" -1 - PiLight -2 - RF -3 - RTL_433 +1 - PiLight
+2 - RF
+3 - RTL_433
4 - RF2 Example to receive from the RF gateway: `mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoRF/config" -m '{"active":2}'` +Example to receive from the Pilight gateway: +`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoRF/config" -m '{"active":1}'` + The active receiver can also be changed with the WebUI. The OpenMQTTGateway RFtoMQTT status message contains a key `active` which is the current active receiver module. +There is example configuration entry for Homea Assistant in the intergrations doc. ## RTL_433 device decoders @@ -66,95 +70,13 @@ This feature is only available on a ESP32 based device with a supported transcei ### Supported Decoders -``` -Registering protocol [2] "Acurite 609TXC Temperature and Humidity Sensor" -Registering protocol [3] "Acurite 592TXR Temp/Humidity, 5n1 Weather Station, 6045 Lightning, 3N1, Atlas" -Registering protocol [4] "Acurite 986 Refrigerator / Freezer Thermometer" -Registering protocol [5] "Acurite 606TX Temperature Sensor" -Registering protocol [6] "Acurite 00275rm,00276rm Temp/Humidity with optional probe" -Registering protocol [7] "Acurite 590TX Temperature with optional Humidity" -Registering protocol [8] "Acurite Grill/Meat Thermometer 01185M" -Registering protocol [9] "Akhan 100F14 remote keyless entry" -Registering protocol [10] "AlectoV1 Weather Sensor (Alecto WS3500 WS4500 Ventus W155/W044 Oregon)" -Registering protocol [11] "Ambient Weather TX-8300 Temperature/Humidity Sensor" -Registering protocol [13] "Auriol AFT 77 B2 temperature sensor" -Registering protocol [14] "Auriol AFW2A1 temperature/humidity sensor" -Registering protocol [15] "Auriol AHFL temperature/humidity sensor" -Registering protocol [16] "Auriol HG02832, HG05124A-DCF, Rubicson 48957 temperature/humidity sensor" -Registering protocol [18] "Blyss DC5-UK-WH" -Registering protocol [20] "Bresser Thermo-/Hygro-Sensor 3CH" -Registering protocol [22] "Burnhard BBQ thermometer" -Registering protocol [23] "Calibeur RF-104 Sensor" -Registering protocol [24] "Cardin S466-TX2" -Registering protocol [25] "Chuango Security Technology" -Registering protocol [26] "Companion WTR001 Temperature Sensor" -Registering protocol [29] "Ecowitt Wireless Outdoor Thermometer WH53/WH0280/WH0281A" -Registering protocol [30] "Eurochron EFTH-800 temperature and humidity sensor" -Registering protocol [34] "Esperanza EWS" -Registering protocol [36] "Fine Offset Electronics, WH2, WH5, Telldus Temperature/Humidity/Rain Sensor" -Registering protocol [37] "Fine Offset Electronics, WH0530 Temperature/Rain Sensor" -Registering protocol [38] "Fine Offset WH1050 Weather Station" -Registering protocol [39] "Fine Offset Electronics WH1080/WH3080 Weather Station" -Registering protocol [41] "FT-004-B Temperature Sensor" -Registering protocol [42] "Generic wireless motion sensor" -Registering protocol [43] "Generic Remote SC226x EV1527" -Registering protocol [44] "Generic temperature sensor 1" -Registering protocol [45] "Govee Water Leak Dectector H5054, Door Contact Sensor B5023" -Registering protocol [46] "Globaltronics QUIGG GT-TMBBQ-05" -Registering protocol [47] "Globaltronics GT-WT-02 Sensor" -Registering protocol [48] "Globaltronics GT-WT-03 Sensor" -Registering protocol [49] "Microchip HCS200 KeeLoq Hopping Encoder based remotes" -Registering protocol [50] "Honeywell ActivLink, Wireless Doorbell" -Registering protocol [51] "HT680 Remote control" -Registering protocol [52] "inFactory, nor-tec, FreeTec NC-3982-913 temperature humidity sensor" -Registering protocol [54] "Interlogix GE UTC Security Devices" -Registering protocol [56] "Kedsum Temperature & Humidity Sensor, Pearl NC-7415" -Registering protocol [57] "Kerui PIR / Contact Sensor" -Registering protocol [58] "LaCrosse TX Temperature / Humidity Sensor" -Registering protocol [59] "LaCrosse TX141-Bv2, TX141TH-Bv2, TX141-Bv3, TX141W, TX145wsdth, (TFA, ORIA) sensor" -Registering protocol [60] "LaCrosse/ELV/Conrad WS7000/WS2500 weather sensors" -Registering protocol [61] "LaCrosse WS-2310 / WS-3600 Weather Station" -Registering protocol [63] "Markisol, E-Motion, BOFU, Rollerhouse, BF-30x, BF-415 curtain remote" -Registering protocol [64] "Maverick et73" -Registering protocol [66] "Missil ML0757 weather station" -Registering protocol [68] "Nexus, FreeTec NC-7345, NX-3980, Solight TE82S, TFA 30.3209 temperature/humidity sensor" -Registering protocol [70] "Opus/Imagintronix XT300 Soil Moisture" -Registering protocol [71] "Oregon Scientific Weather Sensor" -Registering protocol [72] "Oregon Scientific SL109H Remote Thermal Hygro Sensor" -Registering protocol [74] "Philips outdoor temperature sensor (type AJ3650)" -Registering protocol [75] "Philips outdoor temperature sensor (type AJ7010)" -Registering protocol [76] "Prologue, FreeTec NC-7104, NC-7159-675 temperature sensor" -Registering protocol [77] "Quhwa" -Registering protocol [79] "Rubicson Temperature Sensor" -Registering protocol [80] "Rubicson 48659 Thermometer" -Registering protocol [81] "Conrad S3318P, FreeTec NC-5849-913 temperature humidity sensor" -Registering protocol [82] "Silvercrest Remote Control" -Registering protocol [83] "Skylink HA-434TL motion sensor" -Registering protocol [84] "Wireless Smoke and Heat Detector GS 558" -Registering protocol [85] "Solight TE44/TE66, EMOS E0107T, NX-6876-917" -Registering protocol [86] "Springfield Temperature and Soil Moisture" -Registering protocol [87] "TFA Dostmann 30.3221.02 T/H Outdoor Sensor" -Registering protocol [88] "TFA Drop Rain Gauge 30.3233.01" -Registering protocol [89] "TFA pool temperature sensor" -Registering protocol [90] "TFA-Twin-Plus-30.3049, Conrad KW9010, Ea2 BL999" -Registering protocol [91] "Thermopro TP11 Thermometer" -Registering protocol [92] "Thermopro TP08/TP12/TP20 thermometer" -Registering protocol [94] "TS-FT002 Wireless Ultrasonic Tank Liquid Level Meter With Temperature Sensor" -Registering protocol [95] "Visonic powercode" -Registering protocol [96] "Waveman Switch Transmitter" -Registering protocol [97] "WG-PB12V1 Temperature Sensor" -Registering protocol [98] "WS2032 weather station" -Registering protocol [99] "Hyundai WS SENZOR Remote Temperature Sensor" -Registering protocol [100] "WT0124 Pool Thermometer" -Registering protocol [101] "X10 RF" -Registering protocol [102] "X10 Security" -``` +For the most recent support decoder list please check the [rtl_433_esp](https://github.com/NorthernMan54/rtl_433_ESP?tab=readme-ov-file#ook-signal-device-decoders) repository. ### Change Signal RSSI Threshold Delta Delta applied to RSSI floor noise level to determine start and end of signal, defaults to 9db. -`home/OpenMQTTGateway/commands/MQTTtoRF/config {"rssiThreshold": 9}` +`home/OpenMQTTGateway/commands/MQTTtoRF/config {"rssithreshold": 9}` ### Retrieve current status of receiver @@ -183,82 +105,114 @@ Delta applied to RSSI floor noise level to determine start and end of signal, de ## RCSwitch based gateway -### Receiving data from RF signal +The [RCSwitch](https://github.com/1technophile/rc-switch.git) library is an Arduino library that facilitates communication with 433MHz RF modules. It is designed to be lightweight and easy to use, making it suitable for basic RF communication tasks. The library supports both sending and receiving of RF signals, allowing for integration with various RF devices such as remote controls, sensors, and switches. -Subscribe to all the messages with mosquitto or open your MQTT client software: +To enable this module during compilation, add the flag `'-DZgatewayRF="RF"'` or uncomment the line `#define ZgatewayRF "RF"` in the `User_config.h` file. -` sudo mosquitto_sub -t +/# -v` -Generate your RF signals by pressing a remote button or other and you should see : +Other useful definitions can be: -`home/OpenMQTTGateway/433toMQTT {"value":1315156,"protocol":1,"length":24,"delay":317}` +* `#define RF_DISABLE_TRANSMIT` To disable the transmit functions and free up the pin for other uses, add (or uncomment) this line to the `config_rf.h` file. +* `#define repeatRFwMQTT true` To enable repeating the RF signal received by the gateway, set this parameter to true in the `config_rf.h` file. +* `#define RF_on_HAS_as_DeviceTrigger` To send a Home Assistant Device Trigger Message for each RF signal received, add (or uncomment) this line in the `config_rf.h` file. Note that this action also depends on the `ZmqttDiscovery` settings. +* `#define RF_on_HAS_as_MQTTSensor` To send a Home Assistant MQTT sensor message for each RF signal received, add (or uncomment) this line in the `config_rf.h` file. Note that this action also depends on the `ZmqttDiscovery` settings. -### Disabling Transmit function to safe a PIN -To disable transmit functions to allow the use of another pin, add the following to the config_rf.h file : -`#define RF_DISABLE_TRANSMIT` +### Handling RF signal over MQTT +In this chapter, the process of receiving and sending RF signals using MQTT will be explored. By subscribing to MQTT topics and publishing messages, RF devices can be seamlessly integrated with an MQTT broker. -### Send data by MQTT to convert it on RF signal +#### Receiving Data from RF Signal -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTto433" -m '{"value":1315156}'` +To receive data from an RF signal, follow these steps: -This command will send by RF the code 1315156 and use the default parameters (protocol 1, delay 350) +1. Subscribe to all messages using mosquitto or open your MQTT client software: + ```sh + sudo mosquitto_sub -t +/# -v + ``` -Arduino IDE serial data received when publishing data by MQTT +2. Generate your RF signals by pressing a remote button or other RF device. You should see output similar to: + ```json + home/OpenMQTTGateway/433toMQTT {"value":1315156,"protocol":1,"length":24,"delay":317} + ``` + + +#### Send data by MQTT to convert it to an RF signal + +To send an RF signal using MQTT, you can publish a message to the topic `home/OpenMQTTGateway/commands/MQTTto433` with the desired value. For example: + +```sh +mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTto433" -m '{"value":1315156}' +``` + +This command will send the RF code `1315156` using the default parameters (protocol 1, delay 350). + +When publishing data via MQTT, the Arduino IDE serial monitor will display the received value and the corresponding MQTT topic: ![Serial data](../img/OpenMQTTGateway_serial1.jpg) -We see that the Arduino receive the value 1315156 on the MQTT subject "MQTTto433" and send the data by RF +In this example, the Arduino receives the value `1315156` on the MQTT topic `MQTTto433` and transmits the data via RF. -Arduino IDE serial data received when receiving data by 433Mhz +Similarly, when receiving data via 433MHz, the Arduino IDE serial monitor will show the received data: ![Serial data 2](../img/OpenMQTTGateway_serial2.jpg) ### Send data by MQTT with advanced RF parameters -RF sending support three advanced parameters: bits length, RF protocol and RF pulselength +RF sending supports three advanced parameters: bits length, RF protocol, and RF pulse length. --if you want to use a bits number different than 24 put inside your topic "length":24 for example - --if you want to use a different RCswitch protocol put inside your payload the protocol number 2, "protocol":2. - --if you want to use a pulselength 315 put inside your topic "delay":315 +- To use a different bits number, include `"length":24` in your payload. +- To use a different RCSwitch protocol, include `"protocol":2` in your payload. +- To use a different pulse length, include `"delay":315` in your payload. Example: -`mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTto433" -m '{"value":1315156,"protocol":2,"length":24,"delay":315}'` -will make RCSwitch use the protocol 2 with a pulselength of 315ms and a bits number of 24 with a power of 5 -### Repeat the RF signal OpenMQTTGateway receive -So as to repeat the RF signal received by the gateway once set the following parameter to true in config_RF.h +```sh +mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTto433" -m '{"value":1315156,"protocol":2,"length":24,"delay":315}' +``` -`#define repeatRFwMQTT true` +This command will make RCSwitch use protocol 2 with a pulse length of 315ms and a bits number of 24. -### Repeat the RF signal several times -You can add a "repeat" key/value to the MQTTto433 JSON message to override the default number of repeats. + +#### Repeat the RF signal several time + +You can add a "repeat" key/value to the MQTTto433 JSON message to override the default number of repeats. Ensure that `repeatRFwMQTT` is enabled at compile time. Example: -`home/OpenMQTTGateway/commands/MQTTto433 {"value":1315156,"protocol":1,"length":24,"delay":317, "repeat":10}` +```sh +mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTto433" -m '{"value":1315156,"protocol":1,"length":24,"delay":317,"repeat":10}' +``` -### Set Transmit and Receive Frequency and Transmit Power of CC1101 Transceiver +#### Set Transmit and Receive Frequency and Transmit Power of CC1101 Transceiver -Default transmit frequency of the CC1101 module is 433.92 Mhz, and this can be can changed by including the frequency in the transmit message. Parameter is `mhz` and valid values are 300-348 Mhz, 387-464Mhz and 779-928Mhz. Actual frequency support will depend on your CC1101 board. +The default transmit frequency of the CC1101 module is 433.92 MHz. This can be changed by including the desired frequency in the transmit message. The parameter is `frequency`, and valid values are 300-348 MHz, 387-464 MHz, and 779-928 MHz. Actual frequency support will depend on your CC1101 board. -`home/OpenMQTTGateway/commands/MQTTto433 {"value":1150,"protocol":6,"length":12,"delay":450,"repeat":8,"frequency":303.732}` +Example: +```sh +mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTto433" -m '{"value":1150,"protocol":6,"length":12,"delay":450,"repeat":8,"frequency":303.732}' +``` -Default receive frequency of the CC1101 module is 433.92 Mhz, and this can be can changed by sending a message with the frequency. Parameter is `frequency` and valid values are 300-348 Mhz, 387-464Mhz and 779-928Mhz. Actual frequency support will depend on your CC1101 board +The default receive frequency of the CC1101 module is also 433.92 MHz. This can be changed by sending a message with the desired frequency. The parameter is `frequency`, and valid values are 300-348 MHz, 387-464 MHz, and 779-928 MHz. Actual frequency support will depend on your CC1101 board. -`home/OpenMQTTGateway/commands/MQTTtoRF/config {"frequency":433.92}` +Example: +```sh +mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoRF/config" -m '{"frequency":433.92}' +``` -Messages received will include the frequency, and when transmitting on a different frequency the module return to the receive frequency afterwards. ie transmit messages on 303.732 Mhz then receive messages on 433.92 Mhz +Messages received will include the frequency, and when transmitting on a different frequency, the module will return to the receive frequency afterward. For example, transmit messages on 303.732 MHz and then receive messages on 433.92 MHz. -`{"value":4534142,"protocol":6,"length":26,"delay":356,"frequency":315.026}` +Example received message: +```json +{"value":4534142,"protocol":6,"length":26,"delay":356,"frequency":315.026} +``` -You can adjust the tx-power in db for a transmission. Parameter is `cc1101_pa` and valid values in decibel are (-30 -20 -15 -10 -6 0 5 7 10 11 12) Default is max! -That can be done to reduce range and therefore disturbances with other nearby devices. -If you want to send a transmission with a power of 5 db than use the message +You can also adjust the transmit power (tx-power) in decibels (dB) for a transmission. The parameter is `cc1101_pa`, and valid values in decibels are -30, -20, -15, -10, -6, 0, 5, 7, 10, 11, and 12. The default is the maximum value. Adjusting the transmit power can help reduce range and minimize disturbances with other nearby devices. + +Example: +```sh +mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTto433" -m '{"value":1315156,"protocol":2,"length":24,"delay":315,"cc1101_pa":5}' +``` -`{"value":1315156,"protocol":2,"length":24,"delay":315, "cc1101_pa":5}` ## Pilight gateway @@ -276,7 +230,10 @@ Generate your RF signals by pressing a remote button or other and you will see : #### Enabling RAW packet return support First, you need to compile a binary with `Pilight_rawEnabled true` uncommented in config_RF.h. -Once the device is online, you can turn on the RAW packet return support with the following MQTT command: +Once the device is online and the active receiver is Pilght, you can toggle raw packet return. +If current active receiver is not Pilight the toggle command will be ignored and harmless error message will be published. + +You can turn on the RAW packet return support with the following MQTT command: `mosquitto_pub -t "home/OpenMQTTGateway/commands/MQTTtoPilight/protocols" -m '{"rawEnabled":true}'` diff --git a/docs/use/rs232.md b/docs/use/serial.md similarity index 54% rename from docs/use/rs232.md rename to docs/use/serial.md index efdaf27..ba93eea 100644 --- a/docs/use/rs232.md +++ b/docs/use/serial.md @@ -1,32 +1,32 @@ -# RS232 gateway +# RS232/Serial gateway -The RS232 gateway can be used to send and receive data from the serial connection to and from MQTT. Both softwareSerial as hardwareSerial are supported. HardwareSerial can be used for higher baud rates, but is limited to specific pins on most platforms. +The SERIAL gateway can be used to send and receive data from the serial connection to and from MQTT. Both softwareSerial as hardwareSerial are supported. HardwareSerial can be used for higher baud rates, but is limited to specific pins on most platforms. -## Sending an RS232 message +## Sending an SERIAL message Simply publish the message you wish to transmit, minus the prefix and postfix. For example, to send the "Turn On" signal for a Mitsubishi XD221U projector, the code is simply '!' so you would use the command -`mosquitto_pub -t home/OpenMQTTGateway/commands/MQTTtoRS232 -m '{"value": "!"}'` +`mosquitto_pub -t home/OpenMQTTGateway/commands/XtoSERIAL -m '{"value": "!"}'` -It will automatically add the prefix and postfix you set in [config_RS232.h](https://github.com/1technophile/OpenMQTTGateway/blob/master/main/config_RS232.h). +It will automatically add the prefix and postfix you set in [config_SERIAL.h](https://github.com/1technophile/OpenMQTTGateway/blob/master/main/config_SERIAL.h). -## Receiving an RS232 message +## Receiving an SERIAL message -Two modes are available for receiving RS232 messages. +Two modes are available for receiving SERIAL messages. ### Single MQTT message mode (default) To receive a message, subscribe to all with `mosquitto_sub -t +/# -v` and perform an action that should get a response from the device. For example, If I were to send the "Turn On" signal from earlier, I would receive back ```json -home/OpenMQTTGateway/RS232toMQTT {"value":"1"} +home/OpenMQTTGateway/SERIALtoMQTT {"value":"1"} ``` Because this projector echoes back a received command to acknowledge. Some devices will send a NACK, or Negative Acknowledge, to confirm that they received your message but could not comply. That would look like ```json -home/OpenMQTTGateway/RStoMQTT {"value":"!:N"} +home/OpenMQTTGateway/SERIALtoMQTT {"value":"!:N"} ``` ### JSON mode @@ -42,15 +42,15 @@ input received at serial link: output in case of max nesting level 1: ```json -home/OpenMQTTGateway/RS232toMQTT/temperature "{sens1: 22, sens2: 23}" -home/OpenMQTTGateway/RS232toMQTT/humidity "{sens1: 80, sens2: 60}" +home/OpenMQTTGateway/SERIALtoMQTT/temperature "{sens1: 22, sens2: 23}" +home/OpenMQTTGateway/SERIALtoMQTT/humidity "{sens1: 80, sens2: 60}" ``` output in case of max nesting level 2 (or higher): ```json -home/OpenMQTTGateway/RS232toMQTT/temperature/sens1 22 -home/OpenMQTTGateway/RS232toMQTT/temperature/sens2 23 -home/OpenMQTTGateway/RS232toMQTT/humidity/sens1 80 -home/OpenMQTTGateway/RS232toMQTT/humidity/sens2 60 +home/OpenMQTTGateway/SERIALtoMQTT/temperature/sens1 22 +home/OpenMQTTGateway/SERIALtoMQTT/temperature/sens2 23 +home/OpenMQTTGateway/SERIALtoMQTT/humidity/sens1 80 +home/OpenMQTTGateway/SERIALtoMQTT/humidity/sens2 60 ``` diff --git a/docs/use/webui.md b/docs/use/webui.md index 24198c0..b3004a9 100644 --- a/docs/use/webui.md +++ b/docs/use/webui.md @@ -30,6 +30,10 @@ Ability to change the mqtt settings, if the change is unsuccessful it will rever Ability to change the display of sensor to Metric or Imperial, and disable the WebUI Authentication +## Bluetooth Low Energy - BLE + +Ability to add the default AES BLE decryption key, and multiple per-device `macaddress:aeskey` allowing for devices that cannot have their AES key changed. + ## Logging Ability to temporarily change the logging level. diff --git a/docsgen/boards-info.js b/docsgen/boards-info.js new file mode 100644 index 0000000..ce52d05 --- /dev/null +++ b/docsgen/boards-info.js @@ -0,0 +1,248 @@ +'use strict'; +/** + * Universal parser for PlatformIO dependencies. + * Formats URLs and registry strings into a consistent "Registry Style": + * Name @ Version (provider:user) + */ +function smartFormat(dep) { + if (!dep) return ""; + if (typeof dep !== 'string') return dep; + + const cleanDep = dep.trim(); + + // Configuration for Git providers with specific regex for archives, releases, and git repos + const providers = [ + { + id: 'gh', + name: 'github', + // Captures: 1. Author, 2. Repo, 3. Version from path (releases), 4. Version from filename/branch + regex: /github\.com\/([^/]+)\/([^/.]+)(?:\/(?:archive|releases\/download\/([^/]+)|tree)\/)?([^/]+)?(?:\.zip|\.git)?$/i + }, + { + id: 'gl', + name: 'gitlab', + // Captures: 1. Author, 2. Repo, 3. Version from path, 4. Version from filename + regex: /gitlab\.com\/([^/]+)\/([^/.]+)(?:\/(?:-\/)?(?:archive|releases)\/([^/]+))?\/([^/]+)?(?:\.zip|\.git)?$/i + }, + { + id: 'bb', + name: 'bitbucket', + // Captures: 1. Author, 2. Repo, 3. Version from path, 4. Version from filename + regex: /bitbucket\.org\/([^/]+)\/([^/.]+)(?:\/(?:get|downloads)\/([^/]+))?\/([^/]+)?(?:\.zip|\.git)?$/i + } + ]; + + // 1. Try to match against Git providers (GitHub, GitLab, Bitbucket) + for (const p of providers) { + const match = cleanDep.match(p.regex); + if (match) { + let [_, author, repo, pathVer, fileVer] = match; + + // Prioritize version from path (typical in releases) over filename + let version = pathVer || fileVer || "latest"; + + // Clean up version string: remove extensions and 'v' prefix + version = version + .replace(/\.(zip|git|tar\.gz)$/i, '') + .replace(/^v(\d)/i, '$1'); // Removes 'v' only if followed by a number + + // Avoid redundancy if the version string is identical to the repo name + if (version.toLowerCase() === repo.toLowerCase()) { + version = "latest"; + } + + return `${repo} @ ${version} (${p.id}:${author})`; + } + } + + // 2. Fallback for Standard PlatformIO Registry format (e.g., owner/lib @ ^1.0.0) + if (cleanDep.includes('/') || cleanDep.includes('@')) { + const parts = cleanDep.split('@'); + const fullName = parts[0].trim(); // Includes owner/name + + // Clean up version if present + let version = "latest"; + if (parts[1]) { + version = parts[1].trim().replace(/^[\^~=]/, ''); + } + + // Separate owner and library name for consistent formatting + if (fullName.includes('/')) { + const [owner, libName] = fullName.split('/'); + return `${libName.trim()} @ ${version} (pio:${owner.trim()})`; + } + + return `${fullName} @ ${version}`; + } + + // 3. Return original string if no patterns match + return cleanDep; +} + +function rowConfigFromPlatformIO() { + const { execSync } = require('child_process'); + + try { + const jsonConfig = execSync('pio project config --json-output').toString(); + const config = JSON.parse(jsonConfig); + return config; + } catch (error) { + console.error("Make sure PlatformIO Core is installed and in PATH"); + throw error; + } +} + +function cleanValue(v) { + if (typeof v !== 'string') return v; + return v + .replace(/{/g, '') + .replace(/}/g, '') + .replace(/\$/g, '') + .replace(/env:/g, '') + .replace(/'/g, '') + .replace(/-D/g, ''); +} + +function convertJsonToSections(jsonConfig) { + const sections = {}; + jsonConfig.forEach(([sectionName, configArray]) => { + sections[sectionName] = {}; + configArray.forEach(([key, value]) => { + sections[sectionName][key] = value; + }); + }); + return sections; +} + +function cleanLibraries(raw) { + if (!raw) return []; + if (typeof raw === 'string') { + raw = raw.split(',') + } + return raw.map((dep) => smartFormat(dep)); +} + +function extractModulesFromFlags(flags) { + if (!flags) return []; + let flagArray = []; + if (Array.isArray(flags)) { + flagArray = flags; + } else if (typeof flags === 'string') { + flagArray = flags.split(',').map(s => s.trim()).filter(s => s.length > 0); + } else { + return []; + } + const modules = []; + flagArray.forEach((flag) => { + // Match -DZmoduleName, allowing surrounding quotes + const match = flag.match(/^['" ]*-DZ([^=]+)/); + if (match) { + const moduleName = match[1]; + // Additional constraint: must contain 'gateway', 'sensor', or 'actuator' + if (moduleName.includes('gateway') || moduleName.includes('sensor') || moduleName.includes('actuator')) { + modules.push(moduleName); + } + } + //if MQTT_BROKER_MODE = true then modules.push("MQTT Broker Mode"); + const brokerMatch = flag.match(/^['" ]*-DMQTT_BROKER_MODE(?:=([^'"\s]+))?/); + if (brokerMatch) { + const value = brokerMatch[1]; + // Add only if not explicitly set to false (case insensitive) + if (!value || value.toLowerCase() !== 'false') { + modules.push("MQTT Broker Mode"); + } + } + + }); + return modules; +} + +function collectBoardsInformations(sections, { includeTests = false } = {}) { + const rows = []; + + Object.entries(sections).forEach(([section, items]) => { + if (!section.includes('env:')) return; + if (!includeTests && section.includes('-test')) return; + + const env = section.replace('env:', ''); + let uc = ''; + let hardware = ''; + let description = ''; + let modules = []; + let platform = ''; + let partitions = ''; + let libraries = []; + let options = []; + let customImg = ''; + + Object.entries(items).forEach(([k, raw]) => { + const v = cleanValue(raw); + + + if (k === 'board') uc = v; + if (k === 'platform') platform = smartFormat(v); + if (k === 'board_build.partitions') partitions = v; + if (k === 'custom_description') description = v; + if (k === 'custom_hardware') hardware = v; + if (k === 'custom_img') customImg = v; + + if (k === 'lib_deps') { + libraries = cleanLibraries(raw); + } + + if (k === 'build_flags') { + options = v; + modules = extractModulesFromFlags(v); + } + }); + + rows.push({ + Environment: env, + uC: uc, + Hardware: hardware, + Description: description, + Modules: modules, + Platform: platform, + Partitions: partitions, + Libraries: libraries, + Options: options, + CustomImg: customImg + }); + }); + + rows.sort((a, b) => a.Environment.localeCompare(b.Environment, 'en', { sensitivity: 'base' })); + return rows; +} + +// pio project config resolves extra_configs, which pulls in user-specific +// files like prod_env.ini; only environments declared in environments.ini +// belong in the published boards list. +function publicEnvironmentNames() { + const fs = require('fs'); + const path = require('path'); + const ini = fs.readFileSync(path.resolve(__dirname, '..', 'environments.ini'), 'utf8'); + const names = new Set(); + for (const match of ini.matchAll(/^\[env:([^\]]+)\]/gm)) { + names.add(match[1].trim()); + } + return names; +} + +function loadBoardsInfo(options = {}) { + const { includeTests = false } = options; + const config = rowConfigFromPlatformIO(); + const sections = convertJsonToSections(config); + const rows = collectBoardsInformations(sections, { includeTests }); + const publicEnvs = publicEnvironmentNames(); + return rows.filter(row => publicEnvs.has(row.Environment)); +} + +function ensureDir(dir) { + const fs = require('fs'); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); +} + +module.exports = { + loadBoardsInfo, + ensureDir +}; diff --git a/docsgen/common_wu.js b/docsgen/common_wu.js new file mode 100644 index 0000000..bccc307 --- /dev/null +++ b/docsgen/common_wu.js @@ -0,0 +1,77 @@ +// Common templates and constants for web installer manifest generation +// Used by: scripts/gen_wu.js + +const mf_temp32 = (vars) => `{ + "name": "OpenMQTTGateway", + "new_install_prompt_erase": true, + "builds": [ + { + "chipFamily": "ESP32", + "improv": false, + "parts": [ + { "path": "${vars.cp}${vars.bl}", "offset": 4096 }, + { "path": "${vars.cp}${vars.part}", "offset": 32768 }, + { "path": "${vars.cp}${vars.boot}", "offset": 57344 }, + { "path": "${vars.cp}${vars.bin}", "offset": 65536 } + ] + } + ] +}`; + +const mf_temp32c3 = (vars) => `{ + "name": "OpenMQTTGateway", + "new_install_prompt_erase": true, + "builds": [ + { + "chipFamily": "ESP32-C3", + "improv": false, + "parts": [ + { "path": "${vars.cp}${vars.bl}", "offset": 0 }, + { "path": "${vars.cp}${vars.part}", "offset": 32768 }, + { "path": "${vars.cp}${vars.boot}", "offset": 57344 }, + { "path": "${vars.cp}${vars.bin}", "offset": 65536 } + ] + } + ] +}`; + +const mf_temp32s3 = (vars) => `{ + "name": "OpenMQTTGateway", + "new_install_prompt_erase": true, + "builds": [ + { + "chipFamily": "ESP32-S3", + "improv": false, + "parts": [ + { "path": "${vars.cp}${vars.bl}", "offset": 0 }, + { "path": "${vars.cp}${vars.part}", "offset": 32768 }, + { "path": "${vars.cp}${vars.boot}", "offset": 57344 }, + { "path": "${vars.cp}${vars.bin}", "offset": 65536 } + ] + } + ] +}`; + +const mf_temp8266 = (vars) => `{ + "name": "OpenMQTTGateway", + "new_install_prompt_erase": true, + "builds": [ + { + "chipFamily": "ESP8266", + "parts": [{ "path": "${vars.cp}${vars.bin}", "offset": 0 }] + } + ] +}`; + + +const cors_proxy = ''; // 'https://cors.bridged.cc/' +const esp32_boot = 'https://github.com/espressif/arduino-esp32/raw/2.0.7/tools/partitions/boot_app0.bin'; + +module.exports = { + mf_temp32, + mf_temp32c3, + mf_temp32s3, + mf_temp8266, + cors_proxy, + esp32_boot +}; diff --git a/docsgen/gen_wu.js b/docsgen/gen_wu.js new file mode 100644 index 0000000..ae83fbb --- /dev/null +++ b/docsgen/gen_wu.js @@ -0,0 +1,349 @@ +#!/usr/bin/env node + +// Creates web installer manifests for ESP Web Tools firmware installation + +const fs = require('fs'); +const path = require('path'); +const https = require('https'); +const { loadBoardsInfo, ensureDir } = require('./boards-info'); + +const { + mf_temp32, + mf_temp32c3, + mf_temp32s3, + mf_temp8266, + cors_proxy, + esp32_boot +} = require('./common_wu.js'); + +// ============================================================================ +// Directory Configuration +// ============================================================================ + +// Base directories +const ROOT_DIR = path.join(__dirname, '..'); +const DOCS_DIR = path.join(ROOT_DIR, 'docs'); +const VITEPRESS_DIR = path.join(DOCS_DIR, '.vitepress'); +const PUBLIC_DIR = path.join(VITEPRESS_DIR, 'public'); +const COMPONENTS_DIR = path.join(VITEPRESS_DIR, 'components'); +const ARTIFACTS_DIR = path.join(ROOT_DIR, 'generated', 'artifacts'); + +// Feature-specific directories +const FIRMWARE_SRC_DIR = path.join(ARTIFACTS_DIR, 'firmware_build'); +const FIRMWARE_BUILD_DIR = path.join(PUBLIC_DIR, 'firmware_build'); +const BOARDS_INFO_FILE = path.join(PUBLIC_DIR, 'boards-info.json'); + +// Configuration files +const DEFAULTS_CONFIG_PATH = path.join(VITEPRESS_DIR, 'defaults.json'); +const META_CONFIG_PATH = path.join(VITEPRESS_DIR, 'meta.json'); + + + +let meta = require(DEFAULTS_CONFIG_PATH); +try { + const meta_overload = require(META_CONFIG_PATH); + meta = { ...meta, ...meta_overload }; +} catch (e) { + console.warn('meta.json not found or not valid. Using default configuration.'); +} + +// Parse command line arguments +const args = process.argv.slice(2); +const dev = args.includes('--dev') || meta.mode === 'dev'; +const repo = meta.repo || '1technophile/OpenMQTTGateway'; +const firmwareManifestFolder = dev ? `/dev/firmware_build/` : `/firmware_build/`; + +// ============================================================================ +// Utility Functions +// ============================================================================ + +function ensureFirmwareArtifacts() { + if (!fs.existsSync(FIRMWARE_SRC_DIR)) { + throw new Error(`Missing firmware artifacts in ${FIRMWARE_SRC_DIR}. Run "ci.sh build ..." first to populate this folder.`); + } + console.log(`Found firmware artifacts in: ${FIRMWARE_SRC_DIR}`); +} +// Replace version_tag in template and write to destination +function renderVersionTemplate(templatePath, outputPath, version) { + if (!fs.existsSync(templatePath)) { + throw new Error(`Template not found: ${templatePath}`); + } + const content = fs.readFileSync(templatePath, 'utf8').replace(/version_tag/g, version); + fs.writeFileSync(outputPath, content); + console.log(`Generated version file from template: ${outputPath}`); +} + +/** + * Download file from URL + */ +function downloadFile(url) { + return new Promise((resolve, reject) => { + https.get(url, (response) => { + // Handle redirects + if (response.statusCode === 302 || response.statusCode === 301) { + return downloadFile(response.headers.location).then(resolve).catch(reject); + } + if (response.statusCode !== 200) { + return reject(new Error(`Failed to download: ${response.statusCode}`)); + } + const chunks = []; + response.on('data', (chunk) => chunks.push(chunk)); + response.on('end', () => resolve(Buffer.concat(chunks))); + response.on('error', reject); + }).on('error', reject); + }); +} + +/** + * Fetch JSON from URL + */ +function fetchJson(url) { + return new Promise((resolve, reject) => { + https.get(url, { headers: { 'User-Agent': 'OpenMQTTGateway-Script' } }, (response) => { + if (response.statusCode !== 200) { + return reject(new Error(`Failed to fetch: ${response.statusCode}`)); + } + let data = ''; + response.on('data', (chunk) => data += chunk); + response.on('end', () => { + try { + resolve(JSON.parse(data)); + } catch (e) { + reject(e); + } + }); + response.on('error', reject); + }).on('error', reject); + }); +} + +/** + * Download and save asset + */ +async function downloadAsset(asset, destPath) { + const buffer = await downloadFile(asset.browser_download_url); + const filename = asset.browser_download_url.split('/').pop(); + fs.writeFileSync(path.join(destPath, filename), buffer); + console.log(`Downloaded asset: ${filename} to ${destPath}`); +} + +/** + * Create manifest and Vue option for a firmware + * Partition path uses filename only (matches Python; split is redundant but harmless) + */ +function createManifest(name, templateFn) { + const fw = name.split('-firmware')[0]; + const man_file = fw + '.manifest.json'; + const fwp_name = fw + '-partitions.bin'; + const fwb_name = fw + '-bootloader.bin'; + + // Use filename to mirror Python behavior (no directories present today) + const partPath = fwp_name.split('/').pop(); + + const mani_str = templateFn({ + cp: cors_proxy, + part: firmwareManifestFolder + partPath, + bin: firmwareManifestFolder + name, + bl: firmwareManifestFolder + fwb_name, + boot: firmwareManifestFolder + esp32_boot.split('/').pop() + }); + + const outPath = path.join(FIRMWARE_BUILD_DIR, man_file); + fs.writeFileSync(outPath, mani_str); + console.log(`Created manifest for ${fw}: ${outPath}`); +} + +/** + * Create manifest for ESP8266 + * Python adds manif_folder when writing to file, not in return + */ +function createManifest8266(name) { + const fw = name.split('-firmware')[0]; + const man_file = fw + '.manifest.json'; + + const mani_str = mf_temp8266({ + cp: cors_proxy, + bin: firmwareManifestFolder + name + }); + + const outPath = path.join(FIRMWARE_BUILD_DIR, man_file); + fs.writeFileSync(outPath, mani_str); + console.log(`Created manifest for ${fw} (ESP8266): ${outPath}`); + +} + +/** + * Device type matchers + */ +const ESP32_NAMES = ['esp32', 'ttgo', 'heltec', 'thingpulse', 'theengs', 'lilygo', 'shelly', 'tinypico']; +const ESP8266_NAMES = ['nodemcu', 'sonoff', 'rf-wifi-gateway', 'manual-wifi-test', 'rfbridge']; + +const deviceMatchers = { + esp32: (name) => name.includes('firmware.bin') && + !name.includes('esp32c3') && !name.includes('esp32s3') && + ESP32_NAMES.some(key => name.includes(key)), + + esp32c3: (name) => name.includes('firmware.bin') && name.includes('esp32c3'), + + esp32s3: (name) => name.includes('firmware.bin') && name.includes('esp32s3'), + + esp8266: (name) => name.includes('firmware.bin') && + ESP8266_NAMES.some(key => name.includes(key)) +}; + +/** + * Setup dev environment + */ +async function setupDevEnvironment() { + console.log('DEV mode: preparing web upload files...'); + ensureFirmwareArtifacts(); + // Generate OTA latest version definition from template + const tpl = path.join(__dirname, 'latest_version_dev.json.tpl'); + renderVersionTemplate(tpl, path.join(FIRMWARE_BUILD_DIR, 'latest_version_dev.json'), meta.version); + + // Copy the binaries from FIRMWARE_SRC_DIR to FIRMWARE_BUILD_DIR + const files = fs.readdirSync(FIRMWARE_SRC_DIR); + let copied = 0; + for (const name of files) { + if (name.includes('.bin')) { + fs.copyFileSync( + path.join(FIRMWARE_SRC_DIR, name), + path.join(FIRMWARE_BUILD_DIR, name) + ); + copied++; + console.log(`Copied binary: ${name}`); + } + } + console.log(`Copied ${copied} firmware binaries to ${FIRMWARE_BUILD_DIR}`); +} + +/** + * Setup release environment + */ +async function setupReleaseEnvironment() { + console.log('RELEASE mode: downloading and preparing web upload files...'); + + // Generate OTA latest version definition from template + const tpl = path.join(__dirname, 'latest_version.json.tpl'); + renderVersionTemplate(tpl, path.join(FIRMWARE_BUILD_DIR, 'latest_version.json'), meta.version); + + const releaseUrl = `https://api.github.com/repos/${repo}/releases/latest`; + console.log(`Fetching latest release info from: ${releaseUrl}`); + const rel_data = await fetchJson(releaseUrl); + + if (!rel_data.assets) { + console.error('No assets found in the latest release!'); + process.exit(1); + } + + // Download all assets + let downloaded = 0; + for (const asset of rel_data.assets) { + const name = asset.name; + if (name.includes('firmware.bin') || + name.includes('partitions.bin') || + name.includes('bootloader.bin')) { + await downloadAsset(asset, FIRMWARE_BUILD_DIR); + downloaded++; + } + } + console.log(`Downloaded ${downloaded} firmware assets to ${FIRMWARE_BUILD_DIR}`); +} + +/** + * Process firmware files and generate manifests + */ +function processFirmwareFiles(files) { + let manifestCount = 0; + for (const name of files) { + if (deviceMatchers.esp32(name)) { + createManifest(name, mf_temp32); + manifestCount++; + } + if (deviceMatchers.esp32c3(name)) { + createManifest(name, mf_temp32c3); + manifestCount++; + } + if (deviceMatchers.esp32s3(name)) { + createManifest(name, mf_temp32s3); + manifestCount++; + } + if (deviceMatchers.esp8266(name)) { + createManifest8266(name); + manifestCount++; + } + } + console.log(`Generated ${manifestCount} manifest files in ${FIRMWARE_BUILD_DIR}`); + +} + +/** + * Main execution function + */ +// ===================== OpenMQTTGateway Web Uploader Manifest Generator ===================== +// ===================== MAIN SCRIPT STARTS HERE ===================== +async function main() { + console.log('================================================================================'); + console.log(' OpenMQTTGateway Web Uploader Manifest Generator - START'); + console.log('================================================================================'); + + // === [1] Load and generate boards info === + console.log('\n[1/4] Generating boards-info.json ...'); + const boardsInfo = loadBoardsInfo({ verbose: 0 }); + const boardsJson = boardsInfo.map((row) => ({ + environment: row.Environment, + hardware: row.Hardware, + description: row.Description, + microcontroller: row.uC, + modules: row.Modules.filter(Boolean), + platform: row.Platform, + partitions: row.Partitions, + libraries: row.Libraries.filter(Boolean), + options: row.Options, + customImg: row.CustomImg + })); + ensureDir(path.dirname(BOARDS_INFO_FILE)); + fs.writeFileSync(BOARDS_INFO_FILE, JSON.stringify(boardsJson, null, 2), 'utf8'); + console.log(`Generated boards-info.json with ${boardsJson.length} boards: ${BOARDS_INFO_FILE}`); + + // === [2] Ensure output directory === + console.log('\n[2/4] Ensuring output directory ...'); + ensureDir(FIRMWARE_BUILD_DIR); + console.log(`Ensured output directory exists: ${FIRMWARE_BUILD_DIR}`); + + // === [3] Setup environment (dev or release) === + console.log('\n[3/4] Preparing firmware files ...'); + try { + if (dev) { + await setupDevEnvironment(); + } else { + await setupReleaseEnvironment(); + } + } catch (error) { + console.error(`Error setting up environment: ${error.message}`); + process.exit(1); + } + + // === [4] Download boot binary and generate manifests === + console.log('\n[4/4] Downloading boot binary and generating manifests ...'); + console.log(`Downloading boot binary: ${esp32_boot}`); + const boot_bin = await downloadFile(esp32_boot); + const boot_filename = esp32_boot.split('/').pop(); + fs.writeFileSync(path.join(FIRMWARE_BUILD_DIR, boot_filename), boot_bin); + console.log(`Saved boot binary as: ${boot_filename}`); + + const files = fs.readdirSync(FIRMWARE_BUILD_DIR).sort(); + console.log(`Processing firmware files in ${FIRMWARE_BUILD_DIR}...`); + processFirmwareFiles(files); + + console.log('\n================================================================================'); + console.log(' OpenMQTTGateway Web Uploader Manifest Generator - END'); + console.log('================================================================================'); +} +// ===================== MAIN SCRIPT ENDS HERE ===================== + +// Run main function +main().catch(error => { + console.error('Fatal error:', error); + process.exit(1); +}); diff --git a/scripts/latest_version.json b/docsgen/latest_version.json.tpl similarity index 100% rename from scripts/latest_version.json rename to docsgen/latest_version.json.tpl diff --git a/scripts/latest_version_dev.json b/docsgen/latest_version_dev.json.tpl similarity index 100% rename from scripts/latest_version_dev.json rename to docsgen/latest_version_dev.json.tpl diff --git a/environments.ini b/environments.ini index 2929a13..0013819 100644 --- a/environments.ini +++ b/environments.ini @@ -24,9 +24,10 @@ board_build.ldscript = eagle.flash.1m64.ld ;this frees more space for firmware u ;extra_scripts = scripts/compressFirmware.py ;uncomment this to compress the firmware. This helps updating e.g. Sonoff RF Bridge via OTA flash by saving space for the uploaded firmware. custom_description = RF gateway for the Sonoff RF Bridge relying on the internal decoder custom_hardware = RFBridge v1 +custom_img = img/boards/sonoff-rf-bridge.jpg [env:rfbridge-direct] -platform = espressif8266@^2 +platform = ${com.esp8266_platform} board = esp8285 lib_deps = ${com-esp.lib_deps} @@ -42,16 +43,19 @@ build_flags = '-DZsensorGPIOInput="GPIOInput"' '-DINPUT_GPIO=0' '-DGateway_Name="OMG_SRFB_Direct"' + '-fcommon' board_build.flash_mode = dout board_build.ldscript = eagle.flash.1m64.ld ;this frees more space for firmware uplad via OTA. ;extra_scripts = scripts/compressFirmware.py ;uncomment this to compress the firmware. This helps updating e.g. Sonoff RF Bridge via OTA flash by saving space for the uploaded firmware. -custom_description = RF gateway for the Sonoff RF Bridge requiring direct hack, relying on ESPilight library, [tutorial](https://1technophile.blogspot.com/2019/04/sonoff-rf-bridge-pilight-or-how-to.html). +custom_description = 'RF gateway for the Sonoff RF Bridge requiring direct hack, relying on ESPilight library, tutorial.' custom_hardware = RFBridge v1 +custom_img = img/boards/sonoff-rf-bridge.jpg [env:theengs-bridge] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev -extra_scripts = ${com-esp32.extra_scripts} +board_build.flash_mode = qio board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -61,37 +65,142 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=2' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=2' + '-DLED_PIN_ON=0' '-DESP32_ETHERNET=true' '-DETH_PHY_TYPE=ETH_PHY_LAN8720' '-DETH_PHY_ADDR=0' '-DETH_PHY_POWER=5' '-DETH_PHY_MDC=23' '-DETH_PHY_MDIO=18' - '-DETH_CLK_MODE=ETH_CLOCK_GPIO16_OUT' - '-DANEOPIX_IND_DATA_GPIO=32' - '-DANEOPIX_IND_NUM_LEDS=4' - '-DANEOPIX_INFO_LED=0' - '-DANEOPIX_SEND_RECEIVE_LED=1' - '-DANEOPIX_ERROR_LED=1' - '-DANEOPIX_BRIGHTNESS=10' - '-DRGB_INDICATORS=true' + '-DETH_CLK_MODE=ETH_CLOCK_GPIO0_OUT' + '-DETH_PHY_COLD_CYCLE' + '-DLED_ADDRESSABLE_PIN1=32' + '-DLED_ADDRESSABLE_NUM=4' + '-DLED_BROKER=0' + '-DLED_PROCESSING=1' + '-DLED_ERROR=1' + '-DDEFAULT_ADJ_BRIGHTNESS=10' + '-DLED_ADDRESSABLE=true' '-DAttemptBLEConnect=false' '-DUSE_MAC_AS_GATEWAY_NAME' '-DGATEWAY_MANUFACTURER="Theengs"' '-DGATEWAY_MODEL="TBRIDGE01"' - ;'-DBOARD_HAS_PSRAM' - '-UZwebUI="WebUI"' ; Disable WebUI - ;'-mfix-esp32-psram-cache-issue' -custom_description = BLE gateway with external antenna and Ethernet/WiFi connectivity, [user guide](https://tbridge01.theengs.io/) + '-DBOARD_HAS_PSRAM' + '-mfix-esp32-psram-cache-issue' + '-mfix-esp32-psram-cache-strategy=memw' +custom_description = 'BLE gateway with external antenna and Ethernet/WiFi connectivity, user guide' custom_hardware = Theengs Bridge gateway ethernet +custom_img = img/Theengs-Bridge-ble-gateway.png + +[env:theengs-bridge-v11] +platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +board = esp32dev +board_build.flash_mode = qio +board_build.partitions = min_spiffs.csv +lib_deps = + ${com-esp32.lib_deps} + ${libraries.ble} + ${libraries.adafruit_neopixel} + ${libraries.decoder} +build_flags = + ${com-esp32.build_flags} + '-DZgatewayBT="BT"' + '-DESP32_ETHERNET=true' + '-DETH_PHY_TYPE=ETH_PHY_LAN8720' + '-DETH_PHY_ADDR=0' + '-DETH_PHY_POWER=5' + '-DETH_PHY_MDC=23' + '-DETH_PHY_MDIO=18' + '-DETH_CLK_MODE=ETH_CLOCK_GPIO0_OUT' + '-DETH_PHY_COLD_CYCLE' + '-DLED_ADDRESSABLE=true' + '-DLED_ADDRESSABLE_PIN1=32' + '-DLED_ADDRESSABLE_NUM=4' + '-DLED_ERROR=3' + '-DLED_PROCESSING=3' + '-DLED_BROKER=2' + '-DLED_NETWORK=1' + '-DLED_POWER=0' + '-DAttemptBLEConnect=false' + '-DTRIGGER_GPIO=4' + '-DUSE_MAC_AS_GATEWAY_NAME' + '-DGATEWAY_MANUFACTURER="Theengs"' + '-DGATEWAY_MODEL="TBRIDGE02"' + '-DBOARD_HAS_PSRAM' + '-mfix-esp32-psram-cache-issue' + '-mfix-esp32-psram-cache-strategy=memw' + ;'-DSELF_TEST=true' +custom_description = 'BLE gateway with external antenna and Ethernet/WiFi connectivity, user guide' +custom_hardware = Theengs Bridge gateway ethernet +custom_img = img/Theengs-Bridge-ble-gateway.png + +; DISCLAIMER: This is the default environment for Theengs Plug. +; Any modifications to this configuration are not covered by warranty. +; Proceed with caution when making changes. +; +; SAFETY WARNING: Do not modify values related to current limits MAX_CURRENT_ACTUATOR or other +; safety-critical parameters. Doing so may lead to fire hazards or damage to the device. +[env:theengs-plug] +platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +board = esp32dev +board_build.partitions = min_spiffs.csv +lib_deps = + ${com-esp32.lib_deps} + ${libraries.ble} + ${libraries.decoder} + ${libraries.adafruit_neopixel} + ${libraries.rn8209} +build_flags = + ${env.build_flags} + ${com-esp32.build_flags} + '-DZgatewayBT="BT"' + '-DZsensorRN8209="RN8209"' + '-DRN8209_KU=18570' + '-DRN8209_KIA=265263' + '-DRN8209_EC=26675' + '-DTRIGGER_GPIO=4' + '-DZactuatorONOFF="ONOFF"' + '-DACTUATOR_ON=1' + '-DACTUATOR_OFF=0' + '-DACTUATOR_BUTTON_TRIGGER_LEVEL=0' + '-DACTUATOR_TRIGGER=true' + '-DZsensorGPIOInput="GPIOInput"' + '-DINPUT_GPIO=4' + '-DACTUATOR_ONOFF_GPIO=25' + '-DAttemptBLEConnect=false' + '-DLED_ADDRESSABLE=true' + '-DLED_ADDRESSABLE_PIN1=26' + '-DLED_ADDRESSABLE_PIN2=27' + '-DLED_ADDRESSABLE_NUM=2' + '-DLED_ADDRESSABLE_POWER=16' + '-DLED_ERROR=0' + '-DLED_PROCESSING=0' + '-DLED_BROKER=0' + '-DLED_NETWORK=0' + '-DLED_ACTUATOR_ONOFF=1' + ; Maximum current in A DO NOT MODIFY MAX_CURRENT_ACTUATOR + ;----------------------------- + '-DMAX_CURRENT_ACTUATOR=15.0' + ;----------------------------- + '-DWM_PWD_FROM_MAC=true' + '-DUSE_MAC_AS_GATEWAY_NAME' + '-DDEFAULT_LOW_POWER_MODE=DEACTIVATED' + '-DWifiReconnectWatchDog=false' ; Don't reboot on persistent WiFi loss, it would interrupt the relay state + '-DGATEWAY_MANUFACTURER="Theengs"' + '-DGATEWAY_MODEL="TPLUG01"' + '-UZwebUI="WebUI"' ; Disable WebUI +custom_description = 'Smart Plug, BLE Gateway and energy monitoring, user guide' +custom_hardware = Theengs Plug +custom_img = img/Theengs-Plug-OpenMQTTGateway.png [env:esp32dev-all-test] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev -extra_scripts = ${com-esp32.extra_scripts} -board_build.partitions = min_spiffs.csv +board_build.partitions = partitions/alltest_large.csv lib_deps = ${com-esp32.lib_deps} ${libraries.ble} @@ -127,7 +236,7 @@ build_flags = '-DZgatewayBT="BT"' '-DZactuatorONOFF="ONOFF"' '-DACTUATOR_BUTTON_TRIGGER_LEVEL=0' - '-ACTUATOR_TRIGGER=true' + '-DACTUATOR_TRIGGER=true' '-DZactuatorFASTLED="FASTLED"' '-DZactuatorPWM="PWM"' '-DZsensorINA226="INA226"' @@ -160,6 +269,7 @@ build_flags = '-DMQTT_USER=""' '-DMQTT_PASS=""' '-DMQTT_PORT="1883"' + '-DMDNS_SD=true' '-DDEEP_SLEEP_IN_US=120000000' ; Deep sleep for a period of time to conserve battery '-DESP32_EXT0_WAKE_PIN=GPIO_NUM_14' ;Should a water leak be detected immediatly wake the ESP32 and report the problem '-DESP32_EXT0_WAKE_PIN_STATE=0' ;Should a water leak be detected immediatly wake the ESP32 and report the problem, sensor state to look for wakeup @@ -172,7 +282,9 @@ build_flags = [env:esp32dev-rf] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev +board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} ${libraries.rc-switch} @@ -180,11 +292,18 @@ build_flags = ${com-esp32.build_flags} '-DZgatewayRF="RF"' '-DGateway_Name="OMG_ESP32_RF"' + '-DvalueAsATopic=true' custom_description = RF gateway using RCSwitch library +custom_img = img/boards/esp32dev.jpg [env:esp32dev-pilight] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +extra_scripts = + pre:scripts/add_c_flags.py + pre:scripts/add_mlongcalls.py board = esp32dev +board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} ${libraries.esppilight} @@ -193,9 +312,14 @@ build_flags = '-DZgatewayPilight="Pilight"' '-DGateway_Name="OMG_ESP32_Pilight"' custom_description = RF gateway using ESPilight library +custom_img = img/boards/esp32dev.jpg [env:esp32dev-pilight-cc1101] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +extra_scripts = + pre:scripts/add_c_flags.py + pre:scripts/add_mlongcalls.py board = esp32dev board_build.partitions = min_spiffs.csv lib_deps = @@ -208,10 +332,13 @@ build_flags = '-DZradioCC1101="CC1101"' '-DGateway_Name="OMG_ESP32_Pilight-CC1101"' custom_description = Gateway using ESPilight library only, need CC1101 +custom_img = img/boards/esp32dev.jpg [env:esp32dev-somfy-cc1101] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev +board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} ${libraries.somfy_remote} @@ -222,9 +349,14 @@ build_flags = '-DZradioCC1101="CC1101"' '-DGateway_Name="OMG_ESP32_Somfy-CC1101"' custom_description = Gateway using Somfy Remote library, need CC1101 +custom_img = img/boards/esp32dev.jpg [env:esp32dev-pilight-somfy-cc1101] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +extra_scripts = + pre:scripts/add_c_flags.py + pre:scripts/add_mlongcalls.py board = esp32dev board_build.partitions = min_spiffs.csv lib_deps = @@ -239,10 +371,13 @@ build_flags = '-DZradioCC1101="CC1101"' '-DGateway_Name="OMG_ESP32_Pilight-Somfy-CC1101"' custom_description = Gateway using Somfy Remote and ESPilight library, need CC1101 +custom_img = img/boards/esp32dev.jpg [env:esp32dev-weatherstation] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev +board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} ${libraries.rfWeatherStation} @@ -251,10 +386,13 @@ build_flags = '-DZgatewayWeatherStation="WeatherStation"' '-DGateway_Name="OMG_ESP32_WeatherStation"' custom_description = Gateway to retrieve weather station data Ventus W174/W132 (tested), Auriol H13726, Hama EWS 1500, Meteoscan W155/W160 using WeatherStationDataRx +custom_img = img/boards/esp32dev.jpg [env:esp32dev-gf-sun-inverter] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev +board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} ${libraries.emodbus} @@ -264,9 +402,11 @@ build_flags = '-DZgatewayGFSunInverter="GFSunInverter"' '-DGateway_Name="OMG_ESP32_GFSunInverter"' custom_description = RS232 reading of GridFree Sun Inverter +custom_img = img/boards/esp32dev.jpg [env:esp32dev-ir] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev board_build.partitions = min_spiffs.csv lib_deps = @@ -277,11 +417,12 @@ build_flags = '-DZgatewayIR="IR"' '-DGateway_Name="OMG_ESP32_IR"' custom_description = Infrared (Emitting and receiving) using IRremoteESP8266 +custom_img = img/boards/esp32dev.jpg [env:esp32dev-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -290,33 +431,54 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=2' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=2' + '-DLED_PIN_ON=0' '-DGateway_Name="OMG_ESP32_BLE"' custom_description = Regular BLE gateway with adaptive scanning activated, automatically adapts the scan parameters depending on your devices +custom_img = img/boards/esp32dev.jpg + +[env:esp32dev-ble-broker] +platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +board = esp32dev +board_build.partitions = min_spiffs.csv +lib_deps = + ${com-esp32.lib_deps} + ${libraries.ble} + ${libraries.decoder} +build_flags = + ${com-esp32.build_flags} + '-DZgatewayBT="BT"' + '-DLED_PIN=2' + '-DLED_PIN_ON=0' + '-DGateway_Name="OMG_ESP32_BLE"' + '-DMQTT_BROKER_MODE=true' +custom_description = MQTT Broker with BLE gateway with adaptive scanning activated, automatically adapts the scan parameters depending on your devices +custom_img = img/boards/esp32dev.jpg [env:esp32dev-ble-mqtt-undecoded] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} ${libraries.ble} - ${libraries.decoder} build_flags = ${com-esp32.build_flags} + '-DBLEDecoder=false' '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=2' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=2' + '-DLED_PIN_ON=0' '-DGateway_Name="OMG_ESP32_BLE"' '-DMQTTDecodeTopic="undecoded"' custom_description = BLE gateway with the decoding offloaded to Theengs Gateway +custom_img = img/boards/esp32dev.jpg [env:esp32dev-ble-aws] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -326,22 +488,24 @@ build_flags = ${com-esp32.build_flags} '-UZmqttDiscovery="HADiscovery"' '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=2' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=2' + '-DLED_PIN_ON=0' + '-DARDUINO_LOOP_STACK_SIZE=17500' '-DMQTT_SECURE_DEFAULT=true' - '-DMQTT_SECURE_SELF_SIGNED' '-DMQTT_CERT_VALIDATE_DEFAULT=true' + '-DMQTT_SECURE_SIGNED_CLIENT=true' '-DMQTT_SERVER="xxxxxxxxxxxxx-ats.iot.eu-west-2.amazonaws.com"' '-DMQTT_PORT="8883"' '-DMQTT_USER=""' '-DMQTT_PASS=""' '-DAWS_IOT=true' custom_description = BLE gateway with AWS integration capability +custom_img = img/boards/esp32dev.jpg [env:esp32feather-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = featheresp32 -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -350,16 +514,17 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=13' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=13' + '-DLED_PIN_ON=0' '-DGateway_Name="OMG_ESP32_FTH_BLE"' custom_description = BLE Gateway custom_hardware = ESP32 Feather Adafruit +custom_img = img/boards/esp32-feather.jpg [env:esp32-lolin32lite-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = lolin32 -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -368,11 +533,11 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=22' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=22' + '-DLED_PIN_ON=0' '-DGateway_Name="OMG_LOLIN32LITE_BLE"' ;; Low power parameters, uncomment and fill credentials - '-DDEFAULT_LOW_POWER_MODE=2' + '-DDEFAULT_LOW_POWER_MODE=INTERVAL' ; '-DTimeBtwRead=155000' ; '-DScan_duration=2000' ; '-DAttemptBLEConnect=false' @@ -383,13 +548,14 @@ build_flags = ; '-DMQTT_SERVER="192.168.1.17"' ; '-Dwifi_ssid="WIFI_SSID"' ; '-Dwifi_password="WIFI_PASSWORD"' -custom_description = Suitable for low power with BLE gateway, [tutorial](https://1technophile.blogspot.com/2021/04/low-power-esp32-ble-gateway.html) +custom_description = 'Suitable for low power with BLE gateway, tutorial' custom_hardware = LOLIN 32 Lite +custom_img = img/boards/lolin32-lite.jpg [env:esp32-olimex-gtw-ble-eth] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-gateway -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -398,18 +564,19 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=33' - '-DLED_SEND_RECEIVE_ON=1' + '-DLED_PIN=33' + '-DLED_PIN_ON=1' '-DTRIGGER_GPIO=34' '-DESP32_ETHERNET=true' '-DGateway_Name="OMG_ESP32_OLM_GTWE"' custom_description = BLE gateway using ethernet or wifi custom_hardware = OLIMEX ESP32 Gateway +custom_img = img/boards/olimex-esp32-gateway.jpg [env:esp32-olimex-gtw-ble-poe] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-poe -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -422,11 +589,12 @@ build_flags = '-DGateway_Name="OMG_ESP32_OLM_POE"' custom_description = BLE gateway using ethernet, need to be configured through PIO custom_hardware = OLIMEX ESP32 Gateway with POE +custom_img = img/boards/olimex-esp32-poe.jpg [env:esp32-olimex-gtw-ble-poe-iso] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-poe-iso -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -439,11 +607,12 @@ build_flags = '-DGateway_Name="OMG_ESP32_OLM_POE"' custom_description = BLE gateway using ethernet, need to be configured through PIO custom_hardware = OLIMEX ESP32 Gateway with POE and ISO +custom_img = img/boards/olimex-esp32-poe-iso.jpg [env:esp32-wt32-eth01-ble-eth] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-gateway -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -459,11 +628,12 @@ build_flags = '-DGateway_Name="OMG_ESP32_WT32-ETH01"' custom_description = BLE gateway using ethernet, need to be configured through PIO custom_hardware = WT32 +custom_img = img/boards/wt32-eth01.jpg [env:esp32-olimex-gtw-ble-wifi] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-gateway -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -478,12 +648,13 @@ build_flags = '-DGateway_Name="OMG_ESP32_OLM_GTWW"' custom_description = BLE gateway using wifi custom_hardware = OLIMEX ESP32 Gateway +custom_img = img/boards/olimex-esp32-gateway.jpg [env:esp32-m5stick-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = m5stack-core-esp32 -extra_scripts = ${com-esp32.extra_scripts} -board_build.partitions = min_spiffs.csv +board_build.partitions = partitions/no_coredump.csv lib_deps = ${com-esp32.lib_deps} ${libraries.ble} @@ -493,24 +664,25 @@ build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' '-DZgatewayIR="IR"' - '-DLED_SEND_RECEIVE=19' - '-DLED_SEND_RECEIVE_ON=1' + '-DLED_PIN=19' + '-DLED_PIN_ON=1' '-DTRIGGER_GPIO=35' '-DIR_EMITTER_GPIO=17' - '-DDEFAULT_LOW_POWER_MODE=0' + '-DDEFAULT_LOW_POWER_MODE=ALWAYS_ON' '-DGateway_Name="OMG_ESP32_M5STICK_BLE_IR"' board_upload.speed = 921600 custom_description = Expandable module with BLE gateway, display, and little IR emitter custom_hardware = M5Stick Grey +custom_img = img/boards/m5stick.webp [env:esp32-m5stack-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = m5stack-core-esp32 -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} - ${libraries.m5stack} + ${libraries.m5unified} ${libraries.ble} ${libraries.decoder} build_flags = @@ -518,24 +690,25 @@ build_flags = '-DZgatewayBT="BT"' '-DZsensorGPIOInput="GPIOInput"' '-DZboardM5STACK="M5Stack"' - '-DLED_SEND_RECEIVE=15' + '-DLED_PIN=15' '-DTRIGGER_GPIO=37' '-DSLEEP_BUTTON=38' '-DINPUT_GPIO=39' - '-DDEFAULT_LOW_POWER_MODE=0' + '-DDEFAULT_LOW_POWER_MODE=ALWAYS_ON' '-DGateway_Name="OMG_ESP32_M5STACK_BLE"' board_upload.speed = 921600 custom_description = Expandable module with BLE gateway and display custom_hardware = M5Stack Core +custom_img = img/boards/m5stack-core.webp [env:esp32-m5tough-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = m5stack-core-esp32 -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} - ${libraries.m5tough} + ${libraries.m5unified} ${libraries.ble} ${libraries.decoder} build_flags = @@ -546,17 +719,26 @@ build_flags = board_upload.speed = 921600 custom_description = Expandable module with BLE gateway and display, suitable for outdoor custom_hardware = M5Tough rugged +custom_img = img/boards/m5tough.webp [env:esp32-m5stick-c-ble] platform = ${com.esp32_platform} -board = m5stick-c -extra_scripts = ${com-esp32.extra_scripts} -board_build.partitions = min_spiffs.csv +platform_packages = ${com.esp32_platform_packages} +; The modern framework dropped the "m5stick_c" board variant (no +; pins_arduino.h), so target the identical ESP32-PICO-D4 "pico32" variant +; instead — the same silicon the M5StickC-Plus env already uses. M5Unified +; detects the real StickC at runtime, and OMG defines every StickC GPIO +; explicitly below, so the variant's pin defaults are irrelevant. +board = pico32 +; M5Unified is much larger than the old M5StickC lib and overflows min_spiffs' +; 0x1E0000 app slot (~1.9 MB) once IR is also enabled; use the 0x1F0000 layout +; the M5StickC-Plus env already uses. +board_build.partitions = partitions/no_coredump.csv lib_deps = ${com-esp32.lib_deps} ${libraries.ble} ${libraries.decoder} - ${libraries.m5stickc} + ${libraries.m5unified} ${libraries.irremoteesp} build_flags = ${com-esp32.build_flags} @@ -566,28 +748,29 @@ build_flags = '-DZboardM5STICKC="M5StickC"' '-DACTUATOR_ONOFF_GPIO=10' '-DINPUT_GPIO=37' - '-DLED_SEND_RECEIVE=10' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=10' + '-DLED_PIN_ON=0' '-DSLEEP_BUTTON=39' '-DTRIGGER_GPIO=39' '-DIR_EMITTER_INVERTED=true' '-DIR_EMITTER_GPIO=9' - '-DDEFAULT_LOW_POWER_MODE=0' + '-DDEFAULT_LOW_POWER_MODE=ALWAYS_ON' '-DGateway_Name="OMG_ESP32_M5STICK_C_BLE_IR"' board_upload.speed = 1500000 custom_description = Expandable module with BLE gateway, display, and little IR emitter custom_hardware = M5Stick C +custom_img = img/boards/m5stick-c.webp [env:esp32-m5stick-cp-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = pico32 -extra_scripts = ${com-esp32.extra_scripts} -board_build.partitions = min_spiffs.csv +board_build.partitions = partitions/no_coredump.csv lib_deps = ${com-esp32.lib_deps} ${libraries.ble} ${libraries.decoder} - ${libraries.m5stickcp} + ${libraries.m5unified} ${libraries.irremoteesp} build_flags = ${com-esp32.build_flags} @@ -597,23 +780,24 @@ build_flags = '-DZboardM5STICKCP="M5StickCP"' '-DACTUATOR_ONOFF_GPIO=10' '-DINPUT_GPIO=37' - '-DLED_SEND_RECEIVE=10' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=10' + '-DLED_PIN_ON=0' '-DSLEEP_BUTTON=39' '-DTRIGGER_GPIO=39' '-DIR_EMITTER_INVERTED=true' '-DIR_EMITTER_GPIO=9' - '-DDEFAULT_LOW_POWER_MODE=0' + '-DDEFAULT_LOW_POWER_MODE=ALWAYS_ON' '-DGateway_Name="OMG_ESP32_M5STICK_CP_BLE_IR"' board_upload.speed = 1500000 custom_description = Expandable module with BLE gateway, display, and little IR emitter custom_hardware = M5Stick CP +custom_img = img/boards/m5stick-c-plus.webp [env:esp32-m5atom-matrix] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = pico32 -extra_scripts = ${com-esp32.extra_scripts} -board_build.partitions = min_spiffs.csv +board_build.partitions = partitions/no_coredump.csv lib_deps = ${com-esp32.lib_deps} ${libraries.ble} @@ -627,19 +811,25 @@ build_flags = '-DTRIGGER_GPIO=39' '-DSLEEP_BUTTON=39' '-DIR_EMITTER_GPIO=12' - '-DANEOPIX_IND_DATA_GPIO=27' - '-DANEOPIX_IND_NUM_LEDS=25' - '-DRGB_INDICATORS=true' + '-DLED_ADDRESSABLE_PIN1=27' + '-DLED_ADDRESSABLE_NUM=25' + '-DLED_ADDRESSABLE=true' + '-DLED_ERROR=4' + '-DLED_PROCESSING=3' + '-DLED_BROKER=2' + '-DLED_NETWORK=1' + '-DLED_POWER=0' '-DGateway_Name="OMG_ATOM_M"' board_upload.speed = 1500000 custom_description = Compact enclosure ESP32 with BLE gateway custom_hardware = M5 ATOM Matrix +custom_img = img/boards/m5atom-matrix.webp [env:esp32-m5atom-lite] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = pico32 -extra_scripts = ${com-esp32.extra_scripts} -board_build.partitions = min_spiffs.csv +board_build.partitions = partitions/no_coredump.csv lib_deps = ${com-esp32.lib_deps} ${libraries.ble} @@ -653,16 +843,18 @@ build_flags = '-DTRIGGER_GPIO=39' '-DSLEEP_BUTTON=39' '-DIR_EMITTER_GPIO=12' - '-DANEOPIX_IND_DATA_GPIO=27' - '-DANEOPIX_IND_NUM_LEDS=1' - '-DRGB_INDICATORS=true' + '-DLED_ADDRESSABLE_PIN1=27' + '-DLED_ADDRESSABLE_NUM=1' + '-DLED_ADDRESSABLE=true' '-DGateway_Name="OMG_ATOM_L"' board_upload.speed = 1500000 custom_description = Compact enclosure ESP32 with BLE gateway custom_hardware = M5 ATOM Lite +custom_img = img/boards/m5atom-lite.webp [env:esp32doitv1-aithinker-r01-sx1278] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32doit-devkit-v1 board_build.partitions = min_spiffs.csv lib_deps = @@ -711,6 +903,7 @@ board_upload.speed = 921600 board_upload.port = /dev/cu.usbserial-0001 board_monitor.speed = 921600 board_monitor.port = /dev/cu.usbserial-0001 +custom_img = img/boards/esp32doitv1.jpg [env:esp32doitv1-aithinker-r01-sx1278-hcsr501-test] extends = env:esp32doitv1-aithinker-r01-sx1278 @@ -742,6 +935,7 @@ upload_flags = [env:esp32dev-rtl_433] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev board_build.partitions = min_spiffs.csv lib_deps = @@ -779,9 +973,57 @@ build_flags = ; '-DRADIOLIB_DEBUG=true'< ; '-DRADIOLIB_VERBOSE=true' custom_description = Gateway using RTL_433_ESP library, need CC1101 +custom_img = img/boards/esp32dev.jpg + +[env:esp32dev-rtl_433-fsk] +platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +board = esp32dev +board_build.partitions = min_spiffs.csv +lib_deps = + ${com-esp32.lib_deps} + ${libraries.rtl_433_ESP} + ${libraries.smartrc-cc1101-driver-lib} +build_flags = + ${com-esp32.build_flags} +; *** OpenMQTTGateway Config *** + ;'-UZmqttDiscovery' ; disables MQTT Discovery + '-DvalueAsATopic=true' ; MQTT topic includes model and device + '-DLOG_LEVEL=LOG_LEVEL_TRACE' + '-DGateway_Name="OMG_rtl_433_ESP_FSK"' +; *** OpenMQTTGateway Modules *** + '-DOOK_MODULATION=false' ; FSK modulation activated + ;'-DRF_FREQUENCY=915' + '-DRF_FREQUENCY=868.300' + ;-DRF_FREQUENCY=433.9' + '-DZgatewayRTL_433="rtl_433"' + '-DZradioCC1101="CC1101"' +; *** rtl_433_ESP Options *** +; '-DRTL_DEBUG=4' ; rtl_433 verbose mode +; '-DRTL_VERBOSE=58' ; LaCrosse TX141-Bv2, TX141TH-Bv2, TX141-Bv3, TX141W, TX145wsdth sensor +; '-DRAW_SIGNAL_DEBUG=true' ; display raw received messages +; '-DMEMORY_DEBUG=true' ; display memory usage information + '-DDEMOD_DEBUG=true' ; display signal debug info +; '-DMY_DEVICES=true' ; subset of devices + '-DPUBLISH_UNPARSED=true' ; publish unparsed signal details +; '-DRSSI_THRESHOLD=12' ; Apply a delta of 12 to average RSSI level +; '-DAVERAGE_RSSI=5000' ; Display RSSI floor ( Average of 5000 samples ) + '-DSIGNAL_RSSI=true' ; Display during signal receive + '-DNO_DEAF_WORKAROUND=true' +; *** RF Module Options *** + '-DRF_CC1101="CC1101"' ; CC1101 Transceiver Module +; '-DRF_MODULE_CS=5' ; pin to be used as chip select + '-DRF_MODULE_GDO0=12' ; CC1101 pin GDO0 + '-DRF_MODULE_GDO2=27' ; CC1101 pin GDO2 +; *** RadioLib Options *** +; '-DRADIOLIB_DEBUG=true' +; '-DRADIOLIB_VERBOSE=true' +custom_description = Gateway using RTL_433_ESP library and RadioLib with FSK modulation (beta), need CC1101 +custom_img = img/boards/esp32dev.jpg [env:heltec-rtl_433] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = heltec_wifi_lora_32_V2 ; ~/.platformio/packages/framework-arduinoespressif32/variants/.../pins_arduino.h board_build.partitions = min_spiffs.csv @@ -794,7 +1036,7 @@ build_flags = ; *** OpenMQTTGateway Config *** ;'-UZmqttDiscovery' ; disables MQTT Discovery '-DvalueAsATopic=true' ; MQTT topic includes model and device - '-DGateway_Name="OMG_heltec_rtl_433_ESP"' + '-DGateway_Name="OMG_heltec_rtl_433_ESP_OOK"' ; *** OpenMQTTGateway Modules *** '-DZgatewayRTL_433="rtl_433"' '-DZradioSX127x="SX127x"' @@ -808,9 +1050,11 @@ build_flags = ; '-DDISPLAY_METRIC=false' custom_description = Gateway using RTL_433_ESP and RadioLib custom_hardware = ESP32 HELTEC LORA32 V2 +custom_img = img/boards/heltec-wifi-lora-32.png [env:heltec-rtl_433-fsk] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = heltec_wifi_lora_32_V2 ; ~/.platformio/packages/framework-arduinoespressif32/variants/.../pins_arduino.h board_build.partitions = min_spiffs.csv @@ -823,7 +1067,7 @@ build_flags = ; *** OpenMQTTGateway Config *** ;'-UZmqttDiscovery' ; disables MQTT Discovery '-DvalueAsATopic=true' ; MQTT topic includes model and device - '-DGateway_Name="OMG_heltec_rtl_433_ESP"' + '-DGateway_Name="OMG_heltec_rtl_433_ESP_FSK"' '-DOOK_MODULATION=false' ; FSK modulation activated '-DRF_FREQUENCY=915' ;-DRF_FREQUENCY=868.300' @@ -841,11 +1085,12 @@ build_flags = ; '-DDISPLAY_METRIC=false' custom_description = Gateway using RTL_433_ESP and RadioLib with FSK modulation (beta) custom_hardware = ESP32 HELTEC LORA32 V2 +custom_img = img/boards/heltec-wifi-lora-32.png [env:heltec-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = heltec_wifi_lora_32_V2 -extra_scripts = ${com-esp32.extra_scripts} ; ~/.platformio/packages/framework-arduinoespressif32/variants/.../pins_arduino.h board_build.partitions = min_spiffs.csv lib_deps = @@ -866,9 +1111,11 @@ build_flags = ; '-DDISPLAY_METRIC=false' custom_description = Heltec BLE gateway with adaptive scanning activated, automatically adapts the scan parameters depending on your devices custom_hardware = ESP32 HELTEC LORA32 V2 +custom_img = img/boards/heltec-wifi-lora-32.png [env:lilygo-rtl_433] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = ttgo-lora32-v21 ; ~/.platformio/packages/framework-arduinoespressif32/variants/.../pins_arduino.h board_build.partitions = min_spiffs.csv @@ -881,7 +1128,7 @@ build_flags = ; *** OpenMQTTGateway Config *** ;'-UZmqttDiscovery' ; disables MQTT Discovery '-DvalueAsATopic=true' ; MQTT topic includes model and device - '-DGateway_Name="OMG_lilygo_rtl_433_ESP"' + '-DGateway_Name="OMG_lilygo_rtl_433_ESP_OOK"' ; *** OpenMQTTGateway Modules *** '-DZgatewayRTL_433="rtl_433"' '-DZradioSX127x="SX127x"' @@ -895,9 +1142,11 @@ build_flags = ; '-DDISPLAY_METRIC=false' custom_description = For ESP32, Gateway using RTL_433_ESP and RadioLib custom_hardware = ESP32 LILYGO LoRa32 V2.1 +custom_img = img/boards/lilygo-lora32-v21.jpg [env:lilygo-rtl_433-fsk] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = ttgo-lora32-v21 ; ~/.platformio/packages/framework-arduinoespressif32/variants/.../pins_arduino.h board_build.partitions = min_spiffs.csv @@ -910,7 +1159,7 @@ build_flags = ; *** OpenMQTTGateway Config *** ;'-UZmqttDiscovery' ; disables MQTT Discovery '-DvalueAsATopic=true' ; MQTT topic includes model and device - '-DGateway_Name="OMG_lilygo_rtl_433_ESP"' + '-DGateway_Name="OMG_lilygo_rtl_433_ESP_FSK"' '-DOOK_MODULATION=false' ; FSK modulation activated '-DRF_FREQUENCY=915' ;-DRF_FREQUENCY=868.300' @@ -928,11 +1177,110 @@ build_flags = ; '-DDISPLAY_METRIC=false' custom_description = For ESP32, Gateway using RTL_433_ESP and RadioLib with FSK modulation (beta) custom_hardware = ESP32 LILYGO LoRa32 V2.1 +custom_img = img/boards/lilygo-lora32-v21.jpg + +[env:lilygo-t3-s3-rtl_433] +platform = espressif32@6.10.0 +board = lilygo-t3-s3 +board_build.partitions = min_spiffs.csv +lib_deps = + ${com-esp32.lib_deps} + ${libraries.ssd1306} + ${libraries.rtl_433_ESP} +build_flags = + ${com-esp32.build_flags} +; *** OpenMQTTGateway Config *** + ;'-UZmqttDiscovery' ; disables MQTT Discovery + '-DvalueAsATopic=true' ; MQTT topic includes model and device + '-DGateway_Name="OMG_lilygo_rtl_433_ESP_OOK"' +; *** OpenMQTTGateway Modules *** + '-DZgatewayRTL_433="rtl_433"' + '-DZradioSX127x="SX127x"' +; *** ssd1306 Display Options *** + '-DZdisplaySSD1306="LilyGo_SSD1306"' + '-DGenericSSD1306=true' +; '-DLOG_TO_OLED=true' ; Enable log to OLED +; '-DJSON_TO_OLED=true' +; '-DLOG_LEVEL_OLED=LOG_LEVEL_NOTICE' +; '-DDISPLAY_IDLE_LOGO=false' +; '-DDISPLAY_BRIGHTNESS=80' +; '-DDISPLAY_METRIC=false' + + '-DNO_INT_TEMP_READING=true' + ; '-DLED_PIN=37' + '-DOLED_SDA=18' ; SSD1306 pin SDA + '-DOLED_SCL=17' ; SSD1306 pin SCL + '-DRF_SX1276="SX1276"' + '-DRF_MODULE_SCK=5' + '-DRF_MODULE_MISO=3' + '-DRF_MODULE_MOSI=6' + '-DRF_MODULE_CS=7' + '-DRF_MODULE_RST=8' + '-DRF_MODULE_DIO0=9' + '-DRF_MODULE_DIO1=33' + '-DRF_MODULE_DIO2=34' + '-DRF_MODULE_DIO3=21' + '-DRF_MODULE_DIO4=10' + '-DRF_MODULE_DIO5=36' +custom_description = For ESP32, Gateway using RTL_433_ESP and RadioLib with FSK modulation (beta) +custom_hardware = ESP32 LILYGO T3-S3 SX1276 v1.0 +custom_img = img/boards/lilygo-t3-s3.jpg + +[env:lilygo-t3-s3-rtl_433-fsk] +platform = espressif32@6.10.0 +board = lilygo-t3-s3 +board_build.partitions = min_spiffs.csv +lib_deps = + ${com-esp32.lib_deps} + ${libraries.ssd1306} + ${libraries.rtl_433_ESP} +build_flags = + ${com-esp32.build_flags} +; *** OpenMQTTGateway Config *** + ;'-UZmqttDiscovery' ; disables MQTT Discovery + '-DvalueAsATopic=true' ; MQTT topic includes model and device + '-DGateway_Name="OMG_lilygo_rtl_433_ESP_FSK"' + '-DOOK_MODULATION=false' ; FSK modulation activated + '-DRF_FREQUENCY=915' + ;-DRF_FREQUENCY=868.300' + ;-DRF_FREQUENCY=433.9' +; *** OpenMQTTGateway Modules *** + '-DZgatewayRTL_433="rtl_433"' + '-DZradioSX127x="SX127x"' +; *** ssd1306 Display Options *** + '-DZdisplaySSD1306="LilyGo_SSD1306"' + '-DGenericSSD1306=true' +; '-DLOG_TO_OLED=true' ; Enable log to OLED +; '-DJSON_TO_OLED=true' +; '-DLOG_LEVEL_OLED=LOG_LEVEL_NOTICE' +; '-DDISPLAY_IDLE_LOGO=false' +; '-DDISPLAY_BRIGHTNESS=80' +; '-DDISPLAY_METRIC=false' + + '-DNO_INT_TEMP_READING=true' + ; '-DLED_PIN=37' + '-DOLED_SDA=18' ; SSD1306 pin SDA + '-DOLED_SCL=17' ; SSD1306 pin SCL + '-DRF_SX1276="SX1276"' + '-DRF_MODULE_SCK=5' + '-DRF_MODULE_MISO=3' + '-DRF_MODULE_MOSI=6' + '-DRF_MODULE_CS=7' + '-DRF_MODULE_RST=8' + '-DRF_MODULE_DIO0=9' + '-DRF_MODULE_DIO1=33' + '-DRF_MODULE_DIO2=34' + '-DRF_MODULE_DIO3=21' + '-DRF_MODULE_DIO4=10' + '-DRF_MODULE_DIO5=36' +custom_description = For ESP32, Gateway using RTL_433_ESP and RadioLib with FSK modulation (beta) +custom_hardware = ESP32 LILYGO T3-S3 SX1276 v1.0 +custom_img = img/boards/lilygo-t3-s3.jpg [env:lilygo-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = ttgo-lora32-v21 -extra_scripts = ${com-esp32.extra_scripts} ; ~/.platformio/packages/framework-arduinoespressif32/variants/.../pins_arduino.h board_build.partitions = min_spiffs.csv lib_deps = @@ -953,9 +1301,11 @@ build_flags = ; '-DDISPLAY_METRIC=false' custom_description = LilyGo BLE gateway with adaptive scanning activated, automatically adapts the scan parameters depending on your devices custom_hardware = ESP32 LILYGO LoRa32 V2.1 +custom_img = img/boards/lilygo-lora32-v21.jpg [env:esp32dev-multi_receiver] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev board_build.partitions = min_spiffs.csv lib_deps = @@ -979,9 +1329,14 @@ build_flags = '-DRF_MODULE_GDO2=27' ; CC1101 pin GDO2 ; '-DRF_MODULE_INIT_STATUS=true' ; Display transceiver config during startup custom_description = Multi RF library with the possibility to switch between RTL_433_ESP, NewRemoteSwitch and RCSwitch, need CC1101 +custom_img = img/boards/esp32dev.jpg [env:esp32dev-multi_receiver-pilight] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +extra_scripts = + pre:scripts/add_c_flags.py + pre:scripts/add_mlongcalls.py board = esp32dev board_build.partitions = min_spiffs.csv lib_deps = @@ -1005,11 +1360,12 @@ build_flags = '-DRF_MODULE_GDO2=27' ; CC1101 pin GDO2 ; '-DRF_MODULE_INIT_STATUS=true' ; Display transceiver config during startup custom_description = Multi RF library with the possibility to switch between ESPilight, NewRemoteSwitch and RCSwitch, need CC1101 +custom_img = img/boards/esp32dev.jpg [env:tinypico-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = tinypico -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -1022,10 +1378,13 @@ build_flags = board_build.flash_mode = dio custom_description = BLE gateway custom_hardware = ESP32 TinyPICO +custom_img = img/boards/tinypico.jpg [env:ttgo-lora32-v1] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = ttgo-lora32-v1 +board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} ${libraries.ssd1306} @@ -1042,10 +1401,13 @@ build_flags = '-DGateway_Name="OMG_ESP32_LORA"' custom_description = LORA communication using arduino-LoRA configurable frequency custom_hardware= ESP32 TTGO LORA V1 +custom_img = img/boards/ttgo-lora32-v1.jpg [env:ttgo-lora32-v21] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = ttgo-lora32-v21 +board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} ${libraries.ssd1306} @@ -1067,13 +1429,14 @@ build_flags = ; '-DDISPLAY_METRIC=false' custom_description = For ESP32, Gateway using LORA custom_hardware = ESP32 LILYGO LoRa32 V2.1 +custom_img = img/boards/lilygo-lora32-v21.jpg [env:ttgo-t-beam] # See version pinout differences here # https://www.thethingsnetwork.org/forum/t/big-esp32-sx127x-topic-part-3/18436 platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = ttgo-t-beam -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -1085,11 +1448,11 @@ build_flags = '-DZgatewayLORA="LORA"' '-DZgatewayBT="BT"' '-DGateway_Name="OMG_ESP32_BLE_LORA"' - '-DLED_SEND_RECEIVE=21' # T-BEAM board V0.5 -# '-DLED_SEND_RECEIVE=14' # T-BEAM board V0.7 -# '-DLED_SEND_RECEIVE=4' # T-BEAM board V1.0+ + '-DLED_PIN=21' # T-BEAM board V0.5 +# '-DLED_PIN=14' # T-BEAM board V0.7 +# '-DLED_PIN=4' # T-BEAM board V1.0+ '-DTimeLedON=0.05' - '-DLED_SEND_RECEIVE_ON=1' # Set 0 for board V1.0+ + '-DLED_PIN_ON=1' # Set 0 for board V1.0+ # for V0.5 and V0.7 ONLY (V1.0+ as onboard AXP202 dedicated chip, need driver) # it's a 100K/100K divider (so 2 divider) and connected to GPIO35 '-DZsensorADC="ADC"' @@ -1099,10 +1462,13 @@ build_flags = '-DTimeBetweenReadingADC=60000' custom_description = BLE gateway with battery holder custom_hardware = TTGO T BEAM +custom_img = img/boards/ttgo-t-beam.jpg [env:heltec-wifi-lora-32] ; Heltec ESP32 Board with SSD1306 display platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = heltec_wifi_lora_32 +board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} ${libraries.lora} @@ -1113,9 +1479,9 @@ build_flags = '-DZgatewayLORA="LORA"' '-DLORA_BAND=868E6' '-DGateway_Name="OMG_ESP32_LORA"' - '-DLED_SEND_RECEIVE=25' + '-DLED_PIN=25' '-DTimeLedON=0.1' - '-DLED_SEND_RECEIVE_ON=1' + '-DLED_PIN_ON=1' ; *** ssd1306 Display Options *** '-DZdisplaySSD1306="HELTEC_SSD1306"' ; '-DLOG_TO_OLED=true' ; Enable log to OLED @@ -1128,10 +1494,10 @@ custom_description = LORA communication using arduino-LoRA custom_hardware = ESP32 HELTEC LORA32 ; For testing only, not for production use +custom_img = img/boards/heltec-wifi-lora-32.png [env:shelly-plus1] platform = ${com.esp32_solo_platform} board = esp32-solo1 -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -1161,6 +1527,7 @@ build_flags = '-DGATEWAY_MODEL="SPLUS1"' custom_description = BLE, Relay control, Switch custom_hardware = Shelly Plus 1 +custom_img = img/boards/shelly-plus1.jpg [env:nodemcuv2-all-test] platform = ${com.esp8266_platform} @@ -1249,6 +1616,7 @@ build_flags = '-DGateway_Name="OMG_ESP8266_2G"' board_build.flash_mode = dout custom_description = SMS gateway, need A6/A7 GSM module +custom_img = img/boards/nodemcuv2.jpg [env:nodemcuv2-ir] platform = ${com.esp8266_platform} @@ -1264,8 +1632,9 @@ build_flags = '-DGateway_Name="OMG_ESP8266_IR"' board_build.flash_mode = dout custom_description = Infrared gateway using IRremoteESP8266 +custom_img = img/boards/nodemcuv2.jpg -[env:nodemcuv2-rs232] +[env:nodemcuv2-serial] platform = ${com.esp8266_platform} board = nodemcuv2 lib_deps = @@ -1274,10 +1643,11 @@ lib_deps = ${libraries.esp8266_mdns} build_flags = ${com-esp.build_flags} - '-DZgatewayRS232="RS232"' - '-DGateway_Name="OMG_ESP8266_RS232"' + '-DZgatewaySERIAL="SERIAL"' + '-DGateway_Name="OMG_ESP8266_SERIAL"' board_build.flash_mode = dout -custom_description = RS232 gateway +custom_description = SERIAL gateway +custom_img = img/boards/nodemcuv2.jpg [env:avatto-bakeey-ir] platform = ${com.esp8266_platform} @@ -1292,7 +1662,7 @@ build_flags = ${com-esp.build_flags} '-DZgatewayIR="IR"' '-DTRIGGER_GPIO=13' - '-DLED_SEND_RECEIVE=4' + '-DLED_PIN=4' '-DIR_EMITTER_GPIO=14' '-DIR_RECEIVER_GPIO=5' '-UMQTTsetMQTT' ;We remove this function to have sufficient FLASH available for OTA, you should also use ESPWifiManualSetup and 'board_build.ldscript = eagle.flash.1m64.ld' to save flash memory and have OTA working @@ -1300,7 +1670,8 @@ build_flags = '-DGateway_Name="OMG_AVATTO_IR"' board_build.flash_mode = dout custom_description = IR gateway bi directional -custom_hardware = Avatto Bakey IR first version, [tutorial](https://1technophile.blogspot.com/2020/07/avatto-s06-ir-gateway-compatible-with.html) +custom_hardware = 'Avatto Bakey IR first version,tutorial' +custom_img = https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWdLlg_I1Fxg8PKa0LNCwj3fDtSCVn50Zqima9QZvJfPpIyr3Rh7cvg_WPzRkZpzP4_Tu9inXfo3e6CbLLLpZzo5yGOUX_zFT0CnopCtyuEgJyHHJLP8ctfm1UyHP3KZJGzRbZul4F9JBX/ [env:nodemcuv2-rf] platform = ${com.esp8266_platform} @@ -1314,8 +1685,10 @@ build_flags = ${com-esp.build_flags} '-DZgatewayRF="RF"' '-DGateway_Name="OMG_ESP8266_RF"' + '-DvalueAsATopic=true' board_build.flash_mode = dout custom_description = The historic RF gateway using RCSwitch library +custom_img = img/boards/nodemcuv2.jpg [env:nodemcuv2-rf-cc1101] platform = ${com.esp8266_platform} @@ -1331,8 +1704,10 @@ build_flags = '-DZgatewayRF="RF"' '-DZradioCC1101="CC1101"' '-DGateway_Name="OMG_ESP8266_RF-CC1101"' + '-DvalueAsATopic=true' board_build.flash_mode = dout custom_description = RF gateway using RCSwitch library with CC1101 +custom_img = img/boards/nodemcuv2.jpg [env:nodemcuv2-somfy-cc1101] platform = ${com.esp8266_platform} @@ -1350,6 +1725,7 @@ build_flags = '-DGateway_Name="OMG_ESP8266_Somfy-CC1101"' board_build.flash_mode = dout custom_description = Somfy RF gateway using Somfy Remote library, need CC1101 +custom_img = img/boards/nodemcuv2.jpg [env:manual-wifi-test] platform = ${com.esp8266_platform} @@ -1366,18 +1742,6 @@ build_flags = '-DGateway_Name="OMG_TEST_MANUAL_WIFI"' board_build.flash_mode = dout -[env:nodemcuv2-mqtt-fw-test] -platform = ${com.esp8266_platform} -board = nodemcuv2 -lib_deps = - ${com-esp.lib_deps} - ${libraries.wifimanager8266} -build_flags = - ${com-esp.build_flags} - '-DMQTT_SECURE_SELF_SIGNED' - '-DGateway_Name="OMG_TEST_MQTT_FW"' -board_build.flash_mode = dout - [env:rf-wifi-gateway] platform = ${com.esp8266_platform} board = nodemcuv2 @@ -1393,7 +1757,7 @@ build_flags = '-DRF_RECEIVER_GPIO=5' board_build.flash_mode = dout custom_description = RF gateway for USB stick using RCSwitch -custom_hardware = RF Wifi USB stick, [tutorial](https://1technophile.blogspot.com/2019/09/hack-of-rf-wifi-gateway-usb-stick.html) +custom_hardware = 'RF Wifi USB stick, tutorial' [env:nodemcuv2-rf2] platform = ${com.esp8266_platform} @@ -1409,6 +1773,7 @@ build_flags = '-DGateway_Name="OMG_ESP8266_RF2"' board_build.flash_mode = dout custom_description = KAKU RF gateway using NewRemoteSwitch library +custom_img = img/boards/nodemcuv2.jpg [env:nodemcuv2-rf2-cc1101] platform = ${com.esp8266_platform} @@ -1426,9 +1791,10 @@ build_flags = '-DGateway_Name="OMG_ESP8266_RF2-CC1101"' board_build.flash_mode = dout custom_description = KAKU RF gateway using NewRemoteSwitch library, need CC1101 +custom_img = img/boards/nodemcuv2.jpg [env:nodemcuv2-pilight] -platform = espressif8266@^2 +platform = ${com.esp8266_platform} board = nodemcuv2 lib_deps = ${com-esp.lib_deps} @@ -1439,8 +1805,10 @@ build_flags = ${com-esp.build_flags} '-DZgatewayPilight="Pilight"' '-DGateway_Name="OMG_ESP8266_Pilight"' + '-fcommon' board_build.flash_mode = dout custom_description = Gateway using ESPilight without the need of CC1101 +custom_img = img/boards/nodemcuv2.jpg [env:nodemcuv2-weatherstation] platform = ${com.esp8266_platform} @@ -1456,6 +1824,7 @@ build_flags = '-DGateway_Name="OMG_ESP8266_RF3"' board_build.flash_mode = dout custom_description = RF gateway using WeatherStationDataRx library +custom_img = img/boards/nodemcuv2.jpg [env:sonoff-basic] platform = ${com.esp8266_platform} @@ -1473,11 +1842,12 @@ build_flags = '-DACTUATOR_ON=0' '-DACTUATOR_ONOFF_DEFAULT=ACTUATOR_ON' '-DACTUATOR_BUTTON_TRIGGER_LEVEL=0' - '-ACTUATOR_TRIGGER=true' + '-DACTUATOR_TRIGGER=true' '-DGateway_Name="OMG_SONOFF_RELAY"' board_build.flash_mode = dout custom_description = Basic Sonoff wifi relay custom_hardware = Sonoff Basic R1, R2 +custom_img = img/boards/sonoff-basic.jpg [env:sonoff-basic-rfr3] platform = ${com.esp8266_platform} @@ -1496,98 +1866,19 @@ build_flags = '-DACTUATOR_ON=0' '-DACTUATOR_ONOFF_DEFAULT=ACTUATOR_ON' '-DACTUATOR_BUTTON_TRIGGER_LEVEL=0' - '-ACTUATOR_TRIGGER=true' + '-DACTUATOR_TRIGGER=true' '-DRF_RECEIVER_GPIO=4' '-DZgatewayRF="RF"' '-DGateway_Name="OMG_SONOFF_BASIC_RFR3"' board_build.flash_mode = dout -custom_description = Wifi relay and RF receiver using RCSwitch library, [tutorial](https://1technophile.blogspot.com/2019/08/new-sonoff-rfr3-as-433tomqtt-gateway.html) -custom_hardware = Sonoff Basic RFR3, [tutorial](https://1technophile.blogspot.com/2019/08/new-sonoff-rfr3-as-433tomqtt-gateway.html) - -[env:atmega-all-test] -platform = ${com.atmelavr_platform} -board = megaatmega2560 -lib_deps = - ${com-arduino.lib_deps} - ${libraries.irremote} - ${libraries.rfm69} - ${libraries.rfm69spi} - ${libraries.rfm69_low-power} - ${libraries.rc-switch} - ${libraries.newremoteswitch} - ${libraries.bme280} - ${libraries.bmp180} - ${libraries.htu21} - ${libraries.ahtx0} - ${libraries.unifiedsensor} - ${libraries.dht} - ${libraries.tsl2561} - ${libraries.a6lib} - ${libraries.ina226} - ${libraries.fastled} - ${libraries.onewire} - ${libraries.dallastemperature} - ${libraries.rfWeatherStation} - ${libraries.stl} -build_flags = - ${com-arduino.build_flags} - '-DZgatewayRF="RF"' - '-DZgatewayRF="RF315"' - '-DZgatewayRF2="RF2"' - '-DZgatewayIR="IR"' - '-DZactuatorONOFF="ONOFF"' - '-DZactuatorFASTLED="FASTLED"' - '-DZactuatorPWM="PWM"' - '-DZsensorINA226="INA226"' - '-DZsensorHCSR501="HCSR501"' - '-DZsensorADC="ADC"' - '-DZsensorBH1750="BH1750"' - '-DZsensorBME280="BME280"' - '-DZsensorHTU21="HTU21"' - '-DZsensorAHTx0="AHTx0"' - '-DZsensorTSL2561="TSL2561"' - '-DZsensorDHT="DHT"' - '-DZsensorDS1820="DS1820"' - '-DZgatewayRFM69="RFM69"' - '-DZgatewayWeatherStation="WeatherStation"' - '-DZsensorGPIOInput="GPIOInput"' - ;'-DZsensorGPIOKeyCode="GPIOKeyCode"' - '-DZmqttDiscovery="HADiscovery"' - '-DsimplePublishing=true' - '-DGateway_Name="OMG_ATMEGA_ALL"' - '-UZmqttDiscovery="HADiscovery"' - -[env:uno-rf] -platform = ${com.atmelavr_platform} -board = uno -lib_deps = - ${com-arduino.lib_deps} - ${libraries.rc-switch} -build_flags = - ${com-arduino-low-memory.build_flags} - '-UZmqttDiscovery="HADiscovery"' - '-DZgatewayRF="RF"' - '-DGateway_Name="OMG_1_RF"' - '-DDISABLE_LOGGING' -custom_description = RF gateway based on RCSwitch - -[env:uno-fastled] -platform = ${com.atmelavr_platform} -board = uno -lib_deps = - ${com-arduino.lib_deps} - ${libraries.fastled} -build_flags = - ${com-arduino-low-memory.build_flags} - '-DGateway_Name="OMG_1_FL"' - '-DZactuatorFASTLED="FASTLED"' - '-UZmqttDiscovery="HADiscovery"' -custom_description = FastLed control +custom_description = 'Wifi relay and RF receiver using RCSwitch library, tutorial' +custom_hardware = 'Sonoff Basic RFR3, tutorial' +custom_img = img/boards/sonoff-rfr3.jpg [env:esp32dev-ble-datatest] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -1596,17 +1887,19 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=2' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=2' + '-DLED_PIN_ON=0' '-DTimeBtwRead=0' '-DScan_duration=3000' '-DAttemptBLEConnect=false' '-DpubBLEAdvData=true' '-DGateway_Name="OMG_ESP32_BLE"' custom_description = Default BLE gateway with additional servicedata, manufacturerdata and service uuid for analysing decoding issues +custom_img = img/boards/esp32dev.jpg [env:esp32s3-dev-c1-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-s3-devkitc-1 lib_deps = ${com-esp32.lib_deps} @@ -1616,15 +1909,37 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DANEOPIX_IND_DATA_GPIO=48' - '-DANEOPIX_IND_NUM_LEDS=1' - '-DRGB_INDICATORS=true' + '-DLED_ADDRESSABLE_PIN1=48' + '-DLED_ADDRESSABLE_NUM=1' + '-DLED_ADDRESSABLE=true' '-DNO_INT_TEMP_READING=true' ; Internal temperature reading not building on ESP32 C3 or S3 '-DGateway_Name="OMG_ESP32_BLE"' custom_description = BLE gateway on the S3 +custom_img = img/boards/esp32s3-devkit-c1.png + +[env:esp32s3-m5stack-stamps3] +platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +board = esp32-s3-devkitc-1 +lib_deps = + ${com-esp32.lib_deps} + ${libraries.ble} + ${libraries.decoder} + ${libraries.adafruit_neopixel} +build_flags = + ${com-esp32.build_flags} + '-DZgatewayBT="BT"' + '-DLED_ADDRESSABLE_PIN1=21' + '-DLED_ADDRESSABLE_NUM=1' + '-DLED_ADDRESSABLE=true' + '-DNO_INT_TEMP_READING=true' ; Internal temperature reading not building on ESP32 C3 or S3 + '-DGateway_Name="OMG_ESP32_BLE"' +custom_description = BLE gateway on the M5Stack StampS3 +custom_img = img/boards/m5stamp-s3.webp [env:esp32s3-atomS3U] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = m5stack-atoms3 lib_deps = ${com-esp32.lib_deps} @@ -1636,9 +1951,9 @@ build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' '-DZgatewayIR="IR"' - '-DANEOPIX_IND_DATA_GPIO=35' - '-DANEOPIX_IND_NUM_LEDS=1' - '-DRGB_INDICATORS=true' + '-DLED_ADDRESSABLE_PIN1=35' + '-DLED_ADDRESSABLE_NUM=1' + '-DLED_ADDRESSABLE=true' '-DTRIGGER_GPIO=41' '-DIR_EMITTER_GPIO=12' '-DNO_INT_TEMP_READING=true' ; Internal temperature reading not building on ESP32 C3 or S3 @@ -1646,9 +1961,11 @@ build_flags = board_upload.speed = 921600 custom_description = USB module with BLE gateway, and IR emitter custom_hardware = AtomS3U ESP32S3 +custom_img = img/boards/m5atoms3u.webp [env:esp32c3-dev-m1-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-c3-devkitm-1 board_build.partitions = min_spiffs.csv lib_deps = @@ -1659,15 +1976,17 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DANEOPIX_IND_DATA_GPIO=8' - '-DANEOPIX_IND_NUM_LEDS=1' - '-DRGB_INDICATORS=true' + '-DLED_ADDRESSABLE_PIN1=8' + '-DLED_ADDRESSABLE_NUM=1' + '-DLED_ADDRESSABLE=true' '-DNO_INT_TEMP_READING=true' ; Internal temperature reading not building on ESP32 C3 or S3 '-DGateway_Name="OMG_ESP32_BLE"' custom_description = BLE gateway on the C3 +custom_img = img/boards/esp32c3-devkit-m1.png [env:airm2m_core_esp32c3] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = airm2m_core_esp32c3 board_build.partitions = min_spiffs.csv lib_deps = @@ -1678,15 +1997,17 @@ build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' '-DLED_INFO=19' - '-DLED_SEND_RECEIVE=20' + '-DLED_PIN=20' '-DNO_INT_TEMP_READING=true' ; Internal temperature reading not building on ESP32 C3 or S3 '-DGateway_Name="OMG_AirM2M_Core_ESP32C3"' custom_description = BLE gateway on the C3 custom_hardware = AirM2M ESP32C3-CORE ; Espressiv ESP32-C3-DevKitC-02 +custom_img = img/boards/airm2m.png [env:esp32c3-dev-c2-ble] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-c3-devkitm-1 board_build.partitions = min_spiffs.csv lib_deps = @@ -1697,15 +2018,16 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DANEOPIX_IND_DATA_GPIO=8' - '-DANEOPIX_IND_NUM_LEDS=1' - ; '-DANEOPIX_BRIGHTNESS=10' ; 0 - 255, default 20 + '-DLED_ADDRESSABLE_PIN1=8' + '-DLED_ADDRESSABLE_NUM=1' + ; '-DDEFAULT_ADJ_BRIGHTNESS=10' ; 0 - 255, default 20 '-DANEOPIX_COLOR_SCHEME=2' ; blue based signalling colors - '-DRGB_INDICATORS=true' + '-DLED_ADDRESSABLE=true' '-DNO_INT_TEMP_READING=true' ; No internal temperature reading on ESP32 C3 or S3 '-DTRIGGER_GPIO=7' '-DGateway_Name="OpenMQTTGateway_ESP32C3_DKC02"' custom_description = BLE gateway on Espressiv ESP32-C3-DevKitC-02 +custom_img = img/boards/esp32c3-devkit-c02.png [env:esp32c3-dev-c2-ble-no-serial] extends = env:esp32c3-dev-c2-ble @@ -1716,8 +2038,10 @@ build_flags = custom_description = BLE gateway on Espressiv ESP32-C3-DevKitC-02 without logging ; Wemos Lolin C3 mini v2.1.0 +custom_img = img/boards/esp32c3-devkit-c02.png [env:esp32c3_lolin_mini] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = lolin_c3_mini board_build.partitions = min_spiffs.csv monitor_speed = 115200 @@ -1729,11 +2053,11 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DANEOPIX_IND_DATA_GPIO=7' - '-DANEOPIX_IND_NUM_LEDS=1' - ; '-DANEOPIX_BRIGHTNESS=10' ; 0 - 255, default 20 + '-DLED_ADDRESSABLE_PIN1=7' + '-DLED_ADDRESSABLE_NUM=1' + ; '-DDEFAULT_ADJ_BRIGHTNESS=10' ; 0 - 255, default 20 '-DANEOPIX_COLOR_SCHEME=1' ; Alternative LED colour scheme: 2 = blue/gold. 1 = green/gold - '-DRGB_INDICATORS=true' + '-DLED_ADDRESSABLE=true' ; The momentary switch on the board is connected to GPIO9 '-DTRIGGER_GPIO=9' '-DNO_INT_TEMP_READING=true' ; No internal temperature on ESP32 C3 or S3 @@ -1745,6 +2069,7 @@ build_flags = '-DWM_DEBUG=0' ; disable serial logging. custom_description = BLE gateway on ESP32C3 custom_hardware = Wemos Lolin C3 mini v2.1.0 +custom_img = img/boards/lolin-c3-mini.jpg [env:esp32c3_lolin_mini_with_serial] extends = env:esp32c3_lolin_mini @@ -1754,9 +2079,12 @@ build_flags = ; Serial output via USB '-DCONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=true' '-DCONFIG_ESP_CONSOLE_UART=ESP_CONSOLE_USB_SERIAL_JTAG' +custom_img = img/boards/lolin-c3-mini.jpg [env:esp32c3-m5stamp] +; https://docs.m5stack.com/en/core/stamp_c3 platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32-c3-devkitm-1 board_build.partitions = min_spiffs.csv lib_deps = @@ -1769,18 +2097,44 @@ build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' '-DTRIGGER_GPIO=3' - '-DANEOPIX_IND_DATA_GPIO=2' - '-DANEOPIX_IND_NUM_LEDS=1' - '-DRGB_INDICATORS=true' + '-DLED_ADDRESSABLE_PIN1=2' + '-DLED_ADDRESSABLE_NUM=1' + '-DLED_ADDRESSABLE=true' '-DNO_INT_TEMP_READING=true' ; Internal temperature reading not building on ESP32 C3 or S3 '-DUSE_MAC_AS_GATEWAY_NAME' custom_description = BLE gateway on ESP32C3 custom_hardware = M5Stamp C3 +custom_img = img/boards/m5stamp-c3.webp + +[env:esp32c3u-m5stamp] +; https://docs.m5stack.com/en/core/stamp_c3u +platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +board = esp32-c3-devkitm-1 +board_build.partitions = min_spiffs.csv +lib_deps = + ${com-esp32.lib_deps} + ${libraries.wifimanager32} + ${libraries.ble} + ${libraries.decoder} + ${libraries.adafruit_neopixel} +build_flags = + ${com-esp32.build_flags} + '-DZgatewayBT="BT"' + '-DTRIGGER_GPIO=9' + '-DLED_ADDRESSABLE_PIN1=2' + '-DLED_ADDRESSABLE_NUM=1' + '-DLED_ADDRESSABLE=true' + '-DNO_INT_TEMP_READING=true' ; Internal temperature reading not building on ESP32 C3 or S3 + '-DUSE_MAC_AS_GATEWAY_NAME' +custom_description = BLE gateway on ESP32C3 +custom_hardware = M5Stamp C3U +custom_img = img/boards/m5stamp-c3u.webp [env:thingpulse-espgateway] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} board = esp32dev -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = min_spiffs.csv lib_deps = ${com-esp32.lib_deps} @@ -1790,8 +2144,8 @@ lib_deps = build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=2' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=2' + '-DLED_PIN_ON=0' '-DGateway_Name="OMG_THINGPULSE_ETH_BLE"' '-DESP32_ETHERNET=true' '-DETH_PHY_TYPE=ETH_PHY_LAN8720' @@ -1800,32 +2154,81 @@ build_flags = '-DETH_PHY_MDC=23' '-DETH_PHY_MDIO=18' '-DETH_CLK_MODE=ETH_CLOCK_GPIO16_OUT' - '-DANEOPIX_IND_DATA_GPIO=32' - '-DANEOPIX_IND_NUM_LEDS=4' - '-DANEOPIX_INFO_LED=0' - '-DANEOPIX_SEND_RECEIVE_LED=1' - '-DANEOPIX_ERROR_LED=2' - '-DANEOPIX_BRIGHTNESS=255' - '-DRGB_INDICATORS=true' + '-DLED_ADDRESSABLE_PIN1=32' + '-DLED_ADDRESSABLE_NUM=4' + '-DLED_BROKER=0' + '-DLED_PROCESSING=1' + '-DLED_ERROR=2' + '-DDEFAULT_ADJ_BRIGHTNESS=255' + '-DLED_ADDRESSABLE=true' ; '-DsimplePublishing=true' custom_description = BLE Gateway using ethernet or wifi with external antenna custom_hardware = ThingPulse gateway single ESP32 +custom_img = img/boards/thingpulse-espgateway.jpg [env:esp32dev-ble-idf] platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} framework = arduino, espidf board = esp32dev -extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = partitions/min_spiffs.csv +board_build.embed_txtfiles = + managed_components/espressif__esp_insights/server_certs/https_server.crt + managed_components/espressif__esp_rainmaker/server_certs/rmaker_mqtt_server.crt + managed_components/espressif__esp_rainmaker/server_certs/rmaker_claim_service_server.crt + managed_components/espressif__esp_rainmaker/server_certs/rmaker_ota_server.crt lib_deps = ${com-esp32.lib_deps} - ${libraries.ble} ${libraries.decoder} + https://github.com/h2zero/esp-nimble-cpp/archive/2.5.0.zip + h2zero/NimBLEOta@0.2.0 build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' - '-DLED_SEND_RECEIVE=2' - '-DLED_SEND_RECEIVE_ON=0' + '-DLED_PIN=2' + '-DLED_PIN_ON=0' '-DGateway_Name="OMG_ESP32_BLE"' '-DUSE_BLUFI=1' -custom_description = Regular BLE gateway with adaptive scanning activated, automatically adapts the scan parameters depending on your devices + '-DenableMultiGTWSync=false' +custom_description = Regular BLE gateway based on esp-idf with adaptive scanning activated, automatically adapts the scan parameters depending on your devices +custom_img = img/boards/esp32dev.jpg + +[env:isno-super] +platform = ${com.esp32_platform} +platform_packages = ${com.esp32_platform_packages} +board = esp32-s3-devkitc-1 +board_build.flash_size = 8MB +board_upload.flash_size = 8MB +board_build.partitions = default_8MB.csv +lib_deps = + ${com-esp32.lib_deps} + ${libraries.rc-switch} + ${libraries.smartrc-cc1101-driver-lib} + ${libraries.rtl_433_ESP} + ${libraries.newremoteswitch} +build_flags = + ${com-esp32.build_flags} + '-DZgatewayRF="RF"' + '-DZgatewayRF2="RF2"' + '-DZgatewayRTL_433="RTL_433"' + '-DZradioCC1101="CC1101"' + '-DGateway_Name="OMG_ISNO_Super"' + '-DvalueAsATopic=true' + '-DNO_INT_TEMP_READING=true' ; internal temperature sensor not building on ESP32-S3 + '-DRF_CC1101="CC1101"' +; ISNO Super: two CC1101 share one SPI bus, combined on a single antenna through an LC diplexer + '-DRF_MODULE_SCK=4' + '-DRF_MODULE_MISO=5' + '-DRF_MODULE_MOSI=6' +; active radio = 868 MHz (RadioLib / rtl_433 path) + '-DRF_MODULE_CS=7' + '-DRF_MODULE_GDO0=1' + '-DRF_MODULE_GDO2=2' +; same pins for the ELECHOUSE path (ZgatewayRF / ZgatewayRF2) + '-DRF_CC1101_SCK=4' + '-DRF_CC1101_MISO=5' + '-DRF_CC1101_MOSI=6' + '-DRF_CC1101_CS=7' +; park the 433 MHz radio, CS held high by commonRF.cpp + '-DRF_MODULE_SECONDARY_CS=15' +custom_description = ISNO Super, ESP32-S3 with two CC1101 (433 MHz + 868/915 MHz) combined on one antenna through an LC diplexer; the 868/915 MHz radio is active (868 in the EU, 915 in the US), the 433 MHz radio is parked in this environment diff --git a/examples/LoraWaterCounter/OpenGatewaySensorCounter.ino b/examples/LoraWaterCounter/OpenGatewaySensorCounter.ino new file mode 100644 index 0000000..329be40 --- /dev/null +++ b/examples/LoraWaterCounter/OpenGatewaySensorCounter.ino @@ -0,0 +1,199 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "SSD1306.h" + +//LoRa pins +#define SCK 5 // GPIO5 -- SX1278's SCK +#define MISO 19 // GPIO19 -- SX1278's MISnO +#define MOSI 27 // GPIO27 -- SX1278's MOSI +#define SS 18 // GPIO18 -- SX1278's CS +#define RST 23 // GPIO14 -- SX1278's RESET +#define DI0 26 // GPIO26 -- SX1278's IRQ(Interrupt Request) +#define BAND 433E6 + +//OLED pins +#define OLED_SDA 21 +#define OLED_SCL 22 +//#define OLED_RST 16 + +#define LED 25 + +#define DHT_PIN 14 +#define DHT_TYPE DHT22 + +#define CNT_PIN 34 + +#define BAT_PIN 35 + +const int MAX_ANALOG_VAL = 4095; +const float MAX_BATTERY_VOLTAGE = 4.2; + +int cntpkt = 0; +unsigned long counter = 0; +unsigned long last_interrupt_time = 0; +int pulse_seen = 0; // pulse detected by interrupt function +int bounce_delay_ms = 100; + +SSD1306 display(0x3c, OLED_SDA, OLED_SCL); +String rssi = "RSSI --"; +String packSize = "--"; +String packet; + +DHT_Unified dht(DHT_PIN, DHT_TYPE); // Initialize the "dht" object with sensor pin and DHT type (11/22) + +void ICACHE_RAM_ATTR bounceCheck(); + +void setup() { + pinMode(LED, OUTPUT); + + //pinMode(OLED_RST, OUTPUT); + //digitalWrite(OLED_RST, LOW); // set GPIO16 low to reset OLED + //delay(50); + //digitalWrite(OLED_RST, HIGH); // while OLED is running, must set GPIO16 in high + + Serial.begin(115200); + while (!Serial); + Serial.println(); + Serial.println("LoRa Sender Test"); + + SPI.begin(SCK, MISO, MOSI, SS); + LoRa.setPins(SS, RST, DI0); + if (!LoRa.begin(BAND)) { + Serial.println("Starting LoRa failed!"); + while (1); + } + + Serial.println("init ok"); + display.init(); + display.flipScreenVertically(); + display.setFont(ArialMT_Plain_10); + + pinMode(BAT_PIN, INPUT); + pinMode(CNT_PIN, INPUT_PULLUP); + + attachInterrupt(CNT_PIN, bounceCheck, RISING); + + dht.begin(); + sensor_t sensor; + dht.temperature().getSensor(&sensor); + Serial.println(F("------------------------------------")); + Serial.println(F("Temperature Sensor")); + Serial.print(F("Sensor Type: ")); + Serial.println(sensor.name); + Serial.print(F("Driver Ver: ")); + Serial.println(sensor.version); + Serial.print(F("Unique ID: ")); + Serial.println(sensor.sensor_id); + Serial.print(F("Max Value: ")); + Serial.print(sensor.max_value); + Serial.println(F("°C")); + Serial.print(F("Min Value: ")); + Serial.print(sensor.min_value); + Serial.println(F("°C")); + Serial.print(F("Resolution: ")); + Serial.print(sensor.resolution); + Serial.println(F("°C")); + Serial.println(F("------------------------------------")); + // Print humidity sensor details. + dht.humidity().getSensor(&sensor); + Serial.println(F("Humidity Sensor")); + Serial.print(F("Sensor Type: ")); + Serial.println(sensor.name); + Serial.print(F("Driver Ver: ")); + Serial.println(sensor.version); + Serial.print(F("Unique ID: ")); + Serial.println(sensor.sensor_id); + Serial.print(F("Max Value: ")); + Serial.print(sensor.max_value); + Serial.println(F("%")); + Serial.print(F("Min Value: ")); + Serial.print(sensor.min_value); + Serial.println(F("%")); + Serial.print(F("Resolution: ")); + Serial.print(sensor.resolution); + Serial.println(F("%")); + Serial.println(F("------------------------------------")); + + delay(1500); +} + +void loop() { + sensors_event_t event1, event2; + + display.clear(); + display.setTextAlignment(TEXT_ALIGN_LEFT); + display.setFont(ArialMT_Plain_10); + + display.drawString(0, 0, "Sending packet: "); + display.drawString(90, 0, String(cntpkt)); + + String NodeId = WiFi.macAddress(); + // float temp = dht.readTemperature(); + // float hum = dht.readHumidity(); + float battery = getBattery(); + + dht.temperature().getEvent(&event1); + if (isnan(event1.temperature)) { + Serial.println(F("Error reading temperature!")); + } else { + Serial.print(F("Temperature: ")); + Serial.print(event1.temperature); + Serial.println(F("°C")); + } + // Get humidity event and print its value. + dht.humidity().getEvent(&event2); + if (isnan(event2.relative_humidity)) { + Serial.println(F("Error reading humidity!")); + } else { + Serial.print(F("Humidity: ")); + Serial.print(event2.relative_humidity); + Serial.println(F("%")); + } + + // send packet + LoRa.beginPacket(); + + String msg = "{\"model\":\"ESP32CNT\",\"id\":\"" + NodeId + "\",\"count\":\"" + String(counter) + "\",\"tempc\":\"" + String(event1.temperature) + "\",\"hum\":\"" + String(event2.relative_humidity) + "\",\"batt\":\"" + String(battery) + "\"}"; + // Send json string + LoRa.print(msg); + LoRa.endPacket(); + + Serial.println(msg); + + display.drawString(0, 15, String(NodeId)); + display.drawString(0, 30, "count: " + String(counter)); + display.drawString(0, 45, "battery: " + String(battery) + " %"); + display.display(); + + delay(5000); + + cntpkt++; + + digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level) + delay(1000); // wait for a second + digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW + //delay(60000); // wait for 60 seconds + delay(6000); +} + +void ICACHE_RAM_ATTR bounceCheck() { + unsigned long interrupt_time = millis(); + if (interrupt_time - last_interrupt_time > bounce_delay_ms) counter++; // void loop() then notes pulse == 1 and takes action + last_interrupt_time = interrupt_time; +} + +float getBattery(void) { + int rawValue = analogRead(BAT_PIN); + + float voltageLevel = (rawValue / 4095.0) * 2 * 1.1 * 3.3; // calculate voltage level + float perc = voltageLevel / MAX_BATTERY_VOLTAGE * 100; + + return (perc); +} diff --git a/examples/LoraWaterCounter/README.md b/examples/LoraWaterCounter/README.md new file mode 100644 index 0000000..5470f95 --- /dev/null +++ b/examples/LoraWaterCounter/README.md @@ -0,0 +1,65 @@ +# OpenMQTTGateway LoRa Node Example +This repository contains an example of a LoRa node program designed for the ESP32 platform. +The program reads the DHT22 temperature and humidity, the battery level and water consumption via reed switch, packages the data into a JSON format, and sends it over LoRa. + +## Features: +* Uses an SX12XX LoRa module. +* Displays packet sending status, counter and battery level data on an SSD1306 OLED display. +* Sends the ESP32's MAC address as the node ID. +* Sends temperature data in Celsius. + +## Hardware Requirements: +* ESP32 development board. +* SX12XX LoRa module. +* SSD1306 OLED display. + +## Pin Configuration: (Lilygo LoRa32 V2.1_1.6) +* SCK - GPIO5 +* MISO - GPIO19 +* MOSI - GPIO27 +* SS - GPIO18 +* RST - GPIO23 +* DI0 - GPIO26 + +## Setup: +### Hardware Setup: + +Connect the SX1278 LoRa module and the SSD1306 OLED display to the ESP32 according to the pin configuration. +Ensure that the OLED display is powered correctly. + +### Software Setup: + +* Clone this repository. +* Open the provided node program with PlatformIO +* Upload the program to your ESP32. + +## Usage: +Power on the ESP32. +The OLED display will show the status of the packet being sent and the current temperature reading. +The built-in LED on the ESP32 will blink once every time a packet is sent. +Monitor the serial output (at 115200 baud rate) to see the JSON formatted data being sent. + +If you use arduino load ino file. + +## Data Format: +The data is sent in the following JSON format: + +```json +{ + "model": "ESP32CNT", + "id": "ESP32_MAC_ADDRESS", + "count": "COUNTER_IN_LITER", + "tempc": "TEMPERATURE_IN_CELSIUS", + "hum": "HUMIDITY_IN_PERCENTAGE", + "batt": "BATTERY_IN_PERCENTAGE" +} +``` + +## Troubleshooting: +LoRa Initialization Failed: Ensure that the SX1278 LoRa module is connected correctly and powered on. +OLED Display Not Working: Check the connections and ensure that the display is powered correctly. +No Temperature Data: Ensure that the ESP32's internal temperature sensor is functional. +Contributing: +Feel free to contribute to this example by opening issues or submitting pull requests. Any feedback or improvements are welcome! + +I hope this README helps users understand and use your program! Adjustments can be made as necessary to fit any additional details or changes. diff --git a/examples/LoraWaterCounter/platformio.ini b/examples/LoraWaterCounter/platformio.ini new file mode 100644 index 0000000..77aa265 --- /dev/null +++ b/examples/LoraWaterCounter/platformio.ini @@ -0,0 +1,36 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:ttgo-lora32-v1] +platform = espressif32 +board = ttgo-lora32-v1 +framework = arduino +lib_deps = + https://github.com/sandeepmistry/arduino-LoRa.git#f4a1d27 + https://github.com/ThingPulse/esp8266-oled-ssd1306.git#f96fd6a +monitor_speed = 115200 + +[env:ttgo-lora32-v21] +platform = espressif32 +board = ttgo-lora32-v21 +framework = arduino +lib_deps = + https://github.com/sandeepmistry/arduino-LoRa.git#f4a1d27 + https://github.com/ThingPulse/esp8266-oled-ssd1306.git#f96fd6a +monitor_speed = 115200 + +[env:heltec-wifi-lora-32] ; Heltec ESP32 Board with SSD1306 display +platform = espressif32 +board = heltec_wifi_lora_32 +framework = arduino +lib_deps = + https://github.com/sandeepmistry/arduino-LoRa.git#f4a1d27 + https://github.com/ThingPulse/esp8266-oled-ssd1306.git#f96fd6a +monitor_speed = 115200 \ No newline at end of file diff --git a/examples/LoraWaterCounter/src/main.cpp b/examples/LoraWaterCounter/src/main.cpp new file mode 100644 index 0000000..c62cf5e --- /dev/null +++ b/examples/LoraWaterCounter/src/main.cpp @@ -0,0 +1,137 @@ +#include +#include +#include +#include +#include + +#include "SSD1306.h" +#include "rom/ets_sys.h" +#include "soc/rtc_cntl_reg.h" +#include "soc/sens_reg.h" + +#define SCK 5 // GPIO5 -- SX1278's SCK +#define MISO 19 // GPIO19 -- SX1278's MISnO +#define MOSI 27 // GPIO27 -- SX1278's MOSI +#define SS 18 // GPIO18 -- SX1278's CS +#define RST 23 // GPIO23 -- SX1278's RESET +#define DI0 26 // GPIO26 -- SX1278's IRQ(Interrupt Request) +#define BAND 433E6 + +//OLED pins +#define OLED_SDA 21 +#define OLED_SCL 22 +//#define OLED_RST 16 + +#define LED 25 + +#define DHT_PIN 12 +#define DHT_TYPE DHT22 + +#define CNT_PIN 34 + +#define BAT_PIN 35 + +const int MAX_ANALOG_VAL = 4095; +const float MAX_BATTERY_VOLTAGE = 4.2; + +int cntpkt = 0; +unsigned long counter = 0; +unsigned long last_interrupt_time = 0; +int pulse_seen = 0; // pulse detected by interrupt function +int bounce_delay_ms = 100; + +SSD1306 display(0x3c, OLED_SDA, OLED_SCL); +String rssi = "RSSI --"; +String packSize = "--"; +String packet; + +DHT dht(DHT_PIN, DHT_TYPE); // Initialize the "dht" object with sensor pin and DHT type (11/22) + +void ICACHE_RAM_ATTR bounceCheck(); + +void setup() { + pinMode(LED, OUTPUT); + + //pinMode(OLED_RST, OUTPUT); + //digitalWrite(OLED_RST, LOW); // set GPIO16 low to reset OLED + //delay(50); + //digitalWrite(OLED_RST, HIGH); // while OLED is running, must set GPIO16 in high + + Serial.begin(115200); + while (!Serial); + Serial.println(); + Serial.println("LoRa Sender Test"); + + SPI.begin(SCK, MISO, MOSI, SS); + LoRa.setPins(SS, RST, DI0); + if (!LoRa.begin(BAND)) { + Serial.println("Starting LoRa failed!"); + while (1); + } + + Serial.println("init ok"); + display.init(); + display.flipScreenVertically(); + display.setFont(ArialMT_Plain_10); + + pinMode(BAT_PIN, INPUT); + pinMode(CNT_PIN, INPUT_PULLUP); + + attachInterrupt(CNT_PIN, bounceCheck, RISING); + + delay(1500); +} + +void loop() { + display.clear(); + display.setTextAlignment(TEXT_ALIGN_LEFT); + display.setFont(ArialMT_Plain_10); + + display.drawString(0, 0, "Sending packet: "); + display.drawString(90, 0, String(cntpkt)); + + String NodeId = WiFi.macAddress(); + float temp = dht.readTemperature(); + float hum = dht.readHumidity(); + float battery = getBattery(); + // send packet + LoRa.beginPacket(); + // Build json string to send + // Remove this line for test + + String msg = "{\"model\":\"ESP32CNT\",\"id\":\"" + NodeId + "\",\"count\":\"" + String(counter) + "\",\"tempc\":\"" + String(temp) + "\",\"hum\":\"" + String(hum) + "\",\"batt\":\"" + String(battery) + "\"}"; + // Send json string + LoRa.print(msg); + LoRa.endPacket(); + + Serial.println(msg); + + display.drawString(0, 15, String(NodeId)); + display.drawString(0, 30, "count: " + String(counter)); + display.drawString(0, 45, "battery: " + String(battery) + " %"); + display.display(); + + delay(5000); + + cntpkt++; + + digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level) + delay(1000); // wait for a second + digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW + delay(60000); // wait for 60 seconds +} + +void ICACHE_RAM_ATTR bounceCheck() { + unsigned long interrupt_time = millis(); + if (interrupt_time - last_interrupt_time > bounce_delay_ms) counter++; // void loop() then notes pulse == 1 and takes action + last_interrupt_time = interrupt_time; +} + +float getBattery(void) { + int rawValue = analogRead(BAT_PIN); + + float voltageLevel = (rawValue / 4095.0) * 2 * 1.1 * 3.3; // calculate voltage level + float perc = voltageLevel / MAX_BATTERY_VOLTAGE * 100; + + return (perc); +} diff --git a/lib/LEDManager/LEDManager.cpp b/lib/LEDManager/LEDManager.cpp new file mode 100644 index 0000000..4505bdd --- /dev/null +++ b/lib/LEDManager/LEDManager.cpp @@ -0,0 +1,251 @@ +/* + Theengs LEDManager - We Unite Sensors in One Open-Source Interface + + Copyright: (c)Florian ROBERT + + This file is part of LEDManager library. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +#include "LEDManager.h" + +LEDManager::LEDManager() : globalBrightness(255) {} + +void LEDManager::addLEDStrip(int pin, int numLeds) { + LEDStrip ledStrip; + ledStrip.pin = pin; +#ifdef LED_ADDRESSABLE + if (LED_ADDRESSABLE_POWER > -1) { + pinMode(LED_ADDRESSABLE_POWER, OUTPUT); + digitalWrite(LED_ADDRESSABLE_POWER, HIGH); + } + ledStrip.strip = new Adafruit_NeoPixel(numLeds, pin, NEO_GRB + NEO_KHZ800); + ledStrip.strip->begin(); + ledStrip.strip->show(); + ledStrip.strip->setBrightness(globalBrightness); +#else + pinMode(pin, OUTPUT); +#endif + + ledStrip.ledStates.resize(numLeds, {OFF, OFF, 0, 0, 0, 0, 0, false, 255, FADE_AMOUNT, {OFF, 0, -1, false}}); + + ledStrips.push_back(ledStrip); +} + +void LEDManager::setMode(int stripIndex, int ledIndex, Mode mode, uint32_t color, int durationOrBlinkCount) { + if (stripIndex >= 0 && stripIndex < ledStrips.size()) { + if (ledIndex == -1) { + for (int i = 0; i < ledStrips[stripIndex].ledStates.size(); i++) { + setModeForSingleLED(stripIndex, i, mode, color, durationOrBlinkCount); + } + } else if (ledIndex >= 0 && ledIndex < ledStrips[stripIndex].ledStates.size()) { + setModeForSingleLED(stripIndex, ledIndex, mode, color, durationOrBlinkCount); + } + } else if (stripIndex == -1) { + for (int i = 0; i < ledStrips.size(); i++) { + setMode(i, ledIndex, mode, color, durationOrBlinkCount); + } + } +} + +void LEDManager::setModeForSingleLED(int stripIndex, int ledIndex, Mode mode, uint32_t color, int durationOrBlinkCount) { + auto& state = ledStrips[stripIndex].ledStates[ledIndex]; + + if ((state.mode == BLINK || state.mode == PULSE) && state.durationOrBlinkCount > 0) { + state.queuedState = {mode, color, durationOrBlinkCount, true}; + return; + } + + if (mode != BLINK && mode != PULSE) { + state.previousMode = state.mode; + state.previousColor = state.color; + } + state.mode = mode; + state.color = color; + state.durationOrBlinkCount = durationOrBlinkCount; + state.lastUpdateTime = millis(); + state.blinkCounter = 0; + state.isBlinkOn = false; + state.brightness = globalBrightness; + state.fadeAmount = FADE_AMOUNT; + state.queuedState.isQueued = false; +} + +void LEDManager::setBrightness(uint8_t brightness) { +#ifdef LED_ADDRESSABLE + globalBrightness = brightness; + for (auto& ledStrip : ledStrips) { + ledStrip.strip->setBrightness(brightness); + for (auto& state : ledStrip.ledStates) { + state.brightness = brightness; + } + } +#endif +} + +void LEDManager::setLEDColor(int stripIndex, int ledIndex, uint32_t color) { + if (stripIndex < 0 || stripIndex >= ledStrips.size()) return; + if (ledIndex < 0 || ledIndex >= ledStrips[stripIndex].ledStates.size()) return; + + uint8_t r, g, b; + extractRGB(color, r, g, b); + + r = (r * globalBrightness) / 255; + g = (g * globalBrightness) / 255; + b = (b * globalBrightness) / 255; + +#ifdef LED_ADDRESSABLE + ledStrips[stripIndex].strip->setPixelColor(ledIndex, r, g, b); + ledStrips[stripIndex].strip->show(); +#else + // For non-addressable LEDs, we'll use the first LED of each strip + if (ledIndex == 0) { + int pin = ledStrips[stripIndex].pin; + analogWrite(pin, (r + g + b) / 3); // Average of RGB for single-color LED + } +#endif +} + +void LEDManager::update() { + for (int stripIndex = 0; stripIndex < ledStrips.size(); stripIndex++) { + for (int ledIndex = 0; ledIndex < ledStrips[stripIndex].ledStates.size(); ledIndex++) { + auto& state = ledStrips[stripIndex].ledStates[ledIndex]; + switch (state.mode) { + case BLINK: + handleBlink(stripIndex, ledIndex); + break; + case PULSE: + handlePulse(stripIndex, ledIndex); + break; + case STATIC: + handleStatic(stripIndex, ledIndex); + break; + case OFF: + setLEDColor(stripIndex, ledIndex, 0); + break; + } + } +#ifdef LED_ADDRESSABLE + ledStrips[stripIndex].strip->show(); +#endif + } +} + +void LEDManager::handleBlink(int stripIndex, int ledIndex) { + auto& state = ledStrips[stripIndex].ledStates[ledIndex]; + unsigned long currentTime = millis(); + if (currentTime - state.lastUpdateTime >= BLINK_INTERVAL) { + state.lastUpdateTime = currentTime; + if (state.durationOrBlinkCount > 0) { + if (state.blinkCounter == 0) { + state.blinkCounter = state.durationOrBlinkCount * 2; + } else { + state.blinkCounter--; + if (state.blinkCounter == 0) { + if (state.queuedState.isQueued) { + applyQueuedState(stripIndex, ledIndex); + } else { + returnToPreviousState(stripIndex, ledIndex); + } + return; + } + } + } + + state.isBlinkOn = !state.isBlinkOn; + if (state.isBlinkOn) { + setLEDColor(stripIndex, ledIndex, state.color); + } else { + setLEDColor(stripIndex, ledIndex, 0); + } + } +} + +void LEDManager::handlePulse(int stripIndex, int ledIndex) { + auto& state = ledStrips[stripIndex].ledStates[ledIndex]; + unsigned long currentTime = millis(); + if (currentTime - state.lastUpdateTime >= PULSE_INTERVAL) { + state.lastUpdateTime = currentTime; + state.brightness += state.fadeAmount; + if (state.brightness <= 0 || state.brightness >= 255) { + state.fadeAmount = -state.fadeAmount; + state.brightness = constrain(state.brightness, 0, 255); + if (state.durationOrBlinkCount > 0) { + state.durationOrBlinkCount--; + if (state.durationOrBlinkCount == 0) { + if (state.queuedState.isQueued) { + applyQueuedState(stripIndex, ledIndex); + } else { + returnToPreviousState(stripIndex, ledIndex); + } + return; + } + } + } + uint32_t adjustedColor = (state.color & 0xFF000000) | + (((state.color & 0x00FF0000) * state.brightness / 255) & 0x00FF0000) | + (((state.color & 0x0000FF00) * state.brightness / 255) & 0x0000FF00) | + (((state.color & 0x000000FF) * state.brightness / 255) & 0x000000FF); + setLEDColor(stripIndex, ledIndex, adjustedColor); + } +} + +void LEDManager::handleStatic(int stripIndex, int ledIndex) { + auto& state = ledStrips[stripIndex].ledStates[ledIndex]; + unsigned long currentTime = millis(); + if (state.durationOrBlinkCount > 0) { + if (currentTime - state.lastUpdateTime >= static_cast(state.durationOrBlinkCount) * 1000) { + if (state.queuedState.isQueued) { + applyQueuedState(stripIndex, ledIndex); + } else { + returnToPreviousState(stripIndex, ledIndex); + } + return; + } + } + setLEDColor(stripIndex, ledIndex, state.color); +} + +void LEDManager::returnToPreviousState(int stripIndex, int ledIndex) { + auto& state = ledStrips[stripIndex].ledStates[ledIndex]; + state.mode = state.previousMode; + state.color = state.previousColor; + state.durationOrBlinkCount = -1; // Set to infinite for the previous state + state.lastUpdateTime = millis(); + state.blinkCounter = 0; + state.isBlinkOn = false; + state.brightness = globalBrightness; + state.fadeAmount = FADE_AMOUNT; +} + +void LEDManager::applyQueuedState(int stripIndex, int ledIndex) { + auto& state = ledStrips[stripIndex].ledStates[ledIndex]; + state.mode = state.queuedState.mode; + state.color = state.queuedState.color; + state.durationOrBlinkCount = state.queuedState.durationOrBlinkCount; + state.lastUpdateTime = millis(); + state.blinkCounter = 0; + state.isBlinkOn = false; + state.brightness = globalBrightness; + state.fadeAmount = FADE_AMOUNT; + state.queuedState.isQueued = false; +} + +void LEDManager::extractRGB(uint32_t color, uint8_t& r, uint8_t& g, uint8_t& b) { + r = (color >> 16) & 0xFF; + g = (color >> 8) & 0xFF; + b = color & 0xFF; +} \ No newline at end of file diff --git a/lib/LEDManager/LEDManager.h b/lib/LEDManager/LEDManager.h new file mode 100644 index 0000000..e625d64 --- /dev/null +++ b/lib/LEDManager/LEDManager.h @@ -0,0 +1,107 @@ +/* + Theengs LEDManager - We Unite Sensors in One Open-Source Interface + + Copyright: (c)Florian ROBERT + + This file is part of LEDManager library. + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ +#ifndef LED_MANAGER_H +#define LED_MANAGER_H + +#include + +#include + +#ifdef LED_ADDRESSABLE +# include +#endif + +#ifndef BLINK_INTERVAL +# define BLINK_INTERVAL 500 +#endif + +#ifndef PULSE_INTERVAL +# define PULSE_INTERVAL 30 +#endif + +#ifndef FADE_AMOUNT +# define FADE_AMOUNT 5 +#endif + +// Define the pins for the RGB LED power if needed +#ifndef LED_ADDRESSABLE_POWER +# define LED_ADDRESSABLE_POWER -1 +#endif + +class LEDManager { +public: + enum Mode { OFF, + STATIC, + BLINK, + PULSE }; + + LEDManager(); + void init(); + void addLEDStrip(int pin, int numLeds); + void setMode(int stripIndex, int ledIndex, Mode mode, uint32_t color, int durationOrBlinkCount = -1); + void update(); + void setBrightness(uint8_t brightness); + +private: + struct QueuedState { + Mode mode; + uint32_t color; + int durationOrBlinkCount; + bool isQueued; + }; + + struct LEDState { + Mode mode; + Mode previousMode; + uint32_t color; + uint32_t previousColor; + int durationOrBlinkCount; + unsigned long lastUpdateTime; + int blinkCounter; + bool isBlinkOn; + int brightness; + int fadeAmount; + QueuedState queuedState; + }; + + struct LEDStrip { +#ifdef LED_ADDRESSABLE + Adafruit_NeoPixel* strip; +#endif + int pin; + std::vector ledStates; + }; + + std::vector ledStrips; + int globalBrightness; + + void setModeForSingleLED(int stripIndex, int ledIndex, Mode mode, uint32_t color, int durationOrBlinkCount); + void setLEDColor(int stripIndex, int ledIndex, uint32_t color); + void handleBlink(int stripIndex, int ledIndex); + void handlePulse(int stripIndex, int ledIndex); + void handleStatic(int stripIndex, int ledIndex); + void returnToPreviousState(int stripIndex, int ledIndex); + void applyQueuedState(int stripIndex, int ledIndex); + void extractRGB(uint32_t color, uint8_t& r, uint8_t& g, uint8_t& b); +}; + +#endif // LED_MANAGER_H \ No newline at end of file diff --git a/lib/LEDManager/README.md b/lib/LEDManager/README.md new file mode 100644 index 0000000..2f25ccb --- /dev/null +++ b/lib/LEDManager/README.md @@ -0,0 +1,135 @@ +# LEDManager Library + +## Overview + +The LEDManager library provides a flexible and easy-to-use interface for controlling LEDs in projects. It supports both addressable LED strips and individual non-addressable LEDs, offering various modes of operation such as static, blinking, and pulsing. The library is designed to work seamlessly with PlatformIO and can be easily configured using build flags. + +## Features + +- Support for both addressable LED strips and individual non-addressable LEDs +- Multiple operation modes: OFF, STATIC, BLINK, and PULSE +- Individual control of LEDs within each strip (for addressable LEDs) +- Global brightness control +- Queueing of LED states for complex sequences +- Automatic return to previous state after temporary modes +- Compatible with PlatformIO build flags for easy configuration +- Customizable color schemes + +## Installation + +1. Clone this repository or download the ZIP file. +2. Extract the contents to your PlatformIO project's `lib` directory. + +## Configuration + +Configure the LEDManager library using build flags in your `platformio.ini` file: + +```ini +build_flags = + ; For addressable LEDs: + -DLED_ADDRESSABLE=true + ; For non-addressable LEDs, comment out the line above + + ; If the Addressable LED requires power + -DLED_ADDRESSABLE_POWER=15 + + ; Optional timing configurations: + -DBLINK_INTERVAL=500 + -DPULSE_INTERVAL=30 + -DFADE_AMOUNT=5 +``` + +## Usage + +Here's a basic example of how to use the LEDManager library: + +```cpp +#include "LEDManager.h" + +LEDManager ledManager; + +void setup() { + + #ifdef LED_ADDRESSABLE + ledManager.addLEDStrip(5, 30); // Add addressable LED strip on pin 5 with 30 LEDs + #else + ledManager.addLEDStrip(5, 1); // Add non-addressable LED on pin 5 + ledManager.addLEDStrip(6, 1); // Add non-addressable LED on pin 6 + #endif + + ledManager.setBrightness(128); // Set global brightness to 50% +} + +void loop() { + #ifdef LED_ADDRESSABLE + // Set all LEDs on the first strip to static green + ledManager.setMode(0, -1, LEDManager::STATIC, LED_COLOR_GREEN); + + // Blink first 5 LEDs red for 3 times on the first strip + for (int i = 0; i < 5; i++) { + ledManager.setMode(0, i, LEDManager::BLINK, LED_COLOR_RED, 3); + } + #else + // Set first LED to static green + ledManager.setMode(0, 0, LEDManager::STATIC, LED_COLOR_GREEN); + + // Blink second strip LED red + ledManager.setMode(1, 0, LEDManager::BLINK, LED_COLOR_RED, 3); + #endif + + ledManager.update(); + delay(100); +} +``` + +## API Reference + +### Initialization and Setup + +```cpp +LEDManager ledManager; +ledManager.addLEDStrip(int pin, int numLeds); +``` + +### Setting LED Mode + +```cpp +ledManager.setMode(int stripIndex, int ledIndex, Mode mode, uint32_t color, int durationOrBlinkCount = -1); +``` + +- `stripIndex`: Index of the LED strip (0-based) +- `ledIndex`: LED index within the strip (0-based) or -1 for all LEDs in the strip (addressable LEDs only) +- `mode`: `LEDManager::OFF`, `LEDManager::STATIC`, `LEDManager::BLINK`, or `LEDManager::PULSE` +- `color`: Color value (use predefined colors from LEDColorDefinitions.h or custom 24-bit RGB values) +- `durationOrBlinkCount`: Duration for STATIC mode (in milliseconds), blink/pulse count for BLINK/PULSE modes (-1 for infinite) + +### Setting Brightness + +```cpp +ledManager.setBrightness(brightness); +``` + +- `brightness`: Global brightness value (0-255) + +### Updating LEDs + +Call this method in your main loop to update LED states: + +```cpp +ledManager.update(); +``` +## Advanced Configuration + +You can customize the behavior of the LEDManager by defining the following build flags: + +- `BLINK_INTERVAL`: Sets the interval (in milliseconds) between blink states (default: 500) +- `PULSE_INTERVAL`: Sets the interval (in milliseconds) between pulse updates (default: 30) +- `FADE_AMOUNT`: Sets the increment/decrement value for pulsing (default: 5) + +## Contributing + +Contributions to the LEDManager library are welcome! Please feel free to submit a Pull Request. + +## License + +This library is released under the LGPL V3 License. \ No newline at end of file diff --git a/lib/TheengsUtils/TheengsUtils.cpp b/lib/TheengsUtils/TheengsUtils.cpp new file mode 100644 index 0000000..bb96be2 --- /dev/null +++ b/lib/TheengsUtils/TheengsUtils.cpp @@ -0,0 +1,185 @@ +/* + Theengs - IoT Interoperability + + Copyright: (c)Florian ROBERT + + This file is part of Theengs products. + + Theengs 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. + + Theengs 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 . +*/ + +#include "TheengsUtils.h" + +String TheengsUtils::toString(uint64_t input) { + String result = ""; + uint8_t base = 10; + + do { + char c = input % base; + input /= base; + + if (c < 10) + c += '0'; + else + c += 'A' - 10; + result = c + result; + } while (input); + return result; +} + +/* +* @brief Convert the spaces of the certificate into new lines +*/ +std::string TheengsUtils::processCert(const char* cert) { + std::string certStr(cert); + size_t pos = 0; + while ((pos = certStr.find(' ', pos)) != std::string::npos) { + if (pos < 4 || (pos >= 27 && pos <= certStr.length() - 25) || pos >= certStr.length() - 4) { + certStr.replace(pos, 1, "\n"); + } + pos++; + } + return certStr; +} + +#ifdef ESP32 +# include "mbedtls/sha256.h" + +std::string TheengsUtils::generateHash(const std::string& input) { + unsigned char hash[32]; + mbedtls_sha256((unsigned char*)input.c_str(), input.length(), hash, 0); + + char hashString[65]; // Room for null terminator + for (int i = 0; i < 32; ++i) { + sprintf(&hashString[i * 2], "%02x", hash[i]); + } + + return std::string(hashString); +} +#else +std::string TheengsUtils::generateHash(const std::string& input) { + return "Not implemented for ESP8266"; +} +#endif + +unsigned long TheengsUtils::uptime() { + static unsigned long lastUptime = 0; + static unsigned long uptimeAdd = 0; + unsigned long uptime = millis() / 1000 + uptimeAdd; + if (uptime < lastUptime) { + uptime += 4294967; + uptimeAdd += 4294967; + } + lastUptime = uptime; + return uptime; +} + +void TheengsUtils::syncNTP() { + configTime(0, 0, "pool.ntp.org"); + time_t now = time(nullptr); + while (now < 8 * 3600 * 2) { + delay(500); + now = time(nullptr); + } +} + +int TheengsUtils::unixtimestamp() { + return time(nullptr); +} + +String TheengsUtils::UTCtimestamp() { + time_t now; + time(&now); + char buffer[sizeof "yyyy-MM-ddThh:mm:ssZ"]; + strftime(buffer, sizeof buffer, "%FT%TZ", gmtime(&now)); + return buffer; +} + +void TheengsUtils::revert_hex_data(const char* in, char* out, int l) { + //reverting array 2 by 2 to get the data in good order + int i = l - 2, j = 0; + while (i != -2) { + if (i % 2 == 0) + out[j] = in[i + 1]; + else + out[j] = in[i - 1]; + j++; + i--; + } + out[l - 1] = '\0'; +} + +/** + * Retrieve an unsigned long value from a char array extract representing hexadecimal data, reversed or not, + * This value can represent a negative value if canBeNegative is set to true + */ +long TheengsUtils::value_from_hex_data(const char* service_data, int offset, int data_length, bool reverse, bool canBeNegative) { + char data[data_length + 1]; + memcpy(data, &service_data[offset], data_length); + data[data_length] = '\0'; + long value; + if (reverse) { + // reverse data order + char rev_data[data_length + 1]; + revert_hex_data(data, rev_data, data_length + 1); + value = strtol(rev_data, NULL, 16); + } else { + value = strtol(data, NULL, 16); + } + if (value > 65000 && data_length <= 4 && canBeNegative) + value = value - 65535; + return value; +} + +/* + rounds a number to 2 decimal places + example: round(3.14159) -> 3.14 +*/ +double TheengsUtils::round2(float value) { + return (int)(value * 100 + 0.5) / 100.0; +} + +/* +From a byte array to an hexa char array ("A220EE...", double the size) + */ +bool TheengsUtils::_rawToHex(byte* in, char* out, int rawSize) { + for (unsigned char p = 0; p < rawSize; p++) { + sprintf_P(&out[p * 2], PSTR("%02X\r"), in[p]); + } + return true; +} + +/* +From an hexa char array ("A220EE...") to a byte array (half the size) + */ +bool TheengsUtils::_hexToRaw(const char* in, byte* out, int rawSize) { + if (strlen(in) != rawSize * 2) + return false; + char tmp[3] = {0}; + for (unsigned char p = 0; p < rawSize; p++) { + memcpy(tmp, &in[p * 2], 2); + out[p] = strtol(tmp, NULL, 16); + } + return true; +} + +char* TheengsUtils::ip2CharArray(IPAddress ip) { + static char ipChar[16]; + sprintf(ipChar, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + return ipChar; +} + +bool TheengsUtils::to_bool(String const& s) { + return s != "0" && s != "false" && s != "False" && s != "FALSE"; +} \ No newline at end of file diff --git a/lib/TheengsUtils/TheengsUtils.h b/lib/TheengsUtils/TheengsUtils.h new file mode 100644 index 0000000..90b520e --- /dev/null +++ b/lib/TheengsUtils/TheengsUtils.h @@ -0,0 +1,48 @@ +/* + Theengs - IoT Interoperability + + Copyright: (c)Florian ROBERT + + This file is part of Theengs products. + + Theengs 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. + + Theengs 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 . +*/ + +#ifndef THEENGS_UTIL_H +#define THEENGS_UTIL_H + +#include +#include +#include +#include + +class TheengsUtils { +public: + static String toString(uint64_t input); + static std::string processCert(const char* cert); + static std::string generateHash(const std::string& input); + static unsigned long uptime(); + static void syncNTP(); + static int unixtimestamp(); + static String UTCtimestamp(); + static void revert_hex_data(const char* in, char* out, int l); + static long value_from_hex_data(const char* service_data, int offset, int data_length, bool reverse, bool canBeNegative = true); + static double round2(float value); + static bool _rawToHex(byte* in, char* out, int rawSize); + static bool _hexToRaw(const char* in, byte* out, int rawSize); + static char* ip2CharArray(IPAddress ip); + static bool to_bool(String const& s); +}; + +#endif \ No newline at end of file diff --git a/main/TheengsCommon.h b/main/TheengsCommon.h new file mode 100644 index 0000000..44b9276 --- /dev/null +++ b/main/TheengsCommon.h @@ -0,0 +1,118 @@ +#pragma once + +#include "User_config.h" + +#define ARDUINOJSON_USE_LONG_LONG 1 +#define ARDUINOJSON_ENABLE_STD_STRING 1 +#include +#include + +#if defined(ESP32) +# include +extern Preferences preferences; +#endif + +// Flags definition for white list, black list, discovery management +#define device_flags_init 0 << 0 +#define device_flags_isDisc 1 << 0 +#define device_flags_isWhiteL 1 << 1 +#define device_flags_isBlackL 1 << 2 +#define device_flags_connect 1 << 3 +#define isWhite(device) device->isWhtL +#define isBlack(device) device->isBlkL +#define isDiscovered(device) device->isDisc + +enum GatewayState { + WAITING_ONBOARDING, + ONBOARDING, + OFFLINE, + NTWK_CONNECTED, + BROKER_CONNECTED, + PROCESSING, + NTWK_DISCONNECTED, + BROKER_DISCONNECTED, + LOCAL_OTA_IN_PROGRESS, + REMOTE_OTA_IN_PROGRESS, + SLEEPING, + ERROR +}; + +enum PowerMode { + DEACTIVATED = -1, + ALWAYS_ON, + INTERVAL, + ACTION +}; + +struct SYSConfig_s { + bool mqtt; // if true the gateway will publish the received data on the MQTT broker + bool serial; // if true the gateway will publish the received data on the SERIAL + bool blufi; // if true the gateway will be accesible with blufi + bool offline; + bool discovery; // HA discovery convention +#ifdef LED_ADDRESSABLE + int rgbbrightness; // brightness of the RGB LED +#endif + enum PowerMode powerMode; +}; + +extern GatewayState gatewayState; +extern SYSConfig_s SYSConfig; +extern bool ready_to_sleep; +extern char mqtt_topic[]; +extern char gateway_name[]; +extern unsigned long lastDiscovery; // Time of the last discovery to trigger automaticaly to off after DiscoveryAutoOffTimer + +#if BLEDecryptor +extern char ble_aes[]; +extern StaticJsonDocument ble_aes_keys; +#endif + +extern bool enqueueJsonObject(const StaticJsonDocument& jsonDoc, int timeout); +extern bool enqueueJsonObject(const StaticJsonDocument& jsonDoc); +extern void buildTopicFromId(JsonObject& Jsondata, const char* origin); +extern bool pubMQTT(const char* topic, const char* payload); +extern bool pubMQTT(const char* topic, const char* payload, bool retainFlag); +extern bool pubMQTT(String topic, const char* payload); +extern bool pubMQTT(const char* topic, unsigned long payload); +extern bool pubMQTT(const char* topic, unsigned long long payload); +extern bool pubMQTT(const char* topic, String payload); +extern bool pubMQTT(String topic, String payload); +extern bool pubMQTT(String topic, int payload); +extern bool pubMQTT(String topic, unsigned long long payload); +extern bool pubMQTT(String topic, float payload); +extern bool pubMQTT(const char* topic, float payload); +extern bool pubMQTT(const char* topic, int payload); +extern bool pubMQTT(const char* topic, unsigned int payload); +extern bool pubMQTT(const char* topic, long payload); +extern bool pubMQTT(const char* topic, double payload); +extern bool pubMQTT(String topic, unsigned long payload); +extern unsigned long uptime(); +extern bool cmpToMainTopic(const char*, const char*); +extern bool pub(const char*, const char*, bool); +extern bool pub(const char*, const char*); + +// Float-specific overload to log with the correct format specifier. +inline void Config_update(JsonObject& data, const char* key, float& var) { + if (data.containsKey(key)) { + float newVal = data[key].as(); + if (var != newVal) { + var = newVal; + THEENGS_LOG_NOTICE(F("Config %s changed to: %F" CR), key, newVal); + } else { + THEENGS_LOG_NOTICE(F("Config %s unchanged, currently: %F" CR), key, newVal); + } + } +} + +template +void Config_update(JsonObject& data, const char* key, T& var) { + if (data.containsKey(key)) { + if (var != data[key].as()) { + var = data[key].as(); + THEENGS_LOG_NOTICE(F("Config %s changed to: %T" CR), key, data[key].as()); + } else { + THEENGS_LOG_NOTICE(F("Config %s unchanged, currently: %T" CR), key, data[key].as()); + } + } +} diff --git a/main/User_config.h b/main/User_config.h index b80aa3c..bdd7792 100644 --- a/main/User_config.h +++ b/main/User_config.h @@ -1,7 +1,7 @@ /* OpenMQTTGateway - ESP8266 or Arduino program for home automation - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This program enables to: @@ -29,7 +29,7 @@ #define user_config_h /*-------------------VERSION----------------------*/ #ifndef OMG_VERSION -# define OMG_VERSION "version_tag" +# define OMG_VERSION "edge" #endif /*-------------CONFIGURE WIFIMANAGER-------------(only ESP8266 & SONOFF RFBridge)*/ @@ -57,7 +57,7 @@ # define Gateway_Name "OpenMQTTGateway" #endif #ifndef Gateway_Short_Name -# define Gateway_Short_Name "OMG" +# define Gateway_Short_Name "OMG" // 3 characters maximum #endif #ifndef Base_Topic @@ -82,12 +82,7 @@ # endif #endif -#if defined(ESP8266) || defined(ESP32) // for nodemcu, weemos and esp8266 //# define ESPWifiManualSetup true //uncomment you don't want to use wifimanager for your credential settings on ESP -#else // for arduino boards -const byte ip[] = {192, 168, 1, 99}; -const byte mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95}; //W5100 ethernet shield MAC address -#endif //#define ESP32_ETHERNET=true // Uncomment to use Ethernet module on ESP32 Ethernet gateway and adapt the settings to your board below, the default parameter are for OLIMEX ESP32 gateway #ifdef ESP32_ETHERNET @@ -140,28 +135,44 @@ const byte mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95}; //W5100 ethernet shield #define maxConnectionRetryNetwork 5 //maximum Wifi connection attempts with existing credential at start (used to bypass ESP32 issue on wifi connect) #define maxRetryWatchDog 11 //maximum Wifi or MQTT re-connection attempts before restarting +// WifiReconnectWatchDog: restart the ESP if the network can't be recovered after maxRetryWatchDog +// consecutive reconnection attempts in the main loop. This allows the gateway to self-heal from a +// wedged WiFi stack (e.g. the ESP32 driver getting stuck after a long uptime). Disable it on +// environments where an unexpected reboot is undesirable (e.g. a smart plug that would lose its relay state). +#ifndef WifiReconnectWatchDog +# define WifiReconnectWatchDog true +#endif + //set minimum quality of signal so it ignores AP's under that quality #define MinimumWifiSignalQuality 8 /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ //MQTT Parameters definition -#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) -# define parameters_size 65 -# define mqtt_topic_max_size 150 -# ifndef mqtt_max_packet_size -# ifdef MQTT_HTTPS_FW_UPDATE -# ifndef CHECK_OTA_UPDATE -# define CHECK_OTA_UPDATE true // enable to check for the presence of a new version for your environment on Github -# endif -# define mqtt_max_packet_size 2560 -# else -# define mqtt_max_packet_size 1024 -# endif +#define parameters_size 65 +#define mqtt_topic_max_size 150 +#define mqtt_key_max_size 20 +#ifdef MQTT_HTTPS_FW_UPDATE +# ifndef CHECK_OTA_UPDATE +# define CHECK_OTA_UPDATE true // enable to check for the presence of a new version for your environment on Github # endif -#else -# define parameters_size 30 -# define mqtt_topic_max_size 75 -# define mqtt_max_packet_size 128 +#endif + +#ifndef JSON_MSG_BUFFER +# if defined(ESP32) +# define JSON_MSG_BUFFER 1024 // adjusted to minimum size covering largest home assistant discovery messages +# if MQTT_SECURE_DEFAULT +# define JSON_MSG_BUFFER_MAX 2048 // Json message buffer size increased to handle certificate changes through MQTT, used for the queue and the coming MQTT messages +# else +# define JSON_MSG_BUFFER_MAX 1024 // Minimum size for the cover MQTT discovery message +# endif +# elif defined(ESP8266) +# define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 768 or higher it is causing unexpected behaviour on ESP8266, certificates handling with ESP8266 is not tested +# define JSON_MSG_BUFFER_MAX 832 // Minimum size for MQTT discovery message +# endif +#endif + +#ifndef mqtt_max_payload_size +# define mqtt_max_payload_size JSON_MSG_BUFFER_MAX + mqtt_topic_max_size + 10 // maximum size of the MQTT payload #endif #ifndef MQTT_USER @@ -187,113 +198,120 @@ const byte mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95}; //W5100 ethernet shield # define QueueSemaphoreTimeOutLoop 100 // time out for semaphore retrieval from the loop #endif -#if defined(ESP8266) || defined(ESP32) // Uncomment to use a device running TheengsGateway to decode BLE data. (https://github.com/theengs/gateway) // Set the topic to the subscribe topic configured in the TheengGateway // #define MQTTDecodeTopic "MQTTDecode" -// The root ca certificate used for validating the MQTT broker -// The certificate must be in PEM ascii format -const char* certificate PROGMEM = R"EOF(" ------BEGIN CERTIFICATE----- -... ------END CERTIFICATE----- -")EOF"; +#define ATTEMPTS_BEFORE_BG 10 // Number of wifi connection attempts before going to BG protocol +#define ATTEMPTS_BEFORE_B 20 // Number of wifi connection attempts before going to B protocol -# define ATTEMPTS_BEFORE_BG 10 // Number of wifi connection attempts before going to BG protocol -# define ATTEMPTS_BEFORE_B 20 // Number of wifi connection attempts before going to B protocol +#ifndef NTP_SERVER +# define NTP_SERVER "pool.ntp.org" +#endif -# ifndef NTP_SERVER -# define NTP_SERVER "pool.ntp.org" -# endif +#ifndef MQTT_SECURE_DEFAULT +# define MQTT_SECURE_DEFAULT false +#endif -# ifndef MQTT_SECURE_DEFAULT -# define MQTT_SECURE_DEFAULT false -# endif +#ifndef MQTT_CERT_VALIDATE_DEFAULT +# define MQTT_CERT_VALIDATE_DEFAULT false +#endif -# ifndef MQTT_CERT_VALIDATE_DEFAULT -# define MQTT_CERT_VALIDATE_DEFAULT false -# endif +#ifndef AWS_IOT +# define AWS_IOT false +#endif -# ifndef AWS_IOT -# define AWS_IOT false -# endif +#ifndef MQTT_BROKER_MODE +# define MQTT_BROKER_MODE false +#endif -# if AWS_IOT +#if MQTT_BROKER_MODE +// In MQTT broker mode the MQTT web config is not needed +# define WIFIMNG_HIDE_MQTT_CONFIG true +#endif + +#define GITHUB_OTA_SERVER_CERT_HASH "d4d211b4553af9fac371f24c2268d59d2b0fec6b9aa0fdbbde068f078d7daf86" // SHA256 fingerprint of the certificate used by the OTA server + +#if AWS_IOT // Enable the use of ALPN for AWS IoT Core with the port 443 -const char* alpnProtocols[] = {"x-amzn-mqtt-ca", NULL}; -# endif +# define ALPN_PROTOCOLS \ + { "x-amzn-mqtt-ca", NULL } +#endif //# define MQTT_HTTPS_FW_UPDATE //uncomment to enable updating via MQTT message. -# ifdef MQTT_HTTPS_FW_UPDATE +#ifdef MQTT_HTTPS_FW_UPDATE // If used, this should be set to the root CA certificate of the server hosting the firmware. -# ifdef PRIVATE_CERTS -# include "certs/private_ota_cert.h" -# else -# include "certs/default_ota_cert.h" -# endif +# ifdef PRIVATE_CERTS +# include "certs/private_ota_cert.h" +# else +# include "certs/default_ota_cert.h" +# endif -# ifndef MQTT_HTTPS_FW_UPDATE_USE_PASSWORD -# define MQTT_HTTPS_FW_UPDATE_USE_PASSWORD 1 // Set this to 0 if not using TLS connection to MQTT broker to prevent clear text passwords being sent. -# endif +# ifndef MQTT_HTTPS_FW_UPDATE_USE_PASSWORD +# define MQTT_HTTPS_FW_UPDATE_USE_PASSWORD 1 // Set this to 0 if not using TLS connection to MQTT broker to prevent clear text passwords being sent. +# endif +# ifndef OTA_JSON_URL // may be overridden by a build flag to use another OTA server # if DEVELOPMENTOTA -# define OTA_JSON_URL "https://github.com/1technophile/OpenMQTTGateway/raw/gh-pages/dev/firmware_build/latest_version_dev.json" //OTA url used to discover new versions of the firmware from development nightly builds +# define OTA_JSON_URL "https://ota.openmqttgateway.com/binaries/dev/latest_version_dev.json" //OTA url used to discover new versions of the firmware from development nightly builds # else -# define OTA_JSON_URL "https://github.com/1technophile/OpenMQTTGateway/raw/gh-pages/firmware_build/latest_version.json" //OTA url used to discover new versions of the firmware +# define OTA_JSON_URL "https://ota.openmqttgateway.com/binaries/latest_version.json" //OTA url used to discover new versions of the firmware # endif -# define ENTITY_PICTURE "https://github.com/1technophile/OpenMQTTGateway/raw/development/docs/img/Openmqttgateway_logo_mini_margins.png" -# define RELEASE_LINK_DEV "https://github.com/1technophile/OpenMQTTGateway/raw/gh-pages/dev/firmware_build/" -# define RELEASE_LINK "https://github.com/1technophile/OpenMQTTGateway/releases/download/" # endif +# define ENTITY_PICTURE "https://github.com/1technophile/OpenMQTTGateway/raw/development/docs/img/Openmqttgateway_logo_mini_margins.png" +# define RELEASE_LINK_DEV "https://ota.openmqttgateway.com/binaries/dev/" +# define RELEASE_LINK "https://ota.openmqttgateway.com/binaries/" +#else +static const char* OTAserver_cert = ""; +#endif -# ifndef MQTT_SECURE_SELF_SIGNED -# define MQTT_SECURE_SELF_SIGNED 0 -# endif +#ifndef MQTT_SECURE_SIGNED_CLIENT +# define MQTT_SECURE_SIGNED_CLIENT 0 // If using a signed certificate for the broker and using client certificate/key set this to true or 1 +#endif -# ifndef MQTT_SECURE_SELF_SIGNED_CLIENT -# define MQTT_SECURE_SELF_SIGNED_CLIENT 1 // If using a self signed certificate for the broker and not using client certificates set this to false or 0 -# endif +#ifdef PRIVATE_CERTS +# include "certs/private_client_cert.h" +# include "certs/private_client_key.h" +# include "certs/private_server_cert.h" +#else +# include "certs/default_client_cert.h" +# include "certs/default_client_key.h" +# include "certs/default_server_cert.h" +#endif -# ifndef MQTT_SECURE_SELF_SIGNED_INDEX_DEFAULT -# define MQTT_SECURE_SELF_SIGNED_INDEX_DEFAULT 0 -# endif +#include -# if MQTT_SECURE_SELF_SIGNED -# ifdef PRIVATE_CERTS -# include "certs/private_client_cert.h" -# include "certs/private_client_key.h" -# include "certs/private_server_cert.h" -# else -# include "certs/default_client_cert.h" -# include "certs/default_client_key.h" -# include "certs/default_server_cert.h" -# endif +#ifndef CNT_DEFAULT_INDEX +# define CNT_DEFAULT_INDEX 0 // Default set of connection parameters +#endif -struct ss_certs { - const char* server_cert; - const char* client_cert; - const char* client_key; +#if !MQTT_BROKER_MODE +struct ss_cnt_parameters { + std::string server_cert; + std::string client_cert; + std::string client_key; + std::string ota_server_cert; + char mqtt_server[parameters_size]; + char mqtt_port[6]; + char mqtt_user[parameters_size]; + char mqtt_pass[parameters_size]; + bool isConnectionSecure; + bool isCertValidate; + bool validConnection; }; -struct ss_certs certs_array[2] = { - {ss_server_cert, ss_client_cert, ss_client_key}, - {ss_server_cert, ss_client_cert, ss_client_key}}; +# define CNT_PARAMS_ARR \ + { \ + {ss_server_cert, ss_client_cert, ss_client_key, OTAserver_cert, MQTT_SERVER, MQTT_PORT, MQTT_USER, MQTT_PASS, MQTT_SECURE_DEFAULT, MQTT_CERT_VALIDATE_DEFAULT, false}, \ + {"", "", "", "", MQTT_SERVER, MQTT_PORT, MQTT_USER, MQTT_PASS, MQTT_SECURE_DEFAULT, MQTT_CERT_VALIDATE_DEFAULT, false}, \ + { "", "", "", "", MQTT_SERVER, MQTT_PORT, MQTT_USER, MQTT_PASS, MQTT_SECURE_DEFAULT, MQTT_CERT_VALIDATE_DEFAULT, false } \ + } +# define cnt_parameters_array_size 3 -static_assert(MQTT_SECURE_SELF_SIGNED_INDEX_DEFAULT < (sizeof(certs_array) / sizeof(ss_certs)), - "Invalid MQTT self signed default index"); -# endif +extern ss_cnt_parameters cnt_parameters_array[]; #endif -/** - * Deep-sleep for the ESP8266. - * Set the wake pin. - */ -#if defined(DEEP_SLEEP_IN_US) && defined(ESP8266) -# ifndef ESP8266_DEEP_SLEEP_WAKE_PIN -# define ESP8266_DEEP_SLEEP_WAKE_PIN D0 -# endif -#endif +#define MIN_CERT_LENGTH 200 // Minimum length of a certificate to be considered valid /** * Ext wake for Deep-sleep for the ESP32. @@ -305,16 +323,23 @@ static_assert(MQTT_SECURE_SELF_SIGNED_INDEX_DEFAULT < (sizeof(certs_array) / siz # endif #endif -/*------------------DEEP SLEEP parameters ------------------*/ -//DEFAULT_LOW_POWER_MODE -1 to normal mode, low power mode can't be used on this build -//DEFAULT_LOW_POWER_MODE 0 to normal mode (no power consumption optimisations) -//DEFAULT_LOW_POWER_MODE 1 to activate deep sleep -//DEFAULT_LOW_POWER_MODE 2 to activate deep sleep (LCD is turned OFF) -#ifdef ESP32 -# ifndef DEFAULT_LOW_POWER_MODE -# define DEFAULT_LOW_POWER_MODE -1 +#ifdef ESP32_EXT1_WAKE_PIN +# ifndef ESP32_EXT1_WAKE_PIN_STATE +# define ESP32_EXT1_WAKE_PIN_STATE 1 # endif -int lowpowermode = DEFAULT_LOW_POWER_MODE; +#endif + +#ifndef DEEP_SLEEP_IN_US +# define DEEP_SLEEP_IN_US 60000000 // 1 minute +#endif + +/*------------------DEEP SLEEP parameters ------------------*/ +//DEFAULT_LOW_POWER_MODE DEACTIVATED low power mode can't be used on this build to prevent bricking devices that does not support low power mode +//DEFAULT_LOW_POWER_MODE ALWAYS_ON normal mode (no power consumption optimisations) +//DEFAULT_LOW_POWER_MODE INTERVAL to activate deep sleep with intervals and action wake up +//DEFAULT_LOW_POWER_MODE ACTION to activate deep sleep with action wake up +#ifndef DEFAULT_LOW_POWER_MODE +# define DEFAULT_LOW_POWER_MODE DEACTIVATED #endif /*-------------DEFINE THE MODULES YOU WANT BELOW----------------*/ @@ -357,7 +382,7 @@ int lowpowermode = DEFAULT_LOW_POWER_MODE; //#define ZactuatorPWM "PWM" //ESP8266, ESP32 //#define ZsensorSHTC3 "SHTC3" //ESP8266, Arduino, ESP32, Sonoff RF Bridge //#define ZactuatorSomfy "Somfy" //ESP8266, Arduino, ESP32 -//#define ZgatewayRS232 "RS232" //ESP8266, Arduino, ESP32 +//#define ZgatewaySERIAL "SERIAL" //ESP8266, Arduino, ESP32 /*-------------DEFINE YOUR MQTT ADVANCED PARAMETERS BELOW----------------*/ #ifndef will_Topic @@ -421,226 +446,102 @@ int lowpowermode = DEFAULT_LOW_POWER_MODE; # define ota_timeout_millis 30000 #endif -/*-------------ERRORS, INFOS, SEND RECEIVE Display through LED----------------*/ -#ifndef RGB_INDICATORS // Management of Errors, reception/emission and informations indicators with basic LED -/*-------------DEFINE PINs FOR STATUS LEDs----------------*/ -# ifndef LED_SEND_RECEIVE -# ifdef ESP8266 -//# define LED_SEND_RECEIVE 40 -# elif ESP32 -//# define LED_SEND_RECEIVE 40 -# elif __AVR_ATmega2560__ //arduino mega -//# define LED_SEND_RECEIVE 40 -# else //arduino uno/nano -//# define LED_SEND_RECEIVE 40 -# endif -# endif -# ifndef LED_SEND_RECEIVE_ON -# define LED_SEND_RECEIVE_ON HIGH -# endif -# ifndef LED_ERROR -# ifdef ESP8266 -//# define LED_ERROR 42 -# elif ESP32 -//# define LED_ERROR 42 -# elif __AVR_ATmega2560__ //arduino mega -//# define LED_ERROR 42 -# else //arduino uno/nano -//# define LED_ERROR 42 -# endif -# endif -# ifndef LED_ERROR_ON -# define LED_ERROR_ON HIGH -# endif -# ifndef LED_INFO -# ifdef ESP8266 -//# define LED_INFO 44 -# elif ESP32 -//# define LED_INFO 44 -# elif __AVR_ATmega2560__ //arduino mega -//# define LED_INFO 44 -# else //arduino uno/nano -//# define LED_INFO 44 -# endif -# endif -# ifndef LED_INFO_ON -# define LED_INFO_ON HIGH -# endif +// LED index depending on state, each state can have a different LED index or be grouped if there is a limited number of LEDs +#ifndef LED_ERROR +# define LED_ERROR 0 +#endif +#ifndef LED_PROCESSING +# define LED_PROCESSING 0 +#endif +#ifndef LED_BROKER +# define LED_BROKER 0 +#endif +#ifndef LED_NETWORK +# define LED_NETWORK 0 +#endif -# ifdef LED_ERROR -# define SetupIndicatorError() \ - pinMode(LED_ERROR, OUTPUT); \ - ErrorIndicatorOFF(); -# define ErrorIndicatorON() digitalWrite(LED_ERROR, LED_ERROR_ON) -# define ErrorIndicatorOFF() digitalWrite(LED_ERROR, !LED_ERROR_ON) -# else -# define SetupIndicatorError() -# define ErrorIndicatorON() -# define ErrorIndicatorOFF() -# endif -# ifdef LED_SEND_RECEIVE -# define SetupIndicatorSendReceive() \ - pinMode(LED_SEND_RECEIVE, OUTPUT); \ - SendReceiveIndicatorOFF(); -# define SendReceiveIndicatorON() digitalWrite(LED_SEND_RECEIVE, LED_SEND_RECEIVE_ON) -# define SendReceiveIndicatorOFF() digitalWrite(LED_SEND_RECEIVE, !LED_SEND_RECEIVE_ON) -# else -# define SetupIndicatorSendReceive() -# define SendReceiveIndicatorON() -# define SendReceiveIndicatorOFF() -# endif -# ifdef LED_INFO -# define SetupIndicatorInfo() \ - pinMode(LED_INFO, OUTPUT); \ - InfoIndicatorOFF(); -# define InfoIndicatorON() digitalWrite(LED_INFO, LED_INFO_ON) -# define InfoIndicatorOFF() digitalWrite(LED_INFO, !LED_INFO_ON) -# else -# define SetupIndicatorInfo() -# define InfoIndicatorON() -# define InfoIndicatorOFF() -# endif -# define CriticalIndicatorON() // Not used -# define PowerIndicatorON() // Not used -# define PowerIndicatorOFF() // Not used -# define SetupIndicators() // Not used -#else // Management of Errors, reception/emission and informations indicators with RGB LED -# include -# ifndef ANEOPIX_IND_TYPE // needs library constants -# define ANEOPIX_IND_TYPE NEO_GRB + NEO_KHZ800 // ws2812 and alike -# endif -Adafruit_NeoPixel leds(ANEOPIX_IND_NUM_LEDS, ANEOPIX_IND_DATA_GPIO, ANEOPIX_IND_TYPE); -# ifdef ANEOPIX_IND_DATA_GPIO2 // Only used for Critical Indicator -// assume the same LED type -Adafruit_NeoPixel leds2(ANEOPIX_IND_NUM_LEDS, ANEOPIX_IND_DATA_GPIO2, ANEOPIX_IND_TYPE); -# endif +// LED Strip index +#ifndef STRIP_ERROR +# define STRIP_ERROR 0 +#endif +#ifndef STRIP_PROCESSING +# define STRIP_PROCESSING 0 +#endif +#ifndef STRIP_BROKER +# define STRIP_BROKER 0 +#endif +#ifndef STRIP_NETWORK +# define STRIP_NETWORK 0 +#endif +#ifndef STRIP_POWER +# define STRIP_POWER 0 +#endif -# ifndef RGB_LED_POWER -# define RGB_LED_POWER -1 // If the RGB Led is linked to GPIO pin for power define it here +// Single standard LED pin +#ifndef LED_PIN +# ifdef LED_BUILTIN +# define LED_PIN LED_BUILTIN # endif -# ifndef ANEOPIX_BRIGHTNESS -# define ANEOPIX_BRIGHTNESS 20 // Set Default maximum RGB brightness to approx 10% (0-255 scale) +#endif +#ifndef LED_PIN_ON +# define LED_PIN_ON HIGH +#endif +#ifndef LED_ACTUATOR_ONOFF +# ifdef LED_BUILTIN +# define LED_ACTUATOR_ONOFF LED_BUILTIN # endif -# ifndef DEFAULT_ADJ_BRIGHTNESS -# define DEFAULT_ADJ_BRIGHTNESS 255 // Set Default RGB adjustable brightness -# endif -# ifndef ANEOPIX_COLOR_SCHEME // allow for different color combinations -# define ANEOPIX_COLOR_SCHEME 0 -# endif -// Allow to set LED used (for example thingpulse gateway has 4 we use them independently) -# ifndef ANEOPIX_INFO_LED -# define ANEOPIX_INFO_LED 0 // First Led -# endif -# ifndef ANEOPIX_SEND_RECEIVE_LED -# define ANEOPIX_SEND_RECEIVE_LED 0 // First Led -# endif -# ifndef ANEOPIX_ERROR_LED -# define ANEOPIX_ERROR_LED 0 // First Led -# endif -# ifndef ANEOPIX_CRITICAL_LED -# define ANEOPIX_CRITICAL_LED 0 // First Led -# endif -// compile time calculation of color values -# define ANEOPIX_RED ((0xFF * ANEOPIX_BRIGHTNESS) >> 8) << 16 -# define ANEOPIX_RED_DIM ((0x3F * ANEOPIX_BRIGHTNESS) >> 8) << 16 // dimmed /4 -# define ANEOPIX_ORANGE (((0xFF * ANEOPIX_BRIGHTNESS) >> 8) << 16) | \ - (((0xA5 * ANEOPIX_BRIGHTNESS) >> 8) << 8) -# define ANEOPIX_GOLD (((0xFF * ANEOPIX_BRIGHTNESS) >> 8) << 16) | \ - (((0xD7 * ANEOPIX_BRIGHTNESS) >> 8) << 8) -# define ANEOPIX_GREEN ((0xFF * ANEOPIX_BRIGHTNESS) >> 8) << 8 -# define ANEOPIX_GREEN_DIM ((0x3F * ANEOPIX_BRIGHTNESS) >> 8) << 8 // dimmed /4 -# define ANEOPIX_AQUA (((0xFF * ANEOPIX_BRIGHTNESS) >> 8) << 8) | \ - (0xFF * ANEOPIX_BRIGHTNESS) >> 8 -# define ANEOPIX_BLUE (0xFF * ANEOPIX_BRIGHTNESS) >> 8 -# define ANEOPIX_BLUE_DIM (0x3F * ANEOPIX_BRIGHTNESS) >> 8 // dimmed /4 -# define ANEOPIX_BLACK 0 +#endif -# if ANEOPIX_COLOR_SCHEME == 0 -// original color combination remains default -# define ANEOPIX_INFO ANEOPIX_GREEN -# define ANEOPIX_ERROR ANEOPIX_ORANGE -# define ANEOPIX_SENDRECEIVE ANEOPIX_BLUE -# define ANEOPIX_CRITICAL ANEOPIX_RED // second led -# define ANEOPIX_POWER ANEOPIX_GREEN // second led -# define ANEOPIX_BOOT ANEOPIX_BLACK // unused -# define ANEOPIX_OFF ANEOPIX_BLACK -// color combinations tested for good visibility of onboard leds -# elif ANEOPIX_COLOR_SCHEME == 1 -# define ANEOPIX_INFO ANEOPIX_GREEN_DIM // dimmed green info background -# define ANEOPIX_ERROR ANEOPIX_RED_DIM -# define ANEOPIX_SENDRECEIVE ANEOPIX_GOLD // bright gold = sending -# define ANEOPIX_CRITICAL ANEOPIX_BLACK // unused -# define ANEOPIX_POWER ANEOPIX_BLACK // unused -# define ANEOPIX_BOOT ANEOPIX_AQUA -# define ANEOPIX_OFF ANEOPIX_BLACK -# else -# define ANEOPIX_INFO ANEOPIX_BLUE_DIM // dimmed blue info background -# define ANEOPIX_ERROR ANEOPIX_RED_DIM -# define ANEOPIX_SENDRECEIVE ANEOPIX_GOLD // bright gold = sending -# define ANEOPIX_CRITICAL ANEOPIX_BLACK // unused -# define ANEOPIX_POWER ANEOPIX_BLACK // unused -# define ANEOPIX_BOOT ANEOPIX_AQUA -# define ANEOPIX_OFF ANEOPIX_BLACK -# endif -# ifndef ANEOPIX_IND_DATA_GPIO2 -// during boot the RGB LED is on to signal also reboots -# define SetupIndicators() \ - pinMode(RGB_LED_POWER, OUTPUT); \ - digitalWrite(RGB_LED_POWER, HIGH); \ - leds.begin(); \ - leds.setPixelColor(ANEOPIX_INFO_LED, ANEOPIX_BOOT); \ - leds.show(); -# else -# define SetupIndicators() \ - pinMode(RGB_LED_POWER, OUTPUT); \ - digitalWrite(RGB_LED_POWER, HIGH); \ - leds.begin(); \ - leds2.begin(); -# endif -# define ErrorIndicatorON() \ - leds.setPixelColor(ANEOPIX_ERROR_LED, ANEOPIX_ERROR); \ - leds.setBrightness(SYSConfig.rgbbrightness); \ - leds.show(); -# define ErrorIndicatorOFF() \ - leds.setPixelColor(ANEOPIX_ERROR_LED, ANEOPIX_OFF); \ - leds.show(); -# define SendReceiveIndicatorON() \ - leds.setPixelColor(ANEOPIX_SEND_RECEIVE_LED, ANEOPIX_SENDRECEIVE); \ - leds.setBrightness(SYSConfig.rgbbrightness); \ - leds.show(); -# define SendReceiveIndicatorOFF() \ - leds.setPixelColor(ANEOPIX_SEND_RECEIVE_LED, ANEOPIX_OFF); \ - leds.show(); -# define InfoIndicatorON() \ - leds.setPixelColor(ANEOPIX_INFO_LED, ANEOPIX_INFO); \ - leds.setBrightness(SYSConfig.rgbbrightness); \ - leds.show(); -# define InfoIndicatorOFF() \ - leds.setPixelColor(ANEOPIX_INFO_LED, ANEOPIX_OFF); \ - leds.show(); -# ifdef ANEOPIX_IND_DATA_GPIO2 // Used for relay power indicator -// For the critical ON indicator there is no method to turn it off, the only way is to unplug the device -// This enable to have persistence of the indicator to inform the user -# define CriticalIndicatorON() \ - leds2.setPixelColor(ANEOPIX_INFO_LED, ANEOPIX_CRITICAL); \ - leds2.setBrightness(255); \ - leds2.show(); -# define PowerIndicatorON() \ - leds2.setPixelColor(ANEOPIX_INFO_LED, ANEOPIX_INFO); \ - leds2.setBrightness(SYSConfig.rgbbrightness); \ - leds2.show(); -# define PowerIndicatorOFF() \ - leds2.setPixelColor(ANEOPIX_INFO_LED, ANEOPIX_OFF); \ - leds2.show(); -# endif -# define SetupIndicatorInfo() -# define SetupIndicatorSendReceive() -# define SetupIndicatorError() +#ifndef DEFAULT_ADJ_BRIGHTNESS +# define DEFAULT_ADJ_BRIGHTNESS 255 // Set Default RGB adjustable brightness +#endif + +#ifndef LED_POWER_COLOR +# define LED_POWER_COLOR 0x00FF00 // Green +#endif +#ifndef LED_PROCESSING_COLOR +# define LED_PROCESSING_COLOR 0x0000FF // Blue +#endif +#ifndef LED_WAITING_ONBOARD_COLOR +# define LED_WAITING_ONBOARD_COLOR 0xFFA500 // Orange +#endif +#ifndef LED_ONBOARD_COLOR +# define LED_ONBOARD_COLOR 0xFFFF00 // Yellow +#endif +#ifndef LED_NETWORK_OK_COLOR +# define LED_NETWORK_OK_COLOR 0x00FF00 // Green +#endif +#ifndef LED_NETWORK_ERROR_COLOR +# define LED_NETWORK_ERROR_COLOR 0xFFA500 // Orange +#endif +#ifndef LED_BROKER_OK_COLOR +# define LED_BROKER_OK_COLOR 0x00FF00 // Green +#endif +#ifndef LED_BROKER_ERROR_COLOR +# define LED_BROKER_ERROR_COLOR 0xFFA500 // Orange +#endif +#ifndef LED_OFFLINE_COLOR +# define LED_OFFLINE_COLOR 0x0000FF // Blue +#endif +#ifndef LED_OTA_LOCAL_COLOR +# define LED_OTA_LOCAL_COLOR 0xFF00FF // Magenta +#endif +#ifndef LED_OTA_REMOTE_COLOR +# define LED_OTA_REMOTE_COLOR 0x8000FF // Purple +#endif +#ifndef LED_ERROR_COLOR +# define LED_ERROR_COLOR 0xFF0000 // Red +#endif +#ifndef LED_ACTUATOR_ONOFF_COLOR +# define LED_ACTUATOR_ONOFF_COLOR 0x00FF00 // Green +#endif +#ifndef LED_COLOR_BLACK +# define LED_COLOR_BLACK 0x000000 #endif #ifdef ESP8266 //# define TRIGGER_GPIO 14 // pin D5 as full reset button (long press >10s) -#elif ESP32 +#elif defined(ESP32) //# define TRIGGER_GPIO 0 // boot button as full reset button (long press >10s) //# define NO_INT_TEMP_READING true //Define if we don't want internal temperature reading for the ESP32 #endif @@ -660,9 +561,15 @@ Adafruit_NeoPixel leds2(ANEOPIX_IND_NUM_LEDS, ANEOPIX_IND_DATA_GPIO2, ANEOPIX_IN #endif /*--------------MQTT general topics-----------------*/ // global MQTT subject listened by the gateway to execute commands (send RF, IR or others) -#define subjectMQTTtoX "/commands/#" -#define subjectMultiGTWKey "toMQTT" -#define subjectGTWSendKey "MQTTto" +#ifndef subjectMQTTtoX +# define subjectMQTTtoX "/commands/#" +#endif +#ifndef subjectMultiGTWKey +# define subjectMultiGTWKey "toMQTT" +#endif +#ifndef subjectGTWSendKey +# define subjectGTWSendKey "MQTTto" +#endif // key used for launching commands to the gateway #define restartCmd "restart" @@ -673,24 +580,6 @@ Adafruit_NeoPixel leds2(ANEOPIX_IND_NUM_LEDS, ANEOPIX_IND_DATA_GPIO2, ANEOPIX_IN # define valueAsATopic false // define true to integrate msg value into the subject when receiving #endif -#if defined(ESP32) -# define JSON_MSG_BUFFER 816 // adjusted to minimum size covering largest Theengs device JSON properties (RuuviTag_RAWv2) -# define SIGNAL_SIZE_UL_ULL uint64_t -# define STRTO_UL_ULL strtoull -#elif defined(ESP8266) -# define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 768 or higher it is causing unexpected behaviour on ESP8266 -# define SIGNAL_SIZE_UL_ULL uint64_t -# define STRTO_UL_ULL strtoull -#elif defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) -# define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher -# define SIGNAL_SIZE_UL_ULL uint64_t -# define STRTO_UL_ULL strtoul -#else // boards with smaller memory -# define JSON_MSG_BUFFER 64 // Json message max buffer size, don't put 1024 or higher -# define SIGNAL_SIZE_UL_ULL uint32_t -# define STRTO_UL_ULL strtoul -#endif - #if defined(ZgatewayRF) || defined(ZgatewayIR) || defined(ZgatewaySRFB) || defined(ZgatewayWeatherStation) || defined(ZgatewayRTL_433) // variable to avoid duplicates # ifndef time_avoid_duplicate @@ -698,21 +587,69 @@ Adafruit_NeoPixel leds2(ANEOPIX_IND_NUM_LEDS, ANEOPIX_IND_DATA_GPIO2, ANEOPIX_IN # endif #endif -#define TimeBetweenReadingSYS 120 // time between (s) system readings (like memory) +#ifndef TimeBetweenReadingSYS +# define TimeBetweenReadingSYS 120 // time between (s) system readings (like memory) +#endif #define TimeBetweenCheckingSYS 3600 // time between (s) system checkings (like updates) #define TimeLedON 1 // time LED are ON #define InitialMQTTConnectionTimeout 10 // time estimated (s) before the board is connected to MQTT -#define subjectSYStoMQTT "/SYStoMQTT" // system parameters -#define subjectLOGtoMQTT "/LOGtoMQTT" // log informations -#define subjectRLStoMQTT "/RLStoMQTT" // latest release information -#define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config" -#define subjectMQTTtoSYSupdate "/commands/MQTTtoSYS/firmware_update" -#define TimeToResetAtStart 5000 // Time we allow the user at start for the reset command by button press +#ifndef subjectSYStoMQTT +# define subjectSYStoMQTT "/SYStoMQTT" // system parameters +#endif +#ifndef subjectLOGtoMQTT +# define subjectLOGtoMQTT "/LOGtoMQTT" // log informations +#endif +#ifndef subjectRLStoMQTT +# define subjectRLStoMQTT "/RLStoMQTT" // latest release information +#endif +#ifndef subjectMQTTtoSYSset +# define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config" +#endif +#ifndef subjectMQTTtoSYSupdate +# define subjectMQTTtoSYSupdate "/commands/MQTTtoSYS/firmware_update" +#endif +#define TimeToResetAtStart 5000 // Time we allow the user at start for the reset command by button press + +#include + /*-------------------DEFINE LOG LEVEL----------------------*/ #ifndef LOG_LEVEL # define LOG_LEVEL LOG_LEVEL_NOTICE #endif +/*-------------------SIMPLIFIED LOGGING MACROS----------------------*/ +// ArduinoLog levels: SILENT=0, FATAL=1, ERROR=2, WARNING=3, NOTICE=4, TRACE=5, VERBOSE=6 +#if LOG_LEVEL >= LOG_LEVEL_VERBOSE +# define THEENGS_LOG_VERBOSE(...) Log.verbose(__VA_ARGS__) +#else +# define THEENGS_LOG_VERBOSE(...) ((void)0) +#endif +#if LOG_LEVEL >= LOG_LEVEL_TRACE +# define THEENGS_LOG_TRACE(...) Log.trace(__VA_ARGS__) +#else +# define THEENGS_LOG_TRACE(...) ((void)0) +#endif +#if LOG_LEVEL >= LOG_LEVEL_NOTICE +# define THEENGS_LOG_NOTICE(...) Log.notice(__VA_ARGS__) +#else +# define THEENGS_LOG_NOTICE(...) ((void)0) +#endif +#if LOG_LEVEL >= LOG_LEVEL_WARNING +# define THEENGS_LOG_WARNING(...) Log.warning(__VA_ARGS__) +#else +# define THEENGS_LOG_WARNING(...) ((void)0) +#endif +#if LOG_LEVEL >= LOG_LEVEL_ERROR +# define THEENGS_LOG_ERROR(...) Log.error(__VA_ARGS__) +#else +# define THEENGS_LOG_ERROR(...) ((void)0) +#endif +#if LOG_LEVEL >= LOG_LEVEL_FATAL +# define LOG_FATAL(...) Log.fatal(__VA_ARGS__) +#else +# define LOG_FATAL(...) ((void)0) +#endif + /*-------------------ESP Wifi band and tx power ---------------------*/ //Certain sensors are sensitive to Wifi which can cause interference with their normal operation //For example it can cause false triggers on a PIR HC-SR501 @@ -731,72 +668,55 @@ Adafruit_NeoPixel leds2(ANEOPIX_IND_NUM_LEDS, ANEOPIX_IND_DATA_GPIO2, ANEOPIX_IN /*-----------PLACEHOLDERS FOR OLED/LCD DISPLAY--------------*/ // The real definitions are in config_M5.h / config_SSD1306.h -#define pubOled(...) // display the published message onto the OLED display #define displayPrint(...) // only print if not in low power mode #define lpDisplayPrint(...) // print in low power mode -/*----------- SHARED WITH OMG MODULES --------------*/ - -char mqtt_topic[parameters_size + 1] = Base_Topic; -char gateway_name[parameters_size + 1] = Gateway_Name; - -void connectMQTT(); -#ifndef ESPWifiManualSetup -void saveConfig(); -#endif - -unsigned long uptime(); -bool cmpToMainTopic(const char*, const char*); -void pub(const char*, const char*, bool); -// void pub(const char*, JsonObject&); -void pub(const char*, const char*); -// void pub_custom_topic(const char*, JsonObject&, boolean); - -#if defined(ESP32) -# include -Preferences preferences; -#endif - -#ifdef ZmqttDiscovery -unsigned long lastDiscovery = 0; // Time of the last discovery to trigger automaticaly to off after DiscoveryAutoOffTimer -#endif - -#if defined(ESP8266) || defined(ESP32) -# include -// Flags definition for white list, black list, discovery management -# define device_flags_init 0 << 0 -# define device_flags_isDisc 1 << 0 -# define device_flags_isWhiteL 1 << 1 -# define device_flags_isBlackL 1 << 2 -# define device_flags_connect 1 << 3 -# define isWhite(device) device->isWhtL -# define isBlack(device) device->isBlkL -# define isDiscovered(device) device->isDisc - /*--------------------Minimum freeHeap--------------------*/ // Below this parameter we trigger a restart, this avoid stuck boards like seen in https://github.com/1technophile/OpenMQTTGateway/issues/1693 -# define MinimumMemory 40000 +#define MinimumMemory 40000 /*----------------CONFIGURABLE PARAMETERS-----------------*/ -struct SYSConfig_s { - bool discovery; // HA discovery convention - bool ohdiscovery; // OH discovery specificities -# ifdef RGB_INDICATORS - int rgbbrightness; // brightness of the RGB LED -# endif -}; +#ifndef DEFAULT_DISCOVERY +# define DEFAULT_DISCOVERY true +#endif +#ifndef DEFAULT_MQTT +# define DEFAULT_MQTT true +#endif +#ifndef DEFAULT_SERIAL +# define DEFAULT_SERIAL false +#endif +#ifndef DEFAULT_BLUFI +# define DEFAULT_BLUFI true +#endif +#ifndef DEFAULT_OFFLINE +# define DEFAULT_OFFLINE false #endif #if defined(ZgatewayRF) || defined(ZgatewayIR) || defined(ZgatewaySRFB) || defined(ZgatewayWeatherStation) || defined(ZgatewayRTL_433) -bool isAduplicateSignal(SIGNAL_SIZE_UL_ULL); -void storeSignalValue(SIGNAL_SIZE_UL_ULL); +bool isAduplicateSignal(uint64_t); +void storeSignalValue(uint64_t); #endif -// Origin topics -#define subjectBTtoMQTT "/BTtoMQTT" +#ifdef ZgatewayBT +# ifndef BLEDecryptor +# define BLEDecryptor true //true if decrypt encrypted PVVX, BTHome v2 or Victron Energy broadcast data +# ifndef JSON_BLE_AES_CUSTOM_KEYS +# define JSON_BLE_AES_CUSTOM_KEYS 256 // 42 byte BLE Custom Key * 6 rounded up to 256. +# endif +// Runtime default for ble_aes[]. Empty = no default; override at build time +// with -DBLE_AES='"<32-hex-key>"' to ship a stock key. +# ifndef BLE_AES +# define BLE_AES "" +# endif +# endif +#endif #define convertTemp_CtoF(c) ((c * 1.8) + 32) #define convertTemp_FtoC(f) ((f - 32) * 5 / 9) +#ifndef QueueSize +# define QueueSize 18 +#endif + #endif diff --git a/main/Zblufi.ino b/main/Zblufi.ino deleted file mode 100644 index f76f378..0000000 --- a/main/Zblufi.ino +++ /dev/null @@ -1,265 +0,0 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation - - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker - Send and receiving command by MQTT - - This program enables to: - - receive MQTT data from a topic and send signal (RF, IR, BLE, GSM) corresponding to the received MQTT data - - publish MQTT data to a different topic related to received signals (RF, IR, BLE, GSM) - - Copyright: (c)Florian ROBERT - - This file is part of OpenMQTTGateway. - - OpenMQTTGateway 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. - - OpenMQTTGateway 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 . -*/ -#if defined(ESP32) && defined(USE_BLUFI) - -# include "esp_blufi_api.h" - -extern "C" { -# include "esp_blufi.h" -} - -/* store the station info for send back to phone */ -//static bool gl_sta_connected = false; -bool omg_blufi_ble_connected = false; -static uint8_t gl_sta_bssid[6]; -static uint8_t gl_sta_ssid[32]; -static uint8_t gl_sta_passwd[64]; -static int gl_sta_ssid_len; -static bool gl_sta_is_connecting = false; -static esp_blufi_extra_info_t gl_sta_conn_info; - -static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t* param); -void wifi_event_handler(arduino_event_id_t event); -esp_err_t blufi_security_init(void); -void blufi_dh_negotiate_data_handler(uint8_t* data, int len, uint8_t** output_data, int* output_len, bool* need_free); -int blufi_aes_encrypt(uint8_t iv8, uint8_t* crypt_data, int crypt_len); -int blufi_aes_decrypt(uint8_t iv8, uint8_t* crypt_data, int crypt_len); -uint16_t blufi_crc_checksum(uint8_t iv8, uint8_t* data, int len); -void blufi_security_deinit(void); - -static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t* param) { - /* actually, should post to blufi_task handle the procedure, - * now, as a example, we do it more simply */ - switch (event) { - case ESP_BLUFI_EVENT_INIT_FINISH: - Log.notice(F("BLUFI init finish" CR)); - esp_blufi_adv_start(); - break; - case ESP_BLUFI_EVENT_DEINIT_FINISH: - Log.notice(F("BLUFI deinit finish" CR)); - NimBLEDevice::deinit(true); - break; - case ESP_BLUFI_EVENT_BLE_CONNECT: - omg_blufi_ble_connected = true; - esp_blufi_adv_stop(); - blufi_security_init(); - break; - case ESP_BLUFI_EVENT_BLE_DISCONNECT: - omg_blufi_ble_connected = false; - blufi_security_deinit(); - if (WiFi.isConnected()) { - esp_blufi_deinit(); - } else { - esp_blufi_adv_start(); - } - break; - case ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP: - Log.notice(F("BLUFI requset wifi connect to AP" CR)); - WiFi.begin((char*)gl_sta_ssid, (char*)gl_sta_passwd); - gl_sta_is_connecting = true; - break; - case ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP: - Log.notice(F("BLUFI requset wifi disconnect from AP\n" CR)); - WiFi.disconnect(); - break; - case ESP_BLUFI_EVENT_REPORT_ERROR: - Log.notice(F("BLUFI report error, error code %d\n" CR), param->report_error.state); - esp_blufi_send_error_info(param->report_error.state); - break; - case ESP_BLUFI_EVENT_GET_WIFI_STATUS: { - esp_blufi_extra_info_t info; - if (WiFi.isConnected()) { - memset(&info, 0, sizeof(esp_blufi_extra_info_t)); - memcpy(info.sta_bssid, gl_sta_bssid, 6); - info.sta_bssid_set = true; - info.sta_ssid = gl_sta_ssid; - info.sta_ssid_len = gl_sta_ssid_len; - esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONN_SUCCESS, 0, &info); - } else if (gl_sta_is_connecting) { - esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONNECTING, 0, &gl_sta_conn_info); - } else { - esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONN_FAIL, 0, &gl_sta_conn_info); - } - - break; - } - case ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE: - esp_blufi_disconnect(); - break; - case ESP_BLUFI_EVENT_RECV_STA_SSID: - strncpy((char*)gl_sta_ssid, (char*)param->sta_ssid.ssid, param->sta_ssid.ssid_len); - gl_sta_ssid[param->sta_ssid.ssid_len] = '\0'; - Log.notice(F("Recv STA SSID %s" CR), gl_sta_ssid); - break; - case ESP_BLUFI_EVENT_RECV_STA_PASSWD: - strncpy((char*)gl_sta_passwd, (char*)param->sta_passwd.passwd, param->sta_passwd.passwd_len); - gl_sta_passwd[param->sta_passwd.passwd_len] = '\0'; - Log.notice(F("Recv STA PASSWORD %s" CR), gl_sta_passwd); - break; - case ESP_BLUFI_EVENT_GET_WIFI_LIST: { - WiFi.scanNetworks(true); - break; - } - case ESP_BLUFI_EVENT_RECV_CUSTOM_DATA: { - Log.notice(F("Recv Custom Data %" PRIu32 CR), param->custom_data.data_len); - esp_log_buffer_hex("Custom Data", param->custom_data.data, param->custom_data.data_len); - - DynamicJsonDocument json(1024); - auto error = deserializeJson(json, param->custom_data.data); - if (error) { - Log.error(F("deserialize config failed: %s, buffer capacity: %u" CR), error.c_str(), json.capacity()); - break; - } - if (!json.isNull()) { - Log.trace(F("\nparsed json, size: %u" CR), json.memoryUsage()); - if (json.containsKey("mqtt_server")) - strcpy(mqtt_server, json["mqtt_server"]); - if (json.containsKey("mqtt_port")) - strcpy(mqtt_port, json["mqtt_port"]); - if (json.containsKey("mqtt_user")) - strcpy(mqtt_user, json["mqtt_user"]); - if (json.containsKey("mqtt_pass")) - strcpy(mqtt_pass, json["mqtt_pass"]); - if (json.containsKey("mqtt_topic")) - strcpy(mqtt_topic, json["mqtt_topic"]); - if (json.containsKey("mqtt_broker_secure")) - mqtt_secure = json["mqtt_broker_secure"].as(); - if (json.containsKey("gateway_name")) - strcpy(gateway_name, json["gateway_name"]); - saveConfig(); - } - break; - } - case ESP_BLUFI_EVENT_RECV_USERNAME: - break; - case ESP_BLUFI_EVENT_RECV_CA_CERT: - break; - case ESP_BLUFI_EVENT_RECV_CLIENT_CERT: - break; - case ESP_BLUFI_EVENT_RECV_SERVER_CERT: - break; - case ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY: - break; - ; - case ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY: - break; - default: - break; - } -} - -void wifi_event_handler(arduino_event_id_t event) { - switch (event) { - case ARDUINO_EVENT_WIFI_STA_GOT_IP6: - case ARDUINO_EVENT_WIFI_STA_GOT_IP: { - gl_sta_is_connecting = false; - esp_blufi_extra_info_t info; - memset(&info, 0, sizeof(esp_blufi_extra_info_t)); - memcpy(info.sta_bssid, gl_sta_bssid, 6); - info.sta_bssid_set = true; - info.sta_ssid = gl_sta_ssid; - info.sta_ssid_len = gl_sta_ssid_len; - if (omg_blufi_ble_connected == true) { - esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONN_SUCCESS, 0, &info); - } - - break; - } - case ARDUINO_EVENT_WIFI_SCAN_DONE: { - uint16_t apCount = WiFi.scanComplete(); - if (apCount == 0) { - Log.notice(F("No AP found" CR)); - break; - } - wifi_ap_record_t* ap_list = (wifi_ap_record_t*)malloc(sizeof(wifi_ap_record_t) * apCount); - if (!ap_list) { - Log.error(F("malloc error, ap_list is NULL")); - break; - } - ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&apCount, ap_list)); - esp_blufi_ap_record_t* blufi_ap_list = (esp_blufi_ap_record_t*)malloc(apCount * sizeof(esp_blufi_ap_record_t)); - if (!blufi_ap_list) { - if (ap_list) { - free(ap_list); - } - Log.error(F("malloc error, blufi_ap_list is NULL" CR)); - break; - } - for (int i = 0; i < apCount; ++i) { - blufi_ap_list[i].rssi = ap_list[i].rssi; - memcpy(blufi_ap_list[i].ssid, ap_list[i].ssid, sizeof(ap_list[i].ssid)); - } - - if (omg_blufi_ble_connected == true) { - esp_blufi_send_wifi_list(apCount, blufi_ap_list); - } - - free(ap_list); - free(blufi_ap_list); - break; - } - default: - break; - } - return; -} - -static esp_blufi_callbacks_t example_callbacks = { - .event_cb = example_event_callback, - .negotiate_data_handler = blufi_dh_negotiate_data_handler, - .encrypt_func = blufi_aes_encrypt, - .decrypt_func = blufi_aes_decrypt, - .checksum_func = blufi_crc_checksum, -}; - -bool startBlufi() { - esp_err_t ret = ESP_OK; - WiFi.onEvent(wifi_event_handler); - - ret = esp_blufi_register_callbacks(&example_callbacks); - if (ret) { - Log.error(F("%s blufi register failed, error code = %x" CR), __func__, ret); - return false; - } - - if (NimBLEDevice::getInitialized()) { - NimBLEDevice::deinit(true); - delay(50); - } - esp_blufi_btc_init(); - uint8_t mac[6]; - esp_read_mac(mac, ESP_MAC_WIFI_STA); - char advName[20] = {0}; - snprintf(advName, sizeof(advName), "OMGBFI_%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - NimBLEDevice::init(advName); - esp_blufi_gatt_svr_init(); - ble_gatts_start(); - return esp_blufi_profile_init() == ESP_OK; -} - -#endif // defined(ESP32) && defined(USE_BLUFI) diff --git a/main/ZcommonRF.ino b/main/ZcommonRF.ino deleted file mode 100644 index 2d5a41e..0000000 --- a/main/ZcommonRF.ino +++ /dev/null @@ -1,339 +0,0 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation - - Act as a wifi or ethernet gateway between your BLE/433mhz/infrared IR signal and an MQTT broker - Send and receiving command by MQTT - - Copyright: (c)Florian ROBERT - - This file is part of OpenMQTTGateway. - - OpenMQTTGateway 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. - - OpenMQTTGateway 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 . -*/ - -#include "User_config.h" - -#if defined(ZgatewayRF) || defined(ZgatewayPilight) || defined(ZgatewayRTL_433) || defined(ZgatewayRF2) || defined(ZactuatorSomfy) -# ifndef ARDUINO_AVR_UNO - -# ifdef ZradioCC1101 -# include -# endif - -void initCC1101() { -# ifdef ZradioCC1101 //receiving with CC1101 - // Loop on getCC1101() until it returns true and break after 10 attempts - int delayMS = 16; - int delayMaxMS = 500; - for (int i = 0; i < 10; i++) { - if (ELECHOUSE_cc1101.getCC1101()) { - Log.notice(F("C1101 spi Connection OK" CR)); - ELECHOUSE_cc1101.Init(); - ELECHOUSE_cc1101.SetRx(RFConfig.frequency); - break; - } else { - Log.error(F("C1101 spi Connection Error" CR)); - delay(delayMS); - } - // truncated exponential backoff - delayMS = delayMS * 2; - if (delayMS > delayMaxMS) delayMS = delayMaxMS; - } -# endif -} - -void setupCommonRF() { - RFConfig_init(); - RFConfig_load(); -} - -bool validFrequency(float mhz) { - // CC1101 valid frequencies 300-348 MHZ, 387-464MHZ and 779-928MHZ. - if (mhz >= 300 && mhz <= 348) - return true; - if (mhz >= 387 && mhz <= 464) - return true; - if (mhz >= 779 && mhz <= 928) - return true; - return false; -} - -int currentReceiver = ACTIVE_NONE; - -# if !defined(ZgatewayRFM69) && !defined(ZactuatorSomfy) -# if defined(ESP8266) || defined(ESP32) -// Check if a receiver is available -bool validReceiver(int receiver) { - switch (receiver) { -# ifdef ZgatewayPilight - case ACTIVE_PILIGHT: - return true; -# endif -# ifdef ZgatewayRF - case ACTIVE_RF: - return true; -# endif -# ifdef ZgatewayRTL_433 - case ACTIVE_RTL: - return true; -# endif -# ifdef ZgatewayRF2 - case ACTIVE_RF2: - return true; -# endif - default: - Log.error(F("ERROR: stored receiver %d not available" CR), receiver); - } - return false; -} -# endif -# endif - -void disableCurrentReceiver() { - Log.trace(F("disableCurrentReceiver: %d" CR), currentReceiver); - switch (currentReceiver) { - case ACTIVE_NONE: - break; -# ifdef ZgatewayPilight - case ACTIVE_PILIGHT: - disablePilightReceive(); - break; -# endif -# ifdef ZgatewayRF - case ACTIVE_RF: - disableRFReceive(); - break; -# endif -# ifdef ZgatewayRTL_433 - case ACTIVE_RTL: - disableRTLreceive(); - break; -# endif -# ifdef ZgatewayRF2 - case ACTIVE_RF2: - disableRF2Receive(); - break; -# endif -# ifndef ARDUINO_AVR_UNO // Space issues with the UNO - default: - Log.error(F("ERROR: unsupported receiver %d" CR), RFConfig.activeReceiver); -# endif - } -} - -void enableActiveReceiver() { - Log.trace(F("enableActiveReceiver: %d" CR), RFConfig.activeReceiver); - switch (RFConfig.activeReceiver) { -# ifdef ZgatewayPilight - case ACTIVE_PILIGHT: - initCC1101(); - enablePilightReceive(); - currentReceiver = ACTIVE_PILIGHT; - break; -# endif -# ifdef ZgatewayRF - case ACTIVE_RF: - initCC1101(); - enableRFReceive(); - currentReceiver = ACTIVE_RF; - break; -# endif -# ifdef ZgatewayRTL_433 - case ACTIVE_RTL: - initCC1101(); - enableRTLreceive(); - currentReceiver = ACTIVE_RTL; - break; -# endif -# ifdef ZgatewayRF2 - case ACTIVE_RF2: - initCC1101(); - enableRF2Receive(); - currentReceiver = ACTIVE_RF2; - break; -# endif - case ACTIVE_RECERROR: - Log.error(F("ERROR: no receiver selected" CR)); - break; -# ifndef ARDUINO_AVR_UNO // Space issues with the UNO - default: - Log.error(F("ERROR: unsupported receiver %d" CR), RFConfig.activeReceiver); -# endif - } -} - -String stateRFMeasures() { - //Publish RTL_433 state - StaticJsonDocument jsonBuffer; - JsonObject RFdata = jsonBuffer.to(); - RFdata["active"] = RFConfig.activeReceiver; -# if defined(ZradioCC1101) || defined(ZradioSX127x) - RFdata["frequency"] = RFConfig.frequency; - if (RFConfig.activeReceiver == ACTIVE_RTL) { -# ifdef ZgatewayRTL_433 - RFdata["rssithreshold"] = (int)getRTLrssiThreshold(); - RFdata["rssi"] = (int)getRTLCurrentRSSI(); - RFdata["avgrssi"] = (int)getRTLAverageRSSI(); - RFdata["count"] = (int)getRTLMessageCount(); -# endif -# ifdef ZradioSX127x - RFdata["ookthreshold"] = (int)getOOKThresh(); -# endif - } -# endif - pub(subjectcommonRFtoMQTT, RFdata); - - String output; - serializeJson(RFdata, output); - return output; -} - -void RFConfig_fromJson(JsonObject& RFdata) { - bool success = false; - if (RFdata.containsKey("frequency") && validFrequency(RFdata["frequency"])) { - Config_update(RFdata, "frequency", RFConfig.frequency); - Log.notice(F("RF Receive mhz: %F" CR), RFConfig.frequency); - success = true; - } - if (RFdata.containsKey("active")) { - Log.notice(F("RF receiver active: %d" CR), RFConfig.activeReceiver); - Config_update(RFdata, "active", RFConfig.activeReceiver); - success = true; - } -# ifdef ZgatewayRTL_433 - if (RFdata.containsKey("rssithreshold")) { - Log.notice(F("RTL_433 RSSI Threshold : %d " CR), RFConfig.rssiThreshold); - Config_update(RFdata, "rssithreshold", RFConfig.rssiThreshold); - rtl_433.setRSSIThreshold(RFConfig.rssiThreshold); - success = true; - } -# if defined(RF_SX1276) || defined(RF_SX1278) - if (RFdata.containsKey("ookthreshold")) { - Config_update(RFdata, "ookthreshold", RFConfig.newOokThreshold); - Log.notice(F("RTL_433 ookThreshold %d" CR), RFConfig.newOokThreshold); - rtl_433.setOOKThreshold(RFConfig.newOokThreshold); - success = true; - } -# endif - if (RFdata.containsKey("status")) { - Log.notice(F("RF get status:" CR)); - rtl_433.getStatus(); - success = true; - } - if (!success) { - Log.error(F("MQTTtoRF Fail json" CR)); - } -# endif - disableCurrentReceiver(); - enableActiveReceiver(); -# ifdef ESP32 - if (RFdata.containsKey("erase") && RFdata["erase"].as()) { - // Erase config from NVS (non-volatile storage) - preferences.begin(Gateway_Short_Name, false); - if (preferences.isKey("RFConfig")) { - int result = preferences.remove("RFConfig"); - Log.notice(F("RF config erase result: %d" CR), result); - preferences.end(); - return; // Erase prevails on save, so skipping save - } else { - Log.notice(F("RF config not found" CR)); - preferences.end(); - } - } - if (RFdata.containsKey("save") && RFdata["save"].as()) { - StaticJsonDocument jsonBuffer; - JsonObject jo = jsonBuffer.to(); - jo["frequency"] = RFConfig.frequency; - jo["active"] = RFConfig.activeReceiver; -// Don't save those for now, need to be tested -# ifdef ZgatewayRTL_433 -//jo["rssithreshold"] = RFConfig.rssiThreshold; -//jo["ookthreshold"] = RFConfig.newOokThreshold; -# endif - // Save config into NVS (non-volatile storage) - String conf = ""; - serializeJson(jsonBuffer, conf); - preferences.begin(Gateway_Short_Name, false); - int result = preferences.putString("RFConfig", conf); - preferences.end(); - Log.notice(F("RF Config_save: %s, result: %d" CR), conf.c_str(), result); - } -# endif -} - -void RFConfig_init() { - RFConfig.frequency = RF_FREQUENCY; - RFConfig.activeReceiver = ACTIVE_RECEIVER; - RFConfig.rssiThreshold = 0; - RFConfig.newOokThreshold = 0; -} - -void RFConfig_load() { -# ifdef ESP32 - StaticJsonDocument jsonBuffer; - preferences.begin(Gateway_Short_Name, true); - if (preferences.isKey("RFConfig")) { - auto error = deserializeJson(jsonBuffer, preferences.getString("RFConfig", "{}")); - preferences.end(); - if (error) { - Log.error(F("RF Config deserialization failed: %s, buffer capacity: %u" CR), error.c_str(), jsonBuffer.capacity()); - return; - } - if (jsonBuffer.isNull()) { - Log.warning(F("RF Config is null" CR)); - return; - } - JsonObject jo = jsonBuffer.as(); - RFConfig_fromJson(jo); - Log.notice(F("RF Config loaded" CR)); - } else { - preferences.end(); - Log.notice(F("RF Config not found using default" CR)); - enableActiveReceiver(); - } -# else - enableActiveReceiver(); -# endif -} - -void MQTTtoRFset(char* topicOri, JsonObject& RFdata) { - if (cmpToMainTopic(topicOri, subjectMQTTtoRFset)) { - Log.trace(F("MQTTtoRF json set" CR)); - - /* - * Configuration modifications priorities: - * First `init=true` and `load=true` commands are executed (if both are present, INIT prevails on LOAD) - * Then parameters included in json are taken in account - * Finally `erase=true` and `save=true` commands are executed (if both are present, ERASE prevails on SAVE) - */ - if (RFdata.containsKey("init") && RFdata["init"].as()) { - // Restore the default (initial) configuration - RFConfig_init(); - } else if (RFdata.containsKey("load") && RFdata["load"].as()) { - // Load the saved configuration, if not initialised - RFConfig_load(); - } - - // Load config from json if available - RFConfig_fromJson(RFdata); - stateRFMeasures(); - } -} -# else -void RFConfig_init() {} -void RFConfig_load() {} -void MQTTtoRFset(char* topicOri, JsonObject& RFdata) {} -void enableActiveReceiver() {} -# endif -#endif diff --git a/main/ZgatewayBLEConnect.ino b/main/ZgatewayBLEConnect.ino deleted file mode 100644 index 50d878b..0000000 --- a/main/ZgatewayBLEConnect.ino +++ /dev/null @@ -1,502 +0,0 @@ -#ifdef ESP32 -# include "User_config.h" -# ifdef ZgatewayBT -# include "ArduinoJson.h" -# include "ArduinoLog.h" -# include "ZgatewayBLEConnect.h" -# define convertTemp_CtoF(c) ((c * 1.8) + 32) - -extern std::vector devices; - -NimBLERemoteCharacteristic* zBLEConnect::getCharacteristic(const NimBLEUUID& service, - const NimBLEUUID& characteristic) { - BLERemoteCharacteristic* pRemoteCharacteristic = nullptr; - if (!m_pClient) { - Log.error(F("No BLE client" CR)); - } else if (!m_pClient->isConnected() && !m_pClient->connect()) { - Log.error(F("Connect to: %s failed" CR), m_pClient->getPeerAddress().toString().c_str()); - } else { - BLERemoteService* pRemoteService = m_pClient->getService(service); - if (!pRemoteService) { - Log.notice(F("Failed to find service UUID: %s" CR), service.toString().c_str()); - } else { - Log.trace(F("Found service: %s" CR), service.toString().c_str()); - Log.trace(F("Client isConnected, freeHeap: %d" CR), ESP.getFreeHeap()); - pRemoteCharacteristic = pRemoteService->getCharacteristic(characteristic); - if (!pRemoteCharacteristic) { - Log.notice(F("Failed to find characteristic UUID: %s" CR), characteristic.toString().c_str()); - } - } - } - - return pRemoteCharacteristic; -} - -bool zBLEConnect::writeData(BLEAction* action) { - NimBLERemoteCharacteristic* pChar = getCharacteristic(action->service, action->characteristic); - if (pChar && (pChar->canWrite() || pChar->canWriteNoResponse())) { - switch (action->value_type) { - case BLE_VAL_HEX: { - int len = action->value.length(); - if (len % 2) { - Log.error(F("Invalid HEX value length" CR)); - return false; - } - - std::vector buf; - for (auto i = 0; i < len; i += 2) { - std::string temp = action->value.substr(i, 2); - buf.push_back((uint8_t)strtoul(temp.c_str(), nullptr, 16)); - } - return pChar->writeValue((const uint8_t*)&buf[0], buf.size(), !pChar->canWriteNoResponse()); - } - case BLE_VAL_INT: - return pChar->writeValue(strtol(action->value.c_str(), nullptr, 0), !pChar->canWriteNoResponse()); - case BLE_VAL_FLOAT: - return pChar->writeValue(strtod(action->value.c_str(), nullptr), !pChar->canWriteNoResponse()); - default: - return pChar->writeValue(action->value, !pChar->canWriteNoResponse()); - } - } - return false; -} - -bool zBLEConnect::readData(BLEAction* action) { - NimBLERemoteCharacteristic* pChar = getCharacteristic(action->service, action->characteristic); - - if (pChar && pChar->canRead()) { - action->value = pChar->readValue(); - if (action->value != "") { - return true; - } - } - return false; -} - -bool zBLEConnect::processActions(std::vector& actions) { - bool result = false; - if (actions.size() > 0) { - for (auto& it : actions) { - if (NimBLEAddress(it.addr) == m_pClient->getPeerAddress()) { - DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); - JsonObject BLEdata = BLEdataBuffer.to(); - BLEdata["id"] = it.addr; - BLEdata["service"] = it.service.toString(); - BLEdata["characteristic"] = it.characteristic.toString(); - - if (it.write) { - Log.trace(F("processing BLE write" CR)); - BLEdata["write"] = it.value; - result = writeData(&it); - } else { - Log.trace(F("processing BLE read" CR)); - result = readData(&it); - if (result) { - switch (it.value_type) { - case BLE_VAL_HEX: { - char* pHex = NimBLEUtils::buildHexData(nullptr, (uint8_t*)it.value.c_str(), it.value.length()); - BLEdata["read"] = pHex; - free(pHex); - break; - } - case BLE_VAL_INT: { - int ival = *(int*)it.value.data(); - BLEdata["read"] = ival; - break; - } - case BLE_VAL_FLOAT: { - float fval = *(double*)it.value.data(); - BLEdata["read"] = fval; - break; - } - default: - BLEdata["read"] = it.value.c_str(); - break; - } - } - } - - it.complete = result; - BLEdata["success"] = result; - if (result || it.ttl <= 1) { - buildTopicFromId(BLEdata, subjectBTtoMQTT); - handleJsonEnqueue(BLEdata, QueueSemaphoreTimeOutTask); - } - } - } - } - - return result; -} - -/*-----------------------LYWSD03MMC && MHO_C401 HANDLING-----------------------*/ -void LYWSD03MMC_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) { - if (m_taskHandle == nullptr) { - return; // unexpected notification - } - if (!BTProcessLock) { - Log.trace(F("Callback from %s characteristic" CR), pChar->getUUID().toString().c_str()); - - if (length == 5) { - Log.trace(F("Device identified creating BLE buffer" CR)); - DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); - JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); - for (std::vector::iterator it = devices.begin(); it != devices.end(); ++it) { - BLEdevice* p = *it; - if ((strcmp(p->macAdr, (char*)mac_address.c_str()) == 0)) { - if (p->sensorModel_id == BLEconectable::id::LYWSD03MMC) - BLEdata["model"] = "LYWSD03MMC"; - else if (p->sensorModel_id == BLEconectable::id::MHO_C401) - BLEdata["model"] = "MHO-C401"; - } - } - BLEdata["id"] = (char*)mac_address.c_str(); - Log.trace(F("Device identified in CB: %s" CR), (char*)mac_address.c_str()); - BLEdata["tempc"] = (float)((pData[0] | (pData[1] << 8)) * 0.01); - BLEdata["tempf"] = (float)(convertTemp_CtoF((pData[0] | (pData[1] << 8)) * 0.01)); - BLEdata["hum"] = (float)(pData[2]); - BLEdata["volt"] = (float)(((pData[4] * 256) + pData[3]) / 1000.0); - BLEdata["batt"] = (float)(((((pData[4] * 256) + pData[3]) / 1000.0) - 2.1) * 100); - buildTopicFromId(BLEdata, subjectBTtoMQTT); - handleJsonEnqueue(BLEdata, QueueSemaphoreTimeOutTask); - } else { - Log.notice(F("Invalid notification data" CR)); - return; - } - } else { - Log.trace(F("Callback process canceled by BTProcessLock" CR)); - } - - xTaskNotifyGive(m_taskHandle); -} - -void LYWSD03MMC_connect::publishData() { - NimBLEUUID serviceUUID("ebe0ccb0-7a0a-4b0c-8a1a-6ff2997da3a6"); - NimBLEUUID charUUID("ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6"); - NimBLERemoteCharacteristic* pChar = getCharacteristic(serviceUUID, charUUID); - - if (pChar && pChar->canNotify()) { - Log.trace(F("Registering notification" CR)); - if (pChar->subscribe(true, std::bind(&LYWSD03MMC_connect::notifyCB, this, - std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3, std::placeholders::_4))) { - m_taskHandle = xTaskGetCurrentTaskHandle(); - if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(BLE_CNCT_TIMEOUT)) == pdFALSE) { - m_taskHandle = nullptr; - } - } else { - Log.notice(F("Failed registering notification" CR)); - } - } -} - -/*-----------------------DT24 HANDLING-----------------------*/ -void DT24_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) { - if (m_taskHandle == nullptr) { - return; // unexpected notification - } - - if (!BTProcessLock) { - Log.trace(F("Callback from %s characteristic" CR), pChar->getUUID().toString().c_str()); - if (length == 20) { - m_data.assign(pData, pData + length); - return; - } else if (m_data.size() == 20 && length == 16) { - m_data.insert(m_data.end(), pData, pData + length); - - // DT24-BLE data format - // https://github.com/NiceLabs/atorch-console/blob/master/docs/protocol-design.md#dc-meter-report - // Data comes as two packets ( 20 and 16 ), and am only processing first - Log.trace(F("Device identified creating BLE buffer" CR)); - DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); - JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); - BLEdata["model"] = "DT24"; - BLEdata["id"] = (char*)mac_address.c_str(); - Log.trace(F("Device identified in CB: %s" CR), (char*)mac_address.c_str()); - BLEdata["volt"] = (float)(((m_data[4] * 256 * 256) + (m_data[5] * 256) + m_data[6]) / 10.0); - BLEdata["current"] = (float)(((m_data[7] * 256 * 256) + (m_data[8] * 256) + m_data[9]) / 1000.0); - BLEdata["power"] = (float)(((m_data[10] * 256 * 256) + (m_data[11] * 256) + m_data[12]) / 10.0); - BLEdata["energy"] = (float)(((m_data[13] * 256 * 256 * 256) + (m_data[14] * 256 * 256) + (m_data[15] * 256) + m_data[16]) / 100.0); - BLEdata["price"] = (float)(((m_data[17] * 256 * 256) + (m_data[18] * 256) + m_data[19]) / 100.0); - BLEdata["tempc"] = (float)(m_data[24] * 256) + m_data[25]; - BLEdata["tempf"] = (float)(convertTemp_CtoF((m_data[24] * 256) + m_data[25])); - buildTopicFromId(BLEdata, subjectBTtoMQTT); - handleJsonEnqueue(BLEdata, QueueSemaphoreTimeOutTask); - } else { - Log.notice(F("Invalid notification data" CR)); - return; - } - } else { - Log.trace(F("Callback process canceled by BTProcessLock" CR)); - } - - xTaskNotifyGive(m_taskHandle); -} - -void DT24_connect::publishData() { - NimBLEUUID serviceUUID("ffe0"); - NimBLEUUID charUUID("ffe1"); - NimBLERemoteCharacteristic* pChar = getCharacteristic(serviceUUID, charUUID); - - if (pChar && pChar->canNotify()) { - Log.trace(F("Registering notification" CR)); - if (pChar->subscribe(true, std::bind(&DT24_connect::notifyCB, this, - std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3, std::placeholders::_4))) { - m_taskHandle = xTaskGetCurrentTaskHandle(); - if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(BLE_CNCT_TIMEOUT)) == pdFALSE) { - m_taskHandle = nullptr; - } - } else { - Log.notice(F("Failed registering notification" CR)); - } - } -} - -/*-----------------------BM2 HANDLING-----------------------*/ -void BM2_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) { - if (m_taskHandle == nullptr) { - return; // unexpected notification - } - - if (!BTProcessLock) { - Log.trace(F("Callback from %s characteristic" CR), pChar->getUUID().toString().c_str()); - if (length == 16) { - Log.trace(F("Device identified creating BLE buffer" CR)); - DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); - JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); - BLEdata["model"] = "BM2 Battery Monitor"; - BLEdata["id"] = (char*)mac_address.c_str(); - mbedtls_aes_context aes; - mbedtls_aes_init(&aes); - unsigned char output[16]; - unsigned char iv[16] = {}; - unsigned char key[16] = { - 108, - 101, - 97, - 103, - 101, - 110, - 100, - 255, - 254, - 49, - 56, - 56, - 50, - 52, - 54, - 54, - }; - mbedtls_aes_setkey_dec(&aes, key, 128); - mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, 16, iv, (uint8_t*)&pData[0], output); - mbedtls_aes_free(&aes); - float volt = ((output[2] | (output[1] << 8)) >> 4) / 100.0f; - BLEdata["volt"] = volt; - Log.trace(F("volt: %F" CR), volt); - buildTopicFromId(BLEdata, subjectBTtoMQTT); - handleJsonEnqueue(BLEdata, QueueSemaphoreTimeOutTask); - } else { - Log.notice(F("Invalid notification data" CR)); - return; - } - } else { - Log.trace(F("Callback process canceled by BTProcessLock" CR)); - } - - xTaskNotifyGive(m_taskHandle); -} - -void BM2_connect::publishData() { - NimBLEUUID serviceUUID("fff0"); - NimBLEUUID charUUID("fff4"); - NimBLERemoteCharacteristic* pChar = getCharacteristic(serviceUUID, charUUID); - - if (pChar && pChar->canNotify()) { - Log.trace(F("Registering notification" CR)); - if (pChar->subscribe(true, std::bind(&BM2_connect::notifyCB, this, - std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3, std::placeholders::_4))) { - m_taskHandle = xTaskGetCurrentTaskHandle(); - if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(BLE_CNCT_TIMEOUT)) == pdFALSE) { - m_taskHandle = nullptr; - } - } else { - Log.notice(F("Failed registering notification" CR)); - } - } -} - -/*-----------------------HHCCJCY01HHCC HANDLING-----------------------*/ -void HHCCJCY01HHCC_connect::publishData() { - NimBLEUUID serviceUUID("00001204-0000-1000-8000-00805f9b34fb"); - NimBLEUUID charUUID("00001a00-0000-1000-8000-00805f9b34fb"); - NimBLEUUID charUUID2("00001a02-0000-1000-8000-00805f9b34fb"); - NimBLERemoteCharacteristic* pChar = getCharacteristic(serviceUUID, charUUID); - - if (pChar) { - Log.trace(F("Read mode" CR)); - uint8_t buf[2] = {0xA0, 0x1F}; - pChar->writeValue(buf, 2, true); - int batteryValue = -1; - NimBLERemoteCharacteristic* pChar2 = getCharacteristic(serviceUUID, charUUID2); - if (pChar2) { - std::string value; - value = pChar2->readValue(); - const char* val2 = value.c_str(); - batteryValue = val2[0]; - DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); - JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); - BLEdata["model"] = "HHCCJCY01HHCC"; - BLEdata["id"] = (char*)mac_address.c_str(); - BLEdata["batt"] = (int)batteryValue; - buildTopicFromId(BLEdata, subjectBTtoMQTT); - handleJsonEnqueue(BLEdata, QueueSemaphoreTimeOutTask); - } else { - Log.notice(F("Failed getting characteristic" CR)); - } - } else { - Log.notice(F("Failed getting characteristic" CR)); - } -} - -/*-----------------------XMWSDJ04MMC HANDLING-----------------------*/ -void XMWSDJ04MMC_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) { - if (m_taskHandle == nullptr) { - return; // unexpected notification - } - if (!BTProcessLock) { - Log.trace(F("Callback from %s characteristic" CR), pChar->getUUID().toString().c_str()); - - if (length == 6) { - Log.trace(F("Device identified creating BLE buffer" CR)); - DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); - JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); - BLEdata["model"] = "XMWSDJ04MMC"; - BLEdata["id"] = (char*)mac_address.c_str(); - Log.trace(F("Device identified in CB: %s" CR), (char*)mac_address.c_str()); - BLEdata["tempc"] = (float)((pData[0] | (pData[1] << 8)) * 0.1); - BLEdata["tempf"] = (float)(convertTemp_CtoF((pData[0] | (pData[1] << 8)) * 0.1)); - BLEdata["hum"] = (float)((pData[2] | (pData[3] << 8)) * 0.1); - BLEdata["volt"] = (float)((pData[4] | (pData[5] << 8)) / 1000.0); - BLEdata["batt"] = (float)((((pData[4] | (pData[5] << 8)) / 1000.0) - 2.1) * 100); - buildTopicFromId(BLEdata, subjectBTtoMQTT); - handleJsonEnqueue(BLEdata, QueueSemaphoreTimeOutTask); - } else { - Log.notice(F("Invalid notification data" CR)); - return; - } - } else { - Log.trace(F("Callback process canceled by BTProcessLock" CR)); - } - - xTaskNotifyGive(m_taskHandle); -} - -void XMWSDJ04MMC_connect::publishData() { - NimBLEUUID serviceUUID("ebe0ccb0-7a0a-4b0c-8a1a-6ff2997da3a6"); - NimBLEUUID charUUID("ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6"); - NimBLERemoteCharacteristic* pChar = getCharacteristic(serviceUUID, charUUID); - - if (pChar && pChar->canNotify()) { - Log.trace(F("Registering notification" CR)); - if (pChar->subscribe(true, std::bind(&XMWSDJ04MMC_connect::notifyCB, this, - std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3, std::placeholders::_4))) { - m_taskHandle = xTaskGetCurrentTaskHandle(); - if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(BLE_CNCT_TIMEOUT)) == pdFALSE) { - m_taskHandle = nullptr; - } - } else { - Log.notice(F("Failed registering notification" CR)); - } - } -} - -/*-----------------------SBS1 HANDLING-----------------------*/ -void SBS1_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t length, bool isNotify) { - if (m_taskHandle == nullptr) { - return; // unexpected notification - } - if (!BTProcessLock) { - Log.trace(F("Callback from %s characteristic" CR), pChar->getUUID().toString().c_str()); - - if (length) { - m_notifyVal = *pData; - } else { - Log.notice(F("Invalid notification data" CR)); - return; - } - } else { - Log.trace(F("Callback process canceled by BTProcessLock" CR)); - } - - xTaskNotifyGive(m_taskHandle); -} - -bool SBS1_connect::processActions(std::vector& actions) { - NimBLEUUID serviceUUID("cba20d00-224d-11e6-9fb8-0002a5d5c51b"); - NimBLEUUID charUUID("cba20002-224d-11e6-9fb8-0002a5d5c51b"); - NimBLEUUID notifyCharUUID("cba20003-224d-11e6-9fb8-0002a5d5c51b"); - static byte ON[] = {0x57, 0x01, 0x01}; - static byte OFF[] = {0x57, 0x01, 0x02}; - - bool result = false; - if (actions.size() > 0) { - for (auto& it : actions) { - if (NimBLEAddress(it.addr) == m_pClient->getPeerAddress()) { - NimBLERemoteCharacteristic* pChar = getCharacteristic(serviceUUID, charUUID); - NimBLERemoteCharacteristic* pNotifyChar = getCharacteristic(serviceUUID, notifyCharUUID); - - if (it.write && pChar && pNotifyChar) { - Log.trace(F("processing Switchbot %s" CR), it.value.c_str()); - if (pNotifyChar->subscribe(true, - std::bind(&SBS1_connect::notifyCB, - this, std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3, std::placeholders::_4), - true)) { - if (it.value == "on") { - result = pChar->writeValue(ON, 3, false); - } else { - result = pChar->writeValue(OFF, 3, false); - } - - if (result) { - m_taskHandle = xTaskGetCurrentTaskHandle(); - if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(BLE_CNCT_TIMEOUT)) == pdFALSE) { - m_taskHandle = nullptr; - } - result = m_notifyVal == 0x01; - } - } - } - - it.complete = result; - if (result || it.ttl <= 1) { - StaticJsonDocument BLEdataBuffer; - JsonObject BLEdata = BLEdataBuffer.to(); - BLEdata["id"] = it.addr; - BLEdata["state"] = result ? it.value : it.value == "on" ? "off" : "on"; - buildTopicFromId(BLEdata, subjectBTtoMQTT); - handleJsonEnqueue(BLEdata, QueueSemaphoreTimeOutTask); - } - } - } - } - - return result; -} - -# endif //ZgatewayBT -#endif //ESP32 diff --git a/main/ZgatewayRF.ino b/main/ZgatewayRF.ino deleted file mode 100644 index 823359b..0000000 --- a/main/ZgatewayRF.ino +++ /dev/null @@ -1,288 +0,0 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation - - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker - Send and receiving command by MQTT - - This gateway enables to: - - receive MQTT data from a topic and send RF 433Mhz signal corresponding to the received MQTT data - - publish MQTT data to a different topic related to received 433Mhz signal - - Copyright: (c)Florian ROBERT - - This file is part of OpenMQTTGateway. - - OpenMQTTGateway 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. - - OpenMQTTGateway 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 . -*/ -#include "User_config.h" - -#ifdef ZgatewayRF - -# ifdef ZradioCC1101 -# include -# endif - -# include // library for controling Radio frequency switch - -RCSwitch mySwitch = RCSwitch(); - -//SOME CONVERSION function from https://github.com/sui77/rc-switch/tree/master/examples/ReceiveDemo_Advanced -static const char* bin2tristate(const char* bin) { - static char returnValue[50]; - int pos = 0; - int pos2 = 0; - while (bin[pos] != '\0' && bin[pos + 1] != '\0') { - if (bin[pos] == '0' && bin[pos + 1] == '0') { - returnValue[pos2] = '0'; - } else if (bin[pos] == '1' && bin[pos + 1] == '1') { - returnValue[pos2] = '1'; - } else if (bin[pos] == '0' && bin[pos + 1] == '1') { - returnValue[pos2] = 'F'; - } else { - return "-"; - } - pos = pos + 2; - pos2++; - } - returnValue[pos2] = '\0'; - return returnValue; -} - -static char* dec2binWzerofill(unsigned long Dec, unsigned int bitLength) { - static char bin[64]; - unsigned int i = 0; - - while (Dec > 0) { - bin[32 + i++] = ((Dec & 1) > 0) ? '1' : '0'; - Dec = Dec >> 1; - } - - for (unsigned int j = 0; j < bitLength; j++) { - if (j >= bitLength - i) { - bin[j] = bin[31 + i - (j - (bitLength - i))]; - } else { - bin[j] = '0'; - } - } - bin[bitLength] = '\0'; - - return bin; -} - -# if defined(ZmqttDiscovery) && !defined(RF_DISABLE_TRANSMIT) && defined(RFmqttDiscovery) - -void RFtoMQTTdiscovery(SIGNAL_SIZE_UL_ULL MQTTvalue) { - //on the fly switch creation from received RF values - char val[11]; - sprintf(val, "%lu", MQTTvalue); - Log.trace(F("RF Entity Discovered, create HA Discovery CFG" CR)); - char* switchRF[2] = {val, "RF"}; - Log.trace(F("CreateDiscoverySwitch: %s" CR), switchRF[1]); -# if valueAsATopic - String discovery_topic = String(subjectRFtoMQTT) + "/" + String(switchRF[0]); -# else - String discovery_topic = String(subjectRFtoMQTT); -# endif - - String theUniqueId = getUniqueId("-" + String(switchRF[0]), "-" + String(switchRF[1])); - - announceDeviceTrigger( - false, - (char*)discovery_topic.c_str(), - "", "", - (char*)theUniqueId.c_str(), - "", "", "", ""); -} -# endif - -void RFtoMQTT() { - if (mySwitch.available()) { - StaticJsonDocument RFdataBuffer; - JsonObject RFdata = RFdataBuffer.to(); - Log.trace(F("Rcv. RF" CR)); -# ifdef ESP32 - Log.trace(F("RF Task running on core :%d" CR), xPortGetCoreID()); -# endif - SIGNAL_SIZE_UL_ULL MQTTvalue = mySwitch.getReceivedValue(); - int length = mySwitch.getReceivedBitlength(); - const char* binary = dec2binWzerofill(MQTTvalue, length); - - RFdata["value"] = (SIGNAL_SIZE_UL_ULL)MQTTvalue; - RFdata["protocol"] = (int)mySwitch.getReceivedProtocol(); - RFdata["length"] = (int)mySwitch.getReceivedBitlength(); - RFdata["delay"] = (int)mySwitch.getReceivedDelay(); - RFdata["tre_state"] = bin2tristate(binary); - RFdata["binary"] = binary; - -# if defined(ESP32) || defined(ESP8266) - unsigned int* raw = mySwitch.getReceivedRawdata(); - std::string rawDump; - for (unsigned int i = 0; i < length * 2; i++) { - if (i != 0) - rawDump += ","; - rawDump += std::to_string(raw[i]); - } - RFdata["raw"] = rawDump; -# endif -# ifdef ZradioCC1101 // set Receive off and Transmitt on - RFdata["frequency"] = RFConfig.frequency; -# endif - mySwitch.resetAvailable(); - - if (!isAduplicateSignal(MQTTvalue) && MQTTvalue != 0) { // conditions to avoid duplications of RF -->MQTT -# if defined(ZmqttDiscovery) && !defined(RF_DISABLE_TRANSMIT) && defined(RFmqttDiscovery) //component creation for HA - if (SYSConfig.discovery) - RFtoMQTTdiscovery(MQTTvalue); -# endif - RFdata["origin"] = subjectRFtoMQTT; - handleJsonEnqueue(RFdata); - // Casting "receivedSignal[o].value" to (unsigned long) because ArduinoLog doesn't support uint64_t for ESP's - Log.trace(F("Store val: %u" CR), (unsigned long)MQTTvalue); - storeSignalValue(MQTTvalue); - if (repeatRFwMQTT) { - Log.trace(F("Pub RF for rpt" CR)); - RFdata["origin"] = subjectMQTTtoRF; - handleJsonEnqueue(RFdata); - } - } - } -} - -# if simpleReceiving -void MQTTtoRF(char* topicOri, char* datacallback) { -# ifdef ZradioCC1101 // set Receive off and Transmitt on - disableCurrentReceiver(); - ELECHOUSE_cc1101.SetTx(RFConfig.frequency); - Log.notice(F("Transmit frequency: %F" CR), RFConfig.frequency); -# endif - mySwitch.disableReceive(); - mySwitch.enableTransmit(RF_EMITTER_GPIO); - SIGNAL_SIZE_UL_ULL data = STRTO_UL_ULL(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 on Arduino boards - - // RF DATA ANALYSIS - //We look into the subject to see if a special RF protocol is defined - String topic = topicOri; - int valuePRT = 0; - int valuePLSL = 0; - int valueBITS = 0; - int pos = topic.lastIndexOf(RFprotocolKey); - if (pos != -1) { - pos = pos + +strlen(RFprotocolKey); - valuePRT = (topic.substring(pos, pos + 1)).toInt(); - } - //We look into the subject to see if a special RF pulselength is defined - int pos2 = topic.lastIndexOf(RFpulselengthKey); - if (pos2 != -1) { - pos2 = pos2 + strlen(RFpulselengthKey); - valuePLSL = (topic.substring(pos2, pos2 + 3)).toInt(); - } - int pos3 = topic.lastIndexOf(RFbitsKey); - if (pos3 != -1) { - pos3 = pos3 + strlen(RFbitsKey); - valueBITS = (topic.substring(pos3, pos3 + 2)).toInt(); - } - - if ((cmpToMainTopic(topicOri, subjectMQTTtoRF)) && (valuePRT == 0) && (valuePLSL == 0) && (valueBITS == 0)) { - Log.trace(F("MQTTtoRF dflt" CR)); - mySwitch.setProtocol(1, 350); - mySwitch.send(data, 24); - // Acknowledgement to the GTWRF topic - pub(subjectGTWRFtoMQTT, datacallback); - } else if ((valuePRT != 0) || (valuePLSL != 0) || (valueBITS != 0)) { - Log.trace(F("MQTTtoRF usr par." CR)); - if (valuePRT == 0) - valuePRT = 1; - if (valuePLSL == 0) - valuePLSL = 350; - if (valueBITS == 0) - valueBITS = 24; - Log.notice(F("RF Protocol:%d" CR), valuePRT); - Log.notice(F("RF Pulse Lgth: %d" CR), valuePLSL); - Log.notice(F("Bits nb: %d" CR), valueBITS); - mySwitch.setProtocol(valuePRT, valuePLSL); - mySwitch.send(data, valueBITS); - // Acknowledgement to the GTWRF topic - pub(subjectGTWRFtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also - } -# ifdef ZradioCC1101 // set Receive on and Transmitt off - ELECHOUSE_cc1101.SetRx(RFConfig.frequency); - mySwitch.disableTransmit(); - mySwitch.enableReceive(RF_RECEIVER_GPIO); -# endif -} -# endif - -# if jsonReceiving -void MQTTtoRF(char* topicOri, JsonObject& RFdata) { // json object decoding - if (cmpToMainTopic(topicOri, subjectMQTTtoRF)) { - Log.trace(F("MQTTtoRF json" CR)); - SIGNAL_SIZE_UL_ULL data = RFdata["value"]; - if (data != 0) { - int valuePRT = RFdata["protocol"] | 1; - int valuePLSL = RFdata["delay"] | 350; - int valueBITS = RFdata["length"] | 24; - int valueRPT = RFdata["repeat"] | RF_EMITTER_REPEAT; - Log.notice(F("RF Protocol:%d" CR), valuePRT); - Log.notice(F("RF Pulse Lgth: %d" CR), valuePLSL); - Log.notice(F("Bits nb: %d" CR), valueBITS); -# ifdef ZradioCC1101 - disableCurrentReceiver(); - initCC1101(); - int txPower = RFdata["txpower"] | RF_CC1101_TXPOWER; - ELECHOUSE_cc1101.setPA((int)txPower); - Log.notice(F("CC1101 TX Power: %d" CR), txPower); - float txFrequency = RFdata["frequency"] | RFConfig.frequency; - ELECHOUSE_cc1101.SetTx(txFrequency); - Log.notice(F("Transmit frequency: %F" CR), txFrequency); -# endif - mySwitch.enableTransmit(RF_EMITTER_GPIO); - mySwitch.setRepeatTransmit(valueRPT); - mySwitch.setProtocol(valuePRT, valuePLSL); - mySwitch.send(data, valueBITS); - Log.notice(F("MQTTtoRF OK" CR)); - // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also - pub(subjectGTWRFtoMQTT, RFdata); - mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); // Restore the default value - } - - enableActiveReceiver(); - } -} -# endif - -int receiveInterupt = -1; - -void disableRFReceive() { - Log.trace(F("disableRFReceive %d" CR), receiveInterupt); - mySwitch.disableReceive(); -} - -void enableRFReceive() { - Log.notice(F("Enable RF Receiver: %FMhz" CR), RFConfig.frequency); - //RF init parameters - Log.notice(F("RF_EMITTER_GPIO: %d " CR), RF_EMITTER_GPIO); - Log.notice(F("RF_RECEIVER_GPIO: %d " CR), RF_RECEIVER_GPIO); - -# ifdef RF_DISABLE_TRANSMIT - mySwitch.disableTransmit(); -# else - mySwitch.enableTransmit(RF_EMITTER_GPIO); -# endif - receiveInterupt = RF_RECEIVER_GPIO; - mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); - mySwitch.enableReceive(receiveInterupt); - Log.trace(F("ZgatewayRF command topic: %s%s%s" CR), mqtt_topic, gateway_name, subjectMQTTtoRF); - Log.trace(F("ZgatewayRF setup done" CR)); -} -#endif diff --git a/main/ZgatewayRS232.ino b/main/ZgatewayRS232.ino deleted file mode 100644 index f6da25e..0000000 --- a/main/ZgatewayRS232.ino +++ /dev/null @@ -1,209 +0,0 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation - - Act as a wifi or ethernet gateway between your RS232 device and a MQTT broker - Send and receiving command by MQTT - - This gateway enables to: - - receive MQTT data from a topic and send RS232 signal corresponding to the received MQTT data - - publish MQTT data to a different topic related to received RS232 signal - - Copyright: (c)Florian ROBERT - - This file is part of OpenMQTTGateway. - - OpenMQTTGateway 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. - - OpenMQTTGateway 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 . -*/ -#include "User_config.h" - -#ifdef ZgatewayRS232 - -# ifndef RS232_UART // software serial mode -# include -SoftwareSerial RS232SoftSerial(RS232_RX_GPIO, RS232_TX_GPIO); // RX, TX -# endif - -// use pointer to stream class for serial communication to make code -// compatible with both softwareSerial as hardwareSerial. -Stream* RS232Stream = NULL; - -void setupRS232() { -//Initalize serial port -# ifdef RS232_UART // Hardware serial -# if RS232_UART == 0 // init UART0 - Serial.end(); // stop if already initialized -# ifdef ESP32 - Serial.begin(RS232Baud, SERIAL_8N1, RS232_RX_GPIO, RS232_TX_GPIO); -# else - Serial.begin(RS232Baud, SERIAL_8N1); -# endif -# if defined(ESP8266) && defined(RS232_UART0_SWAP) - Serial.swap(); // swap UART0 ports from (GPIO1,GPIO3) to (GPIO15,GPIO13) -# endif - RS232Stream = &Serial; - Log.notice(F("RS232 HW UART0" CR)); - -# elif RS232_UART == 1 // init UART1 - Serial1.end(); // stop if already initialized -# ifdef ESP32 - Serial1.begin(RS232Baud, SERIAL_8N1, RS232_RX_GPIO, RS232_TX_GPIO); -# else - Serial1.begin(RS232Baud, SERIAL_8N1); -# endif - RS232Stream = &Serial1; - Log.notice(F("RS232 HW UART1" CR)); - -# elif RS232_UART == 2 // init UART2 - Serial2.end(); // stop if already initialized -# ifdef ESP32 - Serial2.begin(RS232Baud, SERIAL_8N1, RS232_RX_GPIO, RS232_TX_GPIO); -# else - Serial2.begin(RS232Baud, SERIAL_8N1); -# endif - RS232Stream = &Serial2; - Log.notice(F("RS232 HW UART2" CR)); - -# elif RS232_UART == 3 // init UART3 - Serial3.end(); // stop if already initialized - Serial3.begin(RS232Baud, SERIAL_8N1); - RS232Stream = &Serial3; - Log.notice(F("RS232 HW UART3" CR)); -# endif - -# else // Software serial - // define pin modes for RX, TX: - pinMode(RS232_RX_GPIO, INPUT); - pinMode(RS232_TX_GPIO, OUTPUT); - RS232SoftSerial.begin(RS232Baud); - RS232Stream = &RS232SoftSerial; // get stream of serial - - Log.notice(F("RS232_RX_GPIO: %d" CR), RS232_RX_GPIO); - Log.notice(F("RS232_TX_GPIO: %d" CR), RS232_TX_GPIO); -# endif - - // Flush all bytes in the "link" serial port buffer - while (RS232Stream->available() > 0) - RS232Stream->read(); - - Log.notice(F("RS232Baud: %d" CR), RS232Baud); - Log.trace(F("ZgatewayRS232 setup done" CR)); -} - -# if RS232toMQTTmode == 0 // Convert received data to single MQTT topic -void RS232toMQTT() { - // Send all RS232 output (up to RS232InPost char revieved) as MQTT message - //This function is Blocking, but there should only ever be a few bytes, usually an ACK or a NACK. - if (RS232Stream->available()) { - Log.trace(F("RS232toMQTT" CR)); - static char RS232data[MAX_INPUT]; - static unsigned int input_pos = 0; - static char inChar; - do { - if (RS232Stream->available()) { - inChar = RS232Stream->read(); - RS232data[input_pos] = inChar; - input_pos++; - Log.trace(F("Received %c" CR), inChar); - } - } while (inChar != RS232InPost && input_pos < MAX_INPUT); - RS232data[input_pos] = 0; - input_pos = 0; - Log.trace(F("Publish %s" CR), RS232data); - char* output = RS232data + sizeof(RS232Pre) - 1; - pub(subjectRS232toMQTT, output); - } -} - -# elif RS232toMQTTmode == 1 // Convert recievee JSON data to multiple MQTT topics based (nested) keys -void RS232toMQTT() { - // Assumes valid JSON data at RS232 interface. Use (nested) keys to split JSON data in separate - // sub-MQTT-topics up to the defined nesting level. - if (RS232Stream->available()) { - Log.trace(F("RS232toMQTT" CR)); - - // Allocate the JSON document - StaticJsonDocument doc; - - // Read the JSON document from the "link" serial port - DeserializationError err = deserializeJson(doc, *RS232Stream); - - if (err == DeserializationError::Ok) { - // JSON received, send as MQTT topics - char topic[mqtt_topic_max_size + 1] = subjectRS232toMQTT; - sendMQTTfromNestedJson(doc.as(), topic, 0, RS232maxJSONlevel); - } else { - // Print error to serial log - Log.error(F("Error in RS232JSONtoMQTT, deserializeJson() returned %s"), err.c_str()); - - // Flush all bytes in the "link" serial port buffer - while (RS232Stream->available() > 0) - RS232Stream->read(); - } - } -} - -void sendMQTTfromNestedJson(JsonVariant obj, char* topic, int level, int maxLevel) { - // recursively step through JSON data and send MQTT messages - if (level < maxLevel && obj.is()) { - int topicLength = strlen(topic); - // loop over fields - for (JsonPair pair : obj.as()) { - // check if new key still fits in topic cstring - const char* key = pair.key().c_str(); - Log.trace(F("level=%d, key='%s'" CR), level, pair.key().c_str()); - if (topicLength + 2 + strlen(key) <= mqtt_topic_max_size) { - // add new level to existing topic cstring - topic[topicLength] = '/'; // add slash - topic[topicLength + 1] = '\0'; // terminate - strncat(topic + topicLength, key, mqtt_topic_max_size - topicLength - 2); - - // step recursively into next level - sendMQTTfromNestedJson(pair.value(), topic, level + 1, maxLevel); - - // restore topic - topic[topicLength] = '\0'; - } else { - Log.error(F("Nested key '%s' at level %d does not fit within max topic length of %d, skipping"), - key, level, mqtt_topic_max_size); - } - } - - } else { - // output value at current json level - char output[MAX_INPUT + 1]; - serializeJson(obj, output, MAX_INPUT); - Log.notice(F("level=%d, topic=%s, value: %s\n"), level, topic, output); - - // send MQTT message - pub(topic, &output[0]); - } -} -# endif - -void MQTTtoRS232(char* topicOri, JsonObject& RS232data) { - Log.trace(F("json" CR)); - if (cmpToMainTopic(topicOri, subjectMQTTtoRS232)) { - Log.trace(F("MQTTtoRS232 json" CR)); - const char* data = RS232data["value"]; - const char* prefix = RS232data["prefix"] | RS232Pre; - const char* postfix = RS232data["postfix"] | RS232Post; - Log.trace(F("Value set: %s" CR), data); - Log.trace(F("Prefix set: %s" CR), prefix); - Log.trace(F("Postfix set: %s" CR), postfix); - RS232Stream->print(prefix); - RS232Stream->print(data); - RS232Stream->print(postfix); - } -} -#endif \ No newline at end of file diff --git a/main/ZmqttDiscovery.ino b/main/ZmqttDiscovery.ino deleted file mode 100644 index 4d531ec..0000000 --- a/main/ZmqttDiscovery.ino +++ /dev/null @@ -1,1305 +0,0 @@ -/* - OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation - - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker - Send and receiving command by MQTT - - This is the Home Assistant MQTT Discovery addon. - - Copyright: (c) Rafal Herok - - This file is part of OpenMQTTGateway. - - OpenMQTTGateway 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. - - OpenMQTTGateway 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 . -*/ -#include "User_config.h" - -#ifdef ZmqttDiscovery - -String getMacAddress() { - uint8_t baseMac[6]; - char baseMacChr[13] = {0}; -# if defined(ESP8266) - WiFi.macAddress(baseMac); - sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]); -# elif defined(ESP32) - esp_read_mac(baseMac, ESP_MAC_WIFI_STA); - sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]); -# else - sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); -# endif - return String(baseMacChr); -} - -String getUniqueId(String name, String sufix) { - String uniqueId = (String)getMacAddress() + "-" + name + sufix; - return String(uniqueId); -} - -# ifdef ZgatewayBT -/** - * Create a discover messages form a list of attribute - * - * @param mac the MAC address - * @param sensorList[][0] = component type - * @param sensorList[][1] = name - * @param sensorList[][2] = availability topic - * @param sensorList[][3] = device class - * @param sensorList[][4] = value template - * @param sensorList[][5] = payload on - * @param sensorList[][6] = payload off - * @param sensorList[][7] = unit of measurement - * @param sensorList[][8] = unit of measurement - * @param sensorCount number of sensor - * @param device_name name of sensors - * @param device_manufacturer name of manufacturer - * @param device_model the model - * */ -void createDiscoveryFromList(const char* mac, - const char* sensorList[][9], - int sensorCount, - const char* device_name, - const char* device_manufacturer, - const char* device_model) { - for (int i = 0; i < sensorCount; i++) { - String discovery_topic = String(subjectBTtoMQTT) + "/" + String(mac); - String unique_id = String(mac) + "-" + sensorList[i][1]; - - createDiscovery(sensorList[i][0], - discovery_topic.c_str(), sensorList[i][1], unique_id.c_str(), - will_Topic, sensorList[i][3], sensorList[i][4], - sensorList[i][5], sensorList[i][6], sensorList[i][7], - 0, "", "", false, "", - device_name, device_manufacturer, device_model, mac, false, - sensorList[i][8] //The state class - ); - } -} -# endif - -/** - * @brief Create a message for Discovery Device Trigger. For HA @see https://www.home-assistant.io/integrations/device_trigger.mqtt/ - * @param use_gateway_info Boolean where true mean use the OMG information as Device Information - * @param topic The Topic where the trigger will publish the content - * @param type The type of the trigger, e.g. button_short_press. Entries supported by the HA Frontend: button_short_press, button_short_release, button_long_press, button_long_release, button_double_press, button_triple_press, button_quadruple_press, button_quintuple_press. If set to an unsupported value, will render as subtype type, e.g. button_1 spammed with type set to spammed and subtype set to button_1 - * @param subtype The subtype of the trigger, e.g. button_1. Entries supported by the HA frontend: turn_on, turn_off, button_1, button_2, button_3, button_4, button_5, button_6. If set to an unsupported value, will render as subtype type, e.g. left_button pressed with type set to button_short_press and subtype set to left_button - * @param unique_id Valid only if gateway entry is false, The IDs that uniquely identify the device. For example a serial number. - * @param device_name Valid only if gateway entry is false, The name of the device. - * @param device_manufacturer Valid only if gateway entry is false, The manufacturer of the device. - * @param device_model Valid only if gateway entry is false, The model of the device. - * @param device_id Valid only if gateway entry is false, The connection of the device to the outside world - */ -void announceDeviceTrigger(bool use_gateway_info, char* topic, char* type, char* subtype, char* unique_id, char* device_name, char* device_manufacturer, char* device_model, char* device_id) { - //Create The Json - StaticJsonDocument jsonBuffer; - JsonObject sensor = jsonBuffer.to(); - - // SET Default Configuration - sensor["automation_type"] = "trigger"; // The type of automation, must be ‘trigger’. - - //SET TYPE - if (type && type[0] != 0) { - sensor["type"] = type; - } else { - sensor["type"] = "button_short_press"; - } - - //SET SUBTYPE - if (subtype && subtype[0] != 0) { - sensor["subtype"] = subtype; - } else { - sensor["subtype"] = "turn_on"; - } - - /* Set The topic */ - if (topic && topic[0]) { - char state_topic[mqtt_topic_max_size]; - - strcpy(state_topic, mqtt_topic); - strcat(state_topic, gateway_name); - - strcat(state_topic, topic); - sensor["topic"] = state_topic; - } - - /* Set The Devices */ - StaticJsonDocument jsonDeviceBuffer; - JsonObject device = jsonDeviceBuffer.to(); - JsonArray identifiers = device.createNestedArray("identifiers"); - - if (use_gateway_info) { - device["name"] = gateway_name; -# ifndef GATEWAY_MODEL - String model = ""; - serializeJson(modules, model); - device["model"] = model; -# else - device["model"] = GATEWAY_MODEL; -# endif - - device["manufacturer"] = GATEWAY_MANUFACTURER; - device["sw_version"] = OMG_VERSION; - identifiers.add(getMacAddress()); - - } else { - char deviceid[13]; - memcpy(deviceid, &unique_id[0], 12); - deviceid[12] = '\0'; - - identifiers.add(deviceid); - - /*Set Connection */ - if (device_id && device_id[0] != 0) { - JsonArray connections = device.createNestedArray("connections"); - JsonArray connection_mac = connections.createNestedArray(); - connection_mac.add("mac"); - connection_mac.add(device_id); - } - - //Set manufacturer - if (device_manufacturer && device_manufacturer[0]) { - device["manufacturer"] = device_manufacturer; - } - - //Set name - if (device_name && device_name[0]) { - device["name"] = device_name; - } - - // set The Model - if (device_model && device_model[0]) { - device["model"] = device_model; - } - - device["via_device"] = gateway_name; //device name of the board - } - sensor["device"] = device; //device representing the board - - /* Publish on the topic */ - String topic_to_publish = String(discovery_Topic) + "/device_automation/" + String(unique_id) + "/config"; - Log.trace(F("Announce Device Trigger %s" CR), topic_to_publish.c_str()); - pub_custom_topic((char*)topic_to_publish.c_str(), sensor, true); -} - -/* - * Remove a substring p from a given string s -*/ -std::string remove_substring(std::string s, const std::string& p) { - std::string::size_type n = p.length(); - - for (std::string::size_type i = s.find(p); - i != std::string::npos; - i = s.find(p)) - s.erase(i, n); - - return s; -} - -/** - * @brief Generate message and publish it on an MQTT discovery explorer. For HA @see https://www.home-assistant.io/docs/mqtt/discovery/ - * - * @param sensor_type the Type - * @param st_topic set state topic, - * @param s_name set name, - * @param unique_id set uniqueId - * @param availability_topic set availability_topic, - * @param device_class set device_class, - * @param value_template set value_template, - * @param payload_on set payload_on, - * @param payload_off set payload_off, - * @param unit_of_meas set unit_of_meas, - * @param off_delay set off_delay - * @param payload_available set payload_available, - * @param payload_not_available set payload_not_available - * @param gateway_entity set is a gateway entity, - * @param cmd_topic set command topic - * @param device_name set device name, - * @param device_manufacturer set device manufacturer, - * @param device_model set device model, - * @param device_id set device(BLE)/entity(RTL_433) identification, - * @param retainCmd set retain - * @param state_class set state class - * - * */ -void createDiscovery(const char* sensor_type, - const char* st_topic, const char* s_name, const char* unique_id, - const char* availability_topic, const char* device_class, const char* value_template, - const char* payload_on, const char* payload_off, const char* unit_of_meas, - int off_delay, - const char* payload_available, const char* payload_not_available, bool gateway_entity, const char* cmd_topic, - const char* device_name, const char* device_manufacturer, const char* device_model, const char* device_id, bool retainCmd, - const char* state_class, const char* state_off, const char* state_on, const char* enum_options) { - StaticJsonDocument jsonBuffer; - JsonObject sensor = jsonBuffer.to(); - - // If a component cannot render it's state (f.i. KAKU relays) no state topic - // should be added. Without a state topic HA will use optimistic mode for the - // component by default. The Home Assistant UI for optimistic switches - // (separate on and off icons) allows for multiple - // subsequent on commands. This is required for dimming on KAKU relays like - // the ACM-300. - if (st_topic[0]) { - char state_topic[mqtt_topic_max_size]; - // If not an entity belonging to the gateway we put wild card for the location and gateway name - // allowing to have the entity detected by several gateways and a consistent discovery topic among the gateways - if (gateway_entity) { - strcpy(state_topic, mqtt_topic); - strcat(state_topic, gateway_name); - } else { - strcpy(state_topic, "+/+"); - } - strcat(state_topic, st_topic); - sensor["stat_t"] = state_topic; - } - - if (availability_topic[0] && gateway_entity) { - char avty_topic[mqtt_topic_max_size]; - strcpy(avty_topic, mqtt_topic); - strcat(avty_topic, gateway_name); - strcat(avty_topic, availability_topic); - sensor["avty_t"] = avty_topic; - } - - if (device_class[0]) { - // We check if the class belongs to HAAS classes list - int num_classes = sizeof(availableHASSClasses) / sizeof(availableHASSClasses[0]); - for (int i = 0; i < num_classes; i++) { // see class list and size into config_mqttDiscovery.h - if (strcmp(availableHASSClasses[i], device_class) == 0) { - sensor["dev_cla"] = device_class; //device_class - } - } - } - - if (unit_of_meas[0]) { - // We check if the class belongs to HAAS units list - int num_units = sizeof(availableHASSUnits) / sizeof(availableHASSUnits[0]); - for (int i = 0; i < num_units; i++) { // see units list and size into config_mqttDiscovery.h - if (strcmp(availableHASSUnits[i], unit_of_meas) == 0) { - sensor["unit_of_meas"] = unit_of_meas; //unit_of_measurement*/ - } - } - } - sensor["name"] = s_name; //name - sensor["uniq_id"] = unique_id; //unique_id - if (retainCmd) - sensor["retain"] = retainCmd; // Retain command - if (value_template[0]) { - if (strstr(value_template, " | is_defined") != NULL && SYSConfig.ohdiscovery) { - sensor["val_tpl"] = remove_substring(value_template, " | is_defined"); //OpenHAB compatible HA auto discovery - } else { - sensor["val_tpl"] = value_template; //HA Auto discovery - } - } - if (payload_on[0]) { - if (strcmp(sensor_type, "button") == 0) { - sensor["pl_prs"] = payload_on; // payload_press for a button press - } else if (strcmp(sensor_type, "number") == 0) { - sensor["cmd_tpl"] = payload_on; // payload_on for a switch - } else if (strcmp(sensor_type, "update") == 0) { - sensor["payload_install"] = payload_on; // payload_install for update - } else { - sensor["pl_on"] = payload_on; // payload_on for the rest - } - } - if (payload_off[0]) - sensor["pl_off"] = payload_off; //payload_off - if (strcmp(sensor_type, "device_tracker") == 0) - sensor["source_type"] = "bluetooth_le"; // payload_install for update - if (off_delay != 0) - sensor["off_delay"] = off_delay; //off_delay - if (payload_available[0]) - sensor["pl_avail"] = payload_available; // payload_on - if (payload_not_available[0]) - sensor["pl_not_avail"] = payload_not_available; //payload_off - if (state_class && state_class[0]) - sensor["state_class"] = state_class; //add the state class on the sensors ( https://developers.home-assistant.io/docs/core/entity/sensor/#available-state-classes ) - if (state_on != nullptr) - if (strcmp(state_on, "true") == 0) { - sensor["stat_on"] = true; - } else { - sensor["stat_on"] = state_on; - } - if (state_off != nullptr) - if (strcmp(state_off, "false") == 0) { - sensor["stat_off"] = false; - } else { - sensor["stat_off"] = state_off; - } - if (cmd_topic[0]) { - char command_topic[mqtt_topic_max_size]; - strcpy(command_topic, mqtt_topic); - strcat(command_topic, gateway_name); - strcat(command_topic, cmd_topic); - sensor["cmd_t"] = command_topic; //command_topic - } - - if (enum_options != nullptr) { - sensor["options"] = enum_options; - } - - StaticJsonDocument jsonDeviceBuffer; - JsonObject device = jsonDeviceBuffer.to(); - JsonArray identifiers = device.createNestedArray("ids"); - - if (gateway_entity) { - //device representing the board - device["name"] = String(gateway_name); -# ifndef GATEWAY_MODEL - String model = ""; - serializeJson(modules, model); - device["mdl"] = model; -# else - device["mdl"] = GATEWAY_MODEL; -# endif - device["mf"] = GATEWAY_MANUFACTURER; - if (ethConnected) { -# ifdef ESP32_ETHERNET - device["cu"] = String("http://") + String(ETH.localIP().toString()) + String("/"); //configuration_url -# endif - } else { - device["cu"] = String("http://") + String(WiFi.localIP().toString()) + String("/"); //configuration_url - } - - device["sw"] = OMG_VERSION; - identifiers.add(String(getMacAddress())); - } else { - //The Connections - if (device_id[0]) { - JsonArray connections = device.createNestedArray("cns"); - JsonArray connection_mac = connections.createNestedArray(); - connection_mac.add("mac"); - connection_mac.add(device_id); - //Device representing the actual sensor/switch device - //The Device ID - identifiers.add(device_id); - } - - if (device_manufacturer[0]) { - device["mf"] = device_manufacturer; - } - - if (device_model[0]) { - device["mdl"] = device_model; - } - - // generate unique device name by adding the second half of the device_id only if device_name and device_id are different - if (device_name[0]) { - if (strcmp(device_id, device_name) != 0 && device_id[0]) { - device["name"] = device_name + String("-") + String(device_id + 6); - } else { - device["name"] = device_name; - } - } - - device["via_device"] = String(gateway_name); //device name of the board - } - - sensor["device"] = device; - - String topic = String(discovery_Topic) + "/" + String(sensor_type) + "/" + String(unique_id) + "/config"; - Log.trace(F("Announce Device %s on %s" CR), String(sensor_type).c_str(), topic.c_str()); - pub_custom_topic((char*)topic.c_str(), sensor, true); -} - -void eraseTopic(const char* sensor_type, const char* unique_id) { - if (sensor_type == NULL || unique_id == NULL) { - return; - } - String topic = String(discovery_Topic) + "/" + String(sensor_type) + "/" + String(unique_id) + "/config"; - Log.trace(F("Erase entity discovery %s on %s" CR), String(sensor_type).c_str(), topic.c_str()); - pubMQTT((char*)topic.c_str(), "", true); -} - -# ifdef ZgatewayBT -void btPresenceParametersDiscovery() { - if (BTConfig.presenceEnable) { - createDiscovery("number", //set Type - subjectBTtoMQTT, "BT: Presence detection timer", (char*)getUniqueId("presenceawaytimer", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.presenceawaytimer/60000 }}", //set availability_topic,device_class,value_template, - "{\"presenceawaytimer\":{{value*60000}},\"save\":true}", "", "min", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain, - stateClassNone //State Class - ); - } -} - -void btScanParametersDiscovery() { - if (!BTConfig.adaptiveScan) { - createDiscovery("number", //set Type - subjectBTtoMQTT, "BT: Interval between scans", (char*)getUniqueId("interval", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.interval/1000 }}", //set availability_topic,device_class,value_template, - "{\"interval\":{{value*1000}},\"save\":true}", "", "s", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain, - stateClassNone //State Class - ); - createDiscovery("number", //set Type - subjectBTtoMQTT, "BT: Interval between active scans", (char*)getUniqueId("intervalacts", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.intervalacts/1000 }}", //set availability_topic,device_class,value_template, - "{\"intervalacts\":{{value*1000}},\"save\":true}", "", "s", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain, - stateClassNone //State Class - ); - } -} -# endif - -void pubMqttDiscovery() { - Log.trace(F("omgStatusDiscovery" CR)); - createDiscovery("binary_sensor", //set Type - will_Topic, "SYS: Connectivity", (char*)getUniqueId("connectivity", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "connectivity", "", //set availability_topic,device_class,value_template, - Gateway_AnnouncementMsg, will_Message, "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: Uptime", (char*)getUniqueId("uptime", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "duration", "{{ value_json.uptime }}", //set availability_topic,device_class,value_template, - "", "", "s", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); -# if defined(ESP8266) || defined(ESP32) - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: Free memory", (char*)getUniqueId("freemem", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "data_size", "{{ value_json.freemem }}", //set availability_topic,device_class,value_template, - "", "", "B", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: IP", (char*)getUniqueId("ip", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.ip }}", //set availability_topic,device_class,value_template, - "", "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("switch", //set Type - subjectSYStoMQTT, "SYS: Auto discovery", (char*)getUniqueId("disc", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.disc }}", //set availability_topic,device_class,value_template, - "{\"disc\":true,\"save\":true}", "{\"disc\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset, //set,payload_avalaible,payload_not avalaible ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain, - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - createDiscovery("switch", //set Type - subjectSYStoMQTT, "SYS: OpenHAB discovery", (char*)getUniqueId("ohdisc", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.ohdisc }}", //set availability_topic,device_class,value_template, - "{\"ohdisc\":true,\"save\":true}", "{\"ohdisc\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset, //set,payload_avalaible,payload_not avalaible ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain, - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); -# ifdef RGB_INDICATORS - createDiscovery("number", //set Type - subjectSYStoMQTT, "SYS: LED Brightness", (char*)getUniqueId("rgbb", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ (value_json.rgbb/2.55) | round(0) }}", //set availability_topic,device_class,value_template, - "{\"rgbb\":{{ (value*2.55) | round(0) }},\"save\":true}", "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain, - stateClassNone //State Class - ); -# endif - -# ifdef ZdisplaySSD1306 - createDiscovery("switch", //set Type - subjectSSD1306toMQTT, "SSD1306: Control", (char*)getUniqueId("onstate", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.onstate }}", //set availability_topic,device_class,value_template, - "{\"onstate\":true,\"save\":true}", "{\"onstate\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSSD1306set, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - createDiscovery("switch", //set Type - subjectWebUItoMQTT, "SSD1306: Display metric", (char*)getUniqueId("displayMetric", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.displayMetric }}", //set availability_topic,device_class,value_template, - "{\"displayMetric\":true,\"save\":true}", "{\"displayMetric\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoWebUIset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - createDiscovery("number", //set Type - subjectSSD1306toMQTT, "SSD1306: Brightness", (char*)getUniqueId("brightness", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.brightness }}", //set availability_topic,device_class,value_template, - "{\"brightness\":{{value}},\"save\":true}", "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSSD1306set, //set,payload_available,payload_not available,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifndef ESP32_ETHERNET - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: RSSI", (char*)getUniqueId("rssi", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "signal_strength", "{{ value_json.rssi }}", //set availability_topic,device_class,value_template, - "", "", "dB", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif -# endif -# if defined(ESP32) && !defined(NO_INT_TEMP_READING) - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: Internal temperature", (char*)getUniqueId("tempc", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "temperature", "{{ value_json.tempc | round(1)}}", //set availability_topic,device_class,value_template, - "", "", "°C", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_avalaible,payload_not avalaible ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC - stateClassMeasurement //State Class - ); -# if defined(ZboardM5STICKC) || defined(ZboardM5STICKCP) || defined(ZboardM5TOUGH) - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: Bat voltage", (char*)getUniqueId("m5batvoltage", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "voltage", "{{ value_json.m5batvoltage }}", //set availability_topic,device_class,value_template, - "", "", "V", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a child device, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: Bat current", (char*)getUniqueId("m5batcurrent", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "current", "{{ value_json.m5batcurrent }}", //set availability_topic,device_class,value_template, - "", "", "A", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a child device, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: Vin voltage", (char*)getUniqueId("m5vinvoltage", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "voltage", "{{ value_json.m5vinvoltage }}", //set availability_topic,device_class,value_template, - "", "", "V", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a child device, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: Vin current", (char*)getUniqueId("m5vincurrent", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "current", "{{ value_json.m5vincurrent }}", //set availability_topic,device_class,value_template, - "", "", "A", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a child device, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif -# ifdef ZboardM5STACK - createDiscovery("sensor", //set Type - subjectSYStoMQTT, "SYS: Batt level", (char*)getUniqueId("m5battlevel", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "battery", "{{ value_json.m5battlevel }}", //set availability_topic,device_class,value_template, - "", "", "%", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a child device, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("binary_sensor", //set Type - subjectSYStoMQTT, "SYS: Is Charging", (char*)getUniqueId("m5ischarging", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "{{ value_json.m5ischarging }}", "", //set availability_topic,device_class,value_template, - "", "", "%", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a child device, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("binary_sensor", //set Type - subjectSYStoMQTT, "SYS: Is Charge Full", (char*)getUniqueId("m5ischargefull", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "{{ value_json.m5ischargefull }}", "", //set availability_topic,device_class,value_template, - "", "", "%", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, "", //set,payload_available,payload_not available ,is a child device, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif -# endif - createDiscovery("button", //set Type - will_Topic, "SYS: Restart gateway", (char*)getUniqueId("restart", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "restart", "", //set availability_topic,device_class,value_template, - "{\"cmd\":\"restart\"}", "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("button", //set Type - will_Topic, "SYS: Erase credentials", (char*)getUniqueId("erase", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "", //set availability_topic,device_class,value_template, - "{\"cmd\":\"erase\"}", "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("update", //set Type - subjectRLStoMQTT, "SYS: Firmware Update", (char*)getUniqueId("update", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "firmware", "", //set availability_topic,device_class,value_template, - LATEST_OR_DEV, "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSupdate, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# ifdef ZsensorBME280 -# define BMEparametersCount 5 - Log.trace(F("bme280Discovery" CR)); - char* BMEsensor[BMEparametersCount][8] = { - {"sensor", "temp", "bme", "temperature", jsonTempc, "", "", "°C"}, - {"sensor", "pa", "bme", "pressure", jsonPa, "", "", "hPa"}, - {"sensor", "hum", "bme", "humidity", jsonHum, "", "", "%"}, - {"sensor", "altim", "bme", "", jsonAltim, "", "", "m"}, - {"sensor", "altift", "bme", "", jsonAltif, "", "", "ft"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < BMEparametersCount; i++) { - createDiscovery(BMEsensor[i][0], - BMETOPIC, BMEsensor[i][1], (char*)getUniqueId(BMEsensor[i][1], BMEsensor[i][2]).c_str(), - will_Topic, BMEsensor[i][3], BMEsensor[i][4], - BMEsensor[i][5], BMEsensor[i][6], BMEsensor[i][7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - } -# endif - -# ifdef ZsensorHTU21 -# define HTUparametersCount 2 - Log.trace(F("htu21Discovery" CR)); - char* HTUsensor[HTUparametersCount][8] = { - {"sensor", "temp", "htu", "temperature", jsonTempc, "", "", "°C"}, - {"sensor", "hum", "htu", "humidity", jsonHum, "", "", "%"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < HTUparametersCount; i++) { - //trc(HTUsensor[i][1]); - createDiscovery(HTUsensor[i][0], - HTUTOPIC, HTUsensor[i][1], (char*)getUniqueId(HTUsensor[i][1], HTUsensor[i][2]).c_str(), - will_Topic, HTUsensor[i][3], HTUsensor[i][4], - HTUsensor[i][5], HTUsensor[i][6], HTUsensor[i][7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); - } -# endif - -# ifdef ZsensorLM75 - Log.trace(F("LM75Discovery" CR)); - char* LM75sensor[8] = {"sensor", "temp", "htu", "temperature", jsonTempc, "", "", "°C"}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - createDiscovery(LM75sensor[0], - LM75TOPIC, LM75sensor[1], (char*)getUniqueId(LM75sensor[1], LM75sensor[2]).c_str(), - will_Topic, LM75sensor[3], LM75sensor[4], - LM75sensor[5], LM75sensor[6], LM75sensor[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); -# endif - -# ifdef ZsensorAHTx0 -# define AHTparametersCount 2 - Log.trace(F("AHTx0Discovery" CR)); - char* AHTsensor[AHTparametersCount][8] = { - {"sensor", "temp", "aht", "temperature", jsonTempc, "", "", "°C"}, - {"sensor", "hum", "aht", "humidity", jsonHum, "", "", "%"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < AHTparametersCount; i++) { - createDiscovery(AHTsensor[i][0], - AHTTOPIC, AHTsensor[i][1], (char*)getUniqueId(AHTsensor[i][1], AHTsensor[i][2]).c_str(), - will_Topic, AHTsensor[i][3], AHTsensor[i][4], - AHTsensor[i][5], AHTsensor[i][6], AHTsensor[i][7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); - } -# endif - -# ifdef ZsensorDHT -# define DHTparametersCount 2 - Log.trace(F("DHTDiscovery" CR)); - char* DHTsensor[DHTparametersCount][8] = { - {"sensor", "temp", "dht", "temperature", jsonTempc, "", "", "°C"}, - {"sensor", "hum", "dht", "humidity", jsonHum, "", "", "%"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < DHTparametersCount; i++) { - //trc(DHTsensor[i][1]); - createDiscovery(DHTsensor[i][0], - DHTTOPIC, DHTsensor[i][1], (char*)getUniqueId(DHTsensor[i][1], DHTsensor[i][2]).c_str(), - will_Topic, DHTsensor[i][3], DHTsensor[i][4], - DHTsensor[i][5], DHTsensor[i][6], DHTsensor[i][7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); - } -# endif - -# ifdef ZsensorADC - Log.trace(F("ADCDiscovery" CR)); - char* ADCsensor[8] = {"sensor", "adc", "", "", jsonAdc, "", "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(ADCsensor[1]); - createDiscovery(ADCsensor[0], - ADCTOPIC, ADCsensor[1], (char*)getUniqueId(ADCsensor[1], ADCsensor[2]).c_str(), - will_Topic, ADCsensor[3], ADCsensor[4], - ADCsensor[5], ADCsensor[6], ADCsensor[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifdef ZsensorBH1750 -# define BH1750parametersCount 3 - Log.trace(F("BH1750Discovery" CR)); - char* BH1750sensor[BH1750parametersCount][8] = { - {"sensor", "lux", "BH1750", "illuminance", jsonLux, "", "", "lx"}, - {"sensor", "ftCd", "BH1750", "irradiance", jsonFtcd, "", "", ""}, - {"sensor", "wattsm2", "BH1750", "irradiance", jsonWm2, "", "", "wm²"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < BH1750parametersCount; i++) { - //trc(BH1750sensor[i][1]); - createDiscovery(BH1750sensor[i][0], - subjectBH1750toMQTT, BH1750sensor[i][1], (char*)getUniqueId(BH1750sensor[i][1], BH1750sensor[i][2]).c_str(), - will_Topic, BH1750sensor[i][3], BH1750sensor[i][4], - BH1750sensor[i][5], BH1750sensor[i][6], BH1750sensor[i][7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); - } -# endif - -# ifdef ZsensorMQ2 -# define MQ2parametersCount 2 - Log.trace(F("MQ2Discovery" CR)); - char* MQ2sensor[MQ2parametersCount][8] = { - {"sensor", "gas", "MQ2", "gas", jsonVal, "", "", "ppm"}, - {"binary_sensor", "MQ2", "", "gas", jsonPresence, "true", "false", ""} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < MQ2parametersCount; i++) { - createDiscovery(MQ2sensor[i][0], - subjectMQ2toMQTT, MQ2sensor[i][1], (char*)getUniqueId(MQ2sensor[i][1], MQ2sensor[i][2]).c_str(), - will_Topic, MQ2sensor[i][3], MQ2sensor[i][4], - MQ2sensor[i][5], MQ2sensor[i][6], MQ2sensor[i][7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - } -# endif - -# ifdef ZsensorTEMT6000 -# define TEMT6000parametersCount 3 - Log.trace(F("TEMT6000Discovery" CR)); - char* TEMT6000sensor[TEMT6000parametersCount][8] = { - {"sensor", "lux", "TEMT6000", "illuminance", jsonLux, "", "", "lx"}, - {"sensor", "ftcd", "TEMT6000", "irradiance", jsonFtcd, "", "", ""}, - {"sensor", "wattsm2", "TEMT6000", "irradiance", jsonWm2, "", "", "wm²"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < TEMT6000parametersCount; i++) { - //trc(TEMT6000sensor[i][1]); - createDiscovery(TEMT6000sensor[i][0], - subjectTEMT6000toMQTT, TEMT6000sensor[i][1], (char*)getUniqueId(TEMT6000sensor[i][1], TEMT6000sensor[i][2]).c_str(), - will_Topic, TEMT6000sensor[i][3], TEMT6000sensor[i][4], - TEMT6000sensor[i][5], TEMT6000sensor[i][6], TEMT6000sensor[i][7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); - } -# endif - -# ifdef ZsensorTSL2561 -# define TSL2561parametersCount 3 - Log.trace(F("TSL2561Discovery" CR)); - char* TSL2561sensor[TSL2561parametersCount][8] = { - {"sensor", "lux", "TSL2561", "illuminance", jsonLux, "", "", "lx"}, - {"sensor", "ftcd", "TSL2561", "irradiance", jsonFtcd, "", "", ""}, - {"sensor", "wattsm2", "TSL2561", "irradiance", jsonWm2, "", "", "wm²"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < TSL2561parametersCount; i++) { - //trc(TSL2561sensor[i][1]); - createDiscovery(TSL2561sensor[i][0], - subjectTSL12561toMQTT, TSL2561sensor[i][1], (char*)getUniqueId(TSL2561sensor[i][1], TSL2561sensor[i][2]).c_str(), - will_Topic, TSL2561sensor[i][3], TSL2561sensor[i][4], - TSL2561sensor[i][5], TSL2561sensor[i][6], TSL2561sensor[i][7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); - } -# endif - -# ifdef ZsensorHCSR501 - Log.trace(F("HCSR501Discovery" CR)); - char* HCSR501sensor[8] = {"binary_sensor", "hcsr501", "", "motion", jsonPresence, "true", "false", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(HCSR501sensor[1]); - createDiscovery(HCSR501sensor[0], - subjectHCSR501toMQTT, HCSR501sensor[1], (char*)getUniqueId(HCSR501sensor[1], HCSR501sensor[2]).c_str(), - will_Topic, HCSR501sensor[3], HCSR501sensor[4], - HCSR501sensor[5], HCSR501sensor[6], HCSR501sensor[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifdef ZsensorGPIOInput - Log.trace(F("GPIOInputDiscovery" CR)); - char* GPIOInputsensor[8] = {"binary_sensor", "GPIOInput", "", "", jsonGpio, INPUT_GPIO_ON_VALUE, INPUT_GPIO_OFF_VALUE, ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(GPIOInputsensor[1]); - createDiscovery(GPIOInputsensor[0], - subjectGPIOInputtoMQTT, GPIOInputsensor[1], (char*)getUniqueId(GPIOInputsensor[1], GPIOInputsensor[2]).c_str(), - will_Topic, GPIOInputsensor[3], GPIOInputsensor[4], - GPIOInputsensor[5], GPIOInputsensor[6], GPIOInputsensor[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifdef ZsensorINA226 -# define INA226parametersCount 3 - Log.trace(F("INA226Discovery" CR)); - char* INA226sensor[INA226parametersCount][8] = { - {"sensor", "volt", "INA226", "voltage", jsonVolt, "", "", "V"}, - {"sensor", "current", "INA226", "current", jsonCurrent, "", "", "A"}, - {"sensor", "power", "INA226", "power", jsonPower, "", "", "W"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < INA226parametersCount; i++) { - //trc(INA226sensor[i][1]); - createDiscovery(INA226sensor[i][0], - subjectINA226toMQTT, INA226sensor[i][1], (char*)getUniqueId(INA226sensor[i][1], INA226sensor[i][2]).c_str(), - will_Topic, INA226sensor[i][3], INA226sensor[i][4], - INA226sensor[i][5], INA226sensor[i][6], INA226sensor[i][7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); - } -# endif - -# ifdef ZsensorDS1820 - // Publish any DS1820 sensors found on the OneWire bus - pubOneWire_HADiscovery(); -# endif - -# ifdef ZactuatorONOFF - Log.trace(F("actuatorONOFFDiscovery" CR)); - char* actuatorONOFF[8] = {"switch", "actuatorONOFF", "", "", "{{ value_json.cmd }}", "{\"cmd\":1}", "{\"cmd\":0}", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(actuatorONOFF[1]); - createDiscovery(actuatorONOFF[0], - subjectGTWONOFFtoMQTT, actuatorONOFF[1], (char*)getUniqueId(actuatorONOFF[1], actuatorONOFF[2]).c_str(), - will_Topic, actuatorONOFF[3], actuatorONOFF[4], - actuatorONOFF[5], actuatorONOFF[6], actuatorONOFF[7], - 0, Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoONOFF, - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone, //State Class - "0", "1" //state_off, state_on - ); -# endif - -# ifdef ZsensorRN8209 -# define RN8209parametersCount 4 - Log.trace(F("RN8209Discovery" CR)); - char* RN8209sensor[RN8209parametersCount][8] = { - {"sensor", "volt", "RN8209", "voltage", jsonVolt, "", "", "V"}, - {"sensor", "current", "RN8209", "current", jsonCurrent, "", "", "A"}, - {"sensor", "power", "RN8209", "power", jsonPower, "", "", "W"}, - {"binary_sensor", "inUse", "RN8209", "power", jsonInuseRN8209, "on", "off", ""} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - }; - - for (int i = 0; i < RN8209parametersCount; i++) { - String name = "NRG: " + String(RN8209sensor[i][1]); - createDiscovery(RN8209sensor[i][0], - subjectRN8209toMQTT, (char*)name.c_str(), (char*)getUniqueId(RN8209sensor[i][1], RN8209sensor[i][2]).c_str(), //set state_topic,name,uniqueId - will_Topic, RN8209sensor[i][3], RN8209sensor[i][4], //set availability_topic,device_class,value_template, - RN8209sensor[i][5], RN8209sensor[i][6], RN8209sensor[i][7], //set,payload_on,payload_off,unit_of_meas - 0, Gateway_AnnouncementMsg, will_Message, true, "", //set off_delay,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassMeasurement //State Class - ); - } -# endif - -# ifdef ZgatewayRF - // Sensor to display RF received value - Log.trace(F("gatewayRFDiscovery" CR)); - char* gatewayRF[8] = {"sensor", "gatewayRF", "", "", jsonVal, "", "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(gatewayRF[1]); - createDiscovery(gatewayRF[0], - subjectRFtoMQTT, gatewayRF[1], (char*)getUniqueId(gatewayRF[1], gatewayRF[2]).c_str(), - will_Topic, gatewayRF[3], gatewayRF[4], - gatewayRF[5], gatewayRF[6], gatewayRF[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - -# endif - -# ifdef ZgatewayRF2 - // Sensor to display RF received value - Log.trace(F("gatewayRF2Discovery" CR)); - char* gatewayRF2[8] = {"sensor", "gatewayRF2", "", "", jsonAddress, "", "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(gatewayRF2[1]); - createDiscovery(gatewayRF2[0], - subjectRF2toMQTT, gatewayRF2[1], (char*)getUniqueId(gatewayRF2[1], gatewayRF2[2]).c_str(), - will_Topic, gatewayRF2[3], gatewayRF2[4], - gatewayRF2[5], gatewayRF2[6], gatewayRF2[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifdef ZgatewayRFM69 - // Sensor to display RF received value - Log.trace(F("gatewayRFM69Discovery" CR)); - char* gatewayRFM69[8] = {"sensor", "gatewayRFM69", "", "", jsonVal, "", "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(gatewayRFM69[1]); - createDiscovery(gatewayRFM69[0], - subjectRFM69toMQTT, gatewayRFM69[1], (char*)getUniqueId(gatewayRFM69[1], gatewayRFM69[2]).c_str(), - will_Topic, gatewayRFM69[3], gatewayRFM69[4], - gatewayRFM69[5], gatewayRFM69[6], gatewayRFM69[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifdef ZgatewayLORA - // Sensor to display RF received value - Log.trace(F("gatewayLORADiscovery" CR)); - char* gatewayLORA[8] = {"sensor", "gatewayLORA", "", "", jsonMsg, "", "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(gatewayLORA[1]); - createDiscovery(gatewayLORA[0], - subjectLORAtoMQTT, gatewayLORA[1], (char*)getUniqueId(gatewayLORA[1], gatewayLORA[2]).c_str(), - will_Topic, gatewayLORA[3], gatewayLORA[4], - gatewayLORA[5], gatewayLORA[6], gatewayLORA[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - - createDiscovery("switch", //set Type - subjectLORAtoMQTT, "LORA: CRC", (char*)getUniqueId("enablecrc", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.enablecrc }}", //set availability_topic,device_class,value_template, - "{\"enablecrc\":true,\"save\":true}", "{\"enablecrc\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoLORAset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - - createDiscovery("switch", //set Type - subjectLORAtoMQTT, "LORA: Invert IQ", (char*)getUniqueId("invertiq", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.invertiq }}", //set availability_topic,device_class,value_template, - "{\"invertiq\":true,\"save\":true}", "{\"invertiq\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoLORAset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - - createDiscovery("switch", //set Type - subjectLORAtoMQTT, "LORA: Only Known", (char*)getUniqueId("onlyknown", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.onlyknown }}", //set availability_topic,device_class,value_template, - "{\"onlyknown\":true,\"save\":true}", "{\"onlyknown\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoLORAset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); -# endif - -# ifdef ZgatewaySRFB - // Sensor to display RF received value - Log.trace(F("gatewaySRFBDiscovery" CR)); - char* gatewaySRFB[8] = {"sensor", "gatewaySRFB", "", "", jsonVal, "", "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(gatewaySRFB[1]); - createDiscovery(gatewaySRFB[0], - subjectSRFBtoMQTT, gatewaySRFB[1], (char*)getUniqueId(gatewaySRFB[1], gatewaySRFB[2]).c_str(), - will_Topic, gatewaySRFB[3], gatewaySRFB[4], - gatewaySRFB[5], gatewaySRFB[6], gatewaySRFB[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifdef ZgatewayPilight - // Sensor to display RF received value - Log.trace(F("gatewayPilightDiscovery" CR)); - char* gatewayPilight[8] = {"sensor", "gatewayPilight", "", "", jsonMsg, "", "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(gatewayPilight[1]); - createDiscovery(gatewayPilight[0], - subjectPilighttoMQTT, gatewayPilight[1], (char*)getUniqueId(gatewayPilight[1], gatewayPilight[2]).c_str(), - will_Topic, gatewayPilight[3], gatewayPilight[4], - gatewayPilight[5], gatewayPilight[6], gatewayPilight[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifdef ZgatewayIR - // Sensor to display IR received value - Log.trace(F("gatewayIRDiscovery" CR)); - char* gatewayIR[8] = {"sensor", "gatewayIR", "", "", jsonVal, "", "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(gatewayIR[1]); - createDiscovery(gatewayIR[0], - subjectIRtoMQTT, gatewayIR[1], (char*)getUniqueId(gatewayIR[1], gatewayIR[2]).c_str(), - will_Topic, gatewayIR[3], gatewayIR[4], - gatewayIR[5], gatewayIR[6], gatewayIR[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifdef Zgateway2G - // Sensor to display 2G received value - Log.trace(F("gateway2GDiscovery" CR)); - char* gateway2G[8] = {"sensor", "gateway2G", "", "", jsonMsg, "", "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - - //trc(gateway2G[1]); - createDiscovery(gateway2G[0], - subject2GtoMQTT, gateway2G[1], (char*)getUniqueId(gateway2G[1], gateway2G[2]).c_str(), - will_Topic, gateway2G[3], gateway2G[4], - gateway2G[5], gateway2G[6], gateway2G[7], - 0, Gateway_AnnouncementMsg, will_Message, true, "", - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); -# endif - -# ifdef ZgatewayBT -# ifdef ESP32 - - createDiscovery("number", //set Type - subjectBTtoMQTT, "BT: Connect interval", (char*)getUniqueId("intervalcnct", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.intervalcnct/60000 }}", //set availability_topic,device_class,value_template, - "{\"intervalcnct\":{{value*60000}},\"save\":true}", "", "min", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("number", //set Type - subjectBTtoMQTT, "BT: Scan duration", (char*)getUniqueId("scanduration", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.scanduration/1000 }}", //set availability_topic,device_class,value_template, - "{\"scanduration\":{{value*1000}},\"save\":true}", "", "s", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("button", //set Type - will_Topic, "BT: Force scan", (char*)getUniqueId("force_scan", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "", //set availability_topic,device_class,value_template, - "{\"interval\":0}", "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device ID, retain - stateClassNone //State Class - ); - createDiscovery("button", //set Type - will_Topic, "BT: Erase config", (char*)getUniqueId("erase_bt_config", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "", //set availability_topic,device_class,value_template, - "{\"erase\":true}", "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone //State Class - ); - createDiscovery("switch", //set Type - subjectBTtoMQTT, "BT: Publish only sensors", (char*)getUniqueId("only_sensors", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.onlysensors }}", //set availability_topic,device_class,value_template, - "{\"onlysensors\":true,\"save\":true}", "{\"onlysensors\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - createDiscovery("switch", //set Type - subjectBTtoMQTT, "BT: Adaptive scan", (char*)getUniqueId("adaptive_scan", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.adaptivescan }}", //set availability_topic,device_class,value_template, - "{\"adaptivescan\":true,\"save\":true}", "{\"adaptivescan\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - createDiscovery("switch", //set Type - subjectBTtoMQTT, "BT: Enabled", (char*)getUniqueId("enabled", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.enabled }}", //set availability_topic,device_class,value_template, - "{\"enabled\":true,\"save\":true}", "{\"enabled\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - -# define EntitiesCount 9 - const char* obsoleteEntities[EntitiesCount][2] = { - // Remove previously created entities for version < 1.4.0 - {"switch", "active_scan"}, // Replaced by adaptive scan - // Remove previously created entities for version < 1.3.0 - {"number", "scanbcnct"}, // Now a connect interval - // Remove previously created entities for version < 1.2.0 - {"switch", "restart"}, // Now a button - {"switch", "erase"}, // Now a button - {"switch", "force_scan"}, // Now a button - {"sensor", "interval"}, // Now a number - {"sensor", "scanbcnct"}, // Now a number - {"switch", "ohdiscovery"}, // Now a new key - {"switch", "discovery"}}; // Now a new key - - for (int i = 0; i < EntitiesCount; i++) { - eraseTopic(obsoleteEntities[i][0], (char*)getUniqueId(obsoleteEntities[i][1], "").c_str()); - } - - btScanParametersDiscovery(); - - btPresenceParametersDiscovery(); - - createDiscovery("switch", //set Type - subjectBTtoMQTT, "BT: Publish HASS presence", (char*)getUniqueId("hasspresence", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.hasspresence }}", //set availability_topic,device_class,value_template, - "{\"hasspresence\":true,\"save\":true}", "{\"hasspresence\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - createDiscovery("switch", //set Type - subjectBTtoMQTT, "BT: Publish Advertisement data", (char*)getUniqueId("pubadvdata", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.pubadvdata }}", //set availability_topic,device_class,value_template, - "{\"pubadvdata\":true,\"save\":true}", "{\"pubadvdata\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); - createDiscovery("switch", //set Type - subjectBTtoMQTT, "BT: Connect to devices", (char*)getUniqueId("bleconnect", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.bleconnect }}", //set availability_topic,device_class,value_template, - "{\"bleconnect\":true,\"save\":true}", "{\"bleconnect\":false,\"save\":true}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available ,is a gateway entity, command topic - "", "", "", "", false, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); -# if DEFAULT_LOW_POWER_MODE != -1 - createDiscovery("switch", //set Type - subjectSYStoMQTT, "SYS: Low Power Mode command", (char*)getUniqueId("lowpowermode", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "{{ value_json.lowpowermode | bool }}", //set availability_topic,device_class,value_template, - "{\"lowpowermode\":2}", "{\"lowpowermode\":0}", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoBTset, //set,payload_available,payload_not available,is a gateway entity, command topic - "", "", "", "", true, // device name, device manufacturer, device model, device MAC, retain - stateClassNone, //State Class - "false", "true" //state_off, state_on - ); -# else - // Remove previously created switch for version < 1.4.0 - eraseTopic("switch", (char*)getUniqueId("lowpowermode", "").c_str()); -# endif -# endif -# endif -} -#endif diff --git a/main/ZactuatorFASTLED.ino b/main/actuatorFASTLED.cpp similarity index 88% rename from main/ZactuatorFASTLED.ino rename to main/actuatorFASTLED.cpp index b75dabf..324561f 100644 --- a/main/ZactuatorFASTLED.ino +++ b/main/actuatorFASTLED.cpp @@ -1,5 +1,5 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface This gateway enables to use RGBLED strips like WS2812 @@ -26,6 +26,8 @@ # include +# include "config_FASTLED.h" + enum LEDState { OFF, FIRE, @@ -41,10 +43,12 @@ const long blinkInterval = 300; const long fireUpdate = 10; CRGBPalette16 gPal; +void Fire2012WithPalette(); + void setupFASTLED() { - Log.notice(F("FASTLED_DATA_GPIO: %d" CR), FASTLED_DATA_GPIO); - Log.notice(F("FASTLED_NUM_LEDS: %d" CR), FASTLED_NUM_LEDS); - Log.trace(F("ZactuatorFASTLED setup done " CR)); + THEENGS_LOG_NOTICE(F("FASTLED_DATA_GPIO: %d" CR), FASTLED_DATA_GPIO); + THEENGS_LOG_NOTICE(F("FASTLED_NUM_LEDS: %d" CR), FASTLED_NUM_LEDS); + THEENGS_LOG_TRACE(F("actuatorFASTLED setup done " CR)); FastLED.addLeds(leds, FASTLED_NUM_LEDS); } @@ -94,26 +98,26 @@ void FASTLEDLoop() { FastLED.show(); } -boolean FASTLEDtoMQTT() { +boolean FASTLEDtoX() { return false; } # if jsonReceiving -void MQTTtoFASTLED(char* topicOri, JsonObject& jsonData) { +void XtoFASTLED(const char* topicOri, JsonObject& jsonData) { currentLEDState = GENERAL; //trc(topicOri); //number = (long)strtol(&datacallback[1], NULL, 16); if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetled)) { - Log.trace(F("MQTTtoFASTLED JSON analysis" CR)); + THEENGS_LOG_TRACE(F("MQTTtoFASTLED JSON analysis" CR)); int ledNr = jsonData["led"]; - Log.notice(F("Led numero: %d" CR), ledNr); + THEENGS_LOG_NOTICE(F("Led numero: %d" CR), ledNr); const char* color = jsonData["hex"]; - Log.notice(F("Color hex: %s" CR), color); + THEENGS_LOG_NOTICE(F("Color hex: %s" CR), color); long number = (long)strtol(color, NULL, 16); bool blink = jsonData["blink"]; if (ledNr <= FASTLED_NUM_LEDS) { - Log.notice(F("Blink: %d" CR), blink); + THEENGS_LOG_NOTICE(F("Blink: %d" CR), blink); blinkLED[ledNr] = blink; leds[ledNr] = number; } @@ -122,25 +126,25 @@ void MQTTtoFASTLED(char* topicOri, JsonObject& jsonData) { # endif # if simpleReceiving -void MQTTtoFASTLED(char* topicOri, char* datacallback) { - Log.trace(F("MQTTtoFASTLED: " CR)); +void XtoFASTLED(const char* topicOri, const char* datacallback) { + THEENGS_LOG_TRACE(F("MQTTtoFASTLED: " CR)); currentLEDState = GENERAL; long number = 0; if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLED)) { number = (long)strtol(&datacallback[1], NULL, 16); - Log.notice(F("Number: %l" CR), number); + THEENGS_LOG_NOTICE(F("Number: %l" CR), number); for (int i = 0; i < FASTLED_NUM_LEDS; i++) { leds[i] = number; } FastLED.show(); } else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetbrightness)) { number = (long)strtol(&datacallback[1], NULL, 16); - Log.notice(F("Number: %l" CR), number); + THEENGS_LOG_NOTICE(F("Number: %l" CR), number); FastLED.setBrightness(number); FastLED.show(); } else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetanimation)) { String payload = datacallback; - Log.notice(F("Datacallback: %s" CR), datacallback); + THEENGS_LOG_NOTICE(F("Datacallback: %s" CR), datacallback); if (strstr(datacallback, "fire") != NULL) { currentLEDState = FIRE; gPal = HeatColors_p; diff --git a/main/ZactuatorONOFF.ino b/main/actuatorONOFF.cpp similarity index 69% rename from main/ZactuatorONOFF.ino rename to main/actuatorONOFF.cpp index be00845..de7af8c 100644 --- a/main/ZactuatorONOFF.ino +++ b/main/actuatorONOFF.cpp @@ -1,7 +1,7 @@ /* - OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT Output GPIO defined to High or Low @@ -30,7 +30,15 @@ #ifdef ZactuatorONOFF +# include "LEDManager.h" +# include "TheengsCommon.h" +# include "config_ONOFF.h" + +extern LEDManager ledManager; +extern void ActuatorTrigger(); + # ifdef ESP32 + // Global struct to store live ONOFF configuration data ONOFFConfig_s ONOFFConfig; @@ -48,11 +56,11 @@ void ONOFFConfig_fromJson(JsonObject& ONOFFdata) { preferences.begin(Gateway_Short_Name, false); if (preferences.isKey("ONOFFConfig")) { int result = preferences.remove("ONOFFConfig"); - Log.notice(F("ONOFF config erase result: %d" CR), result); + THEENGS_LOG_NOTICE(F("ONOFF config erase result: %d" CR), result); preferences.end(); return; // Erase prevails on save, so skipping save } else { - Log.notice(F("ONOFF config not found" CR)); + THEENGS_LOG_NOTICE(F("ONOFF config not found" CR)); preferences.end(); } } @@ -67,7 +75,7 @@ void ONOFFConfig_fromJson(JsonObject& ONOFFdata) { preferences.begin(Gateway_Short_Name, false); int result = preferences.putString("ONOFFConfig", conf); preferences.end(); - Log.notice(F("ONOFF Config_save: %s, result: %d" CR), conf.c_str(), result); + THEENGS_LOG_NOTICE(F("ONOFF Config_save: %s, result: %d" CR), conf.c_str(), result); } } @@ -78,35 +86,64 @@ void ONOFFConfig_load() { auto error = deserializeJson(jsonBuffer, preferences.getString("ONOFFConfig", "{}")); preferences.end(); if (error) { - Log.error(F("ONOFF config deserialization failed: %s, buffer capacity: %u" CR), error.c_str(), jsonBuffer.capacity()); + THEENGS_LOG_ERROR(F("ONOFF config deserialization failed: %s, buffer capacity: %u" CR), error.c_str(), jsonBuffer.capacity()); return; } if (jsonBuffer.isNull()) { - Log.warning(F("ONOFF config is null" CR)); + THEENGS_LOG_WARNING(F("ONOFF config is null" CR)); return; } JsonObject jo = jsonBuffer.as(); ONOFFConfig_fromJson(jo); - Log.notice(F("ONOFF config loaded" CR)); + THEENGS_LOG_NOTICE(F("ONOFF config loaded" CR)); } else { preferences.end(); - Log.notice(F("ONOFF config not found" CR)); + THEENGS_LOG_NOTICE(F("ONOFF config not found" CR)); } } # else -void ONOFFConfig_init(){}; -void ONOFFConfig_fromJson(JsonObject& ONOFFdata){}; -void ONOFFConfig_load(){}; +void ONOFFConfig_init() {}; +void ONOFFConfig_fromJson(JsonObject& ONOFFdata) {}; +void ONOFFConfig_load() {}; # endif void updatePowerIndicator() { +# ifdef LED_ACTUATOR_ONOFF if (digitalRead(ACTUATOR_ONOFF_GPIO) == ACTUATOR_ON) { - PowerIndicatorON(); + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_ACTUATOR_ONOFF_COLOR); } else { - PowerIndicatorOFF(); + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_COLOR_BLACK); } +# endif } +//Check regularly temperature of the ESP32 board and switch OFF the relay if temperature is more than MAX_TEMP_ACTUATOR +# ifdef MAX_TEMP_ACTUATOR +extern float intTemperatureRead(); + +void overLimitTemp(void* pvParameters) { +# if defined(ESP32) && !defined(NO_INT_TEMP_READING) + for (;;) { + static float previousInternalTempc = 0; + float internalTempc = intTemperatureRead(); + THEENGS_LOG_TRACE(F("Internal temperature of the ESP32 %F" CR), internalTempc); + // We switch OFF the actuator if the temperature of the ESP32 is more than MAX_TEMP_ACTUATOR two consecutive times, so as to avoid false single readings to trigger the relay OFF. + if (internalTempc > MAX_TEMP_ACTUATOR && previousInternalTempc > MAX_TEMP_ACTUATOR) { + if (digitalRead(ACTUATOR_ONOFF_GPIO) == ACTUATOR_ON) { // This could be with the previous condition, but it is better to trigger the digitalRead only if the previous condition is met to avoid the digitalRead + THEENGS_LOG_ERROR(F("[ActuatorONOFF] OverTemperature detected ( %F > %F ) switching OFF Actuator" CR), internalTempc, MAX_TEMP_ACTUATOR); + ActuatorTrigger(); +# ifdef LED_ACTUATOR_ONOFF + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_ERROR_COLOR, -1); +# endif + } + } + previousInternalTempc = internalTempc; + vTaskDelay(TimeBetweenReadingIntTemp); + } +# endif +} +# endif + void setupONOFF() { # ifdef MAX_TEMP_ACTUATOR xTaskCreate(overLimitTemp, "overLimitTemp", 4000, NULL, 10, NULL); @@ -114,8 +151,8 @@ void setupONOFF() { # ifdef ESP32 ONOFFConfig_init(); ONOFFConfig_load(); - Log.notice(F("Target state on restart: %T" CR), ONOFFConfig.ONOFFState); - Log.notice(F("Use last state on restart: %T" CR), ONOFFConfig.useLastStateOnStart); + THEENGS_LOG_NOTICE(F("Target state on restart: %T" CR), ONOFFConfig.ONOFFState); + THEENGS_LOG_NOTICE(F("Use last state on restart: %T" CR), ONOFFConfig.useLastStateOnStart); # endif pinMode(ACTUATOR_ONOFF_GPIO, OUTPUT); # ifdef ACTUATOR_ONOFF_DEFAULT @@ -128,25 +165,27 @@ void setupONOFF() { } # endif updatePowerIndicator(); - Log.trace(F("ZactuatorONOFF setup done" CR)); + THEENGS_LOG_TRACE(F("actuatorONOFF setup done" CR)); } # if jsonReceiving -void MQTTtoONOFF(char* topicOri, JsonObject& ONOFFdata) { +void XtoONOFF(const char* topicOri, JsonObject& ONOFFdata) { if (cmpToMainTopic(topicOri, subjectMQTTtoONOFF)) { - Log.trace(F("MQTTtoONOFF json data analysis" CR)); + THEENGS_LOG_TRACE(F("MQTTtoONOFF json data analysis" CR)); int boolSWITCHTYPE = ONOFFdata["cmd"] | 99; int gpio = ONOFFdata["gpio"] | ACTUATOR_ONOFF_GPIO; if (boolSWITCHTYPE != 99) { - Log.notice(F("MQTTtoONOFF boolSWITCHTYPE ok: %d" CR), boolSWITCHTYPE); - Log.notice(F("GPIO number: %d" CR), gpio); + THEENGS_LOG_NOTICE(F("MQTTtoONOFF boolSWITCHTYPE ok: %d" CR), boolSWITCHTYPE); + THEENGS_LOG_NOTICE(F("GPIO number: %d" CR), gpio); pinMode(gpio, OUTPUT); digitalWrite(gpio, boolSWITCHTYPE); +# ifdef LED_ACTUATOR_ONOFF if (boolSWITCHTYPE == ACTUATOR_ON) { - PowerIndicatorON(); + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_ACTUATOR_ONOFF_COLOR); } else { - PowerIndicatorOFF(); + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_COLOR_BLACK); } +# endif # ifdef ESP32 if (ONOFFConfig.useLastStateOnStart) { ONOFFdata["save"] = true; @@ -157,30 +196,30 @@ void MQTTtoONOFF(char* topicOri, JsonObject& ONOFFdata) { stateONOFFMeasures(); } else { if (ONOFFdata["cmd"] == "high_pulse") { - Log.notice(F("MQTTtoONOFF high_pulse ok" CR)); - Log.notice(F("GPIO number: %d" CR), gpio); + THEENGS_LOG_NOTICE(F("MQTTtoONOFF high_pulse ok" CR)); + THEENGS_LOG_NOTICE(F("GPIO number: %d" CR), gpio); int pulselength = ONOFFdata["pulse_length"] | 500; - Log.notice(F("Pulse length: %d ms" CR), pulselength); + THEENGS_LOG_NOTICE(F("Pulse length: %d ms" CR), pulselength); pinMode(gpio, OUTPUT); digitalWrite(gpio, HIGH); delay(pulselength); digitalWrite(gpio, LOW); } else if (ONOFFdata["cmd"] == "low_pulse") { - Log.notice(F("MQTTtoONOFF low_pulse ok" CR)); - Log.notice(F("GPIO number: %d" CR), gpio); + THEENGS_LOG_NOTICE(F("MQTTtoONOFF low_pulse ok" CR)); + THEENGS_LOG_NOTICE(F("GPIO number: %d" CR), gpio); int pulselength = ONOFFdata["pulse_length"] | 500; - Log.notice(F("Pulse length: %d ms" CR), pulselength); + THEENGS_LOG_NOTICE(F("Pulse length: %d ms" CR), pulselength); pinMode(gpio, OUTPUT); digitalWrite(gpio, LOW); delay(pulselength); digitalWrite(gpio, HIGH); } else { - Log.error(F("MQTTtoONOFF failed json read" CR)); + THEENGS_LOG_ERROR(F("MQTTtoONOFF failed json read" CR)); } } } if (cmpToMainTopic(topicOri, subjectMQTTtoONOFFset)) { - Log.trace(F("MQTTtoONOFF json set" CR)); + THEENGS_LOG_TRACE(F("MQTTtoONOFF json set" CR)); /* * Configuration modifications priorities: * First `init=true` and `load=true` commands are executed (if both are present, INIT prevails on LOAD) @@ -203,15 +242,15 @@ void MQTTtoONOFF(char* topicOri, JsonObject& ONOFFdata) { # endif # if simpleReceiving -void MQTTtoONOFF(char* topicOri, char* datacallback) { +void XtoONOFF(const char* topicOri, const char* datacallback) { if ((cmpToMainTopic(topicOri, subjectMQTTtoONOFF))) { - Log.trace(F("MQTTtoONOFF" CR)); + THEENGS_LOG_TRACE(F("MQTTtoONOFF" CR)); char* endptr = NULL; long gpio = strtol(datacallback, &endptr, 10); if (datacallback == endptr) gpio = ACTUATOR_ONOFF_GPIO; - Log.notice(F("GPIO number: %d" CR), gpio); + THEENGS_LOG_NOTICE(F("GPIO number: %d" CR), gpio); pinMode(gpio, OUTPUT); bool ON = false; @@ -221,11 +260,13 @@ void MQTTtoONOFF(char* topicOri, char* datacallback) { ON = false; digitalWrite(gpio, ON); +# ifdef LED_ACTUATOR_ONOFF if (ON == ACTUATOR_ON) { - PowerIndicatorON(); + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_ACTUATOR_ONOFF_COLOR); } else { - PowerIndicatorOFF(); + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_COLOR_BLACK); } +# endif // we acknowledge the sending by publishing the value to an acknowledgement topic char b = ON; pub(subjectGTWONOFFtoMQTT, &b); @@ -233,40 +274,19 @@ void MQTTtoONOFF(char* topicOri, char* datacallback) { } # endif -//Check regularly temperature of the ESP32 board and switch OFF the relay if temperature is more than MAX_TEMP_ACTUATOR -# ifdef MAX_TEMP_ACTUATOR -void overLimitTemp(void* pvParameters) { -# if defined(ESP32) && !defined(NO_INT_TEMP_READING) - for (;;) { - static float previousInternalTempc = 0; - float internalTempc = intTemperatureRead(); - Log.trace(F("Internal temperature of the ESP32 %F" CR), internalTempc); - // We switch OFF the actuator if the temperature of the ESP32 is more than MAX_TEMP_ACTUATOR two consecutive times, so as to avoid false single readings to trigger the relay OFF. - if (internalTempc > MAX_TEMP_ACTUATOR && previousInternalTempc > MAX_TEMP_ACTUATOR) { - if (digitalRead(ACTUATOR_ONOFF_GPIO) == ACTUATOR_ON) { // This could be with the previous condition, but it is better to trigger the digitalRead only if the previous condition is met to avoid the digitalRead - Log.error(F("[ActuatorONOFF] OverTemperature detected ( %F > %F ) switching OFF Actuator" CR), internalTempc, MAX_TEMP_ACTUATOR); - ActuatorTrigger(); - CriticalIndicatorON(); - } - } - previousInternalTempc = internalTempc; - vTaskDelay(TimeBetweenReadingIntTemp); - } -# endif -} -# endif - // Check regularly current the relay and switch it OFF if the current is more than MAX_CURRENT_ACTUATOR # ifdef MAX_CURRENT_ACTUATOR void overLimitCurrent(float RN8209current) { static float RN8209previousCurrent = 0; - Log.trace(F("RN8209 Current %F" CR), RN8209current); + THEENGS_LOG_TRACE(F("RN8209 Current %F" CR), RN8209current); // We switch OFF the actuator if the current of the RN8209 is more than MAX_CURRENT_ACTUATOR. if (RN8209current > MAX_CURRENT_ACTUATOR && RN8209previousCurrent > MAX_CURRENT_ACTUATOR) { if (digitalRead(ACTUATOR_ONOFF_GPIO) == ACTUATOR_ON) { // This could be with the previous condition, but it is better to trigger the digitalRead only if the previous condition is met to avoid the digitalRead - Log.error(F("[ActuatorONOFF] OverCurrent detected ( %F > %F ) switching OFF Actuator" CR), RN8209current, MAX_CURRENT_ACTUATOR); + THEENGS_LOG_ERROR(F("[ActuatorONOFF] OverCurrent detected ( %F > %F ) switching OFF Actuator" CR), RN8209current, MAX_CURRENT_ACTUATOR); ActuatorTrigger(); - CriticalIndicatorON(); +# ifdef LED_ACTUATOR_ONOFF + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_ERROR_COLOR, -1); +# endif } } RN8209previousCurrent = RN8209current; @@ -282,13 +302,15 @@ void overLimitCurrent(float RN8209current) {} */ void ActuatorTrigger() { uint8_t level = !digitalRead(ACTUATOR_ONOFF_GPIO); - Log.trace(F("Actuator triggered %d" CR), level); + THEENGS_LOG_TRACE(F("Actuator triggered %d" CR), level); digitalWrite(ACTUATOR_ONOFF_GPIO, level); +# ifdef LED_ACTUATOR_ONOFF if (level == ACTUATOR_ON) { - PowerIndicatorON(); + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_ACTUATOR_ONOFF_COLOR); } else { - PowerIndicatorOFF(); + ledManager.setMode(LED_ACTUATOR_ONOFF, 0, LEDManager::Mode::STATIC, LED_COLOR_BLACK); } +# endif # ifdef ESP32 if (ONOFFConfig.useLastStateOnStart) { @@ -311,6 +333,6 @@ void stateONOFFMeasures() { ONOFFdata["uselaststate"] = ONOFFConfig.useLastStateOnStart; # endif ONOFFdata["origin"] = subjectGTWONOFFtoMQTT; - handleJsonEnqueue(ONOFFdata, QueueSemaphoreTimeOutTask); + enqueueJsonObject(ONOFFdata, QueueSemaphoreTimeOutTask); } #endif diff --git a/main/ZactuatorPWM.ino b/main/actuatorPWM.cpp similarity index 95% rename from main/ZactuatorPWM.ino rename to main/actuatorPWM.cpp index 2efd6fc..f8348e3 100644 --- a/main/ZactuatorPWM.ino +++ b/main/actuatorPWM.cpp @@ -1,5 +1,5 @@ /* - OpenMQTTGateway - ESP32, ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface This actuator enables control over the PWM outputs of microcontrollers. @@ -68,7 +68,7 @@ #include "User_config.h" #ifdef ZactuatorPWM - +# include "TheengsCommon.h" # include "config_PWM.h" static long previousUpdateTime = 0; // milliseconds @@ -128,15 +128,14 @@ void setupPWM() { // Configure the pin for PWM output. // I think this is the fastest frequency that allows for a 16-bit // duty cycle on an ESP32 - ledcSetup(i, 625.0, kNumDutyCycleBits); - ledcAttachPin(channelPins[i], i); + ledcAttachChannel(channelPins[i], 625.0, kNumDutyCycleBits, i); # endif calibrationMinLinear[i] = 0.f; calibrationMaxLinear[i] = 1.f; calibrationGamma[i] = PWM_DEFAULT_GAMMA; } - Log.trace(F("ZactuatorPWM setup done " CR)); + THEENGS_LOG_TRACE(F("actuatorPWM setup done " CR)); } // This applies a power curve to the input to try to make the inputs @@ -187,18 +186,18 @@ void PWMLoop() { # else analogWrite(channelPins[i], dutyCycle); # endif - //Log.notice(F("Setting channel %d : %d" CR),i,dutyCycle); + //THEENGS_LOG_NOTICE(F("Setting channel %d : %d" CR),i,dutyCycle); } } -boolean PWMtoMQTT() { +boolean PWMtoX() { return false; } # if jsonReceiving -void MQTTtoPWM(char* topicOri, JsonObject& jsonData) { +void XtoPWM(const char* topicOri, JsonObject& jsonData) { if (cmpToMainTopic(topicOri, subjectMQTTtoPWMset)) { - Log.trace(F("MQTTtoPWM JSON analysis" CR)); + THEENGS_LOG_TRACE(F("MQTTtoPWM JSON analysis" CR)); // Parse the target value for each channel int modifiedChannelBits = 0; for (int i = 0; i < kNumChannels; ++i) { diff --git a/main/ZactuatorSomfy.ino b/main/actuatorSomfy.cpp similarity index 73% rename from main/ZactuatorSomfy.ino rename to main/actuatorSomfy.cpp index 3e5cddd..536d439 100644 --- a/main/ZactuatorSomfy.ino +++ b/main/actuatorSomfy.cpp @@ -1,15 +1,15 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker +/* + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT - + This actor enables to: - receive MQTT data from a topic and send Somfy RTS remote control signals corresponding to the received MQTT data - + Copyright (C) 2020 Leon Kiefer This file is part of OpenMQTTGateway. - + OpenMQTTGateway 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 @@ -24,44 +24,50 @@ #include "User_config.h" #ifdef ZactuatorSomfy - # include # include # include +# include "config_RF.h" +# include "config_Somfy.h" # ifdef ZradioCC1101 # include # endif +void disableCurrentReceiver(); +void enableActiveReceiver(); +void initCC1101(); +void setupSomfy(); + void setupSomfy() { pinMode(RF_EMITTER_GPIO, OUTPUT); digitalWrite(RF_EMITTER_GPIO, LOW); # if defined(ESP32) if (!EEPROM.begin(max(4, SOMFY_REMOTE_NUM * 2))) { - Log.error(F("failed to initialise EEPROM" CR)); + THEENGS_LOG_ERROR(F("failed to initialise EEPROM" CR)); } # elif defined(ESP8266) EEPROM.begin(max(4, SOMFY_REMOTE_NUM * 2)); # endif - Log.trace(F("ZactuatorSomfy setup done " CR)); + THEENGS_LOG_TRACE(F("actuatorSomfy setup done " CR)); } # if jsonReceiving -void MQTTtoSomfy(char* topicOri, JsonObject& jsonData) { +void XtoSomfy(const char* topicOri, JsonObject& jsonData) { if (cmpToMainTopic(topicOri, subjectMQTTtoSomfy)) { - Log.trace(F("MQTTtoSomfy json data analysis" CR)); - float txFrequency = jsonData["frequency"] | RFConfig.frequency; + THEENGS_LOG_TRACE(F("MQTTtoSomfy json data analysis" CR)); + float txFrequency = jsonData["frequency"] | iRFConfig.getFrequency(); # ifdef ZradioCC1101 // set Receive off and Transmitt on disableCurrentReceiver(); ELECHOUSE_cc1101.SetTx(txFrequency); - Log.notice(F("Transmit frequency: %F" CR), txFrequency); + THEENGS_LOG_NOTICE(F("Transmit frequency: %F" CR), txFrequency); # endif const int remoteIndex = jsonData["remote"]; if (remoteIndex >= SOMFY_REMOTE_NUM) { - Log.warning(F("ZactuatorSomfy remote does not exist" CR)); + THEENGS_LOG_WARNING(F("actuatorSomfy remote does not exist" CR)); return; } const String commandData = jsonData["command"]; diff --git a/main/blufi.cpp b/main/blufi.cpp new file mode 100644 index 0000000..7b1fef5 --- /dev/null +++ b/main/blufi.cpp @@ -0,0 +1,508 @@ +/* + OpenMQTTGateway - ESP8266 or Arduino program for home automation + + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker + Send and receiving command by MQTT + + This program enables to: + - receive MQTT data from a topic and send signal (RF, IR, BLE, GSM) corresponding to the received MQTT data + - publish MQTT data to a different topic related to received signals (RF, IR, BLE, GSM) + + Copyright: (c)Florian ROBERT + + This file is part of OpenMQTTGateway. + + OpenMQTTGateway 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. + + OpenMQTTGateway 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 . +*/ +#if defined(ESP32) && defined(USE_BLUFI) +# include +# include + +# include "NimBLEDevice.h" +# include "NimBLEOta.h" +# include "TheengsCommon.h" +# include "User_config.h" +# include "esp_blufi_api.h" +# include "esp_mac.h" +# include "esp_timer.h" +# include "services/gap/ble_svc_gap.h" + +extern "C" { +# include "esp_blufi.h" +} + +extern void receivingDATA(const char* topicOri, const char* datacallback); + +static esp_timer_handle_t connection_timer = nullptr; +static NimBLEOta* pNimBLEOta; +static NimBLECharacteristic* pCommandCharacteristic; +static NimBLECharacteristic* pRecvFwCharacteristic; + +# ifndef BLUFI_MFG_ID +# define BLUFI_MFG_ID 0xFFFF // Default Manufacturer ID if not defined +# endif + +struct pkt_info { + uint8_t* pkt; + int pkt_len; +}; + +# define DATA_PACKAGE_VALUE 0x02 +# define DATA_SUBTYPE_CUSTOM_DATA 0x07 +# define FRAME_CTRL_DEFAULT 0x00 // Assuming no encryption or checksum on notifications for simplicity + +uint8_t getTypeValue(uint8_t packageType, uint8_t subType) { + return (packageType << 2) | subType; +} + +/* store the station info for send back to phone */ +//static bool gl_sta_connected = false; +bool omg_blufi_ble_connected = false; +static uint8_t gl_sta_bssid[6]; +static uint8_t gl_sta_ssid[32]; +static uint8_t gl_sta_passwd[64]; +static int gl_sta_ssid_len; +static bool gl_sta_is_connecting = false; +static esp_blufi_extra_info_t gl_sta_conn_info; +extern bool ethConnected; +extern bool mqttSetupPending; +extern std::unique_ptr mqtt; +extern WiFiManager wifiManager; + +static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t* param); +void wifi_event_handler(arduino_event_id_t event); +esp_err_t blufi_security_init(void); +void blufi_dh_negotiate_data_handler(uint8_t* data, int len, uint8_t** output_data, int* output_len, bool* need_free); +int blufi_aes_encrypt(uint8_t iv8, uint8_t* crypt_data, int crypt_len); +int blufi_aes_decrypt(uint8_t iv8, uint8_t* crypt_data, int crypt_len); +uint16_t blufi_crc_checksum(uint8_t iv8, uint8_t* data, int len); +void blufi_security_deinit(void); + +uint8_t getNextSequence() { + static uint8_t sequence = 0; + return sequence++; +} + +struct ReceivingCommandTaskData { + uint8_t* data; + uint32_t data_len; +}; + +// Task function to handle receivingCommand +void receivingCommandTask(void* pvParameters) { + ReceivingCommandTaskData* taskData = static_cast(pvParameters); + + DynamicJsonDocument json(JSON_MSG_BUFFER_MAX); + JsonObject jsonBlufi = json.to(); + auto error = deserializeJson(json, taskData->data, taskData->data_len); + if (error) { + THEENGS_LOG_ERROR(F("deserialize config failed: %s, buffer capacity: %u" CR), error.c_str(), json.capacity()); + } else { + if (jsonBlufi.containsKey("target") && jsonBlufi["target"].is()) { + char topic[(parameters_size) * 2 + jsonBlufi["target"].size() + 1]; + snprintf(topic, sizeof(topic), "%s%s%s", mqtt_topic, gateway_name, jsonBlufi["target"].as()); + jsonBlufi.remove("target"); + char jsonStr[JSON_MSG_BUFFER_MAX]; + serializeJson(jsonBlufi, jsonStr); + receivingDATA(topic, jsonStr); + } else { + THEENGS_LOG_NOTICE(F("No target found in the received command using SYS target, default index and save command" CR)); + if (!json.containsKey("cnt_index")) { + json["cnt_index"] = CNT_DEFAULT_INDEX; + json["save_cnt"] = true; + } + char topic[(parameters_size) * 2 + strlen(subjectMQTTtoSYSset) + 1]; + snprintf(topic, sizeof(topic), "%s%s%s", mqtt_topic, gateway_name, subjectMQTTtoSYSset); + char jsonStr[JSON_MSG_BUFFER_MAX]; + serializeJson(jsonBlufi, jsonStr); + receivingDATA(topic, jsonStr); + } + } + + // Clean up dynamically allocated memory, if any + if (taskData->data) { + free(taskData->data); + } + delete taskData; + + // Delete the task when finished + vTaskDelete(NULL); +} + +// We create a task to remove the load from the Bluetooth task +void createReceivingCommandTask(uint8_t* data, uint32_t data_len) { + // Allocate memory for task data and copy over the data + ReceivingCommandTaskData* taskData = new ReceivingCommandTaskData; + taskData->data = static_cast(malloc(data_len)); + memcpy(taskData->data, data, data_len); + taskData->data_len = data_len; + + // Create the task + xTaskCreate(receivingCommandTask, "ReceivingCmdTask", 10000, taskData, 5, NULL); +} + +void sendCustomDataNotification(const char* message) { + if (!omg_blufi_ble_connected) { + return; + } + size_t messageLength = strlen(message); + uint8_t notification[messageLength + 4]; + notification[0] = getTypeValue(DATA_PACKAGE_VALUE, DATA_SUBTYPE_CUSTOM_DATA); + notification[1] = FRAME_CTRL_DEFAULT; + notification[2] = getNextSequence(); + notification[3] = static_cast(messageLength); + memcpy(¬ification[4], message, messageLength); + esp_blufi_send_custom_data(notification, sizeof(notification)); +} + +# ifdef BT_CONNECTION_TIMEOUT_MS +void connection_timeout_callback(void* arg) { + if (omg_blufi_ble_connected) { + THEENGS_LOG_NOTICE(F("BluFi connection timeout reached. Disconnecting." CR)); + esp_blufi_disconnect(); + omg_blufi_ble_connected = false; + } +} + +void restart_connection_timer() { + if (connection_timer == nullptr) { + esp_timer_create_args_t timer_args = { + .callback = connection_timeout_callback, + .arg = NULL, + .name = "blufi_connection_timer"}; + esp_timer_create(&timer_args, &connection_timer); + } + + esp_timer_stop(connection_timer); // Stop the timer if it's running + esp_err_t ret = esp_timer_start_once(connection_timer, BT_CONNECTION_TIMEOUT_MS * 1000); + if (ret != ESP_OK) { + THEENGS_LOG_ERROR(F("Failed to start connection timer: %d" CR), ret); + } +} + +void stop_connection_timer() { + if (connection_timer != nullptr) { + esp_timer_stop(connection_timer); + } +} +# else +void restart_connection_timer() {} +void stop_connection_timer() {} +# endif + +void set_blufi_mfg_data() { + if (!NimBLEDevice::isInitialized() || !NimBLEDevice::getAdvertising()->isAdvertising()) { + THEENGS_LOG_NOTICE(F("Unable to set advertising data" CR)); + return; + } + ble_hs_adv_fields fields; + ble_uuid16_t blufi_uuid = BLE_UUID16_INIT(BLUFI_APP_UUID); + memset(&fields, 0, sizeof(fields)); + fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP; + const char* name = ble_svc_gap_device_name(); + fields.name = (uint8_t*)name; + fields.name_len = strlen(name); + fields.name_is_complete = true; + fields.uuids16 = &blufi_uuid; + fields.num_uuids16 = 1; + fields.uuids16_is_complete = true; + uint8_t omg_blufi_mfg_data[] = {BLUFI_MFG_ID & 0xFF, (BLUFI_MFG_ID >> 8) & 0xFF, 'O', gatewayState}; + fields.mfg_data = omg_blufi_mfg_data; + fields.mfg_data_len = sizeof(omg_blufi_mfg_data); + auto rc = ble_gap_adv_set_fields(&fields); + if (rc != 0) { + THEENGS_LOG_ERROR(F("Failed to set BLE advertising fields: %d" CR), rc); + } else { + THEENGS_LOG_TRACE(F("BLE advertising fields set successfully" CR)); + } +} + +void start_blufi_advertising() { + esp_blufi_adv_start(); + set_blufi_mfg_data(); +} + +static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t* param) { + /* actually, should post to blufi_task handle the procedure, + * now, as a example, we do it more simply */ + ble_gap_conn_desc desc; + + switch (event) { + case ESP_BLUFI_EVENT_INIT_FINISH: { + THEENGS_LOG_TRACE(F("BLUFI init finish" CR)); + start_blufi_advertising(); + break; + } + case ESP_BLUFI_EVENT_DEINIT_FINISH: + THEENGS_LOG_TRACE(F("BLUFI deinit finish" CR)); + NimBLEDevice::deinit(true); + if (connection_timer != nullptr) { + esp_timer_delete(connection_timer); + connection_timer = nullptr; + } + break; + case ESP_BLUFI_EVENT_BLE_CONNECT: + THEENGS_LOG_TRACE(F("BLUFI BLE connect" CR)); + gatewayState = GatewayState::ONBOARDING; + omg_blufi_ble_connected = true; + restart_connection_timer(); + ble_gap_conn_find(param->connect.conn_id, &desc); + // Blufi dosn't provide a callback for subscribe so we emulate it here. + pCommandCharacteristic->getCallbacks()->onSubscribe(pCommandCharacteristic, *(NimBLEConnInfo*)&desc, 2); + pRecvFwCharacteristic->getCallbacks()->onSubscribe(pRecvFwCharacteristic, *(NimBLEConnInfo*)&desc, 2); + esp_blufi_adv_stop(); + blufi_security_init(); + break; + case ESP_BLUFI_EVENT_BLE_DISCONNECT: + THEENGS_LOG_TRACE(F("BLUFI BLE disconnect" CR)); + omg_blufi_ble_connected = false; + stop_connection_timer(); + if (mqtt && mqtt->connected()) { + gatewayState = GatewayState::BROKER_CONNECTED; + } else if (ethConnected || WiFi.status() == WL_CONNECTED) { + gatewayState = GatewayState::NTWK_CONNECTED; + } else if (mqttSetupPending) { + gatewayState = GatewayState::WAITING_ONBOARDING; + } else { + gatewayState = GatewayState::OFFLINE; + } + ble_gap_conn_find(param->connect.conn_id, &desc); + pCommandCharacteristic->getCallbacks()->onSubscribe(pCommandCharacteristic, *(NimBLEConnInfo*)&desc, 0); + pRecvFwCharacteristic->getCallbacks()->onSubscribe(pRecvFwCharacteristic, *(NimBLEConnInfo*)&desc, 0); + blufi_security_deinit(); + start_blufi_advertising(); + break; + case ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP: + THEENGS_LOG_TRACE(F("BLUFI request wifi connect to AP" CR)); + WiFi.begin((char*)gl_sta_ssid, (char*)gl_sta_passwd); + gl_sta_is_connecting = true; + break; + case ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP: + THEENGS_LOG_TRACE(F("BLUFI request wifi disconnect from AP\n" CR)); + WiFi.disconnect(); + break; + case ESP_BLUFI_EVENT_REPORT_ERROR: + THEENGS_LOG_TRACE(F("BLUFI report error, error code %d\n" CR), param->report_error.state); + esp_blufi_send_error_info(param->report_error.state); + break; + case ESP_BLUFI_EVENT_GET_WIFI_STATUS: { + esp_blufi_extra_info_t info; + THEENGS_LOG_TRACE(F("BLUFI get wifi status" CR)); + if (gl_sta_ssid_len > 0 && gl_sta_ssid[0] != '\0') { + THEENGS_LOG_TRACE(F("SSID exists" CR)); + memset(&info, 0, sizeof(esp_blufi_extra_info_t)); + if (memcmp(gl_sta_bssid, "\0\0\0\0\0\0", 6) != 0) { + memcpy(info.sta_bssid, gl_sta_bssid, 6); + info.sta_bssid_set = true; + } + info.sta_ssid = gl_sta_ssid; + info.sta_ssid_len = gl_sta_ssid_len; + esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONN_SUCCESS, 0, &info); + } else if (gl_sta_is_connecting) { + esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONNECTING, 0, &gl_sta_conn_info); + } else { + esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONN_FAIL, 0, &gl_sta_conn_info); + } + + break; + } + case ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE: + THEENGS_LOG_TRACE(F("BLUFI recv slave disconnect a ble connection" CR)); + esp_blufi_disconnect(); + break; + case ESP_BLUFI_EVENT_RECV_STA_SSID: { + // ssid_len comes from an unauthenticated BLE provisioning frame; clamp it + // before the strncpy and the trailing NUL so a crafted long SSID cannot + // write past gl_sta_ssid. + size_t ssid_len = param->sta_ssid.ssid_len; + if (ssid_len > sizeof(gl_sta_ssid) - 1) + ssid_len = sizeof(gl_sta_ssid) - 1; + memcpy(gl_sta_ssid, param->sta_ssid.ssid, ssid_len); + gl_sta_ssid[ssid_len] = '\0'; + THEENGS_LOG_NOTICE(F("Recv STA SSID %s" CR), gl_sta_ssid); + break; + } + case ESP_BLUFI_EVENT_RECV_STA_PASSWD: { + size_t passwd_len = param->sta_passwd.passwd_len; + if (passwd_len > sizeof(gl_sta_passwd) - 1) + passwd_len = sizeof(gl_sta_passwd) - 1; + memcpy(gl_sta_passwd, param->sta_passwd.passwd, passwd_len); + gl_sta_passwd[passwd_len] = '\0'; + THEENGS_LOG_NOTICE(F("Recv STA PASSWORD" CR)); + break; + } + case ESP_BLUFI_EVENT_GET_WIFI_LIST: { + WiFi.scanNetworks(true); + break; + } + case ESP_BLUFI_EVENT_RECV_CUSTOM_DATA: { + THEENGS_LOG_NOTICE(F("Recv Custom Data %" PRIu32 CR), param->custom_data.data_len); + esp_log_buffer_hex("Custom Data", param->custom_data.data, param->custom_data.data_len); + createReceivingCommandTask(param->custom_data.data, param->custom_data.data_len); + break; + } + case ESP_BLUFI_EVENT_RECV_USERNAME: + break; + case ESP_BLUFI_EVENT_RECV_CA_CERT: + break; + case ESP_BLUFI_EVENT_RECV_CLIENT_CERT: + break; + case ESP_BLUFI_EVENT_RECV_SERVER_CERT: + break; + case ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY: + break; + ; + case ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY: + break; + default: + break; + } +} + +void wifi_event_handler(arduino_event_id_t event) { + switch (event) { + case ARDUINO_EVENT_WIFI_STA_GOT_IP6: + case ARDUINO_EVENT_WIFI_STA_GOT_IP: { + gatewayState = GatewayState::NTWK_CONNECTED; +# ifndef ESPWifiManualSetup + wifiManager.stopConfigPortal(); +# endif + gl_sta_is_connecting = false; + esp_blufi_extra_info_t info = {}; + const String current_ssid = WiFi.SSID(); + gl_sta_ssid_len = std::min(current_ssid.length(), sizeof(gl_sta_ssid) - 1); + std::copy_n(current_ssid.c_str(), gl_sta_ssid_len, gl_sta_ssid); + gl_sta_ssid[gl_sta_ssid_len] = '\0'; + uint8_t* bssid = WiFi.BSSID(); + if (bssid) { + std::copy_n(bssid, 6, gl_sta_bssid); + } + info.sta_bssid_set = true; + info.sta_ssid = gl_sta_ssid; + info.sta_ssid_len = gl_sta_ssid_len; + std::copy_n(gl_sta_bssid, 6, info.sta_bssid); + if (omg_blufi_ble_connected == true) { + esp_blufi_send_wifi_conn_report(WIFI_MODE_STA, ESP_BLUFI_STA_CONN_SUCCESS, 0, &info); + } + THEENGS_LOG_NOTICE(F("Connected to SSID: %s" CR), gl_sta_ssid); + break; + } + case ARDUINO_EVENT_WIFI_SCAN_DONE: { + uint16_t apCount = WiFi.scanComplete(); + if (apCount == 0) { + THEENGS_LOG_ERROR(F("No AP found" CR)); + break; + } + THEENGS_LOG_TRACE(F("AP found, count: %d" CR), apCount); + esp_blufi_ap_record_t* blufi_ap_list = (esp_blufi_ap_record_t*)malloc(apCount * sizeof(esp_blufi_ap_record_t)); + if (!blufi_ap_list) { + THEENGS_LOG_ERROR(F("Failed to allocate memory for AP list" CR)); + break; + } + for (int i = 0; i < apCount; ++i) { + THEENGS_LOG_NOTICE(F("%d: %s, Ch:%d (%ddBm)" CR), i + 1, WiFi.SSID(i).c_str(), WiFi.channel(i), WiFi.RSSI(i)); + blufi_ap_list[i].rssi = WiFi.RSSI(i); + size_t ssidLength = strlen(WiFi.SSID(i).c_str()); + if (ssidLength > sizeof(blufi_ap_list[i].ssid) - 1) { + ssidLength = sizeof(blufi_ap_list[i].ssid) - 1; + } + memcpy(blufi_ap_list[i].ssid, WiFi.SSID(i).c_str(), ssidLength); + blufi_ap_list[i].ssid[ssidLength] = '\0'; + } + if (omg_blufi_ble_connected == true) { + if (esp_blufi_send_wifi_list(apCount, blufi_ap_list) != ESP_OK) { + THEENGS_LOG_ERROR(F("Failed to send WiFi list" CR)); + } + } + free(blufi_ap_list); + break; + } + default: + break; + } + return; +} + +static esp_blufi_callbacks_t example_callbacks = { + .event_cb = example_event_callback, + .negotiate_data_handler = blufi_dh_negotiate_data_handler, + .encrypt_func = blufi_aes_encrypt, + .decrypt_func = blufi_aes_decrypt, + .checksum_func = blufi_crc_checksum, +}; + +bool isBlufiConnected() { + return omg_blufi_ble_connected; +} + +bool isStaConnecting() { + return gl_sta_is_connecting; +} + +bool startBlufi() { + esp_err_t ret = ESP_OK; + WiFi.onEvent(wifi_event_handler); + + ret = esp_blufi_register_callbacks(&example_callbacks); + if (ret) { + THEENGS_LOG_ERROR(F("%s blufi register failed, error code = %x" CR), __func__, ret); + return false; + } + + if (NimBLEDevice::isInitialized()) { + NimBLEDevice::deinit(true); + delay(50); + } + esp_blufi_btc_init(); + uint8_t mac[6]; + esp_read_mac(mac, ESP_MAC_WIFI_STA); + char advName[17] = {0}; + // Check length of Gateway_Short_Name + if (strlen(Gateway_Short_Name) > 3) { + THEENGS_LOG_ERROR(F("Gateway_Short_Name is too long, max 3 characters" CR)); + return false; + } + snprintf(advName, sizeof(advName), Gateway_Short_Name "_%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + NimBLEDevice::init(advName); + NimBLEDevice::setMTU(517); + NimBLEDevice::createServer(); // this initializes the GATT server so we need to reset it for blufi to init + ble_gatts_reset(); + esp_blufi_gatt_svr_init(); + pNimBLEOta = new NimBLEOta(); + NimBLEService* pNimBLEOtaSvc = pNimBLEOta->start(); + pCommandCharacteristic = pNimBLEOtaSvc->getCharacteristic(NimBLEUUID((uint16_t)0x8022)); + pRecvFwCharacteristic = pNimBLEOtaSvc->getCharacteristic(NimBLEUUID((uint16_t)0x8020)); + ble_gatts_start(); + THEENGS_LOG_NOTICE(F("BLUFI started" CR)); + return esp_blufi_profile_init() == ESP_OK; +} + +bool stopBlufi() { + esp_err_t result = ESP_OK; + if (omg_blufi_ble_connected) { + esp_blufi_disconnect(); + delay(50); + } + + ble_gap_adv_stop(); + result = esp_blufi_profile_deinit(); + if (result != ESP_OK) { + THEENGS_LOG_ERROR(F("Failed to deinit blufi profile: %d" CR), result); + return false; + } + THEENGS_LOG_NOTICE(F("BLUFI stopped" CR)); + return true; +} + +#endif // defined(ESP32) && defined(USE_BLUFI) \ No newline at end of file diff --git a/main/ZblufiSec.ino b/main/blufiSec.cpp similarity index 74% rename from main/ZblufiSec.ino rename to main/blufiSec.cpp index 7f4cbc4..0ac90c1 100644 --- a/main/ZblufiSec.ino +++ b/main/blufiSec.cpp @@ -6,8 +6,12 @@ #if defined(ESP32) && defined(USE_BLUFI) +# include + +# include "User_config.h" # include "esp_blufi_api.h" # include "esp_crc.h" +# include "esp_random.h" # include "mbedtls/aes.h" # include "mbedtls/dhm.h" # include "mbedtls/md5.h" @@ -48,11 +52,17 @@ static int myrand(void* rng_state, unsigned char* output, size_t len) { extern "C" void btc_blufi_report_error(esp_blufi_error_state_t state); void blufi_dh_negotiate_data_handler(uint8_t* data, int len, uint8_t** output_data, int* output_len, bool* need_free) { + if (data == NULL || len < 3) { + THEENGS_LOG_ERROR(F("BLUFI Invalid data format" CR)); + btc_blufi_report_error(ESP_BLUFI_DATA_FORMAT_ERROR); + return; + } + int ret; uint8_t type = data[0]; if (blufi_sec == NULL) { - Log.error(F("BLUFI Security is not initialized" CR)); + THEENGS_LOG_ERROR(F("BLUFI Security is not initialized" CR)); btc_blufi_report_error(ESP_BLUFI_INIT_SECURITY_ERROR); return; } @@ -66,31 +76,47 @@ void blufi_dh_negotiate_data_handler(uint8_t* data, int len, uint8_t** output_da } blufi_sec->dh_param = (uint8_t*)malloc(blufi_sec->dh_param_len); if (blufi_sec->dh_param == NULL) { + blufi_sec->dh_param_len = 0; /* Reset length to avoid using unallocated memory */ btc_blufi_report_error(ESP_BLUFI_DH_MALLOC_ERROR); - Log.error(F("%s, malloc failed\n" CR), __func__); + THEENGS_LOG_ERROR(F("%s, malloc failed\n" CR), __func__); return; } break; case SEC_TYPE_DH_PARAM_DATA: { if (blufi_sec->dh_param == NULL) { - Log.error(F("%s, blufi_sec->dh_param == NULL" CR), __func__); + THEENGS_LOG_ERROR(F("%s, blufi_sec->dh_param == NULL" CR), __func__); btc_blufi_report_error(ESP_BLUFI_DH_PARAM_ERROR); return; } + + if (len < (blufi_sec->dh_param_len + 1)) { + THEENGS_LOG_ERROR(F("%s, invalid dh param len" CR), __func__); + btc_blufi_report_error(ESP_BLUFI_DH_PARAM_ERROR); + return; + } + uint8_t* param = blufi_sec->dh_param; memcpy(blufi_sec->dh_param, &data[1], blufi_sec->dh_param_len); ret = mbedtls_dhm_read_params(&blufi_sec->dhm, ¶m, ¶m[blufi_sec->dh_param_len]); if (ret) { - Log.error(F("%s read param failed %d" CR), __func__, ret); + THEENGS_LOG_ERROR(F("%s read param failed %d" CR), __func__, ret); btc_blufi_report_error(ESP_BLUFI_READ_PARAM_ERROR); return; } free(blufi_sec->dh_param); blufi_sec->dh_param = NULL; - ret = mbedtls_dhm_make_public(&blufi_sec->dhm, (int)mbedtls_mpi_size(&blufi_sec->dhm.P), blufi_sec->self_public_key, blufi_sec->dhm.len, myrand, NULL); + const int dhm_len = mbedtls_dhm_get_len(&blufi_sec->dhm); + + if (dhm_len > DH_SELF_PUB_KEY_LEN) { + THEENGS_LOG_ERROR(F("%s dhm len not support %d" CR), __func__, dhm_len); + btc_blufi_report_error(ESP_BLUFI_DH_PARAM_ERROR); + return; + } + + ret = mbedtls_dhm_make_public(&blufi_sec->dhm, dhm_len, blufi_sec->self_public_key, DH_SELF_PUB_KEY_LEN, myrand, NULL); if (ret) { - Log.error(F("%s make public failed %d" CR), __func__, ret); + THEENGS_LOG_ERROR(F("%s make public failed %d" CR), __func__, ret); btc_blufi_report_error(ESP_BLUFI_MAKE_PUBLIC_ERROR); return; } @@ -101,18 +127,24 @@ void blufi_dh_negotiate_data_handler(uint8_t* data, int len, uint8_t** output_da &blufi_sec->share_len, myrand, NULL); if (ret) { - Log.error(F("%s mbedtls_dhm_calc_secret failed %d" CR), __func__, ret); + THEENGS_LOG_ERROR(F("%s mbedtls_dhm_calc_secret failed %d" CR), __func__, ret); btc_blufi_report_error(ESP_BLUFI_DH_PARAM_ERROR); return; } - mbedtls_md5(blufi_sec->share_key, blufi_sec->share_len, blufi_sec->psk); + ret = mbedtls_md5(blufi_sec->share_key, blufi_sec->share_len, blufi_sec->psk); - mbedtls_aes_setkey_enc(&blufi_sec->aes, blufi_sec->psk, 128); + if (ret) { + THEENGS_LOG_ERROR(F("%s mbedtls_md5 failed %d" CR), __func__, ret); + btc_blufi_report_error(ESP_BLUFI_CALC_MD5_ERROR); + return; + } + + mbedtls_aes_setkey_enc(&blufi_sec->aes, blufi_sec->psk, PSK_LEN * 8); /* alloc output data */ *output_data = &blufi_sec->self_public_key[0]; - *output_len = blufi_sec->dhm.len; + *output_len = dhm_len; *need_free = false; } break; diff --git a/main/ZboardM5.ino b/main/boardM5.cpp similarity index 63% rename from main/ZboardM5.ino rename to main/boardM5.cpp index d7348c4..f8d8862 100644 --- a/main/ZboardM5.ino +++ b/main/boardM5.cpp @@ -1,7 +1,7 @@ /* - OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT M5 boards management @@ -29,76 +29,55 @@ #include "User_config.h" #if defined(ZboardM5STICKC) || defined(ZboardM5STICKCP) || defined(ZboardM5STACK) || defined(ZboardM5TOUGH) -# ifdef ZboardM5STICKC -# include -# endif -# ifdef ZboardM5STICKCP -# include -# endif -# ifdef ZboardM5STACK -# include -# endif -# ifdef ZboardM5TOUGH -# include -# endif +# include "TheengsCommon.h" +# include "config_M5.h" // pulls in for every M5 board + +void wakeScreen(int brightness); +void displayIntro(int i, int X, int Y); +void drawLogo(int logoSize, int circle1X, int circle1Y, bool circle1, bool circle2, bool circle3, bool circle4, bool circle5, bool circle6); +void sleepScreen(); +void setBrightness(int brightness); + void logToLCD(bool display) { display ? Log.begin(LOG_LEVEL_LCD, &M5.Lcd) : Log.begin(LOG_LEVEL, &Serial); // Log on LCD following LOG_LEVEL_LCD } void setBrightness(int brightness) { -# if defined(ZboardM5STACK) - M5.Lcd.setBrightness(brightness * 2); -# endif -# if defined(ZboardM5STICKC) || defined(ZboardM5STICKCP) || defined(ZboardM5TOUGH) - (!brightness) ? M5.Axp.ScreenBreath(0) : M5.Axp.ScreenBreath(7 + (int)brightness * 0.08); -# endif + // M5Unified drives the backlight uniformly across Core (direct control) and + // the AXP-powered boards (Stick C/CP, Tough), replacing the old per-board + // M5.Lcd.setBrightness / M5.Axp.ScreenBreath split. Map the 0..100 OMG scale + // onto the panel's 0..255 range (100 -> 200, sleep 2 -> 4). + M5.Display.setBrightness(brightness * 2); } void setupM5() { - Log.notice(F("Setup M5" CR)); + THEENGS_LOG_NOTICE(F("Setup M5" CR)); + M5.begin(); // auto-detects the board, initialises the display and power pinMode(SLEEP_BUTTON, INPUT); // M5 stack 320*240 // M5StickC 160*80 // M5Stick LCD not supported - Log.notice(F("Low power set to: %d" CR), lowpowermode); - switch (lowpowermode) // if LOW POWER the intro is bypassed and the brightness set to sleep brightness - { - case 0: - wakeScreen(NORMAL_LCD_BRIGHTNESS); - M5.Lcd.fillScreen(WHITE); - displayIntro(M5.Lcd.width() * 0.25, (M5.Lcd.width() / 2) + M5.Lcd.width() * 0.12, (M5.Lcd.height() / 2) + M5.Lcd.height() * 0.2); + wakeScreen(NORMAL_LCD_BRIGHTNESS); + M5.Lcd.fillScreen(TFT_WHITE); + displayIntro(M5.Lcd.width() * 0.25, (M5.Lcd.width() / 2) + M5.Lcd.width() * 0.12, (M5.Lcd.height() / 2) + M5.Lcd.height() * 0.2); # if LOG_TO_LCD - Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD + Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD # endif - break; - case 1: - wakeScreen(SLEEP_LCD_BRIGHTNESS); - M5.Lcd.fillScreen(WHITE); -# if LOG_TO_LCD - Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD -# endif - break; - case 2: - M5.begin(false, false, false); - break; - } - Log.notice(F("Setup M5 end" CR)); + + THEENGS_LOG_NOTICE(F("Setup M5 end" CR)); } void sleepScreen() { - Log.trace(F("Screen going to sleep" CR)); -# if defined(ZboardM5STACK) - M5.begin(false, false, false); // M5.lcd.sleep() provokes a reset of the ESP -# endif -# if defined(ZboardM5STICKC) || defined(ZboardM5STICKCP) || defined(ZboardM5TOUGH) - M5.Axp.ScreenBreath(0); - M5.Axp.SetLDO2(false); -# endif + THEENGS_LOG_TRACE(F("Screen going to sleep" CR)); + // Backlight off + panel sleep. M5Unified routes this to the AXP LDO on + // Stick/Tough and to the Core's backlight control, so the old M5.begin() + // re-init workaround and the M5.Axp calls are no longer needed. + M5.Display.sleep(); } void wakeScreen(int brightness) { - Log.trace(F("Screen wake up" CR)); - M5.begin(); + THEENGS_LOG_TRACE(F("Screen wake up" CR)); + M5.Display.wakeup(); // undo sleepScreen(); harmless if already awake M5.Lcd.setCursor(0, 0, (M5.Lcd.height() > 200) ? 4 : 2); M5.Lcd.setTextSize(1); M5.Lcd.setRotation(1); @@ -106,17 +85,9 @@ void wakeScreen(int brightness) { } void loopM5() { - static int previousBtnState; - int currentBtnState = digitalRead(SLEEP_BUTTON); - if (currentBtnState != previousBtnState && currentBtnState == 0) { - int newlowpowermode = lowpowermode; - (lowpowermode == 2) ? newlowpowermode = 0 : newlowpowermode = newlowpowermode + 1; - changelowpowermode(newlowpowermode); - } - previousBtnState = currentBtnState; static int previousLogLevel; int currentLogLevel = Log.getLastMsgLevel(); - if (previousLogLevel != currentLogLevel && lowpowermode != 2) { + if (previousLogLevel != currentLogLevel) { switch (currentLogLevel) { case 1: case 2: @@ -139,20 +110,20 @@ void loopM5() { previousLogLevel = currentLogLevel; } -void MQTTtoM5(char* topicOri, JsonObject& M5data) { // json object decoding +void XtoM5(const char* topicOri, JsonObject& M5data) { // json object decoding if (cmpToMainTopic(topicOri, subjectMQTTtoM5set)) { - Log.trace(F("MQTTtoM5 json set" CR)); + THEENGS_LOG_TRACE(F("MQTTtoM5 json set" CR)); // Log display set between M5 lcd (true) and serial monitor (false) if (M5data.containsKey("log-lcd")) { bool displayOnLCD = M5data["log-lcd"]; - Log.notice(F("Set lcd log: %T" CR), displayOnLCD); + THEENGS_LOG_NOTICE(F("Set lcd log: %T" CR), displayOnLCD); logToLCD(displayOnLCD); } } } void displayIntro(int i, int X, int Y) { - Log.trace(F("Intro display on screen" CR)); + THEENGS_LOG_TRACE(F("Intro display on screen" CR)); drawLogo(i, X, Y, false, true, false, false, false, false); delay(50); drawLogo(i, X, Y, false, false, true, false, false, false); @@ -181,52 +152,50 @@ void drawLogo(int logoSize, int circle1X, int circle1Y, bool circle1, bool circl int circle2Y = circle1Y - (logoSize * 0.8); if (line1) { - M5.Lcd.drawLine(circle1X - 2, circle1Y, circle2X - 2, circle2Y, BLUE); - M5.Lcd.drawLine(circle1X - 1, circle1Y, circle2X - 1, circle2Y, BLUE); - M5.Lcd.drawLine(circle1X, circle1Y, circle2X, circle2Y, BLUE); - M5.Lcd.drawLine(circle1X + 1, circle1Y, circle2X + 1, circle2Y, BLUE); - M5.Lcd.drawLine(circle1X + 2, circle1Y, circle2X + 2, circle2Y, BLUE); - M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE); + M5.Lcd.drawLine(circle1X - 2, circle1Y, circle2X - 2, circle2Y, TFT_BLUE); + M5.Lcd.drawLine(circle1X - 1, circle1Y, circle2X - 1, circle2Y, TFT_BLUE); + M5.Lcd.drawLine(circle1X, circle1Y, circle2X, circle2Y, TFT_BLUE); + M5.Lcd.drawLine(circle1X + 1, circle1Y, circle2X + 1, circle2Y, TFT_BLUE); + M5.Lcd.drawLine(circle1X + 2, circle1Y, circle2X + 2, circle2Y, TFT_BLUE); + M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, TFT_WHITE); } if (line2) { - M5.Lcd.drawLine(circle1X - 2, circle1Y, circle3X - 2, circle3Y, BLUE); - M5.Lcd.drawLine(circle1X - 1, circle1Y, circle3X - 1, circle3Y, BLUE); - M5.Lcd.drawLine(circle1X, circle1Y, circle3X, circle3Y, BLUE); - M5.Lcd.drawLine(circle1X + 1, circle1Y, circle3X + 1, circle3Y, BLUE); - M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE); + M5.Lcd.drawLine(circle1X - 2, circle1Y, circle3X - 2, circle3Y, TFT_BLUE); + M5.Lcd.drawLine(circle1X - 1, circle1Y, circle3X - 1, circle3Y, TFT_BLUE); + M5.Lcd.drawLine(circle1X, circle1Y, circle3X, circle3Y, TFT_BLUE); + M5.Lcd.drawLine(circle1X + 1, circle1Y, circle3X + 1, circle3Y, TFT_BLUE); + M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, TFT_WHITE); } - M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, WHITE); + M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, TFT_WHITE); if (circle1) { - M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2, WHITE); + M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2, TFT_WHITE); M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T, TFT_GREEN); - M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, WHITE); + M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, TFT_WHITE); } if (circle2) { - M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3, WHITE); + M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3, TFT_WHITE); M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T, TFT_ORANGE); - M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE); + M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, TFT_WHITE); } if (circle3) { - M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4, WHITE); + M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4, TFT_WHITE); M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T, TFT_PINK); - M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE); + M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, TFT_WHITE); } if (name) { - M5.Lcd.setTextColor(BLUE); + M5.Lcd.setTextColor(TFT_BLUE); M5.Lcd.drawString("penMQTTGateway", circle1X + (circle1X * 0.27), circle1Y, (M5.Lcd.height() > 200) ? 4 : 2); } } void M5Print(char* line1, char* line2, char* line3) { - if (lowpowermode == 2) InfoIndicatorON(); wakeScreen(NORMAL_LCD_BRIGHTNESS); M5.Lcd.fillScreen(TFT_WHITE); drawLogo(M5.Lcd.width() * 0.1875, (M5.Lcd.width() / 2) - M5.Lcd.width() * 0.24, M5.Lcd.height() * 0.5, true, true, true, true, true, true); - M5.Lcd.setTextColor(BLUE); + M5.Lcd.setTextColor(TFT_BLUE); M5.Lcd.drawString(line1, 5, M5.Lcd.height() * 0.7, 1); M5.Lcd.drawString(line2, 5, M5.Lcd.height() * 0.8, 1); M5.Lcd.drawString(line3, 5, M5.Lcd.height() * 0.9, 1); delay(2000); - InfoIndicatorOFF(); // to switch off no need of condition } #endif diff --git a/main/boardTheengs.cpp b/main/boardTheengs.cpp new file mode 100644 index 0000000..f30aec9 --- /dev/null +++ b/main/boardTheengs.cpp @@ -0,0 +1,99 @@ +#if SELF_TEST +# include +# include +# include +# include +# include +# include + +# include "TheengsCommon.h" +# include "User_config.h" + +extern LEDManager ledManager; +extern void ESPRestart(byte reason); + +String getChipModel() { + esp_chip_info_t chip_info; + esp_chip_info(&chip_info); + + switch (chip_info.model) { + case CHIP_ESP32: + return "ESP32"; + case CHIP_ESP32S2: + return "ESP32-S2"; + case CHIP_ESP32S3: + return "ESP32-S3"; + case CHIP_ESP32C3: + return "ESP32-C3"; + case CHIP_ESP32H2: + return "ESP32-H2"; + default: + return "Unknown"; + } +} + +// From https://github.com/ThingPulse/espgateway-ethernet-testbed + +void addTestMessage(JsonArray& data, String name, String value, String result) { + JsonObject object = data.createNestedObject(); + object["name"] = name; + object["value"] = value; + object["result"] = result; +} + +void testDevice() { + StaticJsonDocument<1280> doc; + JsonArray data = doc.to(); + + addTestMessage(data, "Mac Address", String(WiFi.macAddress()), "OK"); + addTestMessage(data, "Chip Model", String(ESP.getChipModel()), "OK"); + addTestMessage(data, "Chip Revision", String(ESP.getChipRevision()), "OK"); + addTestMessage(data, "Available Cores", String(ESP.getChipCores()), ESP.getChipCores() == 2 ? "OK" : "NOK"); + addTestMessage(data, "Heap Size", String(ESP.getHeapSize() / 1024) + "kb", ESP.getHeapSize() > 100000 ? "OK" : "NOK"); + addTestMessage(data, "Free Heap", String(ESP.getFreeHeap() / 1024) + "kb", ESP.getFreeHeap() > 100000 ? "OK" : "NOK"); + addTestMessage(data, "ETH MAC Address", String(ETH.macAddress()), ETH.macAddress() ? "OK" : "NOK"); + addTestMessage(data, "ETH Local IP", ETH.localIP().toString(), ETH.localIP() ? "OK" : "NOK"); + addTestMessage(data, "ETH Full Duplex", ETH.fullDuplex() ? "true" : "false", ETH.fullDuplex() ? "OK" : "NOK"); + addTestMessage(data, "ETH Link Speed", String(ETH.linkSpeed()) + "Mbs", ETH.linkSpeed() ? "OK" : "NOK"); + addTestMessage(data, "Build Date", String(__DATE__), "OK"); + addTestMessage(data, "Build Time", String(__TIME__), "OK"); + Serial.println(); + serializeJson(doc, Serial); + Serial.println(); +} + +void testLeds() { + THEENGS_LOG_NOTICE(F("LED Test" CR)); + ledManager.setMode(0, 0, LEDManager::Mode::STATIC, LED_NETWORK_OK_COLOR, -1); + delay(1000); + ledManager.setMode(0, 1, LEDManager::Mode::STATIC, LED_NETWORK_OK_COLOR, -1); + delay(1000); + ledManager.setMode(0, 2, LEDManager::Mode::STATIC, LED_NETWORK_OK_COLOR, -1); + delay(1000); + ledManager.setMode(0, 3, LEDManager::Mode::STATIC, LED_NETWORK_OK_COLOR, -1); + THEENGS_LOG_NOTICE(F("LED Test Finished" CR)); +} + +void checkSerial() { + THEENGS_LOG_NOTICE(F("READY_FOR_SELFTEST" CR)); + unsigned long start = millis(); + while (millis() - start < 1000) { + if (Serial.available() > 0) { + String input = Serial.readStringUntil('\n'); + input.trim(); // Remove any extra whitespace + if (input == "SELFTEST") { + THEENGS_LOG_NOTICE(F("SELFTEST Launched" CR)); + testLeds(); + // Print 20 times the test data + for (int i = 0; i < 20; i++) { + testDevice(); + delay(1000); + } + THEENGS_LOG_NOTICE(F("SELFTEST Finished" CR)); + // Restart + ESPRestart(9); + } + } + } +} +#endif \ No newline at end of file diff --git a/main/certs/default_client_cert.h b/main/certs/default_client_cert.h index f7e6613..a6d496f 100644 --- a/main/certs/default_client_cert.h +++ b/main/certs/default_client_cert.h @@ -1,4 +1,7 @@ -const char* ss_client_cert PROGMEM = R"EOF(" +#pragma once +#include + +static const char* ss_client_cert PROGMEM = R"EOF(" -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- diff --git a/main/certs/default_client_key.h b/main/certs/default_client_key.h index 6a18da7..f41ddd6 100644 --- a/main/certs/default_client_key.h +++ b/main/certs/default_client_key.h @@ -1,4 +1,7 @@ -const char* ss_client_key PROGMEM = R"EOF(" +#pragma once +#include + +static const char* ss_client_key PROGMEM = R"EOF(" -----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY----- diff --git a/main/certs/default_ota_cert.h b/main/certs/default_ota_cert.h index b060165..a901ab5 100644 --- a/main/certs/default_ota_cert.h +++ b/main/certs/default_ota_cert.h @@ -1,26 +1,27 @@ // The certificate must be in PEM ascii format. -// The default certificate is for github. -const char* OTAserver_cert PROGMEM = R"EOF(" +// The default certificate is for ota.openmqttgateway.com +#pragma once +#include + +static const char* OTAserver_cert PROGMEM = R"EOF(" -----BEGIN CERTIFICATE----- -MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD -QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT -MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j -b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB -CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 -nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt -43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P -T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 -gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO -BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR -TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw -DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr -hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg -06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF -PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls -YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk -CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= +MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF +ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 +b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL +MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv +b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj +ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM +9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw +IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 +VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L +93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm +jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA +A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI +U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs +N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv +o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU +5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy +rqXRfboQnoZsG4q5WTP468SQvvG5 -----END CERTIFICATE----- ")EOF"; diff --git a/main/certs/default_server_cert.h b/main/certs/default_server_cert.h index f51eea7..29977ce 100644 --- a/main/certs/default_server_cert.h +++ b/main/certs/default_server_cert.h @@ -1,4 +1,7 @@ -const char* ss_server_cert PROGMEM = R"EOF(" +#pragma once +#include + +static const char* ss_server_cert PROGMEM = R"EOF(" -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- diff --git a/main/commonRF.cpp b/main/commonRF.cpp new file mode 100644 index 0000000..f949a7e --- /dev/null +++ b/main/commonRF.cpp @@ -0,0 +1,286 @@ +/* + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface + + Act as a wifi or ethernet gateway between your BLE/433mhz/infrared IR signal and an MQTT broker + Send and receiving command by MQTT + + Copyright: (c)Florian ROBERT + + This file is part of OpenMQTTGateway. + + OpenMQTTGateway 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. + + OpenMQTTGateway 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 . +*/ + +#include "User_config.h" + +#if defined(ZgatewayRF) || defined(ZgatewayPilight) || defined(ZgatewayRTL_433) || defined(ZgatewayRF2) || defined(ZactuatorSomfy) + +# ifdef ZradioCC1101 +# include +# endif +# include + +# include "TheengsCommon.h" +# include "config_RF.h" + +# ifdef ZgatewayRTL_433 +# include +extern rtl_433_ESP rtl_433; +# endif + +int currentReceiver = ACTIVE_NONE; +boolean isDriverEnabled = false; +extern void enableActiveReceiver(); +extern void disableCurrentReceiver(); + +// Note: this is currently just a simple wrapper used to make everything work. +// It prevents introducing external dependencies on newly added C++ structures, +// and acts as a first approach to mask the concrete implementations (rf, rf2, +// pilight, etc.). Later this can be extended or replaced by more complete driver +// abstractions without changing the rest of the system. +class ZCommonRFWrapper : public RFReceiver { +public: + ZCommonRFWrapper() : RFReceiver() {} + void enable() override { enableActiveReceiver(); } + void disable() override { disableCurrentReceiver(); } + int getReceiverID() const override { return currentReceiver; } +}; + +ZCommonRFWrapper iRFReceiver; +RFConfiguration iRFConfig(iRFReceiver); + +// Initialize the CC1101 and tune the RX frequency. +// - Uses truncated exponential backoff to avoid tight retry loops +// - Validates the configured frequency before touching the radio +// - Emits explicit logs for success/failure so watchdog resets are traceable +void initCC1101() { +# ifdef ZradioCC1101 // receiving with CC1101 + const float freqMhz = iRFConfig.getFrequency(); + if (!iRFConfig.validFrequency(freqMhz)) { + THEENGS_LOG_ERROR(F("C1101 invalid frequency: %F MHz" CR), freqMhz); + return; + } + + int delayMS = 16; + int delayMaxMS = 500; + bool connected = false; + +# ifdef RF_MODULE_SECONDARY_CS + // Boards carrying two radios on one SPI bus must hold the unused radio's + // chip-select high, or it answers on MISO and corrupts every transfer to the + // radio we do use. + pinMode(RF_MODULE_SECONDARY_CS, OUTPUT); + digitalWrite(RF_MODULE_SECONDARY_CS, HIGH); + THEENGS_LOG_NOTICE(F("Deselected secondary radio CS on GPIO%d" CR), RF_MODULE_SECONDARY_CS); +# endif + +# if defined(RF_CC1101_SCK) && defined(RF_CC1101_MISO) && \ + defined(RF_CC1101_MOSI) && defined(RF_CC1101_CS) + THEENGS_LOG_TRACE(F("initCC1101 with custom SPI pins, SCK=%d, MISO=%d, MOSI=%d, CS=%d" CR), RF_CC1101_SCK, RF_CC1101_MISO, RF_CC1101_MOSI, RF_CC1101_CS); + ELECHOUSE_cc1101.setSpiPin(RF_CC1101_SCK, RF_CC1101_MISO, RF_CC1101_MOSI, RF_CC1101_CS); +# endif + + // Init() must run before getCC1101(): from driver V3.x on it is Init() that + // starts the SPI bus, so the status-register read behind getCC1101() would + // otherwise run on a bus that was never begun. + ELECHOUSE_cc1101.Init(); + + for (int attempt = 1; attempt <= 10; attempt++) { + if (ELECHOUSE_cc1101.getCC1101()) { + connected = true; + THEENGS_LOG_NOTICE(F("C1101 SPI connection OK on attempt %d" CR), attempt); + ELECHOUSE_cc1101.SetRx(freqMhz); + THEENGS_LOG_NOTICE(F("C1101 tuned RX to %F MHz" CR), freqMhz); + break; + } + + THEENGS_LOG_ERROR(F("C1101 SPI connection error (attempt %d), retrying" CR), attempt); + delay(delayMS); + + // truncated exponential backoff + delayMS = delayMS * 2; + if (delayMS > delayMaxMS) delayMS = delayMaxMS; + + ELECHOUSE_cc1101.Init(); + } + + if (!connected) { + THEENGS_LOG_ERROR(F("C1101 init failed after retries, radio left disabled" CR)); + } +# else + THEENGS_LOG_TRACE(F("initCC1101 skipped: ZradioCC1101 not enabled" CR)); +# endif +} + +void setupCommonRF() { + iRFConfig.reInit(); + iRFConfig.loadFromStorage(true); +} + +# if !defined(ZgatewayRFM69) && !defined(ZactuatorSomfy) +// Check if a receiver is available +bool validReceiver(int receiver) { + switch (receiver) { +# ifdef ZgatewayPilight + case ACTIVE_PILIGHT: + return true; +# endif +# ifdef ZgatewayRF + case ACTIVE_RF: + return true; +# endif +# ifdef ZgatewayRTL_433 + case ACTIVE_RTL: + return true; +# endif +# ifdef ZgatewayRF2 + case ACTIVE_RF2: + return true; +# endif + default: + THEENGS_LOG_ERROR(F("ERROR: stored receiver %d not available" CR), receiver); + } + return false; +} +# endif + +void disableCurrentReceiver() { + if (!isDriverEnabled) { + THEENGS_LOG_TRACE(F("Receiver %d is already disabled" CR), currentReceiver); + return; + } + THEENGS_LOG_TRACE(F("disableCurrentReceiver: %d" CR), currentReceiver); + switch (currentReceiver) { + case ACTIVE_NONE: + isDriverEnabled = false; + break; +# ifdef ZgatewayPilight + case ACTIVE_PILIGHT: + disablePilightReceive(); + isDriverEnabled = false; + break; +# endif +# ifdef ZgatewayRF + case ACTIVE_RF: + disableRFReceive(); + isDriverEnabled = false; + break; +# endif +# ifdef ZgatewayRTL_433 + case ACTIVE_RTL: + disableRTLreceive(); + isDriverEnabled = false; + break; +# endif +# ifdef ZgatewayRF2 + case ACTIVE_RF2: + disableRF2Receive(); + isDriverEnabled = false; + break; +# endif + default: + THEENGS_LOG_ERROR(F("ERROR: unsupported receiver %d" CR), iRFConfig.getActiveReceiver()); + } +} + +void enableActiveReceiver() { + if (isDriverEnabled) { + THEENGS_LOG_TRACE(F("Receiver %d is already enabled" CR), currentReceiver); + return; + } + THEENGS_LOG_TRACE(F("enableActiveReceiver: %d" CR), iRFConfig.getActiveReceiver()); + switch (iRFConfig.getActiveReceiver()) { +# ifdef ZgatewayPilight + case ACTIVE_PILIGHT: + initCC1101(); + enablePilightReceive(); + currentReceiver = ACTIVE_PILIGHT; + isDriverEnabled = true; + break; +# endif +# ifdef ZgatewayRF + case ACTIVE_RF: + initCC1101(); + enableRFReceive(iRFConfig.getFrequency(), RF_RECEIVER_GPIO, RF_EMITTER_GPIO); + currentReceiver = ACTIVE_RF; + isDriverEnabled = true; + break; +# endif +# ifdef ZgatewayRTL_433 + case ACTIVE_RTL: + initCC1101(); + enableRTLreceive(); + currentReceiver = ACTIVE_RTL; + isDriverEnabled = true; + break; +# endif +# ifdef ZgatewayRF2 + case ACTIVE_RF2: + initCC1101(); + enableRF2Receive(); + currentReceiver = ACTIVE_RF2; + isDriverEnabled = true; + break; +# endif + case ACTIVE_RECERROR: + THEENGS_LOG_ERROR(F("ERROR: no receiver selected" CR)); + break; + default: + THEENGS_LOG_ERROR(F("ERROR: unsupported receiver %d" CR), iRFConfig.getActiveReceiver()); + } +} + +String stateRFMeasures() { + //Publish RTL_433 state + StaticJsonDocument jsonBuffer; + JsonObject RFdata = jsonBuffer.to(); + + // load the configuration + iRFConfig.toJson(RFdata); + + // load the current state +# if defined(ZradioCC1101) || defined(ZradioSX127x) + if (iRFConfig.getActiveReceiver() == ACTIVE_RTL) { +# ifdef ZgatewayRTL_433 + RFdata["rssithreshold"] = (int)getRTLrssiThreshold(); + RFdata["rssi"] = (int)getRTLCurrentRSSI(); + RFdata["avgrssi"] = (int)getRTLAverageRSSI(); + RFdata["count"] = (int)getRTLMessageCount(); + // Capture high water mark of rtl_433_Decoder stack since it can run out and trigger reboot + extern TaskHandle_t rtl_433_DecoderHandle; + RFdata["rtl433_stack"] = (int)uxTaskGetStackHighWaterMark(rtl_433_DecoderHandle); +# endif +# ifdef ZradioSX127x + RFdata["ookthreshold"] = (int)getOOKThresh(); +# endif + } +# endif + RFdata["origin"] = subjectcommonRFtoMQTT; + enqueueJsonObject(RFdata); + + String output; + serializeJson(RFdata, output); + return output; +} + +void XtoRFset(const char* topicOri, JsonObject& RFdata) { + if (cmpToMainTopic(topicOri, subjectMQTTtoRFset)) { + THEENGS_LOG_TRACE(F("MQTTtoRF json set" CR)); + + iRFConfig.loadFromMessage(RFdata); + + stateRFMeasures(); + } +} +#endif diff --git a/main/config_2G.h b/main/config_2G.h index 8456c8b..9f74096 100644 --- a/main/config_2G.h +++ b/main/config_2G.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This gateway enables to set your parameters for the 2G gateway @@ -26,10 +26,12 @@ #ifndef config_2G_h #define config_2G_h +#include "TheengsCommon.h" + extern void setup2G(); -extern bool _2GtoMQTT(); -extern void MQTTto2G(char* topicOri, char* datacallback); -extern void MQTTto2G(char* topicOri, JsonObject& SMSdata); +extern bool _2GtoX(); +extern void Xto2G(const char* topicOri, const char* datacallback); +extern void Xto2G(const char* topicOri, JsonObject& SMSdata); /*-------------------2G topics & parameters----------------------*/ //433Mhz MQTT Subjects and keys #define subjectMQTTto2G "/commands/MQTTto2G" diff --git a/main/config_ADC.h b/main/config_ADC.h index 393f923..e5188ef 100644 --- a/main/config_ADC.h +++ b/main/config_ADC.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the ADC value @@ -27,7 +27,7 @@ #define config_ADC_h extern void setupADC(); -extern void ADCtoMQTT(); +extern void ADCtoX(); extern void MeasureADC(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ diff --git a/main/config_AHTx0.h b/main/config_AHTx0.h index dba5959..757c990 100644 --- a/main/config_AHTx0.h +++ b/main/config_AHTx0.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This is the Climate Addon: @@ -13,12 +13,12 @@ Connection Schemata: -------------------- - AHT10 ------> Arduino Uno ----------> ESP8266 - ============================================== - Vcc ---------> 5V -------------------> 3v3 (3V) - GND ---------> GND ------------------> GND - SCL ---------> Pin A5 ---------------> D1 - SDA ---------> Pin A4 ---------------> D2 + AHT10 ------> ESP8266 + ======================= + Vcc ---------> 3v3 (3V) + GND ---------> GND + SCL ---------> D1 + SDA ---------> D2 This file is part of OpenMQTTGateway. diff --git a/main/config_BH1750.h b/main/config_BH1750.h index e1f29b6..f254012 100644 --- a/main/config_BH1750.h +++ b/main/config_BH1750.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the BH1750 sensor @@ -26,13 +26,13 @@ Connection Schemata: -------------------- - BH1750 ------> Arduino Uno ----------> ESP8266 - ============================================== - Vcc ---------> 5V -------------------> Vu (5V) - GND ---------> GND ------------------> GND - SCL ---------> Pin A5 ---------------> D1 - SDA ---------> Pin A4 ---------------> D2 - ADD ---------> N/C (Not Connected) --> N/C (Not Connected) + BH1750 ------> ESP8266 + ================================== + Vcc ---------> (5V) + GND ---------> GND + SCL ---------> D1 + SDA ---------> D2 + ADD ---------> N/C (Not Connected) */ #ifndef config_BH1750_h @@ -47,8 +47,7 @@ extern void MeasureLightIntensity(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ #define subjectBH1750toMQTT "/BH1750toMQTT" -//Time used to wait for an interval before resending measured values -unsigned long timebh1750 = 0; -int BH1750_i2c_addr = 0x23; // Light Sensor I2C Address + +#define BH1750_I2C_ADDR 0x23; // Light Sensor I2C Address #endif diff --git a/main/config_BME280.h b/main/config_BME280.h index 3ea6241..b4404f1 100644 --- a/main/config_BME280.h +++ b/main/config_BME280.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables you to set parameters for the BME280 or BMP280 sensors. @@ -26,12 +26,12 @@ Connection Schemata: -------------------- - BME280/BMP280 ------> Arduino Uno ----------> ESP8266 - ===================================================== - Vcc ----------------> 5V/3.3V ----------> 5V/3.3V (5V or 3.3V depends on the BME280/BMP280 board variant) - GND ----------------> GND ----------> GND - SCL ----------------> Pin A5 ----------> D1 - SDA ----------------> Pin A4 ----------> D2 + BME280/BMP280 ------> ESP8266 + ============================== + Vcc ----------------> 5V/3.3V (5V or 3.3V depends on the BME280/BMP280 board variant) + GND ----------------> GND + SCL ----------------> D1 + SDA ----------------> D2 */ #ifndef config_BME280_h @@ -53,9 +53,7 @@ extern void MeasureTempHumAndPressure(); # define BMETOPIC "/CLIMAtoMQTT/bme" #endif -//Time used to wait for an interval before resending measured values -unsigned long timebme280 = 0; -int BME280_i2c_addr = 0x76; // Bosch BME280 I2C Address +#define BME280_I2C_ADDR 0x76 // Only supported for ESP #ifndef BME280_PIN_SDA diff --git a/main/config_BT.h b/main/config_BT.h index a116701..869904a 100644 --- a/main/config_BT.h +++ b/main/config_BT.h @@ -1,15 +1,15 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation +/* + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT - + This files enables to set your parameter for the bluetooth low energy gateway (beacons detection) - + Copyright: (c)Florian ROBERT - + This file is part of OpenMQTTGateway. - + OpenMQTTGateway 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 @@ -26,13 +26,12 @@ #ifndef config_BT_h #define config_BT_h +#include "TheengsCommon.h" + extern void setupBT(); -extern bool BTtoMQTT(); -extern void MQTTtoBT(char* topicOri, JsonObject& RFdata); -extern void pubMainCore(JsonObject& data); +extern void XtoBT(const char* topicOri, JsonObject& RFdata); extern void launchBTDiscovery(bool overrideDiscovery); -extern void stopProcessing(); -extern void lowPowerESP32(); +extern void stopProcessing(bool deinit); extern String stateBTMeasures(bool); #ifdef ESP32 @@ -43,6 +42,7 @@ extern String stateBTMeasures(bool); #define subjectBTtoMQTT "/BTtoMQTT" #define subjectMQTTtoBTset "/commands/MQTTtoBT/config" #define subjectMQTTtoBT "/commands/MQTTtoBT" +#define subjectTrackerSync "internal/trackersync" // Uncomment to send undecoded device data to another gateway device for decoding // #define MQTTDecodeTopic "undecoded" #ifndef UseExtDecoder @@ -64,7 +64,9 @@ extern String stateBTMeasures(bool); # define BLE_FILTER_CONNECTABLE 0 // Sets whether to filter publishing of scanned devices that require a connection. #endif // Setting this to 1 prevents overwriting the publication of the device connection data with the advertised data (Recommended for use with OpenHAB). -#define MinimumRSSI -100 //default minimum rssi value, all the devices below -100 will not be reported +#ifndef MinimumRSSI +# define MinimumRSSI -100 //default minimum rssi value, all the devices below -100 will not be reported +#endif #ifndef Scan_duration # define Scan_duration 10000 //define the duration for a scan; in milliseconds @@ -98,7 +100,10 @@ extern String stateBTMeasures(bool); #endif #ifndef BLEScanDuplicateCacheSize -# define BLEScanDuplicateCacheSize 200 +# define BLEScanDuplicateCacheSize 100 +#endif +#ifndef MaxBLEDevices +# define MaxBLEDevices 80 #endif #ifndef TimeBtwRead # define TimeBtwRead 55555 //define default time between 2 scans; in milliseconds @@ -116,17 +121,25 @@ extern String stateBTMeasures(bool); # define HassPresence false //true if we publish into Home Assistant presence topic #endif -#define HMSerialSpeed 9600 // Communication speed with the HM module, softwareserial doesn't support 115200 -//#define HM_BLUE_LED_STOP true //uncomment to stop the blue led light of HM1X +#ifndef EnableBT +# define EnableBT true +#endif -#define BLEdelimiter "4f4b2b444953413a" // OK+DISA: -#define BLEEndOfDiscovery "4f4b2b4449534345" // OK+DISCE -#define BLEdelimiterLength 16 -#define CRLR "0d0a" -#define CRLR_Length 4 -#define BLE_CNCT_TIMEOUT 3000 +#ifndef BLEDecoder +# define BLEDecoder true //true if we use the Theengs decoder +#endif -unsigned long scanCount = 0; +#if !BLEDecoder +# define UNKWNON_MODEL -1 +#else +# define UNKWNON_MODEL TheengsDecoder::BLE_ID_NUM::UNKNOWN_MODEL +#endif + +#ifndef BLE_CNCT_TIMEOUT +# define BLE_CNCT_TIMEOUT 3000 +#endif + +extern unsigned long scanCount; #ifndef pubBLEAdvData # define pubBLEAdvData false // define true if you want to publish all advertisement data @@ -136,6 +149,10 @@ unsigned long scanCount = 0; # define useBeaconUuidForTopic false // define true to use iBeacon UUID as topic, instead of sender (random) MAC address #endif +#ifndef enableMultiGTWSync +# define enableMultiGTWSync true // //define true to use tracker and closest control devices sync across OpenMQTTGateway and Theengs Gateway gateways +#endif + /*--------------HOME ASSISTANT ROOM PRESENCE--------------*/ #define subjectHomePresence "presence/" // will send Home Assistant room presence message to this topic (first part is same for all rooms, second is room name) @@ -196,9 +213,8 @@ enum ble_val_type { }; struct BLEAction { - std::string value; - char addr[18]; - int addr_type; + NimBLEAttValue value; + NimBLEAddress addr; NimBLEUUID service; NimBLEUUID characteristic; bool write; @@ -210,6 +226,7 @@ struct BLEAction { struct BLEdevice { char macAdr[18]; + char name[20]; int macType; bool isDisc; bool isWhtL; diff --git a/main/config_C37_YL83_HMRD.h b/main/config_C37_YL83_HMRD.h index 018f02a..5ffc48c 100644 --- a/main/config_C37_YL83_HMRD.h +++ b/main/config_C37_YL83_HMRD.h @@ -1,5 +1,5 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface Act as a wifi or ethernet gateway between your RF/infrared IR signal and a MQTT broker Send and receiving command by MQTT @@ -25,7 +25,7 @@ #define config_C37_YL83_HMRD_h extern void setupZsensorC37_YL83_HMRD(); -extern void C37_YL83_HMRDtoMQTT(); +extern void C37_YL83_HMRDtoX(); extern void MeasureC37_YL83_HMRDWater(); /*----------------------------USER PARAMETERS-----------------------------*/ diff --git a/main/config_DHT.h b/main/config_DHT.h index 89f4c8c..01d5cdd 100644 --- a/main/config_DHT.h +++ b/main/config_DHT.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the DHT11/22 sensor diff --git a/main/config_DS1820.h b/main/config_DS1820.h index dfba98a..2e4581c 100644 --- a/main/config_DS1820.h +++ b/main/config_DS1820.h @@ -1,5 +1,5 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface Act as a wifi or ethernet gateway between your RF/infrared IR signal and a MQTT broker Send and receiving command by MQTT @@ -27,7 +27,7 @@ #define config_DS1820_h extern void setupZsensorDS1820(); -extern void DS1820toMQTT(); +extern void DS1820toX(); extern void MeasureDS1820Temp(); extern void pubOneWire_HADiscovery(); diff --git a/main/config_FASTLED.h b/main/config_FASTLED.h index 545ba28..a49db0e 100644 --- a/main/config_FASTLED.h +++ b/main/config_FASTLED.h @@ -1,5 +1,5 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface This files enables you to set your parameters for the FASTLED actuator @@ -24,10 +24,12 @@ #ifndef config_FASTLED_h #define config_FASTLED_h +#include "TheengsCommon.h" + extern void setupFASTLED(); extern void FASTLEDLoop(); -extern void MQTTtoFASTLED(char*, char*); -extern void MQTTtoFASTLED(char*, JsonObject&); +extern void XtoFASTLED(const char*, const char*); +extern void XtoFASTLED(const char*, JsonObject&); /*-------------------FASTLED topics & parameters----------------------*/ //FASTLED MQTT Subjects #define subjectMQTTtoFASTLED "/commands/MQTTtoFASTLED" @@ -82,7 +84,7 @@ extern void MQTTtoFASTLED(char*, JsonObject&); # define FASTLED_ESP8266_D1_GPIO_ORDER # define FASTLED_DATA_GPIO D2 // only D2 works by me //#define FASTLED_CLOCK_GPIO 13 -#elif ESP32 +#elif defined(ESP32) # ifndef FASTLED_DATA_GPIO # define FASTLED_DATA_GPIO 16 # endif diff --git a/main/config_GFSunInverter.h b/main/config_GFSunInverter.h index 7cc1643..58f254c 100644 --- a/main/config_GFSunInverter.h +++ b/main/config_GFSunInverter.h @@ -1,5 +1,5 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface Act as a wifi or ethernet gateway between your GridFree SUN-2000G inverter and a MQTT broker. Send inverter metrics by MQTT. @@ -27,10 +27,6 @@ #ifndef config_GFSunInverter_h #define config_GFSunInverter_h -#include -#include -#include - extern void setupGFSunInverter(); extern void ZgatewayGFSunInverterMQTT(); diff --git a/main/config_GPIOInput.h b/main/config_GPIOInput.h index 5c9a34a..5f3215a 100644 --- a/main/config_GPIOInput.h +++ b/main/config_GPIOInput.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the GPIOInput sensor @@ -27,7 +27,7 @@ #define config_GPIOInput_h extern void setupGPIOInput(); -extern void GPIOInputtoMQTT(); +extern void GPIOInputtoX(); extern void MeasureGPIOInput(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ diff --git a/main/config_GPIOKeyCode.h b/main/config_GPIOKeyCode.h index 9896ccc..8072667 100644 --- a/main/config_GPIOKeyCode.h +++ b/main/config_GPIOKeyCode.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the GPIOKeyCode multi input @@ -27,7 +27,7 @@ #define config_GPIOKeyCode_h extern void setupGPIOKeyCode(); -extern void GPIOKeyCodetoMQTT(); +extern void GPIOKeyCodetoX(); extern void MeasureGPIOKeyCode(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ diff --git a/main/config_HCSR04.h b/main/config_HCSR04.h index 7312dff..3404a0f 100644 --- a/main/config_HCSR04.h +++ b/main/config_HCSR04.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the HCSR04 sensor @@ -26,12 +26,12 @@ Connection Schemata: -------------------- - HC-SR04 ------> Arduino Uno ----------> ESP8266 - ============================================== - Vcc ---------> 5V -------------------> Vu (5V) - GND ---------> GND ------------------> GND - TRI ---------> Pin D6 ---------------> D6 - ECH ---------> Pin D7 ---------------> D7 + HC-SR04 ------> ESP8266 + ======================= + Vcc ---------> Vu (5V) + GND ---------> GND + TRI ---------> D6 + ECH ---------> D7 */ #ifndef config_HCSR04_h diff --git a/main/config_HCSR501.h b/main/config_HCSR501.h index 1482f76..b296fae 100644 --- a/main/config_HCSR501.h +++ b/main/config_HCSR501.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the HC SR-501 sensor @@ -27,7 +27,7 @@ #define config_HCSR501_h extern void setupHCSR501(); -extern void HCSR501toMQTT(); +extern void HCSR501toX(); extern void MeasureHCSR501(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ diff --git a/main/config_HTU21.h b/main/config_HTU21.h index 7efc31b..202321d 100644 --- a/main/config_HTU21.h +++ b/main/config_HTU21.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This is the Climate Addon: @@ -13,12 +13,12 @@ Connection Schemata: -------------------- - HTU21 ------> Arduino Uno ----------> ESP8266 - ============================================== - Vcc ---------> 5V -------------------> Vu (5V) - GND ---------> GND ------------------> GND - SCL ---------> Pin A5 ---------------> D1 - SDA ---------> Pin A4 ---------------> D2 + HTU21 ------> ESP8266 + ====================== + Vcc ---------> Vu (5V) + GND ---------> GND + SCL ---------> D1 + SDA ---------> D2 This file is part of OpenMQTTGateway. diff --git a/main/config_INA226.h b/main/config_INA226.h index ebc37f2..8114586 100644 --- a/main/config_INA226.h +++ b/main/config_INA226.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the INA226 sensor @@ -27,7 +27,7 @@ #define config_INA226_h extern void setupINA226(); -extern void INA226toMQTT(); +extern void INA226toX(); extern void MeasureINA226(); /*----------------------------USER PARAMETERS-----------------------------*/ diff --git a/main/config_IR.h b/main/config_IR.h index f646c2c..2338043 100644 --- a/main/config_IR.h +++ b/main/config_IR.h @@ -1,7 +1,7 @@ /* OpenMQTTGateway - ESP8266 or Arduino program for home automation - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the infrared gateway @@ -26,10 +26,12 @@ #ifndef config_IR_h #define config_IR_h +#include "TheengsCommon.h" + extern void setupIR(); -extern void IRtoMQTT(); -extern void MQTTtoIR(char* topicOri, char* datacallback); -extern void MQTTtoIR(char* topicOri, JsonObject& RFdata); +extern void IRtoX(); +extern void XtoIR(const char* topicOri, const char* datacallback); +extern void XtoIR(const char* topicOri, JsonObject& RFdata); /*-------------------IR topics & parameters----------------------*/ //IR MQTT Subjects #define subjectGTWIRtoMQTT "/IRtoMQTT" @@ -159,17 +161,6 @@ extern void MQTTtoIR(char* topicOri, JsonObject& RFdata); # define IR_COOLIX48 # define IR_HITACHI_AC264 # define IR_HITACHI_AC296 -#elif __AVR_ATmega2560__ -# define IR_COOLIX -# define IR_Whynter -# define IR_LG -# define IR_Sony -# define IR_DISH -# define IR_RC5 -# define IR_Sharp -# define IR_SAMSUNG -# define IR_Raw -# define IR_PANASONIC #else //IR supported protocols on arduino uncomment if you want to send with this protocol, NEC protocol is available per default //#define IR_COOLIX //#define IR_Whynter @@ -193,24 +184,16 @@ extern void MQTTtoIR(char* topicOri, JsonObject& RFdata); #ifndef IR_RECEIVER_GPIO # ifdef ESP8266 # define IR_RECEIVER_GPIO 2 //D4 /replace by 4 with sonoff rf bridge -# elif ESP32 +# elif defined(ESP32) # define IR_RECEIVER_GPIO 26 -# elif __AVR_ATmega2560__ -# define IR_RECEIVER_GPIO 2 // 2 = D2 on arduino mega -# else -# define IR_RECEIVER_GPIO 0 // 0 = D2 on arduino UNO # endif #endif #ifndef IR_EMITTER_GPIO # ifdef ESP8266 # define IR_EMITTER_GPIO 16 //D0/ replace by 0 (D3) if you use IR LOLIN controller shield /replace by 5 with sonoff rf bridge -# elif ESP32 +# elif defined(ESP32) # define IR_EMITTER_GPIO 14 -# elif __AVR_ATmega2560__ -# define IR_EMITTER_GPIO 9 -# else -# define IR_EMITTER_GPIO 9 # endif #endif diff --git a/main/config_LM75.h b/main/config_LM75.h index 9b42cb9..5f0b7ea 100644 --- a/main/config_LM75.h +++ b/main/config_LM75.h @@ -1,7 +1,7 @@ /* OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This is a Temperature Addon: @@ -13,12 +13,12 @@ Connection Schemata: -------------------- - LM75 ------> Arduino Uno ----------> ESP8266 - ============================================== - Vcc ---------> 5V -------------------> Vu (5V) - GND ---------> GND ------------------> GND - SCL ---------> Pin A5 ---------------> D1 - SDA ---------> Pin A4 ---------------> D2 + LM75 ------> ESP8266 + ====================== + Vcc ---------> Vu (5V) + GND ---------> GND + SCL ---------> D1 + SDA ---------> D2 This file is part of OpenMQTTGateway. @@ -39,7 +39,7 @@ #define config_LM75_h extern void setupLM75(); -extern void LM75toMQTT(); +extern void LM75toX(); #define lm75_always true // if false when the current value of the parameter is the same as previous one don't send it by MQTT #define TimeBetweenReadinglm75 30000 diff --git a/main/config_LORA.h b/main/config_LORA.h index 2db7f66..6e8ffac 100644 --- a/main/config_LORA.h +++ b/main/config_LORA.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the LORA gateway @@ -26,10 +26,12 @@ #ifndef config_LORA_h #define config_LORA_h +#include "TheengsCommon.h" + extern void setupLORA(); -extern void LORAtoMQTT(); -extern void MQTTtoLORA(char* topicOri, char* datacallback); -extern void MQTTtoLORA(char* topicOri, JsonObject& RFdata); +extern void LORAtoX(); +extern void XtoLORA(const char* topicOri, const char* datacallback); +extern void XtoLORA(const char* topicOri, JsonObject& RFdata); /*----------------------LORA topics & parameters-------------------------*/ #define subjectLORAtoMQTT "/LORAtoMQTT" #define subjectMQTTtoLORA "/commands/MQTTtoLORA" @@ -112,6 +114,7 @@ struct LORAConfig_s { }; #ifdef ZmqttDiscovery +# include "config_mqttDiscovery.h" extern void launchLORADiscovery(bool overrideDiscovery); // This structure stores the entities of the devices and is they have been discovered or not // The uniqueId is composed of the device id + the key @@ -125,11 +128,13 @@ struct LORAdevice { bool isDisc; }; -const char LORAparameters[3][4][12] = { +const char LORAparameters[5][4][12] = { // LORA key, name, unit, device_class - {"tempc", "temperature", "°C", "temperature"}, - {"hum", "humidity", "%", "humidity"}, - {"moi", "moisture", "%", "humidity"}}; + {"tempc", HASS_CLASS_TEMPERATURE, HASS_UNIT_CELSIUS, HASS_CLASS_TEMPERATURE}, + {"hum", HASS_CLASS_HUMIDITY, HASS_UNIT_PERCENT, HASS_CLASS_HUMIDITY}, + {"moi", "moisture", HASS_UNIT_PERCENT, HASS_CLASS_HUMIDITY}, + {"batt", HASS_CLASS_BATTERY, HASS_UNIT_PERCENT, HASS_CLASS_BATTERY}, + {"count", HASS_CLASS_WATER, HASS_UNIT_LITER, HASS_CLASS_WATER}}; #endif diff --git a/main/config_M5.h b/main/config_M5.h index 47f7e40..bf41fc4 100644 --- a/main/config_M5.h +++ b/main/config_M5.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to use M5Stick C board components (display) @@ -26,18 +26,12 @@ #ifndef config_M5_h #define config_M5_h -#ifdef ZboardM5STICKC -# include -#endif -#ifdef ZboardM5STICKCP -# include -#endif -#ifdef ZboardM5STACK -# include -#endif -#ifdef ZboardM5TOUGH -# include -#endif +// All M5 boards (Core / Stick C / Stick C Plus / Tough) are driven through the +// unified M5Unified + M5GFX libraries, which build on the modern Arduino core +// and auto-detect the board at runtime. This replaces the per-board libraries +// (M5Stack / M5StickC / M5StickC-Plus / M5Tough) that were pinned to Arduino +// core 2.x (espressif32@6.1.0) because they don't compile on core 3.x. +#include extern void setupM5(); extern void loopM5(); @@ -74,7 +68,7 @@ extern void loopM5(); // Simple construct for displaying message in lcd and oled displays #define displayPrint(...) \ - if (lowpowermode < 2) M5Print(__VA_ARGS__) // only print if not in low power mode + if (SYSConfig.powerMode < 1) M5Print(__VA_ARGS__) // only print if not in low power mode #define lpDisplayPrint(...) M5Print(__VA_ARGS__) // print in low power mode void M5Print(char*, char* = "", char* = ""); diff --git a/main/config_MQ2.h b/main/config_MQ2.h index b553318..9b8908a 100644 --- a/main/config_MQ2.h +++ b/main/config_MQ2.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This is the MQ2 GAS Sensor Addon based on modules with a MQ: @@ -11,12 +11,12 @@ Connection Scheme: -------------------- - MQ-2 -------> Arduino Uno ----------> ESP8266 - ============================================== - Vcc ---------> 3.3V or 5V------------> 3.3V or 5V - GND ---------> GND ------------------> GND - A0 ----------> Pin A0 ---------------> A0 - D0 ----------> Pin D4 ---------------> D4 + MQ-2 -------> ESP8266 + ========================== + Vcc ---------> 3.3V or 5V + GND ---------> GND + A0 ----------> A0 + D0 ----------> D4 This file is part of OpenMQTTGateway. @@ -37,7 +37,7 @@ #define config_MQ2_h extern void setupZsensorMQ2(); -extern void MQ2toMQTT(); +extern void MQ2toX(); #ifndef MQ2SENSORADCPIN # ifdef ESP32 @@ -62,7 +62,4 @@ extern void MQ2toMQTT(); /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ #define subjectMQ2toMQTT "/GAStoMQTT/mq2" -//Time used to wait for an interval before resending measured values -unsigned long timemq2 = 0; - #endif \ No newline at end of file diff --git a/main/config_ONOFF.h b/main/config_ONOFF.h index 4300569..406154a 100644 --- a/main/config_ONOFF.h +++ b/main/config_ONOFF.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the ON OFF actuator @@ -26,9 +26,11 @@ #ifndef config_ONOFF_h #define config_ONOFF_h +#include "TheengsCommon.h" + extern void setupONOFF(); -extern void MQTTtoONOFF(char* topicOri, char* datacallback); -extern void MQTTtoONOFF(char* topicOri, JsonObject& RFdata); +extern void XtoONOFF(const char* topicOri, const char* datacallback); +extern void XtoONOFF(const char* topicOri, JsonObject& RFdata); extern void stateONOFFMeasures(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ @@ -70,7 +72,7 @@ extern void stateONOFFMeasures(); #ifndef ACTUATOR_ONOFF_GPIO # ifdef ESP8266 # define ACTUATOR_ONOFF_GPIO 15 //12 for sonoff basic relay -# elif ESP32 +# elif defined(ESP32) # define ACTUATOR_ONOFF_GPIO 15 # else # define ACTUATOR_ONOFF_GPIO 13 diff --git a/main/config_PWM.h b/main/config_PWM.h index c5a6122..bdb56a9 100644 --- a/main/config_PWM.h +++ b/main/config_PWM.h @@ -1,5 +1,5 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface This files enables you to set your parameters for the PWM actuator @@ -22,12 +22,15 @@ */ /*-------------------PWM topics & parameters----------------------*/ +#ifndef config_PWM_h +#define config_PWM_h +#include "TheengsCommon.h" // PWM MQTT Subjects extern void setupPWM(); extern void PWMLoop(); -extern void MQTTtoPWM(char*, JsonObject&); +extern void XtoPWM(const char*, JsonObject&); #define subjectMQTTtoPWM "/commands/MQTTtoPWM" #define subjectMQTTtoPWMset subjectMQTTtoPWM "/set" //set channel(s) with JSON struct {"r":0-1,"g":0-1,"b":0-1,"w0":0-1,"w0":0-1,"fade":} @@ -55,3 +58,5 @@ extern void MQTTtoPWM(char*, JsonObject&); #ifndef PWM_DEFAULT_GAMMA # define PWM_DEFAULT_GAMMA 2.2f #endif + +#endif // config_PWM_h diff --git a/main/config_RF.h b/main/config_RF.h index 6c41275..9de6b3d 100644 --- a/main/config_RF.h +++ b/main/config_RF.h @@ -1,15 +1,15 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation +/* + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT - + This files enables to set your parameter for the radiofrequency gateways (ZgatewayRF and ZgatewayRF2) with RCswitch and newremoteswitch library - + Copyright: (c)Florian ROBERT - + This file is part of OpenMQTTGateway. - + OpenMQTTGateway 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 @@ -25,36 +25,31 @@ */ #ifndef config_RF_h #define config_RF_h +#pragma once -#include -#include +#include #ifdef ZgatewayRF -extern void setupRF(); -extern void RFtoMQTT(); -extern void MQTTtoRF(char* topicOri, char* datacallback); -extern void MQTTtoRF(char* topicOri, JsonObject& RFdata); +extern void RFtoX(); +extern void XtoRF(const char* topicOri, const char* datacallback); +extern void XtoRF(const char* topicOri, JsonObject& RFdata); extern void disableRFReceive(); -extern void enableRFReceive(); +extern void enableRFReceive(float rfFrequency, int rfReceiverGPIO, int rfEmitterGPIO); #endif #ifdef ZgatewayRF2 -extern void RF2toMQTT(); -extern void MQTTtoRF2(char* topicOri, char* datacallback); -extern void MQTTtoRF2(char* topicOri, JsonObject& RFdata); +extern void RF2toX(); +extern void XtoRF2(const char* topicOri, const char* datacallback); +extern void XtoRF2(const char* topicOri, JsonObject& RFdata); extern void disableRF2Receive(); extern void enableRF2Receive(); #endif #ifdef ZgatewayPilight extern void setupPilight(); -extern void PilighttoMQTT(); -extern void MQTTtoPilight(char* topicOri, char* datacallback); -extern void MQTTtoPilight(char* topicOri, JsonObject& RFdata); +extern void PilighttoX(); extern void disablePilightReceive(); extern void enablePilightReceive(); #endif #ifdef ZgatewayRTL_433 -# include -rtl_433_ESP rtl_433; extern void RTL_433Loop(); extern void setupRTL_433(); @@ -73,98 +68,118 @@ extern void launchRTL_433Discovery(bool overrideDiscovery); # define uniqueIdSize 60 // longest model + longest key # define modelNameSize 31 // longest model +# define typeSize 10 // longest type struct RTL_433device { char uniqueId[uniqueIdSize]; char modelName[modelNameSize]; + char type[typeSize]; bool isDisc; }; -const char parameters[40][4][24] = { +const char parameters[51][4][24] = { // RTL_433 key, name, unit, device_class - {"temperature_C", "temperature", "°C", "temperature"}, - {"temperature_1_C", "temperature", "°C", "temperature"}, - {"temperature_2_C", "temperature", "°C", "temperature"}, - {"temperature_F", "temperature", "°F", "temperature"}, - {"time", "timestamp", "", "timestamp"}, - {"battery_ok", "battery", "%", "battery"}, - {"humidity", "humidity", "%", "humidity"}, - {"moisture", "moisture", "%", "humidity"}, - {"pressure_hPa", "pressure", "hPa", "pressure"}, - {"pressure_kPa", "pressure", "kPa", "pressure"}, - {"wind_speed_km_h", "wind speed", "km/h", "wind_speed"}, - {"wind_avg_km_h", "wind average", "km/h", "wind_speed"}, - {"wind_avg_mi_h", "wind average", "mi/h", "wind_speed"}, - {"wind_avg_m_s", "wind average", "m/s", "wind_speed"}, - {"wind_speed_m_s", "wind speed", "m/s", "wind_speed"}, - {"gust_speed_km_h", "gust speed", "km/h", "wind_speed"}, - {"wind_max_km_h", "wind max", "km/h", "wind_speed"}, - {"wind_max_m_s", "wind max", "m/s", "wind_speed"}, - {"gust_speed_m_s", "gust speed", "m/s", "wind_speed"}, - {"wind_dir_deg", "wind direction", "°", ""}, - {"rain_mm", "rain", "mm", "precipitation"}, - {"rain_rate_mm_h", "rain", "mm/h", "precipitation_intensity"}, - {"rain_in", "rain", "in", "precipitation"}, - {"rain_rate_in_h", "rain", "in/h", "precipitation_intensity"}, - {"rssi", "rssi", "dB", "signal_strength"}, - {"snr", "snr", "dB", ""}, - {"noise", "noise", "dB", ""}, - {"depth_cm", "depth", "cm", ""}, - {"power_W", "power", "W", "power"}, - {"light_lux", "light", "lx", ""}, - {"lux", "lux", "lx", ""}, - {"uv", "uv", "UV index", ""}, - {"uvi", "uvi", "UV index", ""}, - {"storm_dist", "storm distance", "mi", ""}, - {"strike_distance", "strike distance", "mi", ""}, - {"tamper", "tamper", "", ""}, - {"alarm", "alarm", "", ""}, - {"motion", "motion", "", "motion"}, - {"strike_count", "strike count", "", ""}, // from rtl_433_mqtt_hass.py - {"event", "Status", "", "moisture"}}; + {"alarm", "Alarm", "", ""}, + {"battery_mV", "Battery Voltage", "mV", "voltage"}, + {"battery_ok", "Battery", "", "battery"}, + {"co2_ppm", "Carbon Dioxide", "ppm", "carbon_dioxide"}, + {"depth_cm", "Depth", "cm", "distance"}, + {"estimated_pm10_0_ug_m3", "Estimated PM10", "μg/m³", "pm10"}, + {"event", "Status", "", ""}, + {"group", "Group", "", ""}, + {"gust_speed_km_h", "Gust speed", "km/h", "wind_speed"}, + {"gust_speed_m_s", "Gust speed", "m/s", "wind_speed"}, + {"humidity", "Humidity", "%", "humidity"}, + {"light_lux", "Illuminance", "lx", "illuminance"}, + {"lux", "Illuminance", "lx", "illuminance"}, + {"moisture", "Moisture", "%", "humidity"}, + {"motion", "Motion", "", "motion"}, + {"noise", "Noise", "dB", "sound_pressure"}, + {"pm1_ug_m3", "PM1", "μg/m³", "pm1"}, + {"pm10_ug_m3", "PM10", "μg/m³", "pm10"}, + {"pm2_5_ug_m3", "PM2.5", "μg/m³", "pm25"}, + {"power_W", "Power", "W", "power"}, + {"pressure_hPa", "Pressure", "hPa", "pressure"}, + {"pressure_kPa", "Pressure", "kPa", "pressure"}, + {"rain_in", "Rain", "in", "precipitation"}, + {"rain_mm", "Rain", "mm", "precipitation"}, + {"rain_rate_in_h", "Rain", "in/h", "precipitation_intensity"}, + {"rain_rate_mm_h", "Rain", "mm/h", "precipitation_intensity"}, + {"rssi", "RSSI", "dB", "signal_strength"}, + {"snr", "SNR", "dB", ""}, + {"state", "State", "", ""}, + {"storm_dist_km", "Storm distance", "km", "distance"}, + {"storm_dist", "Storm distance", "mi", "distance"}, + {"strike_count", "Strike count", "", ""}, // from rtl_433_mqtt_hass.py + {"strike_distance_km", "Strike distance", "km", "distance"}, + {"strike_distance", "Strike distance", "mi", "distance"}, + {"tamper", "Tamper", "", ""}, + {"temperature_1_C", "Temperature", "°C", "temperature"}, + {"temperature_2_C", "Temperature", "°C", "temperature"}, + {"temperature_C", "Temperature", "°C", "temperature"}, + {"temperature_F", "Temperature", "°F", "temperature"}, + {"time", "Timestamp", "", "timestamp"}, + {"unit", "Unit", "", ""}, + {"uv", "UV value", "", ""}, + {"uvi", "UV index", "", ""}, + {"wind_avg_km_h", "Wind average", "km/h", "wind_speed"}, + {"wind_avg_m_s", "Wind average", "m/s", "wind_speed"}, + {"wind_avg_mi_h", "Wind average", "mi/h", "wind_speed"}, + {"wind_dir_deg", "Wind direction", "°", ""}, + {"wind_max_km_h", "Wind max", "km/h", "wind_speed"}, + {"wind_max_m_s", "Wind max", "m/s", "wind_speed"}, + {"wind_speed_km_h", "Wind speed", "km/h", "wind_speed"}, + {"wind_speed_m_s", "Wind speed", "m/s", "wind_speed"}}; # endif # ifdef RTL_433_DISCOVERY_LOGGING -# define DISCOVERY_TRACE_LOG(...) Log.trace(__VA_ARGS__) +# define DISCOVERY_TRACE_LOG(...) THEENGS_LOG_TRACE(__VA_ARGS__) # else # define DISCOVERY_TRACE_LOG(...) # endif #endif + +extern RFConfiguration iRFConfig; + /*-------------------RF topics & parameters----------------------*/ //433Mhz MQTT Subjects and keys -#define subjectMQTTtoRF "/commands/MQTTto433" -#define subjectRFtoMQTT "/433toMQTT" -#define subjectcommonRFtoMQTT "/RFtoMQTT" -#define subjectGTWRFtoMQTT "/433toMQTT" -#define RFprotocolKey "433_" // protocol will be defined if a subject contains RFprotocolKey followed by a value of 1 digit -#define RFbitsKey "RFBITS_" // bits will be defined if a subject contains RFbitsKey followed by a value of 2 digits -#define repeatRFwMQTT false // do we repeat a received signal by using MQTT with RF gateway -#define RFpulselengthKey "PLSL_" // pulselength will be defined if a subject contains RFprotocolKey followed by a value of 3 digits +#define subjectMQTTtoRF "/commands/MQTTto433" +#define subjectRFtoMQTT "/433toMQTT" +#define subjectRFtoMQTTvalueAsATopic "/433toMQTT/#" +#define subjectcommonRFtoMQTT "/RFtoMQTT" +#define subjectGTWRFtoMQTT "/433toMQTT" +#define RFprotocolKey "433_" // protocol will be defined if a subject contains RFprotocolKey followed by a value of 1 digit +#define RFbitsKey "RFBITS_" // bits will be defined if a subject contains RFbitsKey followed by a value of 2 digits +#define repeatRFwMQTT false // do we repeat a received signal by using MQTT with RF gateway +#define RFpulselengthKey "PLSL_" // pulselength will be defined if a subject contains RFprotocolKey followed by a value of 3 digits // subject monitored to listen traffic processed by other gateways to store data and avoid ntuple #define subjectMultiGTWRF "+/+/433toMQTT" //RF number of signal repetition - Can be overridden by specifying "repeat" in a JSON message. #define RF_EMITTER_REPEAT 20 #define RF2_EMITTER_REPEAT 2 // Actual repeats is 2^R, where R is the here configured amount //#define RF_DISABLE_TRANSMIT //Uncomment this line to disable RF transmissions. (RF Receive will work as normal.) -#define RFmqttDiscovery true //uncomment this line so as to create a discovery switch for each RF signal received +//#define RF_on_HAS_as_DeviceTrigger //uncomment this line so as to create a Home Assistant device trigger for each RF signal received +#define RF_on_HAS_as_MQTTSensor //uncomment this line so as to create a Home Assistant MQTT sensor for each RF signal received /*-------------------RF2 topics & parameters----------------------*/ //433Mhz newremoteswitch MQTT Subjects and keys -#define subjectMQTTtoRF2 "/commands/MQTTtoRF2" -#define subjectRF2toMQTT "/RF2toMQTT" -#define subjectGTWRF2toMQTT "/RF2toMQTT" -#define RF2codeKey "ADDRESS_" // code will be defined if a subject contains RF2codeKey followed by a value of 7 digits -#define RF2periodKey "PERIOD_" // period will be defined if a subject contains RF2periodKey followed by a value of 3 digits -#define RF2unitKey "UNIT_" // number of your unit value will be defined if a subject contains RF2unitKey followed by a value of 1-2 digits -#define RF2groupKey "GROUP_" // number of your group value will be defined if a subject contains RF2groupKey followed by a value of 1 digit -#define RF2dimKey "DIM" // number of your dim value will be defined if a subject contains RF2dimKey and the payload contains the dim value as digits +#define subjectMQTTtoRF2 "/commands/MQTTtoRF2" +#define subjectRF2toMQTT "/RF2toMQTT" +#define subjectRF2toMQTTvalueAsATopic "/RF2toMQTT/#" +#define subjectGTWRF2toMQTT "/RF2toMQTT" +#define RF2codeKey "ADDRESS_" // code will be defined if a subject contains RF2codeKey followed by a value of 7 digits +#define RF2periodKey "PERIOD_" // period will be defined if a subject contains RF2periodKey followed by a value of 3 digits +#define RF2unitKey "UNIT_" // number of your unit value will be defined if a subject contains RF2unitKey followed by a value of 1-2 digits +#define RF2groupKey "GROUP_" // number of your group value will be defined if a subject contains RF2groupKey followed by a value of 1 digit +#define RF2dimKey "DIM" // number of your dim value will be defined if a subject contains RF2dimKey and the payload contains the dim value as digits /*-------------------ESPPiLight topics & parameters----------------------*/ //433Mhz Pilight MQTT Subjects and keys -#define subjectMQTTtoPilight "/commands/MQTTtoPilight" -#define subjectMQTTtoPilightProtocol "/commands/MQTTtoPilight/protocols" -#define subjectPilighttoMQTT "/PilighttoMQTT" -#define subjectGTWPilighttoMQTT "/PilighttoMQTT" -#define repeatPilightwMQTT false // do we repeat a received signal by using MQTT with Pilight gateway +#define subjectMQTTtoPilight "/commands/MQTTtoPilight" +#define subjectMQTTtoPilightProtocol "/commands/MQTTtoPilight/protocols" +#define subjectPilighttoMQTT "/PilighttoMQTT" +#define subjectPilighttoMQTTvalueAsATopic "/PilighttoMQTT/#" +#define subjectGTWPilighttoMQTT "/PilighttoMQTT" +#define repeatPilightwMQTT false // do we repeat a received signal by using MQTT with Pilight gateway //#define Pilight_rawEnabled true // enables Pilight RAW return - switchable via MQTT /*-------------------RTL_433 topics & parameters----------------------*/ @@ -175,7 +190,7 @@ const char parameters[40][4][24] = { /*-------------------RF frequency----------------------*/ //Match frequency to the hardware version of the radio used. #ifndef RF_FREQUENCY -# define RF_FREQUENCY 433.92 +# define RF_FREQUENCY 433.92f #endif /** @@ -186,13 +201,6 @@ const char parameters[40][4][24] = { * 4 = ZgatewayRF2 */ -struct RFConfig_s { - float frequency; - int rssiThreshold; - int newOokThreshold; - int activeReceiver; -}; - #define ACTIVE_NONE -1 #define ACTIVE_RECERROR 0 #define ACTIVE_PILIGHT 1 @@ -200,7 +208,17 @@ struct RFConfig_s { #define ACTIVE_RTL 3 #define ACTIVE_RF2 4 -RFConfig_s RFConfig; +#ifdef ZgatewayRF +# define ACTIVE_RECEIVER ACTIVE_RF +#elif defined(ZgatewayRF2) +# define ACTIVE_RECEIVER ACTIVE_RF2 +#elif defined(ZgatewayPilight) +# define ACTIVE_RECEIVER ACTIVE_PILIGHT +#elif defined(ZgatewayRTL_433) +# define ACTIVE_RECEIVER ACTIVE_RTL +#else +# define ACTIVE_RECEIVER ACTIVE_NONE +#endif /*-------------------CC1101 DefaultTXPower----------------------*/ //Adjust the default TX-Power for sending radio if ZradioCC1101 is used. @@ -212,23 +230,17 @@ RFConfig_s RFConfig; /*-------------------PIN DEFINITIONS----------------------*/ #ifndef RF_RECEIVER_GPIO # ifdef ESP8266 -# define RF_RECEIVER_GPIO 0 // D3 on nodemcu // put 4 with rf bridge direct mod -# elif ESP32 +# define RF_RECEIVER_GPIO 4 // D2 on nodemcu, don't use 0 (D3): a receiver holding it low at reset forces the ESP8266 into flash mode +# elif defined(ESP32) # define RF_RECEIVER_GPIO 27 // D27 on DOIT ESP32 -# elif __AVR_ATmega2560__ -# define RF_RECEIVER_GPIO 1 //1 = D3 on mega -# else -# define RF_RECEIVER_GPIO 1 //1 = D3 on arduino # endif #endif #ifndef RF_EMITTER_GPIO # ifdef ESP8266 # define RF_EMITTER_GPIO 3 // RX on nodemcu if it doesn't work with 3, try with 4 (D2) // put 5 with rf bridge direct mod -# elif ESP32 +# elif defined(ESP32) # define RF_EMITTER_GPIO 12 // D12 on DOIT ESP32 -# elif __AVR_ATmega2560__ -# define RF_EMITTER_GPIO 4 # else //IMPORTANT NOTE: On arduino UNO connect IR emitter pin to D9 , comment #define IR_USE_TIMER2 and uncomment #define IR_USE_TIMER1 on library IRremote/boarddefs.h so as to free pin D3 for RF RECEIVER PIN //RF PIN definition diff --git a/main/config_RFM69.h b/main/config_RFM69.h index a8d7037..1ab570f 100644 --- a/main/config_RFM69.h +++ b/main/config_RFM69.h @@ -1,7 +1,7 @@ /* OpenMQTTGateway - ESP8266 or Arduino program for home automation - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the radiofrequency gateways (ZgatewayRF and ZgatewayRF2) with RCswitch and newremoteswitch library @@ -26,10 +26,12 @@ #ifndef config_RFM69_h #define config_RFM69_h +#include "TheengsCommon.h" + extern void setupRFM69(); -extern bool RFM69toMQTT(); -extern void MQTTtoRFM69(char* topicOri, char* datacallback); -extern void MQTTtoRFM69(char* topicOri, JsonObject& RFdata); +extern bool RFM69toX(); +extern void XtoRFM69(const char* topicOri, const char* datacallback); +extern void XtoRFM69(const char* topicOri, JsonObject& RFdata); /*----------------------RFM69 topics & parameters -------------------------*/ // Topic where the message from RFM69 will be published by the gateway, // appended with the nodeID of the sender @@ -43,12 +45,12 @@ extern void MQTTtoRFM69(char* topicOri, JsonObject& RFdata); #define defaultRFM69ReceiverId 99 // Default values -const char PROGMEM ENCRYPTKEY[] = "sampleEncryptKey"; -const char PROGMEM MDNS_NAME[] = "rfm69gw1"; -const char PROGMEM MQTT_BROKER[] = "raspi2"; -const char PROGMEM RFM69AP_NAME[] = "RFM69-AP"; -#define NETWORKID 200 //the same on all nodes that talk to each other -#define NODEID 10 +#define RFM69_ENCRYPTKEY "sampleEncryptKey"; +#define RFM69_MDNS_NAME "rfm69gw1"; +#define RFM69_MQTT_BROKER "raspi2"; +#define RFM69_RFM69AP_NAME "RFM69-AP"; +#define RFM69_NETWORKID 200 //the same on all nodes that talk to each other +#define RFM69_NODEID 10 //Match frequency to the hardware version of the radio #define FREQUENCY RF69_433MHZ diff --git a/main/config_RN8209.h b/main/config_RN8209.h index 744ce39..ca5c5b7 100644 --- a/main/config_RN8209.h +++ b/main/config_RN8209.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the RN8209 sensor @@ -27,7 +27,7 @@ #define config_RN8209_h extern void setupRN8209(); -extern void RN8209toMQTT(); +extern void RN8209toX(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ #define subjectRN8209toMQTT "/RN8209toMQTT" @@ -43,6 +43,10 @@ extern void RN8209toMQTT(); # define RN8209_EC 28250 #endif +#ifndef RN8209_TASK_STACK_SIZE_OVERRIDE +# define RN8209_TASK_STACK_SIZE_OVERRIDE 5500 +#endif + #ifndef TimeBetweenReadingRN8209 # define TimeBetweenReadingRN8209 500 // time between 2 RN8209 readings in ms #endif diff --git a/main/config_RS232.h b/main/config_RS232.h deleted file mode 100644 index a91cbe1..0000000 --- a/main/config_RS232.h +++ /dev/null @@ -1,152 +0,0 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation - - Act as a wifi or ethernet gateway between your RS232 device and a MQTT broker - Send and receiving command by MQTT - - This files enables to set your parameter for the RS232 gateway - - Copyright: (c)Florian ROBERT - - This file is part of OpenMQTTGateway. - - OpenMQTTGateway 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. - - OpenMQTTGateway 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 . -*/ -#ifndef config_RS232_h -#define config_RS232_h - -extern void setupRS232(); -extern void RS232toMQTT(); -extern void MQTTtoRS232(char* topicOri, JsonObject& RS232data); - -/*-------------------RS232 topics & parameters----------------------*/ - -// Settings RS232 to MQTT topic -#define subjectRS232toMQTT "/RS232toMQTT" - -// setting to specify mode used for sending MQTT messages: -// 0: RAW: all recieved input at RS232 interface is collected in single MQTT message -// defined by RS232toMQTTsubject -// -// 1: JSON: Assumes input at RS232 interface to be valid JSON. JSON keys are used to -// split the JSON data in separate MQTT sub-topics. This will be repeated for -// sub-keys up to the specified nesting level (RS232maxJSONlevel). -// -// EXAMPLE: "{temperature: {sens1: 22, sens2: 23}, humidity: {sens1: 80, sens2: 60}}" -// - with RS232maxJSONlevel=1: -// ./RS232toMQTT/temperature ==> "{sens1: 22, sens2: 23}" -// ./RS232toMQTT/humidity ==> "{sens1: 80, sens2: 60}" -// -// - with RS232maxJSONlevel=2 (or higher): -// ./RS232toMQTT/temperature/sens1 ==> 22 -// ./RS232toMQTT/temperature/sens2 ==> 23 -// ./RS232toMQTT/humidity/sens1 ==> 80 -// ./RS232toMQTT/humidity/sens2 ==> 60 -// -#ifndef RS232toMQTTmode -# define RS232toMQTTmode 0 -#endif - -// settings for RS232TopicMode 0 (RAW) -#define RS232InPost '\n' // Hacky way to get last character of postfix for incoming -#define MAX_INPUT 200 // how much serial data we expect - -// settings for RS232TopicMode 1 (JSON) -#define RS232maxJSONlevel 2 // Max nested level in which JSON keys are converted to seperate sub-topics -#define RS232JSONDocSize 1024 // bytes to reserve for the JSON doc - -// settings for MQTT to RS232 -#define subjectMQTTtoRS232 "/commands/MQTTtoRS232" -#define RS232Pre "00" // The prefix for the RS232 message -#define RS232Post "\r" // The postfix for the RS232 message - -//Setup for RS232 -#ifndef RS232Baud -# define RS232Baud 9600 // The serial connection Baud -#endif - -/*-------------------PIN DEFINITIONS----------------------*/ -#ifndef RS232_UART -// set hardware serial UART to be used for device communication or -// use software emulaton if not defined -// -// VALUES: -// - not defined: use software emulation (pins set by RS232_RX_GPIO & RS232_TX_GPIO) -// -// - 0: use HW UART0 (serial), warning: default used for logging & usb -// ESP8266: (TX0 GPIO1, RX0 GPIO3) -// (TX0 GPIO15, RX0 GPIO13) with UART0 swap enabled -// ESP32: (TX0 by RS232_TX_GPIO, RX0 by RS232_RX_GPIO) -// ATmega2560: (TX0 pin1, RX0 pin0) -// Arduino Uno: (TX0 pin1, RX0 pin0) -// -// - 1: use HW UART1 (serial1) -// ESP8266: (TX1 GPIO2, RX none) only transmit available -// ESP32: (TX1 by RS232_TX_GPIO, RX1 by RS232_RX_GPIO) -// ATmega2560: (TX1 pin18, RX1 pin19) -// Arduino Uno: N/A -// -// - 2: use HW UART2 (serial2) -// ESP8266: N/A -// ESP32: (TX2 by RS232_TX_GPIO, RX2 by RS232_RX_GPIO) -// ATmega2560: (TX2 pin16, RX1 pin17) -// Arduino Uno: N/A -// -// - 3: use HW UART3 (serial3) -// ESP8266: N/A -// ESP32: N/A -// ATmega2560: (TX2 pin14, RX1 pin15) -// Arduino Uno: N/A -// -// defaults -# ifdef ESP32 -# define RS232_UART 1 // use HW UART ESP32 -# else -# undef RS232_UART // default use software serial -//# define RS232_UART 1 // define to use HW UART -# endif -#endif - -#ifndef RS232_UART0_SWAP -// option for ESP8266 only to swap UART0 ports from (GPIO1,GPIO3) to (GPIO15,GPIO13) -# define RS232_UART0_SWAP -#endif - -#ifndef RS232_RX_GPIO -// define receive pin (for software serial or ESP32 with configurable HW UART) -# if defined(ESP8266) && !defined(RS232_UART) -# define RS232_RX_GPIO 4 //D2 -# elif defined(ESP32) -# define RS232_RX_GPIO 26 -# elif defined(__AVR_ATmega2560__) && !defined(RS232_UART) -# define RS232_RX_GPIO 2 // 2 = D2 on arduino mega -# else -# define RS232_RX_GPIO 0 // 0 = D2 on arduino UNO -# endif -#endif - -#ifndef RS232_TX_GPIO -// define transmit pin (for software serial and/or ESP32) -# if defined(ESP8266) && !defined(RS232_UART) -# define RS232_TX_GPIO 2 //D4 -# elif ESP32 -# define RS232_TX_GPIO 14 -# elif defined(__AVR_ATmega2560__) && !defined(RS232_UART) -# define RS232_TX_GPIO 9 -# else -# define RS232_TX_GPIO 9 -# endif -#endif - -#endif \ No newline at end of file diff --git a/main/config_SERIAL.h b/main/config_SERIAL.h new file mode 100644 index 0000000..00cf5d1 --- /dev/null +++ b/main/config_SERIAL.h @@ -0,0 +1,145 @@ +/* + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface + + Act as a wifi or ethernet gateway between your SERIAL device and a MQTT broker + Send and receiving command by MQTT + + This files enables to set your parameter for the SERIAL gateway + + Copyright: (c)Florian ROBERT + + This file is part of OpenMQTTGateway. + + OpenMQTTGateway 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. + + OpenMQTTGateway 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 . +*/ +#ifndef config_SERIAL_h +#define config_SERIAL_h + +#include "TheengsCommon.h" + +extern void setupSERIAL(); +extern void SERIALtoX(); +extern bool XtoSERIAL(const char* topicOri, JsonObject& SERIALdata); + +/*-------------------SERIAL topics & parameters----------------------*/ + +// Settings SERIAL to MQTT topic +#define subjectSERIALtoMQTT "/SERIALtoMQTT" + +// setting to specify mode used for sending MQTT messages: +// 0: RAW: all recieved input at SERIAL interface is collected in single MQTT message +// defined by SERIALtoMQTTsubject +// +// 1: JSON: Assumes input at SERIAL interface to be valid JSON. JSON keys are used to +// split the JSON data in separate MQTT sub-topics. This will be repeated for +// sub-keys up to the specified nesting level (SERIALmaxJSONlevel). +// +// EXAMPLE: "{temperature: {sens1: 22, sens2: 23}, humidity: {sens1: 80, sens2: 60}}" +// - with SERIALmaxJSONlevel=1: +// ./SERIALtoMQTT/temperature ==> "{sens1: 22, sens2: 23}" +// ./SERIALtoMQTT/humidity ==> "{sens1: 80, sens2: 60}" +// +// - with SERIALmaxJSONlevel=2 (or higher): +// ./SERIALtoMQTT/temperature/sens1 ==> 22 +// ./SERIALtoMQTT/temperature/sens2 ==> 23 +// ./SERIALtoMQTT/humidity/sens1 ==> 80 +// ./SERIALtoMQTT/humidity/sens2 ==> 60 +// +#ifndef SERIALtoMQTTmode +# define SERIALtoMQTTmode 0 +#endif + +// settings for SERIALTopicMode 0 (RAW) +#define SERIALInPost '\n' // Hacky way to get last character of postfix for incoming +#define MAX_INPUT JSON_MSG_BUFFER // how much serial data we expect + +// settings for SERIALTopicMode 1 (JSON) +#define SERIALmaxJSONlevel 2 // Max nested level in which JSON keys are converted to seperate sub-topics + +// settings for MQTT to SERIAL +#define subjectMQTTtoSERIAL "/commands/MQTTtoSERIAL" +#ifndef SERIALPre +# define SERIALPre "00" // The prefix for the SERIAL message +#endif +#ifndef SERIALPost +# define SERIALPost "\r" // The postfix for the SERIAL message +#endif + +//Setup for SERIAL +#ifndef SERIALBaud +# define SERIALBaud 9600 // The serial connection Baud +#endif + +#ifndef SERIAL_CONFIG +# define SERIAL_CONFIG SERIAL_8N1 // The serial frame format (data/parity/stop bits), e.g. SERIAL_8E1 for 8 data bits/even parity/1 stop bit +#endif + +/*-------------------PIN DEFINITIONS----------------------*/ +#ifndef SERIAL_UART +// set hardware serial UART to be used for device communication or +// use software emulaton if not defined +// +// VALUES: +// - not defined: use software emulation (pins set by SERIAL_RX_GPIO & SERIAL_TX_GPIO) +// +// - 0: use HW UART0 (serial), warning: default used for logging & usb +// ESP8266: (TX0 GPIO1, RX0 GPIO3) +// (TX0 GPIO15, RX0 GPIO13) with UART0 swap enabled +// ESP32: (TX0 by SERIAL_TX_GPIO, RX0 by SERIAL_RX_GPIO) +// +// - 1: use HW UART1 (serial1) +// ESP8266: (TX1 GPIO2, RX none) only transmit available +// ESP32: (TX1 by SERIAL_TX_GPIO, RX1 by SERIAL_RX_GPIO) +// +// - 2: use HW UART2 (serial2) +// ESP8266: N/A +// ESP32: (TX2 by SERIAL_TX_GPIO, RX2 by SERIAL_RX_GPIO) +// +// - 3: use HW UART3 (serial3) +// ESP8266: N/A +// ESP32: N/A +// +// defaults +# ifdef ESP32 +# define SERIAL_UART 1 // use HW UART ESP32 +# else +# undef SERIAL_UART // default use software serial +//# define SERIAL_UART 1 // define to use HW UART +# endif +#endif + +#ifndef SERIAL_UART0_SWAP +// option for ESP8266 only to swap UART0 ports from (GPIO1,GPIO3) to (GPIO15,GPIO13) +# define SERIAL_UART0_SWAP +#endif + +#ifndef SERIAL_RX_GPIO +// define receive pin (for software serial or ESP32 with configurable HW UART) +# if defined(ESP8266) && !defined(SERIAL_UART) +# define SERIAL_RX_GPIO 4 //D2 +# elif defined(ESP32) +# define SERIAL_RX_GPIO 26 +# endif +#endif + +#ifndef SERIAL_TX_GPIO +// define transmit pin (for software serial and/or ESP32) +# if defined(ESP8266) && !defined(SERIAL_UART) +# define SERIAL_TX_GPIO 2 //D4 +# elif defined(ESP32) +# define SERIAL_TX_GPIO 14 +# endif +#endif + +#endif \ No newline at end of file diff --git a/main/config_SHTC3.h b/main/config_SHTC3.h index 0f26535..b1a4686 100644 --- a/main/config_SHTC3.h +++ b/main/config_SHTC3.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the SHTC311/22 sensor @@ -27,7 +27,7 @@ #define config_SHTC3_h extern void setupSHTC3(); -extern void SHTC3toMQTT(); +extern void SHTC3toX(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ diff --git a/main/config_SRFB.h b/main/config_SRFB.h index c617389..362539b 100644 --- a/main/config_SRFB.h +++ b/main/config_SRFB.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the radiofrequency gateway on sonoff rf bridge (ZgatewaySRFB) @@ -27,10 +27,12 @@ #ifndef config_SRFB_h #define config_SRFB_h +#include "TheengsCommon.h" + extern void setupSRFB(); -extern bool SRFBtoMQTT(); -extern void MQTTtoSRFB(char* topicOri, char* datacallback); -extern void MQTTtoSRFB(char* topicOri, JsonObject& RFdata); +extern bool SRFBtoX(); +extern void XtoSRFB(const char* topicOri, const char* datacallback); +extern void XtoSRFB(const char* topicOri, JsonObject& RFdata); /*-------------------RF topics & parameters----------------------*/ //433Mhz MQTT Subjects and keys #define subjectMQTTtoSRFB "/commands/MQTTtoSRFB" diff --git a/main/config_SSD1306.h b/main/config_SSD1306.h index 6f66229..526b2ce 100644 --- a/main/config_SSD1306.h +++ b/main/config_SSD1306.h @@ -1,7 +1,7 @@ /* OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT Supported boards with displays @@ -34,11 +34,7 @@ #ifndef config_SSD1306_h #define config_SSD1306_h -#include -#include -#include - -#include "SSD1306Wire.h" +#include "TheengsCommon.h" #include "config_WebUI.h" /*-------------------DEFINE LOG LEVEL----------------------*/ @@ -105,17 +101,33 @@ #define subjectMQTTtoSSD1306set "/commands/MQTTtoSSD1306/config" #define subjectSSD1306toMQTT "/SSD1306toMQTT" +/*-------------------Display Blanking via Touch----------------------*/ + +#ifdef DISPLAY_BLANKING +# ifndef DISPLAY_BLANKING_TOUCH_GPIO +# define DISPLAY_BLANKING_TOUCH_GPIO 2 // GPIO pin for touch sensor +# endif +# ifndef DISPLAY_BLANKING_START +# define DISPLAY_BLANKING_START 30 // 30 seconds after last touch +# endif +# ifndef DISPLAY_BLANKING_THRESHOLD +# define DISPLAY_BLANKING_THRESHOLD 10 +# endif +# define TOUCH_READINGS 100 // Number of readings to average +# define TOUCH_THRESHOLD 0.2 // 20% change in reading +#endif + /*-------------------EXTERNAL FUNCTIONS----------------------*/ extern void setupSSD1306(); extern void loopSSD1306(); -extern void MQTTtoSSD1306(char*, JsonObject&); +extern void XtoSSD1306(const char*, JsonObject&); extern String stateSSD1306Display(); // Simple construct for displaying message in lcd and oled displays #define displayPrint(...) \ - if (lowpowermode < 2) ssd1306Print(__VA_ARGS__) // only print if not in low power mode + if (SYSConfig.powerMode < 1) ssd1306Print(__VA_ARGS__) // only print if not in low power mode #define lpDisplayPrint(...) ssd1306Print(__VA_ARGS__) // print in low power mode void ssd1306Print(char*, char*, char*); @@ -124,53 +136,4 @@ void ssd1306Print(char*); /*-------------------End of Global Variables----------------------*/ -// This pattern was borrowed from HardwareSerial and modified to support the ssd1306 display - -class OledSerial : public Stream { -public: - OledSerial(int); - void begin(); - void drawLogo(int xshift, int yshift); - boolean displayPage(webUIQueueMessage*); - - SSD1306Wire* display; - - int available(void); // Dummy functions - int peek(void); // Dummy functions - int read(void); // Dummy functions - void flush(void); // Dummy functions - - void fillScreen(OLEDDISPLAY_COLOR); // fillScreen display and set color - - // This is a bit of lazy programmer simplification for the semaphore and core detecting code. Not sure if it is truly space efficient. - - inline size_t write(uint8_t x) { - return write(&x, 1); - } - - size_t write(const uint8_t* buffer, size_t size); - inline size_t write(const char* buffer, size_t size) { - return write((uint8_t*)buffer, size); - } - inline size_t write(const char* s) { - return write((uint8_t*)s, strlen(s)); - } - inline size_t write(unsigned long n) { - return write((uint8_t)n); - } - inline size_t write(long n) { - return write((uint8_t)n); - } - inline size_t write(unsigned int n) { - return write((uint8_t)n); - } - inline size_t write(int n) { - return write((uint8_t)n); - } - -protected: -}; - -extern OledSerial Oled; - #endif diff --git a/main/config_Somfy.h b/main/config_Somfy.h index dc397af..5d3533e 100644 --- a/main/config_Somfy.h +++ b/main/config_Somfy.h @@ -1,6 +1,6 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This actor enables to: @@ -24,11 +24,10 @@ #ifndef config_Somfy_h #define config_Somfy_h -#include -#include +#include "TheengsCommon.h" extern void setupSomfy(); -extern void MQTTtoSomfy(char* topicOri, JsonObject& RFdata); +extern void XtoSomfy(const char* topicOri, JsonObject& RFdata); /*----------------------------USER PARAMETERS-----------------------------*/ #define EEPROM_ADDRESS_START 0 #define SOMFY_REMOTE_NUM 1 diff --git a/main/config_TEMT6000.h b/main/config_TEMT6000.h index e8dac39..2d71363 100644 --- a/main/config_TEMT6000.h +++ b/main/config_TEMT6000.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This is the Light Meter Addon based on modules with a TEMT6000: @@ -49,7 +49,4 @@ extern void MeasureLightIntensityTEMT6000(); /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ #define subjectTEMT6000toMQTT "/LIGHTtoMQTT" -//Time used to wait for an interval before resending measured values -unsigned long timetemt6000 = 0; - #endif \ No newline at end of file diff --git a/main/config_TSL2561.h b/main/config_TSL2561.h index 17d804a..b319146 100644 --- a/main/config_TSL2561.h +++ b/main/config_TSL2561.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files exposes light level measured by a TSL2651 module @@ -27,13 +27,13 @@ Connection Schemata: -------------------- - TSL2561 ------> Arduino Uno ----------> ESP8266 - ============================================== - Vcc ---------> 3.3V -----------------> Vu (3.3V) - GND ---------> GND ------------------> GND - SCL ---------> Pin A5 ---------------> D1 - SDA ---------> Pin A4 ---------------> D2 - ADD ---------> N/C (Not Connected) --> N/C (Not Connected) + TSL2561 ------> ESP8266 + =================================== + Vcc ---------> Vu (3.3V) + GND ---------> GND + SCL ---------> D1 + SDA ---------> D2 + ADD ---------> N/C (Not Connected) */ #ifndef config_TSL2561_h @@ -48,8 +48,4 @@ extern void MeasureLightIntensityTSL2561(); /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ #define subjectTSL12561toMQTT "/LIGHTtoMQTT" -//Time used to wait for an interval before resending measured values -unsigned long timetsl2561 = 0; -//int TSL2561_i2c_addr = 0x37; // Light Sensor I2C Address (Set in Adafruit library) - #endif \ No newline at end of file diff --git a/main/config_Touch.h b/main/config_Touch.h index 4a537ad..0e9c991 100644 --- a/main/config_Touch.h +++ b/main/config_Touch.h @@ -1,7 +1,7 @@ /* - OpenMQTTGateway - ESP8266 or Arduino program for home automation + Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the esp32's touch buttons @@ -28,10 +28,10 @@ #define config_Touch_h extern void setupTouch(); -extern void touchToMQTT(); +extern void touchtoX(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define TOUCHTOPIC "/touchToMQTT" +#define subjectTouchtoMQTT "/touchToMQTT" // Time between readings of the touch sensor. Don't make it too short, as // reading one touch sensor takes 0.5 ms. diff --git a/main/config_WeatherStation.h b/main/config_WeatherStation.h index 2d2bdee..e91b701 100644 --- a/main/config_WeatherStation.h +++ b/main/config_WeatherStation.h @@ -1,7 +1,7 @@ /* OpenMQTTGateway - ESP8266 or Arduino program for home automation - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the DHT11/22 sensor @@ -26,11 +26,8 @@ #ifndef config_WeatherStation_h #define config_WeatherStation_h -#include -#include - extern void setupWeatherStation(); -extern void ZgatewayWeatherStationtoMQTT(); +extern void ZgatewayWeatherStationtoX(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ #define subjectRFtoMQTT "/433toMQTT" @@ -39,12 +36,8 @@ extern void ZgatewayWeatherStationtoMQTT(); #ifndef RF_WS_RECEIVER_GPIO # ifdef ESP8266 # define RF_WS_RECEIVER_GPIO 0 // D3 on nodemcu // put 4 with rf bridge direct mod -# elif ESP32 +# elif defined(ESP32) # define RF_WS_RECEIVER_GPIO 27 // D27 on DOIT ESP32 -# elif __AVR_ATmega2560__ -# define RF_WS_RECEIVER_GPIO 1 //1 = D3 on mega -# else -# define RF_WS_RECEIVER_GPIO 1 //1 = D3 on arduino # endif #endif diff --git a/main/config_WebContent.h b/main/config_WebContent.h index 05104d2..11d0369 100644 --- a/main/config_WebContent.h +++ b/main/config_WebContent.h @@ -1,7 +1,7 @@ /* OpenMQTTGateway - ESP8266 or Arduino program for home automation - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This files enables to set your parameter for the DHT11/22 sensor @@ -41,15 +41,15 @@ #endif // Configuration Menu -#define configure_1 "

" -#define configure_2 "

" +#define configure_1 "

" +#define configure_2 "

" /*#if defined(ZgatewayCloud) # define configure_3 "

" #else # define configure_3 #endif*/ #ifndef ESPWifiManualSetup -# define configure_3 "

" +# define configure_3 "

" #else # define configure_3 #endif @@ -62,7 +62,11 @@ #else # define configure_6 #endif -#define configure_7 +#ifdef ZgatewayBT +# define configure_7 "

" +#else +# define configure_7 +#endif #define configure_8 /*------------------- ----------------------*/ @@ -99,16 +103,41 @@ const char information_body[] = body_header "