Merge pull request #926 from cyberman54/master

sync dev to master
This commit is contained in:
Verkehrsrot 2022-12-31 19:37:49 +01:00 committed by GitHub
commit bdcd0cf504
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
73 changed files with 1230 additions and 756 deletions

View File

@ -2,12 +2,23 @@ name: PlatformIO CI
on: on:
pull_request: pull_request:
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'LICENSE'
- 'README.md'
push: push:
branches: branches:
- master - master
- build-workflow - build-workflow
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'LICENSE'
- 'README.md'
workflow_dispatch: workflow_dispatch:
jobs: jobs:
build: build:
strategy: strategy:

19
.github/workflows/docs.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: publish-docs
on:
push:
branches:
- master
- mkdocs
paths:
- 'mkdocs.yml'
- 'docs/**'
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v3
with:
python-version: 3.x
- run: pip install mkdocs-material
- run: mkdocs gh-deploy --force

585
README.md
View File

@ -1,21 +1,30 @@
# ESP32-Paxcounter # ESP32-Paxcounter
![logo](docs/assets/paxcounter_logo_white.png)
**Wifi & Bluetooth driven, LoRaWAN enabled, battery powered mini Paxcounter built on cheap ESP32 LoRa IoT boards** **Wifi & Bluetooth driven, LoRaWAN enabled, battery powered mini Paxcounter built on cheap ESP32 LoRa IoT boards**
Tutorial (in german language): https://www.heise.de/select/make/2019/1/1551099236518668 [Tutorial (in german language): heise.de](https://www.heise.de/select/make/2019/1/1551099236518668)
[![CodeFactor](https://www.codefactor.io/repository/github/cyberman54/esp32-paxcounter/badge)](https://www.codefactor.io/repository/github/cyberman54/esp32-paxcounter) [![CodeFactor](https://www.codefactor.io/repository/github/cyberman54/esp32-paxcounter/badge)](https://www.codefactor.io/repository/github/cyberman54/esp32-paxcounter)
[![PlatformIO CI](https://github.com/cyberman54/ESP32-Paxcounter/actions/workflows/build.yml/badge.svg?event=push)](https://github.com/cyberman54/ESP32-Paxcounter/actions/workflows/build.yml)
---
<img src="img/Paxcounter-title.jpg"> **Documentation**: <a href="https://cyberman54.github.io/ESP32-Paxcounter" target="_blank">https://cyberman54.github.io/ESP32-Paxcounter</a>
<img src="img/Paxcounter-ttgo.jpg">
<img src="img/Paxcounter-lolin.gif">
<img src="img/Paxcounter-Screen.png">
<img src="img/TTGO-case.jpg">
<img src="img/TTGO-curves.jpg">
<img src="img/Paxcounter-LEDmatrix.jpg">
<img src="img/Paxcounter-Clock2.png">
<img src="img/Paxcounter-ttgo-twristband.jpg">
**Source Code**: <a href="https://github.com/cyberman54/ESP32-Paxcounter" target="_blank">https://github.com/cyberman54/ESP32-Paxcounter</a>
---
<img src="docs/img/Paxcounter-title.jpg">
<img src="docs/img/Paxcounter-ttgo.jpg">
<img src="docs/img/Paxcounter-lolin.gif">
<img src="docs/img/Paxcounter-Screen.png">
<img src="docs/img/TTGO-case.jpg">
<img src="docs/img/TTGO-curves.jpg">
<img src="docs/img/Paxcounter-LEDmatrix.jpg">
<img src="docs/img/Paxcounter-Clock2.png">
<img src="docs/img/Paxcounter-ttgo-twristband.jpg">
# Use case # Use case
@ -23,563 +32,15 @@ Paxcounter is an [ESP32](https://www.espressif.com/en/products/socs/esp32) MCU b
Intention of this project is to do this without intrusion in privacy: You don't need to track people owned devices, if you just want to count them. Therefore, Paxcounter does not persistenly store MAC adresses and does no kind of fingerprinting the scanned devices. Intention of this project is to do this without intrusion in privacy: You don't need to track people owned devices, if you just want to count them. Therefore, Paxcounter does not persistenly store MAC adresses and does no kind of fingerprinting the scanned devices.
Data can either be be stored on a local SD-card, transferred to cloud using LoRaWAN network (e.g. TheThingsNetwork or Helium) or MQTT over TCP/IP, or transmitted to a local host using serial (SPI) interface. Data can either be stored on a local SD-card, transferred to cloud using LoRaWAN network (e.g. TheThingsNetwork or Helium) or MQTT over TCP/IP, or transmitted to a local host using serial (SPI) interface.
You can build this project battery powered using ESP32 deep sleep mode and reach long uptimes with a single 18650 Li-Ion cell. You can build this project battery powered using ESP32 deep sleep mode and reach long uptimes with a single 18650 Li-Ion cell.
# Hardware
**Supported ESP32 based boards**:
*With LoRa radio data transfer*:
- **LilyGo: [Paxcounter-Board*](https://www.aliexpress.com/item/32915894264.html?spm=a2g0o.productlist.0.0.3d656325QrcfQc&algo_pvid=4a150199-63e7-4d21-bdb1-b48164537744&algo_exp_id=4a150199-63e7-4d21-bdb1-b48164537744-2&pdp_ext_f=%7B%22sku_id%22%3A%2212000023374441919%22%7D)**
- TTGO: T1*, T2*, T3*, T-Beam, T-Fox
- Heltec: LoRa-32 v1 and v2
- Pycom: LoPy, LoPy4, FiPy
- Radioshuttle.de: [ECO Power Board](https://www.radioshuttle.de/esp32-eco-power/esp32-eco-power-board/)
- WeMos: LoLin32 + [LoraNode32 shield](https://github.com/hallard/LoLin32-Lora),
LoLin32lite + [LoraNode32-Lite shield](https://github.com/hallard/LoLin32-Lite-Lora)
- Adafruit ESP32 Feather + LoRa Wing + OLED Wing, #IoT Octopus32 (Octopus + ESP32 Feather)
- M5Stack: [Basic Core IoT*](https://m5stack.com/collections/m5-core/products/basic-core-iot-development-kit) + [Lora Module RA-01H](https://m5stack.com/collections/m5-module/products/lora-module-868mhz), [Fire IoT*](https://m5stack.com/collections/m5-core/products/fire-iot-development-kit)
*Without LoRa*:
- LilyGo: [T-Dongle S3*](https://github.com/Xinyuan-LilyGO/T-Dongle-S3)
- Pyom: WiPy
- WeMos: LoLin32, LoLin32 Lite, WeMos D32, [Wemos32 Oled](https://www.instructables.com/id/ESP32-With-Integrated-OLED-WEMOSLolin-Getting-Star/)
- Crowdsupply: [TinyPICO](https://www.crowdsupply.com/unexpected-maker/tinypico)
- TTGO: [T-Display](https://www.aliexpress.com/item/33048962331.html)
- TTGO: [T-Wristband](https://www.aliexpress.com/item/4000527495064.html)
- Generic ESP32
*) supports microSD/TF-card for local logging of paxcounter data
Depending on board hardware following features are supported:
- LoRaWAN communication, supporting various payload formats (see enclosed .js converters)
- MQTT communication via TCP/IP and Ethernet interface (note: payload transmitted over MQTT will be base64 encoded)
- SPI serial communication to a local host
- LED (shows power & status)
- OLED Display (shows detailed status)
- RGB LED (shows colorized status)
- Button (short press: flip display page / long press: send alarm message)
- Battery voltage monitoring (analog read / AXP192 / IP5306)
- GPS (Generic serial NMEA, or Quectel L76 I2C)
- Environmental sensors (Bosch BMP180/BME280/BME680 I2C; SDS011 serial)
- Real Time Clock (Maxim DS3231 I2C)
- IF482 (serial) and DCF77 (gpio) time telegram generator
- Switch external power / battery
- LED Matrix display (similar to [this 64x16 model](https://www.instructables.com/id/64x16-RED-LED-Marquee/), can be ordered on [Aliexpress](https://www.aliexpress.com/item/P3-75-dot-matrix-led-module-3-75mm-high-clear-top1-for-text-display-304-60mm/32616683948.html))
- SD-card (see section SD-card here) for logging pax data
Target platform must be selected in `platformio.ini`.<br>
Hardware dependent settings (pinout etc.) are stored in board files in /hal directory. If you want to use a ESP32 board which is not yet supported, use hal file generic.h and tailor pin mappings to your needs. Pull requests for new boards welcome.<br>
Some <b>3D printable cases</b> can be found (and, if wanted so, ordered) on Thingiverse, see
<A HREF="https://www.thingiverse.com/thing:2670713">Heltec</A>,
<A HREF="https://www.thingiverse.com/thing:2811127">TTGOv2</A>,
<A HREF="https://www.thingiverse.com/thing:3005574">TTGOv2.1</A>,
<A HREF="https://www.thingiverse.com/thing:3385109">TTGO</A>,
<A HREF="https://www.thingiverse.com/thing:3041339">T-BEAM</A>,
<A HREF="https://www.thingiverse.com/thing:3203177">T-BEAM parts</A>,
for example.<br>
<b>Power consumption</b> was metered at around 450 - 1000mW, depending on board and user settings in paxcounter.conf.
By default bluetooth sniffing not installed (#define *BLECOUNTER* 0 in paxcounter.conf). If you enable bluetooth be aware that this goes on expense of wifi sniffing results, because then wifi and bt stack must share the 2,4 GHz RF ressources of ESP32. If you need to sniff wifi and bt in parallel and need best possible results, use two boards - one for wifi only and one for bt only - and add counted results.
# Preparing
## Install Platformio
Install <A HREF="https://platformio.org/">PlatformIO IDE for embedded development</A> to make this project. Platformio integrates with your favorite IDE, choose eg. Visual Studio, Atom, Eclipse etc.
Compile time configuration is spread across several files. Before compiling the code, edit or create the following files:
## platformio.ini
Edit `platformio_orig.ini` (for ESP32 CPU based boards) *or* `platformio_orig_s3.ini` (for ESP32-S3 CPU based boards) and select desired board in section **board**. To add a new board, create an appropriate hardware abstraction layer file in hal subdirectory, and add a pointer to this file in section **board**. Copy or rename to `platformio.ini` in the root directory of the project. Now start Platformio. Note: Platformio is looking for `platformio.ini` in the root directory and won't start if it does not find this file!
## paxcounter.conf
Edit `src/paxcounter_orig.conf` and tailor settings in this file according to your needs and use case. Please take care of the duty cycle regulations of the LoRaWAN network you're going to use. Copy or rename to `src/paxcounter.conf`.
If your device has a **real time clock** it can be updated by either LoRaWAN network or GPS time, according to settings *TIME_SYNC_INTERVAL* and *TIME_SYNC_LORAWAN* in `paxcounter.conf`.
## src/lmic_config.h
Edit `src/lmic_config.h` and tailor settings in this file according to your country and device hardware. Please take care of national regulations when selecting the frequency band for LoRaWAN.
## src/loraconf.h
Create file `src/loraconf.h` using the template [src/loraconf_sample.h](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/loraconf_sample.h) and adjust settings to use your personal values. To join the network and activate your paxcounter, you must configure either OTAA or ABP join method. You should use OTAA, whenever possible. To understand the differences of the two methods, [this article](https://www.thethingsnetwork.org/docs/devices/registration.html) may be useful.
To configure OTAA, leave `#define LORA_ABP` deactivated (commented). To use ABP, activate (uncomment) `#define LORA_ABP` in the file `src/loraconf.h`.
The file `src/loraconf_sample.h` contains more information about the values to provide.
## src/ota.conf
Create file `src/ota.conf` using the template [src/ota.sample.conf](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/ota.sample.conf) and enter your WIFI network&key. These settings are used for downloading updates via WiFi, either from a remote https server, or locally via WebUI. If you want to use a remote server, you need a <A HREF="https://github.com/paxexpress/docs">PAX.express repository</A>. Enter your PAX.express credentials in ota.conf. If you don't need wireless firmware updates just rename ota.sample.conf to ota.conf.
# Building
Use <A HREF="https://platformio.org/">PlatformIO</A> with your preferred IDE for development and building this code. Make sure you have latest PlatformIO version.
# Uploading
- **by cable, via USB/UART interface:**
To upload the code via cable to your ESP32 board this needs to be switched from run to bootloader mode. Boards with USB bridge like Heltec and TTGO usually have an onboard logic which allows soft switching by the upload tool. In PlatformIO this happenes automatically.<p>
The LoPy/LoPy4/FiPy board needs to be set manually. See these
<A HREF="https://www.thethingsnetwork.org/labs/story/program-your-lopy-from-the-arduino-ide-using-lmic">instructions</A> how to do it. Don't forget to press on board reset button after switching between run and bootloader mode.<p>
The original Pycom firmware is not needed, so there is no need to update it before flashing Paxcounter. Just flash the compiled paxcounter binary (.elf file) on your LoPy/LoPy4/FiPy. If you later want to go back to the Pycom firmware, download the firmware from Pycom and flash it over.
- **over the air (OTA), download via WiFi:**
After the ESP32 board is initially flashed and has joined a LoRaWAN network, the firmware can update itself by OTA. This process is kicked off by sending a remote control command (see below) via LoRaWAN to the board. The board then tries to connect via WiFi to a cloud service (<A HREF="https://github.com/paxexpress">PAX.express</A>), checks for update, and if available downloads the binary and reboots with it. If something goes wrong during this process, the board reboots back to the current version. Prerequisites for OTA are: 1. You own a PAX.express repository, 2. you pushed the update binary to your PAX.express repository, 3. internet access via encrypted (WPA2) WiFi is present at the board's site, 4. WiFi credentials were set in ota.conf and initially flashed to the board. Step 2 runs automated, just enter the credentials in ota.conf and set `upload_protocol = custom` in platformio.ini. Then press build and lean back watching platformio doing build and upload.
- **over the air (OTA), upload via WiFi:**
If option *BOOTMENU* is defined in `paxcounter.conf`, the ESP32 board will try to connect to a known WiFi access point each time cold starting (after a power cycle or a reset), using the WiFi credentials given in `ota.conf`. Once connected to the WiFi it will fire up a simple webserver, providing a bootstrap menu waiting for a user interaction (pressing "START" button in menu). This process will time out after *BOOTDELAY* seconds, ensuring booting the device to runmode. Once a user interaction in bootstrap menu was detected, the timeout will be extended to *BOOTTIMEOUT* seconds. During this time a firmware upload can be performed manually by user, e.g. using a smartphone in tethering mode providing the firmware upload file.
# Legal note
**Depending on your country's laws it may be illegal to sniff wireless networks for MAC addresses. Please check and respect your country's laws before using this code!**
(e.g. US citizens may want to check [Section 18 U.S. Code § 2511](https://www.law.cornell.edu/uscode/text/18/2511) and [discussion](https://github.com/schollz/howmanypeoplearearound/issues/4) on this)
(e.g. UK citizens may want to check [Data Protection Act 1998](https://ico.org.uk/media/1560691/wi-fi-location-analytics-guidance.pdf) and [GDPR 2018](https://ico.org.uk/for-organisations/guide-to-the-general-data-protection-regulation-gdpr/key-definitions/))
(e.g. Citizens in the the Netherlands and EU may want to read [this article](https://www.ivir.nl/publicaties/download/PrivacyInformatie_2016_6.pdf) and [this article](https://autoriteitpersoonsgegevens.nl/nl/nieuws/europese-privacytoezichthouders-publiceren-opinie-eprivacyverordening)) and [this decision](https://edpb.europa.eu/news/national-news/2021/dutch-dpa-fines-municipality-wi-fi-tracking_en)
(e.g. Citizens in Germany may want to read [this article of Wissenschaftliche Dienste des Deutschen Bundestages](https://www.bundestag.de/resource/blob/538890/3dfae197d2c930693aa16d1619204f58/WD-3-206-17-pdf-data.pdf)
Note: If you use this software you do this at your own risk. That means that you alone - not the authors of this software - are responsible for the legal compliance of an application using this or build from this software and/or usage of a device created using this software. You should take special care and get prior legal advice if you plan metering passengers in public areas and/or publish data drawn from doing so.
# Privacy disclosure
Paxcounter generates identifiers for sniffed Wifi or Bluetooth MAC adresses and and collects them temporary in the device's RAM for a configurable scan cycle time (default 60 seconds). After each scan cycle the collected identifiers are cleared. Identifiers are generated by using the last 2 bytes of universal MAC adresses. Personal MAC adresses remain untouched and are not evaluated. Identifiers and MAC adresses are never transferred to the LoRaWAN network. No persistent storing of MAC adresses, identifiers or timestamps and no other kind of analytics than counting are implemented in this code. Wireless networks are not touched by this code, but MAC adresses from wireless devices as well within as not within wireless networks, regardless if encrypted or unencrypted, are sniffed and processed by this code.
# LED blink pattern
**Mono color LED:**
- Single Flash (50ms): seen a new Wifi or BLE device
- Quick blink (20ms on each 1/5 second): joining LoRaWAN network in progress or pending
- Small blink (10ms on each 1/2 second): LoRaWAN data transmit in progress or pending
- Long blink (200ms on each 2 seconds): LoRaWAN stack error
**RGB LED:**
- Green: seen a new Wifi device
- Magenta: seen a new BLE device
- Yellow: joining LoRaWAN network in progress or pending
- Pink: LORAWAN MAC transmit in progress
- Blue: LoRaWAN data transmit in progress or pending
- Red: LoRaWAN stack error
# Display
If you're using a device with OLED display, or if you add such one to the I2C bus, the device shows live data on the display. You can flip display pages showing
- recent count of pax
- histogram
- GPS data
- BME sensor data
- time of day
- blank page
by pressing the button of the device.
# Sensors and Peripherals
You can add up to 3 user defined sensors. Insert your sensor's payload scheme in [*sensor.cpp*](src/sensor.cpp). Bosch BMP180 / BME280 / BME680 environment sensors are supported, to activate configure BME in board's hal file before build. Furthermore, SDS011, RTC DS3231, generic serial NMEA GPS, I2C LoPy GPS are supported, and to be configured in board's hal file. See [*generic.h*](src/hal/generic.h) for all options and for proper configuration of BME280/BME680.
Output of user sensor data can be switched by user remote control command 0x14 sent to Port 2.
Output of sensor and peripheral data is internally switched by a bitmask register. Default mask can be tailored by editing *cfg.payloadmask* initialization value in [*configmanager.cpp*](src/configmanager.cpp) following this scheme:
| Bit | Sensordata | Default
| --- | ------------- | -------
| 0 | Paxcounter | on
| 1 | unused | off
| 2 | BME280/680 | on
| 3 | GPS* | on
| 4 | User sensor 1 | on
| 5 | User sensor 2 | on
| 6 | User sensor 3 | on
| 7 | Batterylevel | off
*) GPS data can also be combined with paxcounter payload on port 1, *#define GPSPORT 1* in paxcounter.conf to enable
# Power saving mode
Paxcounter supports a battery friendly power saving mode. In this mode the device enters deep sleep, after all data is polled from all sensors and the dataset is completeley sent through all user configured channels (LORAWAN / SPI / MQTT / SD-Card). Set *#define SLEEPCYCLE* in paxcounter.conf to enable power saving mode and to specify the duration of a sleep cycle. Power consumption in deep sleep mode depends on your hardware, i.e. if on board peripherals can be switched off or set to a chip specific sleep mode either by MCU or by power management unit (PMU) as found on TTGO T-BEAM v1.0/V1.1. See *power.cpp* for power management, and *reset.cpp* for sleep and wakeup logic.
# Time sync
Paxcounter can keep a time-of-day synced with external or on board time sources. Set *#define TIME_SYNC_INTERVAL* in paxcounter.conf to enable time sync. Supported external time sources are GPS, LORAWAN network time and LORAWAN application timeserver time. Supported on board time sources are the RTC of ESP32 and a DS3231 RTC chip, both are kept sycned as fallback time sources. Time accuracy depends on board's time base which generates the pulse per second. Supported are GPS PPS, SQW output of RTC, and internal ESP32 hardware timer. Time base is selected by #defines in the board's hal file, see example in [**generic.h**](src/hal/generic.h). Bonus: If your LORAWAN network does not support network time, you can run a Node-Red timeserver application using the enclosed [**Timeserver code**](/src/Node-RED/Timeserver.json). Configure the MQTT nodes in Node-Red for the LORAWAN application used by your paxocunter device. Time can also be set without precision liability, by simple remote command, see section remote control.
# Wall clock controller
Paxcounter can be used to sync a wall clock which has a DCF77 or IF482 time telegram input. Set *#define HAS_IF482* or *#define HAS_DCF77* in board's hal file to setup clock controller. Use case of this function is to integrate paxcounter and clock. Accurary of the synthetic DCF77 signal depends on accuracy of on board's time base, see above.
# Mobile PaxCounter using <A HREF="https://opensensemap.org/">openSenseMap</A>
This describes how to set up a mobile PaxCounter:<br> Follow all steps so far for preparing the device, selecting the packed payload format. In `paxcounter.conf` set PAYLOAD_OPENSENSEBOX to 1. Register a new sensebox on https://opensensemap.org/. In the sensor configuration select "TheThingsNetwork" and set decoding profile to "LoRa serialization". Enter your TTN Application and Device ID. Setup decoding option using `[{"decoder":"latLng"},{"decoder":"uint16",sensor_id":"yoursensorid"}]`
# SD-card
Data can be stored on SD-card if the board provides an SD card interface, either with SPI or MMC mode. To enable this feature, specify interface mode and hardware pins in board's hal file (src/hal/<board.h>):
#define HAS_SDCARD 1 // SD-card interface, using SPI mode
OR
#define HAS_SDCARD 2 // SD-card interface, using MMC mode
// Pins for SPI interface
#define SDCARD_CS (13) // fill in the correct numbers for your board
#define SDCARD_MOSI (15)
#define SDCARD_MISO (2)
#define SDCARD_SCLK (14)
This is an example of a board with MMC SD-card interface: https://www.aliexpress.com/item/32915894264.html. For this board use file src/hal/ttgov21new.h and add the lines given above.
Another approach would be this tiny board: https://www.aliexpress.com/item/32424558182.html (needs 5V).
In this case you choose the correct file for your ESP32-board in the src/hal-directory and add the lines given above. Edit the pin numbers given in the example, according to your wiring.
Data is written on SD-card to a single file. After 3 write operations the data is flushed to the disk to minimize flash write cycles. Thus, up to the last 3 records of data will get lost when the PAXCOUNTER looses power during operation.
Format of the resulting file is CSV, thus easy import in LibreOffice, Excel, Influx, etc. Each record contains timestamp (in ISO8601 format), paxcount (wifi and ble) and battery voltage (optional). Voltage is logged if the device has a battery voltage sensor (to be configured in board hal file).
File contents example:
timestamp,wifi,ble[,voltage]
2022-01-30T21:12:41Z,11,25[,4100]
2022-01-30T21:14:24Z,10,21[,4070]
2022-01-30T21:16:08Z,12,26[,4102]
2022-01-30T21:17:52Z,11,26[,4076]
If you want to change this, modify src/sdcard.cpp and include/sdcard.h.
# Integration into "The Things Stack Community Edition" aka "The Things Stack V3"
To use the ESP32-Paxcounter in The Things Stack Community Edition you need an account to reach the console. Go to:
- [The Things Stack Community Edition Console](https://console.cloud.thethings.network/)
- choose your region and go to applications
- create an application by clicking "**+ Add application**" and give it a id, name, etc.
- create a device by clicking "**+ Add end device**"
- Select the end device: choose the Brand "**Open Source Community Projects**" and the Model "**ESP32-Paxcounter**", leave Hardware Version to "**Unknown**" and select your **Firmware Version** and **Profile (Region)**
- Enter registration data: choose the **frequency plan** (for EU choose the recommended), set the **AppEUI** (Fill with zeros), set the **DeviceEUI** (generate), set the **AppKey** (generate), choose a **device ID** and hit "Register end device"
- got to Applications -> "your App ID" -> Payload formatters -> Uplink, choose "**Repository**" and hit "Save changes"
The "Repository" payload decoder uses the packed format, explained below. If you want to use MyDevices from Cayenne you should use the Cayenne payload decoder instead.
# TTN Mapper
If you want your devices to be feeding the [TTN Mapper](https://ttnmapper.org/), just follow this manual: https://docs.ttnmapper.org/integration/tts-integration-v3.html - different than indicated in the manual you can leave the payload decoder to "Repository" for the ESP32-Paxcounter and you are fine.
# Payload format
You can select different payload formats in `paxcounter.conf`:
- ***Plain*** uses big endian format and generates json fields, e.g. useful for TTN console
- ***Packed*** uses little endian format and generates json fields
- [***CayenneLPP***](https://mydevices.com/cayenne/docs/lora/#lora-cayenne-low-power-payload-reference-implementation) generates MyDevices Cayenne readable fields
**Decrepated information from the things network v2 >>**
If you're using [TheThingsNetwork](https://www.thethingsnetwork.org/) (TTN) you may want to use a payload converter. Go to TTN Console - Application - Payload Formats and paste the code example below in tabs Decoder and Converter. This way your MQTT application can parse the fields `pax`, `ble` and `wifi`.
To add your device to myDevices Cayenne platform select "Cayenne-LPP" from Lora device list and use the CayenneLPP payload encoder.
To track a paxcounter device with on board GPS and at the same time contribute to TTN coverage mapping, you simply activate the [TTNmapper integration](https://www.thethingsnetwork.org/docs/applications/ttnmapper/) in TTN Console. Both formats *plain* and *packed* generate the fields `latitude`, `longitude` and `hdop` required by ttnmapper. Important: set TTN mapper port filter to '4' (paxcounter GPS Port).
**<< Decrepated information from the things network v2**
Hereafter described is the default *plain* format, which uses MSB bit numbering. Under /TTN in this repository you find some ready-to-go decoders which you may copy to your TTN console:
[**plain_decoder.js**](src/TTN/plain_decoder.js) |
[**plain_converter.js**](src/TTN/plain_converter.js) |
[**packed_decoder.js**](src/TTN/packed_decoder.js) |
[**packed_converter.js**](src/TTN/packed_converter.js)
**Port #1:** Paxcount data
byte 1-2: Number of unique devices, seen on Wifi [00 00 if Wifi scan disabled]
byte 3-4: Number of unique devices, seen on Bluetooth [ommited if BT scan disabled]
**Port #2:** Device status query result
byte 1-2: Battery or USB Voltage [mV], 0 if no battery probe
byte 3-10: Uptime [seconds]
byte 11: CPU temperature [°C]
bytes 12-15: Free RAM [bytes]
byte 16: Last CPU core 0 reset reason
bytes 17-20: Number of restarts since last power cycle
**Port #3:** Device configuration query result
byte 1: Lora DR (0..15, see rcommand 0x05) [default 5]
byte 2: Lora TXpower (2..15) [default 15]
byte 3: Lora ADR (1=on, 0=off) [default 1]
byte 4: Screensaver status (1=on, 0=off) [default 0]
byte 5: Display status (1=on, 0=off) [default 0]
byte 6: Counter mode (0=cyclic unconfirmed, 1=cumulative, 2=cyclic confirmed) [default 0]
bytes 7-8: RSSI limiter threshold value (negative, MSB) [default 0]
byte 9: Scan and send cycle in seconds/2 (0..255) [default 120]
byte 10: Wifi channel hopping interval in seconds/100 (0..255), 0 means no hopping [default 50]
byte 11: Bluetooth channel switch interval in seconds/100 (0..255) [default 10]
byte 12: Bluetooth scanner status (1=on, 0=0ff) [default 1]
byte 13: Wifi antenna switch (0=internal, 1=external) [default 0]
byte 14: 0 (reserved)
byte 15: RGB LED luminosity (0..100 %) [default 30]
byte 16: Payloadmask (Bitmask, 0..255, see rcommand 0x14)
byte 17: 0 (reserved)
bytes 18-28: Software version (ASCII format, terminating with zero)
**Port #4:** GPS data (only if device has fature GPS, and GPS data is enabled and GPS has a fix)
bytes 1-4: Latitude
bytes 5-8: Longitude
byte 9: Number of satellites
bytes 10-11: HDOP
bytes 12-13: Altitude [meter]
**Port #5:** Button pressed alarm
byte 1: static value 0x01
**Port #6:** (unused)
**Port #7:** Environmental sensor data (only if device has feature BME)
bytes 1-2: Temperature [°C]
bytes 3-4: Pressure [hPa]
bytes 5-6: Humidity [%]
bytes 7-8: Indoor air quality index (0..500), see below
Indoor air quality classification:
0-50 good
51-100 average
101-150 little bad
151-200 bad
201-300 worse
301-500 very bad
**Port #8:** Battery voltage data (only if device has feature BATT)
bytes 1-2: Battery or USB Voltage [mV], 0 if no battery probe
**Port #9:** Time/Date
bytes 1-4: board's local time/date in UNIX epoch (number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds)
**Ports #10, #11, #12:** User sensor data
Format is specified by user in function `sensor_read(uint8_t sensor)`, see `src/sensor.cpp`.
# Remote control
The device listenes for remote control commands on LoRaWAN Port 2. Multiple commands per downlink are possible by concatenating them, but must not exceed a maximum of 10 bytes per downlink.
Note: settings can be stored in NVRAM to make them persistant (reloaded during device startup / restart). To store settings, use command 0x21.
Send for example `83` `86` as Downlink on Port 2 to get battery status and time/date from the device.
<img src="img/paxcounter_downlink_example.png">
0x01 set scan RSSI limit
1 ... 255 used for wifi and bluetooth scan radius (greater values increase scan radius, values 50...110 make sense)
0 = RSSI limiter disabled [default]
0x02 set counter mode
0 = cyclic unconfirmed, mac counter reset after each wifi scan cycle, data is sent only once [default]
1 = cumulative counter, mac counter is never reset
2 = cyclic confirmed, like 0 but data is resent until confirmation by network received
0x03 set GPS data on/off
0 = GPS data off
1 = GPS data on, sends GPS data on port 4 (default, use port 1 for mobile pax counter), if GPS is present and has a fix
0x04 set display on/off
0 = display off
1 = display on [default]
0x05 set LoRa datarate
0 ... 15 see LoRaWAN regional parameters for details [default: 5]
Example for EU868:
DataRate Configuration Bit/s
0 LoRa: SF12 / 125 kHz 250
1 LoRa: SF11 / 125 kHz 440
2 LoRa: SF10 / 125 kHz 980
3 LoRa: SF9 / 125 kHz 1760
4 LoRa: SF8 / 125 kHz 3125
5 LoRa: SF7 / 125 kHz 5470
6* LoRa: SF7 / 250 kHz 11000
7* FSK: 50 kbps 50000
8 .. 14 reserved for future use (RFU)
15 ignored (device keeps current setting)
*) not supported by TheThingsNetwork
0x06 set LoRa TXpower
0 ... 255 desired TX power in dBm [default: 14]
0x07 set LoRa Adaptive Data Rate mode
0 = ADR off
1 = ADR on [default]
If ADR is set to off, SF value is shown inverted on display.
0x08 do nothing
useful to clear pending commands from LoRaWAN server quere, or to check RSSI on device
0x09 reset functions (send this command UNconfirmed only to avoid boot loops!)
0 = restart device (coldstart)
1 = (reserved, currently does nothing)
2 = reset device to factory settings and restart device
3 = flush send queues
4 = restart device (warmstart)
8 = reboot device to maintenance mode (local web server)
9 = reboot device to OTA update via Wifi mode
0x0A set payload send cycle
5 ... 255 payload send cycle in seconds/2
e.g. 120 -> payload is transmitted each 240 seconds [default]
0x0B set Wifi channel hopping interval timer
0 ... 255 duration for scanning a wifi channel in seconds/100
e.g. 50 -> each channel is scanned for 500 milliseconds [default]
0 means no hopping, scanning on fixed single channel WIFI_CHANNEL_1
0x0C set Bluetooth channel switch interval timer
0 ... 255 duration for scanning a bluetooth advertising channel in seconds/100
e.g. 8 -> each channel is scanned for 80 milliseconds [default]
0x0E set Bluetooth scanner
0 = disabled
1 = enabled [default]
0x0F set WIFI antenna switch (works on LoPy/LoPy4/FiPy only)
0 = internal antenna [default]
1 = external antenna
0x10 set RGB led luminosity (works on LoPy/LoPy4/FiPy and LoRaNode32 shield only)
0 ... 100 percentage of luminosity (100% = full light)
e.g. 50 -> 50% of luminosity [default]
0x13 set user sensor mode
byte 1 = user sensor number (1..3)
byte 2 = sensor mode (0 = disabled / 1 = enabled [default])
0x14 set payload mask
byte 1 = sensor data payload mask (0..255, meaning of bits see below)
0x01 = COUNT_DATA
0x02 = RESERVED_DATA
0x04 = MEMS_DATA
0x08 = GPS_DATA
0x10 = SENSOR_1_DATA
0x20 = SENSOR_2_DATA
0x40 = SENSOR_3_DATA
0x80 = BATT_DATA
bytes can be combined eg COUNT_DATA + SENSOR_1_DATA + BATT_DATA: `0x01 | 0x10 | 0x80 = 0x91`
0x15 set BME data on/off
0 = BME data off
1 = BME data on, sends BME data on port 7 [default]
0x16 set battery data on/off
0 = battery data off [default]
1 = battery data on, sends voltage on port 8
0x17 set Wifi scanner
0 = disabled
1 = enabled [default]
0x18 reserved
unused, does nothing
0x19 set sleep cycle
bytes 1..2 = device sleep cycle in seconds/10 (MSB), 1 ... 255
e.g. {0x04, 0xB0} -> device sleeps 200 minutes after each send cycle [default = 0]
0x20 load device configuration
Current device runtime configuration will be loaded from NVRAM, replacing current settings immediately (use with care!)
0x21 store device configuration
Current device runtime configuration is stored in NVRAM, will be reloaded after restart
0x80 get device configuration
Device answers with it's current configuration on Port 3.
0x81 get device status
Device answers with it's current status on Port 2.
0x83 get battery status
Device answers with battery voltage on Port 8.
0x84 get device GPS status
Device answers with it's current status on Port 4.
0x85 get BME280 / BME680 sensor data
Device answers with BME sensor data set on Port 7.
0x86 get time/date
Device answers with it's current time on Port 2:
bytes 1..4 = time/date in UTC epoch seconds (LSB)
byte 5 = time source & status, see below
bits 0..3 time source
0x00 = GPS
0x01 = RTC
0x02 = LORA
0x03 = unsynched
0x04 = set (source unknown)
bits 4..7 esp32 sntp time status
0x00 = SNTP_SYNC_STATUS_RESET
0x01 = SNTP_SYNC_STATUS_COMPLETED
0x02 = SNTP_SYNC_STATUS_IN_PROGRESS
0x87 sync time/date
Device synchronizes it's time/date by calling the preconfigured time source.
0x88 set time/date
bytes 1..4 = time/date to set in UTC epoch seconds (MSB, e.g. https://www.epochconverter.com/hex)
# License # License
Copyright 2018-2022 Oliver Brandmueller <ob@sysadm.in> Copyright 2018-2022 Oliver Brandmueller <ob@sysadm.in>
Copyright 2018-2022 Klaus Wilting <verkehrsrot@arcor.de> Copyright 2018-2022 Klaus Wilting <verkehrsrot@arcor.de>
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
@ -608,4 +69,4 @@ Thanks to
- [sbamueller](https://github.com/sbamueller) for writing the tutorial in Make Magazine - [sbamueller](https://github.com/sbamueller) for writing the tutorial in Make Magazine
- [Stefan](https://github.com/nerdyscout) for paxcounter opensensebox integration - [Stefan](https://github.com/nerdyscout) for paxcounter opensensebox integration
- [August Quint](https://github.com/AugustQu) for adding SD card data logger and SDS011 support - [August Quint](https://github.com/AugustQu) for adding SD card data logger and SDS011 support
- [t-huyeng](https://github.com/t-huyeng) for adding a CI workflow to this project - [t-huyeng](https://github.com/t-huyeng) for adding a CI workflow and rework documentation

BIN
docs/assets/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 771 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 771 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="122.00592mm"
height="16.933891mm"
viewBox="0 0 122.00592 16.933891"
version="1.1"
id="svg5"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<g
id="layer1"
transform="translate(-49.372895,-60.450918)">
<text
xml:space="preserve"
transform="matrix(0.26458333,0,0,0.26458333,-0.52916663,0)"
id="text234"
style="font-size:85.3333px;font-family:Bahnschrift;-inkscape-font-specification:Bahnschrift;text-align:center;white-space:pre;shape-inside:url(#rect236);fill:#FFFFFF;"><tspan
x="181.60622"
y="289.05921"
id="tspan7955">PA co ter</tspan></text>
<path
style="fill:#FFFFFF;stroke:#FFFFFF;stroke-width:0.167;stroke-linecap:round;stroke-dasharray:none;stroke-opacity:1;image-rendering:auto"
d="m 123.45503,64.868531 c -1.00185,1.358933 -4.36443,10.09418 -4.56275,11.368693 l -0.0147,0.124487"
id="path589" />
<path
style="fill:#FFFFFF;stroke:#FFFFFF;stroke-width:0.167;stroke-linecap:round;stroke-dasharray:none;stroke-opacity:1;image-rendering:auto"
d="m 128.33846,64.868531 c -1.00185,1.358933 -4.36443,10.09418 -4.56275,11.368693 l -0.0147,0.124487"
id="path589-7" />
<path
style="fill:#FFFFFF;stroke:#FFFFFF;stroke-width:0.167;stroke-linecap:round;stroke-dasharray:none;stroke-opacity:1;image-rendering:auto"
d="m 134.98871,64.868531 c -1.00185,1.358933 -4.36443,10.09418 -4.56275,11.368693 l -0.0147,0.124487"
id="path589-7-2" />
<path
style="fill:#FFFFFF;stroke:#FFFFFF;stroke-width:0.167;stroke-linecap:round;stroke-dasharray:none;stroke-opacity:1;image-rendering:auto"
d="m 139.71331,64.868531 c -1.00185,1.358933 -4.36443,10.09418 -4.56275,11.368693 l -0.0147,0.124487"
id="path589-7-2-3" />
<path
style="fill:#FFFFFF;stroke:#FFFFFF;stroke-width:0.291229;stroke-linecap:round;stroke-dasharray:none;stroke-opacity:1;image-rendering:auto"
d="m 86.68711,60.708031 c -2.209645,1.87375 -9.626034,13.918244 -10.063442,15.675592 l -0.03243,0.171648"
id="path589-4" />
<path
style="fill:#FFFFFF;stroke:#FFFFFF;stroke-width:0.291229;stroke-linecap:round;stroke-dasharray:none;stroke-opacity:1;image-rendering:auto"
d="m 77.262326,60.708031 c 2.209645,1.87375 9.626034,13.918244 10.063442,15.675592 l 0.03243,0.171648"
id="path589-4-6" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -0,0 +1,192 @@
# Custom sensors
You can add up to 3 user defined sensors. Insert your sensor's payload scheme in [`sensor.cpp`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/sensor.cpp).
The following exampls show how to add a custom temperature and humidty sensor.
1. Add variables or needed libraries
2. Add sensor specific code to `sensor_init` in [`sensor.cpp`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/sensor.cpp)
3. Add sensor specific code to `sensor_read` function in [`sensor.cpp`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/sensor.cpp)
4. Add Payload functions to [`payload.h`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/include/payload.h) and [`payload.cpp`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/payload.cpp) (Optional)
5. Use payload functions in [`sensor.cpp`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/sensor.cpp) to send sensor data
## Example 1: Custom Temperature and Humidity Sensor *GY-21*
To use a custom sensor you first have to enable the Sensor which you want to use. For this you have to edit or add `HAS_SENSOR_1` in either the `paxcounter.conf` or the `hal` file of your board.
=== "Activate Sensor 1"
```c linenums="132" title="src/paxcounter_orig.conf"
#define HAS_SENSOR_1 1
```
=== "Activate Sensor 2"
```c linenums="132" title="src/paxcounter_orig.conf"
#define HAS_SENSOR_2 1
```
=== "Activate Sensor 3"
```c linenums="132" title="src/paxcounter_orig.conf"
#define HAS_SENSOR_3 1
```
You might also add a constant for your custom sensor in the `paxcounter.conf` file. This is optional but can be used to identify the sensor type.
```c linenums="133" title="src/paxcounter_orig.conf"
#define HAS_GY21 1 // (1)
```
1. See usage of this in the example below
### 1. Add variables or needed libraries
If you want to use any libary for you custom sensor you have to add it to the `platformio.ini` file.
In this example we use the [`HTU2xD_SHT2x_Si70xx`](https://github.com/enjoyneering/HTU2xD_SHT2x_Si70xx.git) for the GY-21 sensor.
<!-- FIXME comments did not work for ini file type-->
```yaml linenums="127" title="platformio.ini"
[env:usb] # (1)
upload_protocol = esptool
lib_deps = # (2)
${common.lib_deps_all}
https://github.com/enjoyneering/HTU2xD_SHT2x_Si70xx.git
```
1. Selected the env you want to use. In this example we use the `usb` env.
2. Add the libary to the `lib_deps` section.
Add the import of libary in the `sensor.cpp` file.
```c linenums="5" title="sensor.cpp"
#if (HAS_GY21) // (1)
#include <HTU2xD_SHT2x_Si70xx.h>
HTU2xD_SHT2x_SI70xx ht2x(HTU2xD_SENSOR, HUMD_12BIT_TEMP_14BIT); // sensor type, resolution
double temperature, humidity;
#endif // HAS_GY21
```
1. Define `HAS_GY21` either in hal file of your board or in `paxcounter.conf` file.
### 2. Add sensor specific code to `sensor_init` function
```c linenums="1" title="src/sensor.cpp"
#if (HAS_GY21) // (1)
if (ht2x.begin() != true) // reset sensor, set heater off, set resolution, check power
// (sensor doesn't operate correctly if VDD < +2.25v)
{
ESP_LOGE(TAG, "HTU2xD/SHT2x not connected, fail or VDD < +2.25v");
} else {
ESP_LOGE(TAG, "HTU2xD/SHT2x/GY21 found");
}
#endif // HAS_GY21
```
1. Define `HAS_GY21` either in hal file of your board or in `paxcounter.conf` file.
### 3. Add sensor specific code to sensor_read function
In this case we choose that our custom sensor is Sensor 3. This means the data will be sent on `SENSOR3PORT` which is by default `12`. You can change this in the `paxcounter.conf` file.
```c linenums="78" title="src/sensor.cpp"
case 3:
#if (HAS_GY21)
ESP_LOGE(TAG, "Reading Sensor 3, GY21"); // (1)
temperature =
ht2x.readTemperature(); // accuracy +-0.3C in range 0C..60C at 14-bit
delay(100);
humidity =
ht2x.readHumidity(); // accuracy +-2% in range 20%..80%/25C at 12-bit
ESP_LOGE(TAG, "GY21: Temperature: %f", temperature); // (2)
ESP_LOGE(TAG, "GY21: Humidity: %f", humidity); // (3)
#endif // HAS_GY21
break;
```
1. These logs are only for debugging. You can remove them if you want.
2. These logs are only for debugging. You can remove them if you want.
3. These logs are only for debugging. You can remove them if you want.
### 4. Payload functions for a custom sensor
If you have added your custom sensor code as described before you can also add custom payload function if you need others than the provided ones. For this you have to change two files. First you have to add your payload function to the `payload.h` file.
=== "Example for a custom temperature / humidity payload function"
```c linenums="57" title="src/payload.h"
void addTempHum(float temperature, float humidity);
```
Then you have to add your payload function to the `payload.cpp` file. You can provide functions for all payload formates (see [Payload Formats](../payloadformat.md)) or just add it for the one you are using.
Example for a custom temperature / humidity payload function
=== "Plain payload format"
```c linenums="128" title="src/payload.cpp"
void PayloadConvert::addTempHum(float temperature, float humidity) {
int16_t temperature = (int16_t)(temperature); // float -> int
uint16_t humidity = (uint16_t)(humidity); // float -> int
buffer[cursor++] = highByte(temperature);
buffer[cursor++] = lowByte(temperature);
buffer[cursor++] = highByte(humidity);
buffer[cursor++] = lowByte(humidity);
}
```
=== "Packed payload format"
```c linenums="230" title="src/payload.cpp"
void PayloadConvert::addTempHum(float temperature, float humidity) {
writeFloat(temperature);
writeFloat(humidity);
}
```
=== "Cayenne payload format"
```c linenums="488" title="src/payload.cpp"
void PayloadConvert::addTempHum(float temperature, float humidity) {
// data value conversions to meet cayenne data type definition
// 0.1°C per bit => -3276,7 .. +3276,7 °C
int16_t temp = temperature * 10;
// 0.5% per bit => 0 .. 128 %C
uint16_t hum = humidity * 2;
#if (PAYLOAD_ENCODER == 3)
buffer[cursor++] = LPP_TEMPERATURE_CHANNEL;
#endif
buffer[cursor++] = LPP_TEMPERATURE; // 2 bytes 0.1 °C Signed MSB
buffer[cursor++] = highByte(temperature);
buffer[cursor++] = lowByte(temperature);
#if (PAYLOAD_ENCODER == 3)
buffer[cursor++] = LPP_HUMIDITY_CHANNEL;
#endif
buffer[cursor++] = LPP_HUMIDITY; // 1 byte 0.5 % Unsigned
buffer[cursor++] = humidity;
}
```
### 5. Sending the data
After you have added your custom sensor code and payload function you can send the data. For this you have to add the following code to the `sensor.cpp` file.
```c linenums="78" title="src/sensor.cpp" hl_lines="11"
case 3:
#if (HAS_GY21)
ESP_LOGE(TAG, "Reading Sensor 3, GY21");
temperature =
ht2x.readTemperature(); // accuracy +-0.3C in range 0C..60C at 14-bit
delay(100);
humidity =
ht2x.readHumidity(); // accuracy +-2% in range 20%..80%/25C at 12-bit
ESP_LOGE(TAG, "GY21: Temperature: %f", temperature);
ESP_LOGE(TAG, "GY21: Humidity: %f", humidity);
payload.addTempHum(temperature, humidity); // (1)
#endif // HAS_GY21
break;
```
1. Add your custom payload function here.
Now you can build and upload the code to your ESP. Do not forget to erase the flash before uploading since you probably changed the `paxcounter.conf` file.

148
docs/configuration/index.md Normal file
View File

@ -0,0 +1,148 @@
# Configuration
## Sensors and Peripherals
You can add up to 3 user defined sensors. Insert your sensor's payload scheme in [`sensor.cpp`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/sensor.cpp). More examples and a detailed description can be found in the [sensor documentation](custom-sensors.md).
### Supported Peripherals
* Bosch BMP180 / BME280 / BME680
* SDS011
* RTC DS3231
* generic serial NMEA GPS
* I2C Lopy GPS
For these peripherals no additional code is needed. To activate configure them in the board's hal file before building the code.
See [`generic.h`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/hal/generic.h) for all options and for proper configuration of BME280/BME680.
=== "BME/ BMP Configuration"
```c linenums="37" title="src/hal/generic.h"
--8<-- "src/hal/generic.h:37:49"
```
=== "SDS011 Configuration"
```c linenums="51" title="src/hal/generic.h"
--8<-- "src/hal/generic.h:51:56"
```
=== "Custom Sensors Configuration"
```c linenums="57" title="src/hal/generic.h"
--8<-- "src/hal/generic.h:57:60"
```
=== "Complete `generic.h`"
```c linenums="1" title="src/hal/generic.h"
--8<-- "src/hal/generic.h"
```
Output of user sensor data can be switched by user remote control command `0x14` sent to Port 2.
Output of sensor and peripheral data is internally switched by a bitmask register. Default mask can be tailored by editing *cfg.payloadmask* initialization value in [`configmanager.cpp`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/configmanager.cpp) following this scheme:
| Bit | Sensordata | Default |
| --- | ------------- | ------- |
| 0 | Paxcounter | on |
| 1 | unused | off |
| 2 | BME280/680 | on |
| 3 | GPS* | on |
| 4 | User sensor 1 | on |
| 5 | User sensor 2 | on |
| 6 | User sensor 3 | on |
| 7 | Batterylevel | off |
\*) GPS data can also be combined with paxcounter payload on port 1, `#define GPSPORT 1` in paxcounter.conf to enable
```c linenums="102" title="src/paxcounter_orig.conf"
--8<-- "src/paxcounter_orig.conf:102:102"
```
## Power saving mode
Paxcounter supports a battery friendly power saving mode. In this mode the device enters deep sleep, after all data is polled from all sensors and the dataset is completeley sent through all user configured channels (LORAWAN / SPI / MQTT / SD-Card). Set `#define SLEEPCYCLE` in paxcounter.conf to enable power saving mode and to specify the duration of a sleep cycle.
```c linenums="20" title="src/paxcounter_orig.conf"
--8<-- "src/paxcounter_orig.conf:20:20"
```
Power consumption in deep sleep mode depends on your hardware, i.e. if on board peripherals can be switched off or set to a chip specific sleep mode either by MCU or by power management unit (PMU) as found on TTGO T-BEAM v1.0/V1.1. See [`power.cpp`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/power.cpp) for power management, and [`reset.cpp`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/reset.cpp) for sleep and wakeup logic.
## Time sync
Paxcounter can keep a time-of-day synced with external or on board time sources. Set `#define TIME_SYNC_INTERVAL` in `paxcounter.conf` to enable time sync.
```c linenums="88" title="src/paxcounter_orig.conf"
--8<-- "src/paxcounter_orig.conf:88:88"
```
Supported external time sources are GPS, LORAWAN network time and LORAWAN application timeserver time. Supported on board time sources are the RTC of ESP32 and a DS3231 RTC chip, both are kept sycned as fallback time sources. Time accuracy depends on board's time base which generates the pulse per second. Supported are GPS PPS, SQW output of RTC, and internal ESP32 hardware timer. Time base is selected by #defines in the board's hal file, see example in [`generic.h`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/hal/generic.h).
```c linenums="87" title="src/hal/generic.h"
--8<-- "src/hal/generic.h:87:96"
```
!!! tip
If your LORAWAN network does not support network time, you can run a Node-Red timeserver application using the enclosed [**Timeserver code**](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/Node-RED/Timeserver.json). Configure the MQTT nodes in Node-Red for the LORAWAN application used by your paxocunter device. Time can also be set without precision liability, by simple remote command, see section remote control.
## Wall clock controller
Paxcounter can be used to sync a wall clock which has a DCF77 or IF482 time telegram input. Set `#define HAS_IF482` or `#define HAS_DCF77` in board's hal file to setup clock controller. Use case of this function is to integrate paxcounter and clock. Accurary of the synthetic DCF77 signal depends on accuracy of on board's time base, see above.
## Mobile PaxCounter using <A HREF="https://opensensemap.org/">openSenseMap</A>
This describes how to set up a mobile PaxCounter:<br> Follow all steps so far for preparing the device, selecting the packed payload format. In `paxcounter.conf` set `PAYLOAD_OPENSENSEBOX` to `1`.
```c linenums="60" title="src/paxcounter_orig.conf"
--8<-- "src/paxcounter_orig.conf:60:60"
```
Register a new sensebox on [https://opensensemap.org/](https://opensensemap.org). In the sensor configuration select "TheThingsNetwork" and set decoding profile to "LoRa serialization". Enter your TTN Application and Device ID. Setup decoding option using:
```json
[{"decoder":"latLng"},{"decoder":"uint16",sensor_id":"yoursensorid"}]
```
## SD-card
Data can be stored on SD-card if the board provides an SD card interface, either with SPI or MMC mode. To enable this feature, specify interface mode and hardware pins in board's hal file (`src/hal/<board.h\>`):
```c
#define HAS_SDCARD 1 // SD-card interface, using SPI mode
//OR
#define HAS_SDCARD 2 // SD-card interface, using MMC mode
// Pins for SPI interface
#define SDCARD_CS (13) // fill in the correct numbers for your board
#define SDCARD_MOSI (15)
#define SDCARD_MISO (2)
#define SDCARD_SCLK (14)
```
This is an example of a board with MMC SD-card interface: [https://www.aliexpress.com/item/32915894264.html](https://www.aliexpress.com/item/32915894264.html). For this board use file [`src/hal/ttgov21new.h`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/hal/ttgov21new.h) and add the lines given above.
Another approach would be this tiny board: [https://www.aliexpress.com/item/32424558182.html](https://www.aliexpress.com/item/32424558182.html) (needs 5V).
In this case you choose the correct file for your ESP32-board in the src/hal-directory and add the lines given above. Edit the pin numbers given in the example, according to your wiring.
Data is written on SD-card to a single file. After 3 write operations the data is flushed to the disk to minimize flash write cycles. Thus, up to the last 3 records of data will get lost when the Paxcounter looses power during operation.
Format of the resulting file is CSV, thus easy import in LibreOffice, Excel, InfluxDB, etc. Each record contains timestamp (in ISO8601 format), paxcount (wifi and ble) and battery voltage (optional). Voltage is logged if the device has a battery voltage sensor (to be configured in board hal file).
File contents example:
```csv
timestamp,wifi,ble[,voltage]
2022-01-30T21:12:41Z,11,25[,4100]
2022-01-30T21:14:24Z,10,21[,4070]
2022-01-30T21:16:08Z,12,26[,4102]
2022-01-30T21:17:52Z,11,26[,4076]
```
If you want to change this, modify `src/sdcard.cpp` and `include/sdcard.h`.
Additionally, it's possible to redirect system console output to a plain text file on SD card. This can be useful for debugging headless devices in the field. In `paxcounter.conf` set `SDLOGGING` to `1`.
```c linenums="16" title="src/paxcounter_orig.conf"
--8<-- "src/paxcounter_orig.conf:16:16"
```

32
docs/display-led.md Normal file
View File

@ -0,0 +1,32 @@
# Display
<!-- TODO update image -->
![Display Image](img/Paxcounter-Screen.png)
If you're using a device with OLED display, or if you add such one to the I2C bus, the device shows live data on the display. You can flip display pages showing
- recent count of pax
- histogram
- GPS data
- BME sensor data
- time of day
- blank page
by pressing the button of the device.
# LED blink pattern
**Mono color LED:**
- Single Flash (50ms): seen a new Wifi or BLE device
- Quick blink (20ms on each 1/5 second): joining LoRaWAN network in progress or pending
- Small blink (10ms on each 1/2 second): LoRaWAN data transmit in progress or pending
- Long blink (200ms on each 2 seconds): LoRaWAN stack error
**RGB LED:**
- Green: seen a new Wifi device
- Magenta: seen a new BLE device
- Yellow: joining LoRaWAN network in progress or pending
- Pink: LORAWAN MAC transmit in progress
- Blue: LoRaWAN data transmit in progress or pending
- Red: LoRaWAN stack errors

129
docs/getting-started.md Normal file
View File

@ -0,0 +1,129 @@
# Preparing
## Install Platformio
Install <A HREF="https://platformio.org/">PlatformIO IDE for embedded development</A> to build this project. Platformio integrates with your favorite IDE, choose e.g. [Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=platformio.platformio-ide), Atom, Eclipse etc.
Compile time configuration is spread across several files. Before compiling the code, edit or create the following files:
## platformio.ini
Edit `platformio_orig.ini` (for ESP32 CPU based boards) *or* `platformio_orig_s3.ini` (for ESP32-S3 CPU based boards) and select desired board in section **board**. To add a new board, create an appropriate hardware abstraction layer file in hal subdirectory, and add a pointer to this file in section **board**. Copy or rename to `platformio.ini` in the root directory of the project. Now start Platformio.
### Selecting a board
```ini linenums="6" title="Uncomment your board"
--8<-- "platformio_orig.ini:6:36"
```
=== "Copy"
``` bash
cp platformio_orig.ini platformio.ini
```
=== "Rename"
``` bash
mv platformio_orig.ini platformio.ini
```
??? info "platformio_orig_s3.ini"
=== "Copy"
``` bash
cp platformio_orig_s3.ini platformio.ini
```
=== "Rename"
``` bash
mv platformio_orig_s3.ini platformio.ini
```
!!! info
Platformio is looking for `platformio.ini` in the root directory and won't start if it does not find this file!
## paxcounter.conf
Edit `src/paxcounter_orig.conf` and tailor settings in this file according to your needs and use case. Please take care of the duty cycle regulations of the LoRaWAN network you're going to use. Copy or rename to `src/paxcounter.conf`.
=== "Copy"
``` bash
cp src/paxcounter_orig.conf src/paxcounter.conf
```
=== "Rename"
``` bash
mv src/paxcounter_orig.conf src/paxcounter.conf
```
If your device has a **real time clock** it can be updated by either LoRaWAN network or GPS time, according to settings *TIME_SYNC_INTERVAL* and *TIME_SYNC_LORAWAN* in `paxcounter.conf`.
```c linenums="85" title="paxcounter.conf"
--8<-- "src/paxcounter_orig.conf:85:85"
```
## src/lmic_config.h
Edit `src/lmic_config.h` and tailor settings in this file according to your country and device hardware. Please take care of national regulations when selecting the frequency band for LoRaWAN.
```c linenums="9" title="national regulations in src/lmic_config.h "
--8<-- "src/lmic_config.h:9:18"
```
## src/loraconf.h
Create file `src/loraconf.h` using the template [src/loraconf_sample.h](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/loraconf_sample.h) and adjust settings to use your personal values. To join the network and activate your paxcounter, you must configure either OTAA or ABP join method. You should use OTAA, whenever possible. To understand the differences of the two methods, [this article](https://www.thethingsnetwork.org/docs/devices/registration.html) may be useful.
=== "Copy"
``` bash
cp src/loraconf_sample.h src/loraconf.h
```
=== "Rename"
``` bash
mv src/loraconf_sample.h src/loraconf.h
```
To configure OTAA, leave `#define LORA_ABP` deactivated (commented). To use ABP, activate (uncomment) `#define LORA_ABP` in the file `src/loraconf.h`.
The file `src/loraconf_sample.h` contains more information about the values to provide.
=== "Activate OTAA (Default), Deactivate ABP"
``` c linenums="18" title="src/loraconf.h"
--8<-- "src/loraconf_sample.h:18:18"
```
=== "Deactivate OTAA, Activate ABP"
``` c linenums="18" title="src/loraconf.h"
#define LORA_ABP
```
## src/ota.conf
Create file `src/ota.conf` using the template [src/ota_sample.conf](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/ota_sample.conf) and enter your WIFI network & key. These settings are used for downloading updates via WiFi, either from a remote https server, or locally via WebUI. If you want to use a remote server, you need a <A HREF="https://github.com/paxexpress/docs">PAX.express repository</A>. Enter your PAX.express credentials in ota.conf. If you don't need wireless firmware updates just rename ota.sample.conf to ota.conf.
=== "Copy"
``` bash
cp src/ota_sample.conf src/ota.conf
```
=== "Rename"
``` bash
mv src/ota_sample.conf src/ota.conf
```
# Building
Use <A HREF="https://platformio.org/">PlatformIO</A> with your preferred IDE for development and building this code. Make sure you have latest PlatformIO version.
# Uploading
!!! warning
1. After editing `paxcounter.conf`, use "clean" button before "build" in PlatformIO!
2. Clear NVRAM of the board to delete previous stored runtime settings (`pio run -t erase`)
- **by cable, via USB/UART interface:**
To upload the code via cable to your ESP32 board this needs to be switched from run to bootloader mode. Boards with USB bridge like Heltec and TTGO usually have an onboard logic which allows soft switching by the upload tool. In PlatformIO this happenes automatically.<p>
The LoPy/LoPy4/FiPy board needs to be set manually. See these
<A HREF="https://www.thethingsnetwork.org/labs/story/program-your-lopy-from-the-arduino-ide-using-lmic">instructions</A> how to do it. Don't forget to press on board reset button after switching between run and bootloader mode.<p>
The original Pycom firmware is not needed, so there is no need to update it before flashing Paxcounter. Just flash the compiled paxcounter binary (.elf file) on your LoPy/LoPy4/FiPy. If you later want to go back to the Pycom firmware, download the firmware from Pycom and flash it over.
- **over the air (OTA), download via WiFi:**
After the ESP32 board is initially flashed and has joined a LoRaWAN network, the firmware can update itself by OTA. This process is kicked off by sending a remote control command (see below) via LoRaWAN to the board. The board then tries to connect via WiFi to a cloud service (<A HREF="https://github.com/paxexpress">PAX.express</A>), checks for update, and if available downloads the binary and reboots with it. If something goes wrong during this process, the board reboots back to the current version. Prerequisites for OTA are: 1. You own a PAX.express repository, 2. you pushed the update binary to your PAX.express repository, 3. internet access via encrypted (WPA2) WiFi is present at the board's site, 4. WiFi credentials were set in ota.conf and initially flashed to the board. Step 2 runs automated, just enter the credentials in ota.conf and set `upload_protocol = custom` in platformio.ini. Then press build and lean back watching platformio doing build and upload.
- **over the air (OTA), upload via WiFi:**
If option *BOOTMENU* is defined in `paxcounter.conf`, the ESP32 board will try to connect to a known WiFi access point each time cold starting (after a power cycle or a reset), using the WiFi credentials given in `ota.conf`. Once connected to the WiFi it will fire up a simple webserver, providing a bootstrap menu waiting for a user interaction (pressing "START" button in menu). This process will time out after *BOOTDELAY* seconds, ensuring booting the device to runmode. Once a user interaction in bootstrap menu was detected, the timeout will be extended to *BOOTTIMEOUT* seconds. During this time a firmware upload can be performed manually by user, e.g. using a smartphone in tethering mode providing the firmware upload file.

76
docs/hardware.md Normal file
View File

@ -0,0 +1,76 @@
# Hardware
### Supported ESP32 based boards:
*With LoRa radio data transfer*:
- **LilyGo: [Paxcounter-Board*](https://www.aliexpress.com/item/32915894264.html?spm=a2g0o.productlist.0.0.3d656325QrcfQc&algo_pvid=4a150199-63e7-4d21-bdb1-b48164537744&algo_exp_id=4a150199-63e7-4d21-bdb1-b48164537744-2&pdp_ext_f=%7B%22sku_id%22%3A%2212000023374441919%22%7D)**
- TTGO: T1*, T2*, T3*, T-Beam, T-Fox
- Heltec: LoRa-32 v1 and v2
- Pycom: LoPy, LoPy4, FiPy
- Radioshuttle.de: [ECO Power Board](https://www.radioshuttle.de/esp32-eco-power/esp32-eco-power-board/)
- WeMos: LoLin32 + [LoraNode32 shield](https://github.com/hallard/LoLin32-Lora),
LoLin32lite + [LoraNode32-Lite shield](https://github.com/hallard/LoLin32-Lite-Lora)
- Adafruit ESP32 Feather + LoRa Wing + OLED Wing, #IoT Octopus32 (Octopus + ESP32 Feather)
- M5Stack: [Basic Core IoT*](https://m5stack.com/collections/m5-core/products/basic-core-iot-development-kit) + [Lora Module RA-01H](https://m5stack.com/collections/m5-module/products/lora-module-868mhz), [Fire IoT*](https://m5stack.com/collections/m5-core/products/fire-iot-development-kit)
*Without LoRa*:
- LilyGo: [T-Dongle S3*](https://github.com/Xinyuan-LilyGO/T-Dongle-S3)
- Pyom: WiPy
- WeMos: LoLin32, LoLin32 Lite, WeMos D32, [Wemos32 Oled](https://www.instructables.com/id/ESP32-With-Integrated-OLED-WEMOSLolin-Getting-Star/)
- Crowdsupply: [TinyPICO](https://www.crowdsupply.com/unexpected-maker/tinypico)
- TTGO: [T-Display](https://www.aliexpress.com/item/33048962331.html)
- TTGO: [T-Wristband](https://www.aliexpress.com/item/4000527495064.html)
- Generic ESP32
*) supports microSD/TF-card for local logging of paxcounter data
Depending on board hardware following features are supported:
- LoRaWAN communication, supporting various payload formats (see enclosed .js converters)
- MQTT communication via TCP/IP and Ethernet interface (note: payload transmitted over MQTT will be base64 encoded)
- SPI serial communication to a local host
- [LED](display-led.md) (shows power & status)
- [OLED Display](display-led.md) (shows detailed status)
- RGB LED (shows colorized status)
- Button (short press: flip display page / long press: send alarm message)
- Battery voltage monitoring (analog read / AXP192 / IP5306)
- GPS (Generic serial NMEA, or Quectel L76 I2C)
- Environmental sensors (Bosch BMP180/BME280/BME680 I2C; SDS011 serial)
- Real Time Clock (Maxim DS3231 I2C)
- IF482 (serial) and DCF77 (gpio) time telegram generator
- Switch external power / battery
- LED Matrix display (similar to [this 64x16 model](https://www.instructables.com/id/64x16-RED-LED-Marquee/), can be ordered on [Aliexpress](https://www.aliexpress.com/item/P3-75-dot-matrix-led-module-3-75mm-high-clear-top1-for-text-display-304-60mm/32616683948.html))
- SD-card (see section SD-card here) for logging pax data
Target platform must be selected in `platformio.ini`.<br>
Hardware dependent settings (pinout etc.) are stored in board files in [/hal](https://github.com/cyberman54/ESP32-Paxcounter/tree/master/src/hal) directory. If you want to use a ESP32 board which is not yet supported, use hal file generic.h and tailor pin mappings to your needs. Pull requests for new boards welcome.<br>
### 3D printed cases
Some 3D printable cases can be found (and, if wanted so, ordered) on Thingiverse, see
- <A HREF="https://www.thingiverse.com/thing:2670713">Heltec</A>
- <A HREF="https://www.thingiverse.com/thing:2811127">TTGOv2</A>
- <A HREF="https://www.thingiverse.com/thing:3005574">TTGOv2.1</A>
- <A HREF="https://www.thingiverse.com/thing:3385109">TTGO</A>
- <A HREF="https://www.thingiverse.com/thing:3041339">T-BEAM</A>
- <A HREF="https://www.thingiverse.com/thing:3203177">T-BEAM parts</A>
### Power consumption
<b>Power consumption</b> was metered at around 450 - 1000mW, depending on board and user settings in `paxcounter.conf`.
By default, bluetooth sniffing is not started. If you enable bluetooth be aware that this goes on expense of wifi sniffing results, because then wifi and bt stack must share the 2,4 GHz RF ressources of ESP32. If you need to sniff wifi and bt in parallel and need best possible results, use two boards - one for wifi only and one for bt only - and add counted results.
=== "Deactivate BLE sniffing (Default)"
``` c linenums="29" title="paxcounter.conf"
#define BLECOUNTER 0
```
=== "Activate BLE sniffing"
``` c linenums="29" title="paxcounter.conf"
#define BLECOUNTER 1
```

View File

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

View File

Before

Width:  |  Height:  |  Size: 4.2 MiB

After

Width:  |  Height:  |  Size: 4.2 MiB

View File

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 47 KiB

View File

Before

Width:  |  Height:  |  Size: 2.4 MiB

After

Width:  |  Height:  |  Size: 2.4 MiB

View File

Before

Width:  |  Height:  |  Size: 167 KiB

After

Width:  |  Height:  |  Size: 167 KiB

View File

Before

Width:  |  Height:  |  Size: 292 KiB

After

Width:  |  Height:  |  Size: 292 KiB

View File

Before

Width:  |  Height:  |  Size: 229 KiB

After

Width:  |  Height:  |  Size: 229 KiB

View File

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 74 KiB

View File

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 56 KiB

View File

Before

Width:  |  Height:  |  Size: 131 KiB

After

Width:  |  Height:  |  Size: 131 KiB

View File

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

View File

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

42
docs/index.md Normal file
View File

@ -0,0 +1,42 @@
# ESP32-Paxcounter
![logo](assets/paxcounter_logo_white.png)
**Wifi & Bluetooth driven, LoRaWAN enabled, battery powered mini Paxcounter built on cheap ESP32 LoRa IoT boards**
[Tutorial (in german language)](https://www.heise.de/select/make/2019/1/1551099236518668)
[![CodeFactor](https://www.codefactor.io/repository/github/cyberman54/esp32-paxcounter/badge)](https://www.codefactor.io/repository/github/cyberman54/esp32-paxcounter)
[![PlatformIO CI](https://github.com/cyberman54/ESP32-Paxcounter/actions/workflows/build.yml/badge.svg?event=push)](https://github.com/cyberman54/ESP32-Paxcounter/actions/workflows/build.yml)
---
**Documentation**: <a href="https://cyberman54.github.io/ESP32-Paxcounter" target="_blank">https://cyberman54.github.io/ESP32-Paxcounter</a>
**Source Code**: <a href="https://github.com/cyberman54/ESP32-Paxcounter" target="_blank">https://github.com/cyberman54/ESP32-Paxcounter</a>
---
## Use case
Paxcounter is an [ESP32](https://www.espressif.com/en/products/socs/esp32) MCU based device for metering passenger flows in realtime. It counts how many mobile devices are around. This gives an estimation how many people are around. Paxcounter detects Wifi and Bluetooth signals in the air, focusing on mobile devices by evaluating their MAC adresses.
!!! info
Intention of this project is to do this without intrusion in privacy: You don't need to track people owned devices, if you just want to count them. Therefore, Paxcounter does not persistenly store MAC adresses and *does no kind of fingerprinting the scanned devices.
Data can either be be stored on a local SD-card, transferred to cloud using LoRaWAN network (e.g. TheThingsNetwork or Helium) or MQTT over TCP/IP, or transmitted to a local host using serial (SPI) interface.
You can build this project battery powered using ESP32 deep sleep mode and reach long uptimes with a single 18650 Li-Ion cell.
## Impressions
<img src="img/Paxcounter-title.jpg">
<img src="img/Paxcounter-ttgo.jpg">
<img src="img/Paxcounter-lolin.gif">
<img src="img/Paxcounter-Screen.png">
<img src="img/TTGO-case.jpg">
<img src="img/TTGO-curves.jpg">
<img src="img/Paxcounter-LEDmatrix.jpg">
<img src="img/Paxcounter-Clock2.png">
<img src="img/Paxcounter-ttgo-twristband.jpg">

23
docs/integrations.md Normal file
View File

@ -0,0 +1,23 @@
# Integration LoRaWAN
## "The Things Stack Community Edition" aka "The Things Stack V3"
To use the ESP32-Paxcounter in The Things Stack Community Edition you need an account to reach the console. Go to:
- [The Things Stack Community Edition Console](https://console.cloud.thethings.network/)
- choose your region and go to applications
- create an application by clicking "**+ Add application**" and give it a id, name, etc.
- create a device by clicking "**+ Add end device**"
- Select the end device: choose the Brand "**Open Source Community Projects**" and the Model "**ESP32-Paxcounter**", leave Hardware Version to "**Unknown**" and select your **Firmware Version** and **Profile (Region)**
- Enter registration data: choose the **frequency plan** (for EU choose the recommended), set the **AppEUI** (Fill with zeros), set the **DeviceEUI** (generate), set the **AppKey** (generate), choose a **device ID** and hit "Register end device"
- got to Applications -> "your App ID" -> Payload formatters -> Uplink, choose "**Repository**" and hit "Save changes"
The "Repository" payload decoder uses the packed format, explained below. If you want to use MyDevices from Cayenne you should use the Cayenne payload decoder instead.
## TTN Mapper
If you want your devices to be feeding the [TTN Mapper](https://ttnmapper.org/), just follow this manual: [https://docs.ttnmapper.org/integration/tts-integration-v3.html](https://docs.ttnmapper.org/integration/tts-integration-v3.html) - different than indicated in the manual you can leave the payload decoder to "Repository" for the ESP32-Paxcounter and you are fine.
## ChirpStack
!!! todo

20
docs/legalnote.md Normal file
View File

@ -0,0 +1,20 @@
# Legal note
**Depending on your country's laws it may be illegal to sniff wireless networks for MAC addresses. Please check and respect your country's laws before using this code!**
- (e.g. US citizens may want to check [Section 18 U.S. Code § 2511](https://www.law.cornell.edu/uscode/text/18/2511) and [discussion](https://github.com/schollz/howmanypeoplearearound/issues/4) on this)
- (e.g. UK citizens may want to check [Data Protection Act 1998](https://ico.org.uk/media/1560691/wi-fi-location-analytics-guidance.pdf) and [GDPR 2018](https://ico.org.uk/for-organisations/guide-to-the-general-data-protection-regulation-gdpr/key-definitions/))
- (e.g. Citizens in the the Netherlands and EU may want to read [this article](https://www.ivir.nl/publicaties/download/PrivacyInformatie_2016_6.pdf) and [this article](https://autoriteitpersoonsgegevens.nl/nl/nieuws/europese-privacytoezichthouders-publiceren-opinie-eprivacyverordening) and [this decision](https://edpb.europa.eu/news/national-news/2021/dutch-dpa-fines-municipality-wi-fi-tracking_en))
- (e.g. Citizens in Germany may want to read [this article of Wissenschaftliche Dienste des Deutschen Bundestages](https://www.bundestag.de/resource/blob/538890/3dfae197d2c930693aa16d1619204f58/WD-3-206-17-pdf-data.pdf))
!!! info
If you use this software you do this at your own risk. That means that you alone - not the authors of this software - are responsible for the legal compliance of an application using this or build from this software and/or usage of a device created using this software. You should take special care and get prior legal advice if you plan metering passengers in public areas and/or publish data drawn from doing so.
# Privacy disclosure
Paxcounter generates identifiers for sniffed Wifi or Bluetooth MAC adresses and and collects them temporary in the device's RAM for a configurable scan cycle time (default 60 seconds). After each scan cycle the collected identifiers are cleared. Identifiers are generated by using the last 2 bytes of universal MAC adresses. Personal MAC adresses remain untouched and are not evaluated. Identifiers and MAC adresses are never transferred to the LoRaWAN network. No persistent storing of MAC adresses, identifiers or timestamps and no other kind of analytics than counting are implemented in this code. Wireless networks are not touched by this code, but MAC adresses from wireless devices as well within as not within wireless networks, regardless if encrypted or unencrypted, are sniffed and processed by this code.

35
docs/license-credits.md Normal file
View File

@ -0,0 +1,35 @@
# License
Copyright 2018-2022 Oliver Brandmueller <ob@sysadm.in>
Copyright 2018-2022 Klaus Wilting <verkehrsrot@arcor.de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
!!! info
Parts of the source files in this repository are made available under different licenses,
see file <A HREF="https://github.com/cyberman54/ESP32-Paxcounter/blob/master/LICENSE">LICENSE.txt</A> in this repository. Refer to each individual source file for more details.
# Credits
Thanks to
- [Oliver Brandmüller](https://github.com/spmrider) for idea and initial setup of this project
- [Charles Hallard](https://github.com/hallard) for major code contributions to this project
- [robbi5](https://github.com/robbi5) for the payload converter
- [Caspar Armster](https://www.dasdigidings.de/) for the The Things Stack V3 payload converter
- [terrillmoore](https://github.com/mcci-catena) for maintaining the LMIC for arduino LoRaWAN stack
- [sbamueller](https://github.com/sbamueller) for writing the tutorial in Make Magazine
- [Stefan](https://github.com/nerdyscout) for paxcounter opensensebox integration
- [August Quint](https://github.com/AugustQu) for adding SD card data logger and SDS011 support
- [t-huyeng](https://github.com/t-huyeng) for adding a CI workflow and rework documentation

107
docs/payloadformat.md Normal file
View File

@ -0,0 +1,107 @@
# Payload format
You can select different payload formats in [`paxcounter.conf`](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/paxcounter_orig.conf):
- ***Plain*** uses big endian format and generates json fields, e.g. useful for TTN console
- ***Packed*** uses little endian format and generates json fields
- [***CayenneLPP***](https://mydevices.com/cayenne/docs/lora/#lora-cayenne-low-power-payload-reference-implementation) generates MyDevices Cayenne readable fields
```c linenums="20" title="src/paxcounter_orig.conf"
--8<-- "src/paxcounter_orig.conf:20:20"
```
!!! danger "Decrepated information from the things network v2"
If you're using [TheThingsNetwork](https://www.thethingsnetwork.org/) (TTN) you may want to use a payload converter. Go to TTN Console - Application - Payload Formats and paste the code example below in tabs Decoder and Converter. This way your MQTT application can parse the fields `pax`, `ble` and `wifi`.
To add your device to myDevices Cayenne platform select "Cayenne-LPP" from Lora device list and use the CayenneLPP payload encoder.
To track a paxcounter device with on board GPS and at the same time contribute to TTN coverage mapping, you simply activate the [TTNmapper integration](https://www.thethingsnetwork.org/docs/applications/ttnmapper/) in TTN Console. Both formats *plain* and *packed* generate the fields `latitude`, `longitude` and `hdop` required by ttnmapper. Important: set TTN mapper port filter to '4' (paxcounter GPS Port).
Hereafter described is the default *plain* format, which uses MSB bit numbering. Under /TTN in this repository you find some ready-to-go decoders which you may copy to your TTN console:
[**plain_decoder.js**](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/TTN/plain_decoder.js) |
[**plain_converter.js**](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/TTN/plain_converter.js) |
[**packed_decoder.js**](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/TTN/packed_decoder.js) |
[**packed_converter.js**](https://github.com/cyberman54/ESP32-Paxcounter/blob/master/src/TTN/packed_converter.js)
**Port #1:** Paxcount data
byte 1-2: Number of unique devices, seen on Wifi [00 00 if Wifi scan disabled]
byte 3-4: Number of unique devices, seen on Bluetooth [ommited if BT scan disabled]
**Port #2:** Device status query result
byte 1-2: Battery or USB Voltage [mV], 0 if no battery probe
byte 3-10: Uptime [seconds]
byte 11: CPU temperature [°C]
bytes 12-15: Free RAM [bytes]
byte 16: Last CPU core 0 reset reason
bytes 17-20: Number of restarts since last power cycle
**Port #3:** Device configuration query result
byte 1: Lora DR (0..15, see rcommand 0x05) [default 5]
byte 2: Lora TXpower (2..15) [default 15]
byte 3: Lora ADR (1=on, 0=off) [default 1]
byte 4: Screensaver status (1=on, 0=off) [default 0]
byte 5: Display status (1=on, 0=off) [default 0]
byte 6: Counter mode (0=cyclic unconfirmed, 1=cumulative, 2=cyclic confirmed) [default 0]
bytes 7-8: RSSI limiter threshold value (negative, MSB) [default 0]
byte 9: Scan and send cycle in seconds/2 (0..255) [default 120]
byte 10: Wifi channel hopping interval in seconds/100 (0..255), 0 means no hopping [default 50]
byte 11: Bluetooth channel switch interval in seconds/100 (0..255) [default 10]
byte 12: Bluetooth scanner status (1=on, 0=0ff) [default 1]
byte 13: Wifi antenna switch (0=internal, 1=external) [default 0]
bytes 14-15: Sleep cycle in seconds/10 (MSB) [default 0]
byte 16: Payloadmask (Bitmask, 0..255, see rcommand 0x14)
byte 17: 0 (reserved)
bytes 18-28: Software version (ASCII format, terminating with zero)
**Port #4:** GPS data (only if device has fature GPS, and GPS data is enabled and GPS has a fix)
bytes 1-4: Latitude
bytes 5-8: Longitude
byte 9: Number of satellites
bytes 10-11: HDOP
bytes 12-13: Altitude [meter]
**Port #5:** Button pressed alarm
byte 1: static value 0x01
**Port #6:** (unused)
**Port #7:** Environmental sensor data (only if device has feature BME)
bytes 1-2: Temperature [°C]
bytes 3-4: Pressure [hPa]
bytes 5-6: Humidity [%]
bytes 7-8: Indoor air quality index (0..500), see below
Indoor air quality classification:
0-50 good
51-100 average
101-150 little bad
151-200 bad
201-300 worse
301-500 very bad
**Port #8:** Battery voltage data (only if device has feature BATT)
bytes 1-2: Battery or USB Voltage [mV], 0 if no battery probe
**Port #9:** Time/Date
bytes 1-4: board's local time/date in UNIX epoch (number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds)
**Ports #10, #11, #12:** User sensor data
Format is specified by user in function `sensor_read(uint8_t sensor)`, see `src/sensor.cpp`.

3
docs/releases.md Normal file
View File

@ -0,0 +1,3 @@
# Releases
See all releases at [https://github.com/cyberman54/ESP32-Paxcounter/releases](https://github.com/cyberman54/ESP32-Paxcounter/releases).

204
docs/remotecontrol.md Normal file
View File

@ -0,0 +1,204 @@
# Remote control
The device listenes for remote control commands on LoRaWAN Port 2. Multiple commands per downlink are possible by concatenating them, but must not exceed a maximum of 10 bytes per downlink.
!!! info
Settings can be stored in NVRAM to make them persistant (reloaded during device startup / restart). To store settings, use command `0x21`.
Send for example `83` `86` as Downlink on Port 2 to get battery status and time/date from the device.
![Remote Control](img/paxcounter_downlink_example.png)
#### 0x01 set scan RSSI limit
1 ... 255 used for wifi and bluetooth scan radius (greater values increase scan radius, values 50...110 make sense)
0 = RSSI limiter disabled [default]
#### 0x02 set counter mode
0 = cyclic unconfirmed, mac counter reset after each wifi scan cycle, data is sent only once [default]
1 = cumulative counter, mac counter is never reset
2 = cyclic confirmed, like 0 but data is resent until confirmation by network received
#### 0x03 set GPS data on/off
0 = GPS data off
1 = GPS data on, sends GPS data on port 4 (default, use port 1 for mobile pax counter), if GPS is present and has a fix
#### 0x04 set display on/off
0 = display off
1 = display on [default]
#### 0x05 set LoRa datarate
0 ... 15 see LoRaWAN regional parameters for details [default: 5]
Example for EU868:
DataRate Configuration Bit/s
0 LoRa: SF12 / 125 kHz 250
1 LoRa: SF11 / 125 kHz 440
2 LoRa: SF10 / 125 kHz 980
3 LoRa: SF9 / 125 kHz 1760
4 LoRa: SF8 / 125 kHz 3125
5 LoRa: SF7 / 125 kHz 5470
6* LoRa: SF7 / 250 kHz 11000
7* FSK: 50 kbps 50000
8 .. 14 reserved for future use (RFU)
15 ignored (device keeps current setting)
*) not supported by TheThingsNetwork
#### 0x06 set LoRa TXpower
0 ... 255 desired TX power in dBm [default: 14]
#### 0x07 set LoRa Adaptive Data Rate mode
0 = ADR off
1 = ADR on [default]
If ADR is set to off, SF value is shown inverted on display.
#### 0x08 do nothing
useful to clear pending commands from LoRaWAN server quere, or to check RSSI on device
#### 0x09 reset functions (send this command UNconfirmed only to avoid boot loops!)
0 = restart device (coldstart)
1 = (reserved, currently does nothing)
2 = reset device to factory settings and restart device
3 = flush send queues
4 = restart device (warmstart)
8 = reboot device to maintenance mode (local web server)
9 = reboot device to OTA update via Wifi mode
#### 0x0A set payload send cycle
5 ... 255 payload send cycle in seconds/2
e.g. 120 -> payload is transmitted each 240 seconds [default]
#### 0x0B set Wifi channel hopping interval timer
0 ... 255 duration for scanning a wifi channel in seconds/100
e.g. 50 -> each channel is scanned for 500 milliseconds [default]
0 means no hopping, scanning on fixed single channel WIFI_CHANNEL_1
#### 0x0C set Bluetooth channel switch interval timer
0 ... 255 duration for scanning a bluetooth advertising channel in seconds/100
e.g. 8 -> each channel is scanned for 80 milliseconds [default]
#### 0x0E set Bluetooth scanner
0 = disabled
1 = enabled [default]
#### 0x0F set WIFI antenna switch (works on LoPy/LoPy4/FiPy only)
0 = internal antenna [default]
1 = external antenna
#### 0x10 set RGB led luminosity (works on LoPy/LoPy4/FiPy and LoRaNode32 shield only)
0 ... 100 percentage of luminosity (100% = full light)
e.g. 50 -> 50% of luminosity [default]
#### 0x13 set user sensor mode
byte 1 = user sensor number (1..3)
byte 2 = sensor mode (0 = disabled / 1 = enabled [default])
#### 0x14 set payload mask
byte 1 = sensor data payload mask (0..255, meaning of bits see below)
0x01 = COUNT_DATA
0x02 = RESERVED_DATA
0x04 = MEMS_DATA
0x08 = GPS_DATA
0x10 = SENSOR_1_DATA
0x20 = SENSOR_2_DATA
0x40 = SENSOR_3_DATA
0x80 = BATT_DATA
bytes can be combined eg COUNT_DATA + SENSOR_1_DATA + BATT_DATA: `0x01 | 0x10 | 0x80 = 0x91`
#### 0x15 set BME data on/off
0 = BME data off
1 = BME data on, sends BME data on port 7 [default]
#### 0x16 set battery data on/off
0 = battery data off [default]
1 = battery data on, sends voltage on port 8
#### 0x17 set Wifi scanner
0 = disabled
1 = enabled [default]
#### 0x18 reserved
unused, does nothing
#### 0x19 set sleep cycle
bytes 1..2 = device sleep cycle in seconds/10 (MSB), 0..65535 (0 = no sleep)
e.g. {0x04, 0xB0} -> device sleeps 200 minutes after each send cycle [default = 0]
#### 0x20 load device configuration
Current device runtime configuration will be loaded from NVRAM, replacing current settings immediately (use with care!)
#### 0x21 store device configuration
Current device runtime configuration is stored in NVRAM, will be reloaded after restart
#### 0x80 get device configuration
Device answers with it's current configuration on Port 3.
#### 0x81 get device status
Device answers with it's current status on Port 2.
#### 0x83 get battery status
Device answers with battery voltage on Port 8.
#### 0x84 get device GPS status
Device answers with it's current status on Port 4.
#### 0x85 get BME280 / BME680 sensor data
Device answers with BME sensor data set on Port 7.
#### 0x86 get time/date
Device answers with it's current time on Port 2:
bytes 1..4 = time/date in UTC epoch seconds (LSB)
byte 5 = time source & status, see below
bits 0..3 time source
0x00 = GPS
0x01 = RTC
0x02 = LORA
0x03 = unsynched
0x04 = set (source unknown)
bits 4..7 esp32 sntp time status
0x00 = SNTP_SYNC_STATUS_RESET
0x01 = SNTP_SYNC_STATUS_COMPLETED
0x02 = SNTP_SYNC_STATUS_IN_PROGRESS
#### 0x87 sync time/date
Device synchronizes it's time/date by calling the preconfigured time source.
#### 0x88 set time/date
bytes 1..4 = time/date to set in UTC epoch seconds (MSB, e.g. https://www.epochconverter.com/hex)

View File

@ -17,6 +17,5 @@ void flushQueues(void);
bool allQueuesEmtpy(void); bool allQueuesEmtpy(void);
void setSendIRQ(TimerHandle_t xTimer); void setSendIRQ(TimerHandle_t xTimer);
void setSendIRQ(void); void setSendIRQ(void);
void initSendDataTimer(uint8_t sendcycle);
#endif // _SENDDATA_H_ #endif // _SENDDATA_H_

View File

@ -21,8 +21,6 @@
#include "BintrayClient.h" #include "BintrayClient.h"
// Local logging tag
static const char TAG[] = __FILE__;
BintrayClient::BintrayClient(const String &user, const String &repository, const String &package) BintrayClient::BintrayClient(const String &user, const String &repository, const String &package)
: m_user(user), m_repo(repository), m_package(package), : m_user(user), m_repo(repository), m_package(package),

55
mkdocs.yml Normal file
View File

@ -0,0 +1,55 @@
site_name: Documentation
site_description: ESP32-Paxcounter Documentation
theme:
name: material
logo: assets/paxcounter_logo_white.svg
favicon: assets/favicon.png
features:
- navigation.instant
- navigation.tracking
- navigation.indexes
- content.code.annotate
palette:
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
toggle:
icon: material/brightness-4
name: Switch to system preference
primary: indigo
nav:
- Intro: index.md
- Hardware: hardware.md
- Getting Started: getting-started.md
- Display & LED: display-led.md
- Legal note: legalnote.md
- Configuration:
- configuration/index.md
- Custom Sensors: configuration/custom-sensors.md
- Integrations: integrations.md
- Payload Format: payloadformat.md
- Remote control: remotecontrol.md
- Licence & Credits: license-credits.md
- Releases: releases.md
markdown_extensions:
- pymdownx.highlight:
anchor_linenums: true
- pymdownx.inlinehilite
- pymdownx.snippets
- pymdownx.superfences
- attr_list
- md_in_html
- admonition
- pymdownx.details
- pymdownx.tabbed:
alternate_style: true
repo_url: https://github.com/cyberman54/ESP32-Paxcounter

View File

@ -46,7 +46,7 @@ description = Paxcounter is a device for metering passenger flows in realtime. I
[common] [common]
; for release_version use max. 10 chars total, use any decimal format like "a.b.c" ; for release_version use max. 10 chars total, use any decimal format like "a.b.c"
release_version = 3.4.3 release_version = 3.4.4
; DEBUG LEVEL: For production run set to 0, otherwise device will leak RAM while running! ; DEBUG LEVEL: For production run set to 0, otherwise device will leak RAM while running!
; 0=None, 1=Error, 2=Warn, 3=Info, 4=Debug, 5=Verbose ; 0=None, 1=Error, 2=Warn, 3=Info, 4=Debug, 5=Verbose
debug_level = 3 debug_level = 3
@ -60,8 +60,8 @@ upload_speed = 115200 ; set by build.py and taken from hal file
lib_deps_lora = lib_deps_lora =
mcci-catena/MCCI LoRaWAN LMIC library @ ^4.1.1 mcci-catena/MCCI LoRaWAN LMIC library @ ^4.1.1
lib_deps_display = lib_deps_display =
https://github.com/bitbank2/OneBitDisplay.git bitbank2/OneBitDisplay @ ^2.2.1
https://github.com/bitbank2/bb_spi_lcd.git bitbank2/bb_spi_lcd @ ^2.4.0
ricmoo/QRCode @ ^0.0.1 ricmoo/QRCode @ ^0.0.1
lib_deps_ledmatrix = lib_deps_ledmatrix =
seeed-studio/Ultrathin_LED_Matrix @ ^1.0.0 seeed-studio/Ultrathin_LED_Matrix @ ^1.0.0
@ -70,14 +70,13 @@ lib_deps_rgbled =
lib_deps_gps = lib_deps_gps =
mikalhart/TinyGPSPlus @ ^1.0.3 mikalhart/TinyGPSPlus @ ^1.0.3
lib_deps_sensors = lib_deps_sensors =
adafruit/Adafruit Unified Sensor @ ^1.1.6 adafruit/Adafruit Unified Sensor @ ^1.1.7
adafruit/Adafruit BME280 Library @ ^2.2.2 adafruit/Adafruit BME280 Library @ ^2.2.2
adafruit/Adafruit BMP085 Library @ ^1.2.1 adafruit/Adafruit BMP085 Library @ ^1.2.1
boschsensortec/BSEC Software Library @ 1.6.1480 boschsensortec/BSEC Software Library @ 1.6.1480
lewapek/Nova Fitness Sds dust sensors library @ ^1.5.1 lewapek/Nova Fitness Sds dust sensors library @ ^1.5.1
lib_deps_basic = lib_deps_basic =
;greyrook/libpax @ ^1.0.1 greyrook/libpax @ ^1.1.0
https://github.com/cyberman54/libpax.git
https://github.com/SukkoPera/Arduino-Rokkit-Hash.git https://github.com/SukkoPera/Arduino-Rokkit-Hash.git
bblanchon/ArduinoJson @ ^6 bblanchon/ArduinoJson @ ^6
makuna/RTC @ ^2.3.5 makuna/RTC @ ^2.3.5
@ -100,6 +99,8 @@ build_flags_basic =
'-D LIBPAX_WIFI' '-D LIBPAX_WIFI'
'-D LIBPAX_BLE' '-D LIBPAX_BLE'
'-D LIBPAX_ARDUINO' '-D LIBPAX_ARDUINO'
'-DUSE_ESP_IDF_LOG'
'-DTAG=__FILE__'
build_flags_all = build_flags_all =
${common.build_flags_basic} ${common.build_flags_basic}
-mfix-esp32-psram-cache-issue -mfix-esp32-psram-cache-issue
@ -129,7 +130,7 @@ upload_protocol = esptool
[env:dev] [env:dev]
upload_protocol = esptool upload_protocol = esptool
platform = https://github.com/platformio/platform-espressif32.git#feature/arduino-upstream platform = https://github.com/platformio/platform-espressif32.git#develop
platform_packages = framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git platform_packages = framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git
[env:ci] [env:ci]

View File

@ -1,6 +1,6 @@
[board] [board]
halfile = ttgotdongles3.h ;halfile = ttgotdongles3.h
;halfile = ttgotdongledisplays3.h halfile = ttgotdongledisplays3.h
;halfile = ttgotdisplays3.h ;halfile = ttgotdisplays3.h
[platformio] [platformio]
@ -10,7 +10,7 @@ description = Paxcounter is a device for metering passenger flows in realtime. I
[common] [common]
; for release_version use max. 10 chars total, use any decimal format like "a.b.c" ; for release_version use max. 10 chars total, use any decimal format like "a.b.c"
release_version = 3.4.3 release_version = 3.4.4
; DEBUG LEVEL: For production run set to 0, otherwise device will leak RAM while running! ; DEBUG LEVEL: For production run set to 0, otherwise device will leak RAM while running!
; 0=None, 1=Error, 2=Warn, 3=Info, 4=Debug, 5=Verbose ; 0=None, 1=Error, 2=Warn, 3=Info, 4=Debug, 5=Verbose
debug_level = 3 debug_level = 3
@ -22,11 +22,10 @@ platform_espressif32 = espressif32@5.3.0
monitor_speed = 115200 monitor_speed = 115200
upload_speed = 115200 ; set by build.py and taken from hal file upload_speed = 115200 ; set by build.py and taken from hal file
lib_deps_all = lib_deps_all =
bitbank2/BitBang_I2C@^2.2.1 bitbank2/BitBang_I2C@ ^2.2.1
https://github.com/bitbank2/bb_spi_lcd.git bitbank2/bb_spi_lcd @ ^2.4.0
fastled/FastLED @ ^3.5.0 fastled/FastLED @ ^3.5.0
;greyrook/libpax @ ^1.0.1 greyrook/libpax @ ^1.1.0
https://github.com/cyberman54/libpax.git
https://github.com/SukkoPera/Arduino-Rokkit-Hash.git https://github.com/SukkoPera/Arduino-Rokkit-Hash.git
bblanchon/ArduinoJson @ ^6 bblanchon/ArduinoJson @ ^6
mathertel/OneButton @ ^2.0.3 mathertel/OneButton @ ^2.0.3
@ -40,6 +39,8 @@ build_flags_basic =
'-D LIBPAX_WIFI' '-D LIBPAX_WIFI'
'-D LIBPAX_BLE' '-D LIBPAX_BLE'
'-D LIBPAX_ARDUINO' '-D LIBPAX_ARDUINO'
'-DUSE_ESP_IDF_LOG'
'-DTAG=__FILE__'
build_flags_all = build_flags_all =
${common.build_flags_basic} ${common.build_flags_basic}
-mfix-esp32-psram-cache-issue -mfix-esp32-psram-cache-issue

View File

@ -45,7 +45,7 @@ function Decoder(bytes, port) {
if (port === 3) { if (port === 3) {
// device config data // device config data
return decode(bytes, [uint8, uint8, int16, uint8, uint8, uint8, uint8, bitmap1, bitmap2, version], ['loradr', 'txpower', 'rssilimit', 'sendcycle', 'wifichancycle', 'blescantime', 'rgblum', 'flags', 'payloadmask', 'version']); return decode(bytes, [uint8, uint8, int16, uint8, uint8, uint8, uint16, bitmap1, bitmap2, version], ['loradr', 'txpower', 'rssilimit', 'sendcycle', 'wifichancycle', 'blescantime', 'sleepcycle', 'flags', 'payloadmask', 'version']);
} }
if (port === 4) { if (port === 4) {

View File

@ -53,7 +53,7 @@ function decodeUplink(input) {
if (input.fPort === 3) { if (input.fPort === 3) {
// device config data // device config data
data = decode(input.bytes, [uint8, uint8, int16, uint8, uint8, uint8, uint8, bitmap1, bitmap2, version], ['loradr', 'txpower', 'rssilimit', 'sendcycle', 'wifichancycle', 'blescantime', 'rgblum', 'flags', 'payloadmask', 'version']); data = decode(input.bytes, [uint8, uint8, int16, uint8, uint8, uint8, uint16, bitmap1, bitmap2, version], ['loradr', 'txpower', 'rssilimit', 'sendcycle', 'wifichancycle', 'blescantime', 'sleepcycle', 'flags', 'payloadmask', 'version']);
} }
if (input.fPort === 4) { if (input.fPort === 4) {

View File

@ -4,8 +4,6 @@
#include <Arduino.h> #include <Arduino.h>
// Local logging tag
static const char TAG[] = __FILE__;
typedef enum { ANTENNA_INT = 0, ANTENNA_EXT } antenna_type_t; typedef enum { ANTENNA_INT = 0, ANTENNA_EXT } antenna_type_t;

View File

@ -2,8 +2,6 @@
#include "bmesensor.h" #include "bmesensor.h"
// Local logging tag
static const char TAG[] = __FILE__;
bmeStatus_t bme_status = {0, 0, 0, 0, 0, 0, 0, 0}; bmeStatus_t bme_status = {0, 0, 0, 0, 0, 0, 0, 0};

View File

@ -1,8 +1,6 @@
#include "boot.h" #include "boot.h"
#include "reset.h" #include "reset.h"
// Local logging tag
static const char TAG[] = __FILE__;
static hw_timer_t *wdTimer = NULL; static hw_timer_t *wdTimer = NULL;
static WebServer server(80); static WebServer server(80);

View File

@ -3,8 +3,6 @@
#include "globals.h" #include "globals.h"
#include "button.h" #include "button.h"
// Local logging tag
static const char TAG[] = __FILE__;
OneButton button(HAS_BUTTON, !BUTTON_ACTIVEHIGH, !!BUTTON_PULLUP); OneButton button(HAS_BUTTON, !BUTTON_ACTIVEHIGH, !!BUTTON_PULLUP);
TaskHandle_t buttonLoopTask; TaskHandle_t buttonLoopTask;

View File

@ -3,8 +3,6 @@
#include "globals.h" #include "globals.h"
#include "configmanager.h" #include "configmanager.h"
// Local logging tag
static const char TAG[] = __FILE__;
// namespace for device runtime preferences // namespace for device runtime preferences
#define DEVCONFIG "paxcntcfg" #define DEVCONFIG "paxcntcfg"

View File

@ -4,8 +4,6 @@
// Basic config // Basic config
#include "cyclic.h" #include "cyclic.h"
// Local logging tag
static const char TAG[] = __FILE__;
Ticker cyclicTimer; Ticker cyclicTimer;

View File

@ -13,8 +13,6 @@ https://github.com/udoklein/dcf77
#include "dcf77.h" #include "dcf77.h"
// Local logging tag
static const char TAG[] = __FILE__;
// triggered by second timepulse to ticker out DCF signal // triggered by second timepulse to ticker out DCF signal
void DCF77_Pulse(uint8_t bit) { void DCF77_Pulse(uint8_t bit) {

View File

@ -37,8 +37,6 @@ MY_FONT_LARGE: 16x32px = 8 chars / line @ 2 lines
#include "globals.h" #include "globals.h"
#include "display.h" #include "display.h"
// local Tag for logging
static const char TAG[] = __FILE__;
static uint8_t plotbuf[PLOTBUFFERSIZE] = {0}; static uint8_t plotbuf[PLOTBUFFERSIZE] = {0};
uint8_t DisplayIsOn = 0; uint8_t DisplayIsOn = 0;
@ -200,7 +198,6 @@ void dp_refresh(bool nextPage) {
// line 3: wifi + bluetooth counters // line 3: wifi + bluetooth counters
// WIFI:abcde BLTH:abcde // WIFI:abcde BLTH:abcde
#if ((WIFICOUNTER) && (BLECOUNTER))
if (cfg.wifiscan) if (cfg.wifiscan)
dp->printf("WIFI:%-5u", count.wifi_count); dp->printf("WIFI:%-5u", count.wifi_count);
else else
@ -209,18 +206,6 @@ void dp_refresh(bool nextPage) {
dp->printf("BLTH:%-5u", count.ble_count); dp->printf("BLTH:%-5u", count.ble_count);
else else
dp->printf(" BLTH:off"); dp->printf(" BLTH:off");
#elif ((WIFICOUNTER) && (!BLECOUNTER))
if (cfg.wifiscan)
dp->printf("WIFI:%-5u", count.wifi_count);
else
dp->printf("WIFI:off ");
#elif ((!WIFICOUNTER) && (BLECOUNTER))
if (cfg.blescan)
dp->printf("BLTH:%-5u", count.ble_count);
dp->printf("BLTH:off");
#else
dp->printf("Sniffer disabled");
#endif
dp->printf("\r\n"); dp->printf("\r\n");
// line 4: Battery + GPS status + Wifi channel // line 4: Battery + GPS status + Wifi channel

View File

@ -3,8 +3,6 @@
#include "globals.h" #include "globals.h"
#include "gpsread.h" #include "gpsread.h"
// Local logging tag
static const char TAG[] = __FILE__;
TinyGPSPlus gps; TinyGPSPlus gps;
TaskHandle_t GpsTask; TaskHandle_t GpsTask;

View File

@ -2,8 +2,6 @@
#include "globals.h" #include "globals.h"
#include "i2c.h" #include "i2c.h"
// Local logging tag
static const char TAG[] = __FILE__;
SemaphoreHandle_t I2Caccess; SemaphoreHandle_t I2Caccess;

View File

@ -81,8 +81,6 @@ not evaluated by model BU-190, use "F" instead for this model
#include "if482.h" #include "if482.h"
// Local logging tag
static const char TAG[] = __FILE__;
String IF482_Frame(time_t t) { String IF482_Frame(time_t t) {
char mon, out[IF482_FRAME_SIZE + 1], buf[IF482_FRAME_SIZE - 3]; char mon, out[IF482_FRAME_SIZE + 1], buf[IF482_FRAME_SIZE - 3];

View File

@ -1,7 +1,5 @@
#include "irqhandler.h" #include "irqhandler.h"
// Local logging tag
static const char TAG[] = __FILE__;
TaskHandle_t irqHandlerTask = NULL; TaskHandle_t irqHandlerTask = NULL;

View File

@ -6,8 +6,6 @@
#define MATRIX_DISPLAY_PAGES (2) // number of display pages #define MATRIX_DISPLAY_PAGES (2) // number of display pages
#define LINE_DIAGRAM_DIVIDER (2) // scales pax numbers to led rows #define LINE_DIAGRAM_DIVIDER (2) // scales pax numbers to led rows
// local Tag for logging
static const char TAG[] = __FILE__;
uint8_t MatrixDisplayIsOn = 0; uint8_t MatrixDisplayIsOn = 0;
static uint8_t displaybuf[LED_MATRIX_WIDTH * LED_MATRIX_HEIGHT / 8] = {0}; static uint8_t displaybuf[LED_MATRIX_WIDTH * LED_MATRIX_HEIGHT / 8] = {0};

View File

@ -1,7 +1,5 @@
#include "libpax_helpers.h" #include "libpax_helpers.h"
// Local logging tag
static const char TAG[] = __FILE__;
// libpax payload // libpax payload
struct count_payload_t count_from_libpax; struct count_payload_t count_from_libpax;

View File

@ -35,10 +35,10 @@ uplinkDecoder:
- description: Device config data - description: Device config data
input: input:
fPort: 3 fPort: 3
bytes: [0x09, 0x0F, 0x00, 0x00, 0x78, 0x32, 0x0A, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] bytes: [0x09, 0x0F, 0x00, 0x00, 0x78, 0x32, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
output: output:
data: data:
bytes: [0x09, 0x0F, 0x00, 0x00, 0x78, 0x32, 0x0A, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] bytes: [0x09, 0x0F, 0x00, 0x00, 0x78, 0x32, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
port: 3 port: 3
loradr: 9 loradr: 9
txpower: 15 txpower: 15
@ -46,7 +46,7 @@ uplinkDecoder:
sendcycle: 120 sendcycle: 120
wifichancycle: 50 wifichancycle: 50
blescantime: 10 blescantime: 10
rgblum: 30 sleepcycle: 0
flags: flags:
adr: 0 adr: 0
antenna: 0 antenna: 0

View File

@ -53,7 +53,7 @@ function decodeUplink(input) {
if (input.fPort === 3) { if (input.fPort === 3) {
// device config data // device config data
data = decode(input.bytes, [uint8, uint8, int16, uint8, uint8, uint8, uint8, bitmap1, bitmap2, version], ['loradr', 'txpower', 'rssilimit', 'sendcycle', 'wifichancycle', 'blescantime', 'rgblum', 'flags', 'payloadmask', 'version']); data = decode(input.bytes, [uint8, uint8, int16, uint8, uint8, uint8, uint16, bitmap1, bitmap2, version], ['loradr', 'txpower', 'rssilimit', 'sendcycle', 'wifichancycle', 'blescantime', 'sleepcycle', 'flags', 'payloadmask', 'version']);
} }
if (input.fPort === 4) { if (input.fPort === 4) {

View File

@ -3,8 +3,6 @@
#if (HAS_LORA) #if (HAS_LORA)
#include "lorawan.h" #include "lorawan.h"
// Local logging Tag
static const char TAG[] = __FILE__;
#if CLOCK_ERROR_PROCENTAGE > 7 #if CLOCK_ERROR_PROCENTAGE > 7
#warning CLOCK_ERROR_PROCENTAGE value in lmic_config.h is too high; values > 7 will cause side effects #warning CLOCK_ERROR_PROCENTAGE value in lmic_config.h is too high; values > 7 will cause side effects

View File

@ -79,9 +79,6 @@ BME_IRQ <- setBMEIRQ() <- Ticker.h
// Basic Config // Basic Config
#include "main.h" #include "main.h"
// local Tag for logging
static const char TAG[] = __FILE__;
char clientId[20] = {0}; // unique ClientID char clientId[20] = {0}; // unique ClientID
void setup() { void setup() {
@ -93,6 +90,13 @@ void setup() {
(*((uint32_t volatile *)ETS_UNCACHED_ADDR((DR_REG_RTCCNTL_BASE + 0xd4)))) = 0; (*((uint32_t volatile *)ETS_UNCACHED_ADDR((DR_REG_RTCCNTL_BASE + 0xd4)))) = 0;
#endif #endif
// hash 6 byte device MAC to 4 byte clientID
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_WIFI_STA);
const uint32_t hashedmac = myhash((const char *)mac, 6);
snprintf(clientId, 20, "paxcounter_%08x", hashedmac);
// setup debug output or silence device // setup debug output or silence device
#if (VERBOSE) #if (VERBOSE)
Serial.begin(115200); Serial.begin(115200);
@ -102,15 +106,15 @@ void setup() {
esp_log_level_set("*", ESP_LOG_NONE); esp_log_level_set("*", ESP_LOG_NONE);
#endif #endif
// initialize SD interface and mount SD card, if present
#if (HAS_SDCARD)
if (sdcard_init())
strcat_P(features, " SD");
#endif
// load device configuration from NVRAM and set runmode // load device configuration from NVRAM and set runmode
do_after_reset(); do_after_reset();
// hash 6 byte device MAC to 4 byte clientID
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_WIFI_STA);
const uint32_t hashedmac = myhash((const char *)mac, 6);
snprintf(clientId, 20, "paxcounter_%08x", hashedmac);
ESP_LOGI(TAG, "Starting %s v%s (runmode=%d / restarts=%d)", clientId, ESP_LOGI(TAG, "Starting %s v%s (runmode=%d / restarts=%d)", clientId,
PROGVERSION, RTC_runmode, RTC_restarts); PROGVERSION, RTC_runmode, RTC_restarts);
ESP_LOGI(TAG, "code build date: %d", compileTime()); ESP_LOGI(TAG, "code build date: %d", compileTime());
@ -218,7 +222,7 @@ void setup() {
pinMode(HAS_TWO_LED, OUTPUT); pinMode(HAS_TWO_LED, OUTPUT);
strcat_P(features, " LED2"); strcat_P(features, " LED2");
#endif #endif
// use simple LED for power display if we have additional RGB LED, else for status // use LED for power display if we have additional RGB LED, else for status
#ifdef HAS_RGB_LED #ifdef HAS_RGB_LED
switch_LED(LED_ON); switch_LED(LED_ON);
#endif #endif
@ -270,8 +274,7 @@ void setup() {
if (RTC_runmode == RUNMODE_MAINTENANCE) if (RTC_runmode == RUNMODE_MAINTENANCE)
start_boot_menu(); start_boot_menu();
#if ((WIFICOUNTER) || (BLECOUNTER)) // start libpax lib (includes timer to trigger cyclic senddata)
// use libpax timer to trigger cyclic senddata
ESP_LOGI(TAG, "Starting libpax..."); ESP_LOGI(TAG, "Starting libpax...");
struct libpax_config_t configuration; struct libpax_config_t configuration;
libpax_default_config(&configuration); libpax_default_config(&configuration);
@ -296,14 +299,6 @@ void setup() {
} else { } else {
init_libpax(); init_libpax();
} }
#else
// use stand alone timer to trigger cyclic senddata
initSendDataTimer(cfg.sendcycle * 2);
#endif
#if (BLECOUNTER)
strcat_P(features, " BLE");
#endif
// start rcommand processing task // start rcommand processing task
ESP_LOGI(TAG, "Starting rcommand interpreter..."); ESP_LOGI(TAG, "Starting rcommand interpreter...");
@ -358,11 +353,6 @@ void setup() {
_ASSERT(mqtt_init() == ESP_OK); _ASSERT(mqtt_init() == ESP_OK);
#endif #endif
#if (HAS_SDCARD)
if (sdcard_init())
strcat_P(features, " SD");
#endif
#if (HAS_SDS011) #if (HAS_SDS011)
ESP_LOGI(TAG, "init fine-dust-sensor"); ESP_LOGI(TAG, "init fine-dust-sensor");
if (sds011_init()) if (sds011_init())
@ -401,13 +391,6 @@ void setup() {
strcat_P(features, " IF482"); strcat_P(features, " IF482");
#endif #endif
#if (WIFICOUNTER)
strcat_P(features, " WIFI");
#else
// remove wifi driver from RAM, if option wifi not compiled
esp_wifi_deinit();
#endif
// start state machine // start state machine
ESP_LOGI(TAG, "Starting Interrupt Handler..."); ESP_LOGI(TAG, "Starting Interrupt Handler...");
xTaskCreatePinnedToCore(irqHandler, // task function xTaskCreatePinnedToCore(irqHandler, // task function

View File

@ -2,8 +2,6 @@
#include "mqttclient.h" #include "mqttclient.h"
static const char TAG[] = __FILE__;
static QueueHandle_t MQTTSendQueue; static QueueHandle_t MQTTSendQueue;
TaskHandle_t mqttTask; TaskHandle_t mqttTask;

View File

@ -32,8 +32,6 @@ const int port = 443;
int volatile contentLength = 0; int volatile contentLength = 0;
bool volatile isValidContentType = false; bool volatile isValidContentType = false;
// Local logging tag
static const char TAG[] = __FILE__;
// helper function to extract header value from header // helper function to extract header value from header
inline String getHeaderValue(String header, String headerName) { inline String getHeaderValue(String header, String headerName) {

View File

@ -13,6 +13,7 @@
#define BOOTMENU 0 // 0 = no bootmenu, 1 = device brings up boot menu before starting application #define BOOTMENU 0 // 0 = no bootmenu, 1 = device brings up boot menu before starting application
#define BOOTDELAY 30 // time [seconds] while devices waits in boot menue for input #define BOOTDELAY 30 // time [seconds] while devices waits in boot menue for input
#define BOOTTIMEOUT 300 // time [seconds] while devices waits to finish upload a firmware file #define BOOTTIMEOUT 300 // time [seconds] while devices waits to finish upload a firmware file
#define SDLOGGING 0 // set to 1 for system logging to SD card (if device has one)
// Payload send cycle and encoding // Payload send cycle and encoding
#define SENDCYCLE 30 // payload send cycle [seconds/2], 0 .. 255 #define SENDCYCLE 30 // payload send cycle [seconds/2], 0 .. 255
@ -25,9 +26,9 @@
((GPS_DATA | MEMS_DATA | COUNT_DATA | SENSOR1_DATA | SENSOR2_DATA | SENSOR3_DATA) & \ ((GPS_DATA | MEMS_DATA | COUNT_DATA | SENSOR1_DATA | SENSOR2_DATA | SENSOR3_DATA) & \
(~BATT_DATA) & (~RESERVED_DATA)) (~BATT_DATA) & (~RESERVED_DATA))
// MAC sniffing parameters // MAC sniffing settings
#define BLECOUNTER 1 // set to 0 if you do not want to install the BLE sniffer #define BLECOUNTER 0 // set to 0 if you do not want to start the BLE sniffer
#define WIFICOUNTER 1 // set to 0 if you do not want to install the WIFI sniffer #define WIFICOUNTER 1 // set to 0 if you do not want to start the WIFI sniffer
#define RSSILIMIT 0 // 0...-128, set to 0 if you do not want to filter signals #define RSSILIMIT 0 // 0...-128, set to 0 if you do not want to filter signals
// BLE scan parameters // BLE scan parameters

View File

@ -47,8 +47,8 @@ void PayloadConvert::addConfig(configData_t value) {
buffer[cursor++] = value.blescantime; buffer[cursor++] = value.blescantime;
buffer[cursor++] = value.blescan; buffer[cursor++] = value.blescan;
buffer[cursor++] = value.wifiant; buffer[cursor++] = value.wifiant;
buffer[cursor++] = 0; // reserved buffer[cursor++] = highByte(value.sleepcycle);
buffer[cursor++] = value.rgblum; buffer[cursor++] = lowByte(value.sleepcycle);
buffer[cursor++] = value.payloadmask; buffer[cursor++] = value.payloadmask;
buffer[cursor++] = 0; // reserved buffer[cursor++] = 0; // reserved
memcpy(buffer + cursor, value.version, 10); memcpy(buffer + cursor, value.version, 10);
@ -171,7 +171,7 @@ void PayloadConvert::addConfig(configData_t value) {
writeUint8(value.sendcycle); writeUint8(value.sendcycle);
writeUint8(value.wifichancycle); writeUint8(value.wifichancycle);
writeUint8(value.blescantime); writeUint8(value.blescantime);
writeUint8(value.rgblum); writeUint16(value.sleepcycle);
writeBitmap(value.adrmode ? true : false, value.screensaver ? true : false, writeBitmap(value.adrmode ? true : false, value.screensaver ? true : false,
value.screenon ? true : false, value.countermode ? true : false, value.screenon ? true : false, value.countermode ? true : false,
value.blescan ? true : false, value.wifiant ? true : false, 0, 0); value.blescan ? true : false, value.wifiant ? true : false, 0, 0);

View File

@ -2,8 +2,6 @@
#include "globals.h" #include "globals.h"
#include "power.h" #include "power.h"
// Local logging tag
static const char TAG[] = __FILE__;
int8_t batt_level = -1; // percent batt level, global variable, -1 means no batt int8_t batt_level = -1; // percent batt level, global variable, -1 means no batt

View File

@ -2,8 +2,6 @@
#include "globals.h" #include "globals.h"
#include "rcommand.h" #include "rcommand.h"
// Local logging tag
static const char TAG[] = __FILE__;
static QueueHandle_t RcmdQueue; static QueueHandle_t RcmdQueue;
TaskHandle_t rcmdTask; TaskHandle_t rcmdTask;
@ -54,7 +52,6 @@ void set_reset(uint8_t val[]) {
void set_rssi(uint8_t val[]) { void set_rssi(uint8_t val[]) {
cfg.rssilimit = val[0] * -1; cfg.rssilimit = val[0] * -1;
#if ((WIFICOUNTER) || (BLECOUNTER))
libpax_counter_stop(); libpax_counter_stop();
libpax_config_t current_config; libpax_config_t current_config;
libpax_get_current_config(&current_config); libpax_get_current_config(&current_config);
@ -62,7 +59,6 @@ void set_rssi(uint8_t val[]) {
current_config.ble_rssi_threshold = cfg.rssilimit; current_config.ble_rssi_threshold = cfg.rssilimit;
libpax_update_config(&current_config); libpax_update_config(&current_config);
init_libpax(); init_libpax();
#endif
ESP_LOGI(TAG, "Remote command: set RSSI limit to %d", cfg.rssilimit); ESP_LOGI(TAG, "Remote command: set RSSI limit to %d", cfg.rssilimit);
} }
@ -73,13 +69,8 @@ void set_sendcycle(uint8_t val[]) {
cfg.sendcycle = val[0]; cfg.sendcycle = val[0];
ESP_LOGI(TAG, "Remote command: set send cycle to %d seconds", ESP_LOGI(TAG, "Remote command: set send cycle to %d seconds",
cfg.sendcycle * 2); cfg.sendcycle * 2);
#if ((WIFICOUNTER) || (BLECOUNTER))
libpax_counter_stop(); libpax_counter_stop();
init_libpax(); init_libpax();
#else
// modify senddata timer
initSendDataTimer(cfg.sendcycle * 2);
#endif
} }
void set_sleepcycle(uint8_t val[]) { void set_sleepcycle(uint8_t val[]) {
@ -91,7 +82,6 @@ void set_sleepcycle(uint8_t val[]) {
void set_wifichancycle(uint8_t val[]) { void set_wifichancycle(uint8_t val[]) {
cfg.wifichancycle = val[0]; cfg.wifichancycle = val[0];
#if (WIFICOUNTER)
libpax_counter_stop(); libpax_counter_stop();
libpax_config_t current_config; libpax_config_t current_config;
libpax_get_current_config(&current_config); libpax_get_current_config(&current_config);
@ -109,19 +99,16 @@ void set_wifichancycle(uint8_t val[]) {
current_config.wifi_channel_switch_interval = cfg.wifichancycle; current_config.wifi_channel_switch_interval = cfg.wifichancycle;
libpax_update_config(&current_config); libpax_update_config(&current_config);
init_libpax(); init_libpax();
#endif
} }
void set_blescantime(uint8_t val[]) { void set_blescantime(uint8_t val[]) {
cfg.blescantime = val[0]; cfg.blescantime = val[0];
#if (BLECOUNTER)
libpax_counter_stop(); libpax_counter_stop();
libpax_config_t current_config; libpax_config_t current_config;
libpax_get_current_config(&current_config); libpax_get_current_config(&current_config);
current_config.blescantime = cfg.blescantime; current_config.blescantime = cfg.blescantime;
libpax_update_config(&current_config); libpax_update_config(&current_config);
init_libpax(); init_libpax();
#endif
} }
void set_countmode(uint8_t val[]) { void set_countmode(uint8_t val[]) {
@ -144,10 +131,8 @@ void set_countmode(uint8_t val[]) {
"Remote command: set counter mode called with invalid parameter(s)"); "Remote command: set counter mode called with invalid parameter(s)");
return; return;
} }
#if ((WIFICOUNTER) || (BLECOUNTER))
libpax_counter_stop(); libpax_counter_stop();
init_libpax(); // re-inits counter mode from cfg.countermode init_libpax(); // re-inits counter mode from cfg.countermode
#endif
} }
void set_screensaver(uint8_t val[]) { void set_screensaver(uint8_t val[]) {
@ -258,28 +243,24 @@ void set_loraadr(uint8_t val[]) {
void set_blescan(uint8_t val[]) { void set_blescan(uint8_t val[]) {
ESP_LOGI(TAG, "Remote command: set BLE scanner to %s", val[0] ? "on" : "off"); ESP_LOGI(TAG, "Remote command: set BLE scanner to %s", val[0] ? "on" : "off");
cfg.blescan = val[0] ? 1 : 0; cfg.blescan = val[0] ? 1 : 0;
#if (BLECOUNTER)
libpax_counter_stop(); libpax_counter_stop();
libpax_config_t current_config; libpax_config_t current_config;
libpax_get_current_config(&current_config); libpax_get_current_config(&current_config);
current_config.blecounter = cfg.blescan; current_config.blecounter = cfg.blescan;
libpax_update_config(&current_config); libpax_update_config(&current_config);
init_libpax(); init_libpax();
#endif
} }
void set_wifiscan(uint8_t val[]) { void set_wifiscan(uint8_t val[]) {
ESP_LOGI(TAG, "Remote command: set WIFI scanner to %s", ESP_LOGI(TAG, "Remote command: set WIFI scanner to %s",
val[0] ? "on" : "off"); val[0] ? "on" : "off");
cfg.wifiscan = val[0] ? 1 : 0; cfg.wifiscan = val[0] ? 1 : 0;
#if (WIFICOUNTER)
libpax_counter_stop(); libpax_counter_stop();
libpax_config_t current_config; libpax_config_t current_config;
libpax_get_current_config(&current_config); libpax_get_current_config(&current_config);
current_config.wificounter = cfg.wifiscan; current_config.wificounter = cfg.wifiscan;
libpax_update_config(&current_config); libpax_update_config(&current_config);
init_libpax(); init_libpax();
#endif
} }
void set_wifiant(uint8_t val[]) { void set_wifiant(uint8_t val[]) {

View File

@ -2,9 +2,6 @@
#include "globals.h" #include "globals.h"
#include "reset.h" #include "reset.h"
// Local logging tag
static const char TAG[] = __FILE__;
// Conversion factor for micro seconds to seconds // Conversion factor for micro seconds to seconds
#define uS_TO_S_FACTOR 1000000ULL #define uS_TO_S_FACTOR 1000000ULL
@ -100,11 +97,6 @@ void enter_deepsleep(const uint32_t wakeup_sec, gpio_num_t wakeup_gpio) {
sds011_sleep(); sds011_sleep();
#endif #endif
// flush & close sd card, if we have
#if (HAS_SDCARD)
sdcard_close();
#endif
// wait a while (max 100 sec) to clear send queues // wait a while (max 100 sec) to clear send queues
ESP_LOGI(TAG, "Waiting until send queues are empty..."); ESP_LOGI(TAG, "Waiting until send queues are empty...");
for (int i = 100; i > 0; i--) { for (int i = 100; i > 0; i--) {
@ -169,6 +161,12 @@ void enter_deepsleep(const uint32_t wakeup_sec, gpio_num_t wakeup_gpio) {
gettimeofday(&RTC_sleep_start_time, NULL); gettimeofday(&RTC_sleep_start_time, NULL);
RTC_millis += esp_timer_get_time() / 1000; RTC_millis += esp_timer_get_time() / 1000;
ESP_LOGI(TAG, "Going to sleep, good bye."); ESP_LOGI(TAG, "Going to sleep, good bye.");
// flush & close sd card, if we have
#if (HAS_SDCARD)
sdcard_close();
#endif
esp_deep_sleep_start(); esp_deep_sleep_start();
} }

View File

@ -2,8 +2,6 @@
#include "rtctime.h" #include "rtctime.h"
// Local logging tag
static const char TAG[] = __FILE__;
RtcDS3231<TwoWire> Rtc(Wire); // RTC hardware i2c interface RtcDS3231<TwoWire> Rtc(Wire); // RTC hardware i2c interface

View File

@ -5,9 +5,6 @@
// check whether your card reader supports SPI oder SDMMC and select appropriate // check whether your card reader supports SPI oder SDMMC and select appropriate
// SD interface in board hal file // SD interface in board hal file
// Local logging tag
static const char TAG[] = __FILE__;
#include "sdcard.h" #include "sdcard.h"
sdmmc_card_t *card; sdmmc_card_t *card;
@ -17,9 +14,9 @@ static bool useSDCard = false;
// This file stream will be used for payload logging // This file stream will be used for payload logging
static FILE *data_file; static FILE *data_file;
// This file stream will be used for system logging
#ifdef SD_LOGGING #if (SDLOGGING)
// This file stream will be used for system logging
static FILE *log_file; static FILE *log_file;
// Save UART stdout stream // Save UART stdout stream
@ -30,7 +27,6 @@ static FILE *uart_stdout = stdout;
// @important Do NOT use the ESP_LOG* macro's in this function ELSE // @important Do NOT use the ESP_LOG* macro's in this function ELSE
// recursive loop and stack overflow! So use printf() instead for debug // recursive loop and stack overflow! So use printf() instead for debug
// messages. // messages.
// CURRENTLY NOT WORKING DUE TO AN ISSUE IN ARDUINO-ESP32
int print_to_sd_card(const char *fmt, va_list args) { int print_to_sd_card(const char *fmt, va_list args) {
static bool static_fatal_error = false; static bool static_fatal_error = false;
static const uint32_t WRITE_CACHE_CYCLE = 5; static const uint32_t WRITE_CACHE_CYCLE = 5;
@ -53,12 +49,8 @@ int print_to_sd_card(const char *fmt, va_list args) {
} }
// #2 Smart commit after x writes // #2 Smart commit after x writes
counter_write++; if (counter_write++ % WRITE_CACHE_CYCLE == 0)
if (counter_write % WRITE_CACHE_CYCLE == 0) {
printf("%s() fsync'ing log file (WRITE_CACHE_CYCLE=%u)\n",
WRITE_CACHE_CYCLE);
fsync(fileno(log_file)); fsync(fileno(log_file));
}
} }
// #3 ALWAYS Write to stdout! // #3 ALWAYS Write to stdout!
@ -119,7 +111,8 @@ bool sdcard_init(bool create) {
return false; return false;
} }
// Use settings defined above to initialize SD card and mount FAT filesystem. // Use settings defined above to initialize SD card and mount FAT
// filesystem.
ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config, ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config,
&card); &card);
@ -153,7 +146,7 @@ bool sdcard_init(bool create) {
if (ret == ESP_FAIL) { if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "failed to mount filesystem"); ESP_LOGE(TAG, "failed to mount filesystem");
} else { } else {
ESP_LOGE(TAG, "SD-card not found (%d)", ret); ESP_LOGI(TAG, "No SD-card found (%d)", ret);
} }
return false; return false;
} }
@ -188,16 +181,12 @@ bool sdcard_init(bool create) {
useSDCard = false; useSDCard = false;
} }
#ifdef SD_LOGGING #if (SDLOGGING)
snprintf(bufferFilename, sizeof(bufferFilename), "/%s.log", SDCARD_FILE_NAME); snprintf(bufferFilename, sizeof(bufferFilename), "/%s.log", SDCARD_FILE_NAME);
if (openFile(&log_file, bufferFilename)) { if (openFile(&log_file, bufferFilename)) {
ESP_LOGI(TAG, "redirecting serial output to SD-card"); ESP_LOGI(TAG, "redirecting serial output to SD-card");
esp_log_set_vprintf(&print_to_sd_card); esp_log_set_vprintf(&print_to_sd_card);
// Change stdout for THIS TASK ONLY
// stdout = log_file;
// Change stdout for all new tasks which will be created
//_GLOBAL_REENT->_stdout = log_file;
} else { } else {
useSDCard = false; useSDCard = false;
} }
@ -209,7 +198,7 @@ bool sdcard_init(bool create) {
void sdcard_flush(void) { void sdcard_flush(void) {
if (data_file) if (data_file)
fsync(fileno(data_file)); fsync(fileno(data_file));
#ifdef SD_LOGGING #if (SDLOGGING)
if (log_file) if (log_file)
fsync(fileno(log_file)); fsync(fileno(log_file));
#endif #endif
@ -220,11 +209,9 @@ void sdcard_close(void) {
return; return;
ESP_LOGI(TAG, "closing SD-card"); ESP_LOGI(TAG, "closing SD-card");
sdcard_flush(); sdcard_flush();
#ifdef SD_LOGGING #if (SDLOGGING)
// Reset logging output back to normal // Redirect logging output back to console
ESP_LOGI(TAG, "redirect console back to serial output"); ESP_LOGI(TAG, "redirect console back to serial output");
// stdout = uart_stdout;
//_GLOBAL_REENT->_stdout = uart_stdout;
esp_log_set_vprintf(&vprintf); esp_log_set_vprintf(&vprintf);
#endif #endif
fcloseall(); fcloseall();

View File

@ -2,8 +2,6 @@
#if (HAS_SDS011) #if (HAS_SDS011)
// Local logging tag
static const char TAG[] = __FILE__;
#include "sds011read.h" #include "sds011read.h"

View File

@ -1,8 +1,6 @@
// Basic Config // Basic Config
#include "senddata.h" #include "senddata.h"
// Local logging tag
static const char TAG[] = __FILE__;
void setSendIRQ(TimerHandle_t xTimer) { void setSendIRQ(TimerHandle_t xTimer) {
xTaskNotify(irqHandlerTask, SENDCYCLE_IRQ, eSetBits); xTaskNotify(irqHandlerTask, SENDCYCLE_IRQ, eSetBits);
@ -10,19 +8,6 @@ void setSendIRQ(TimerHandle_t xTimer) {
void setSendIRQ(void) { setSendIRQ(NULL); } void setSendIRQ(void) { setSendIRQ(NULL); }
void initSendDataTimer(uint8_t sendcycle) {
static TimerHandle_t SendDataTimer = NULL;
if (SendDataTimer == NULL) {
SendDataTimer =
xTimerCreate("SendDataTimer", pdMS_TO_TICKS(sendcycle * 1000), pdTRUE,
(void *)0, setSendIRQ);
xTimerStart(SendDataTimer, 0);
} else {
xTimerChangePeriod(SendDataTimer, pdMS_TO_TICKS(sendcycle * 1000), 0);
}
}
// put data to send in RTos Queues used for transmit over channels Lora and SPI // put data to send in RTos Queues used for transmit over channels Lora and SPI
void SendPayload(uint8_t port) { void SendPayload(uint8_t port) {
ESP_LOGD(TAG, "sending Payload for Port %d", port); ESP_LOGD(TAG, "sending Payload for Port %d", port);
@ -81,16 +66,14 @@ void sendData() {
#if (HAS_SDS011) #if (HAS_SDS011)
sdsStatus_t sds_status; sdsStatus_t sds_status;
#endif #endif
#if ((WIFICOUNTER) || (BLECOUNTER))
struct count_payload_t count = struct count_payload_t count =
count_from_libpax; // copy values from global libpax var count_from_libpax; // copy values from global libpax var
ESP_LOGD(TAG, "Sending count results: pax=%d / wifi=%d / ble=%d", count.pax, ESP_LOGD(TAG, "Sending count results: pax=%d / wifi=%d / ble=%d", count.pax,
count.wifi_count, count.ble_count); count.wifi_count, count.ble_count);
#endif
while (bitmask) { while (bitmask) {
switch (bitmask & mask) { switch (bitmask & mask) {
#if ((WIFICOUNTER) || (BLECOUNTER))
case COUNT_DATA: case COUNT_DATA:
payload.reset(); payload.reset();
@ -138,8 +121,6 @@ void sendData() {
SendPayload(COUNTERPORT); SendPayload(COUNTERPORT);
break; // case COUNTDATA break; // case COUNTDATA
#endif // ((WIFICOUNTER) || (BLECOUNTER))
#if (HAS_BME) #if (HAS_BME)
case MEMS_DATA: case MEMS_DATA:
payload.reset(); payload.reset();

View File

@ -2,8 +2,6 @@
#include "globals.h" #include "globals.h"
#include "sensor.h" #include "sensor.h"
// Local logging tag
static const char TAG[] = __FILE__;
#define SENSORBUFFER \ #define SENSORBUFFER \
10 // max. size of user sensor data buffer in bytes [default=20] 10 // max. size of user sensor data buffer in bytes [default=20]

View File

@ -30,8 +30,6 @@ licenses. Refer to LICENSE.txt file in repository for more details.
#include <sys/param.h> #include <sys/param.h>
#include <rom/crc.h> #include <rom/crc.h>
static const char TAG[] = __FILE__;
#define HEADER_SIZE 4 #define HEADER_SIZE 4
// SPI transaction size needs to be at least 8 bytes and dividable by 4, see // SPI transaction size needs to be at least 8 bytes and dividable by 4, see
// https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/spi_slave.html // https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/spi_slave.html

View File

@ -4,8 +4,6 @@
#error You must define at most one of IF482 or DCF77! #error You must define at most one of IF482 or DCF77!
#endif #endif
// Local logging tag
static const char TAG[] = __FILE__;
// symbol to display current time source // symbol to display current time source
// G = GPS / R = RTC / L = LORA / * = no sync / ? = never synced // G = GPS / R = RTC / L = LORA / * = no sync / ? = never synced

View File

@ -21,8 +21,6 @@ accept this.
#include "timesync.h" #include "timesync.h"
// Local logging tag
static const char TAG[] = __FILE__;
static bool timeSyncPending = false; static bool timeSyncPending = false;
static uint8_t time_sync_seqNo = (uint8_t)random(TIME_SYNC_MAX_SEQNO), static uint8_t time_sync_seqNo = (uint8_t)random(TIME_SYNC_MAX_SEQNO),