├── .gitignore
├── .vscode
└── extensions.json
├── LICENSE
├── README.md
├── img
├── 3.3v.jpg
├── board.jpg
└── half-assembled.jpg
├── platformio.ini
└── src
├── Config.h
├── SerialCom.h
├── Types.h
└── esp8266-vindriktning-particle-sensor.ino
/.gitignore:
--------------------------------------------------------------------------------
1 | .pio
2 | .vscode/.browse.c_cpp.db*
3 | .vscode/c_cpp_properties.json
4 | .vscode/launch.json
5 | .vscode/ipch
6 |
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | // See http://go.microsoft.com/fwlink/?LinkId=827846
3 | // for the documentation about the extensions.json format
4 | "recommendations": [
5 | "platformio.platformio-ide"
6 | ]
7 | }
8 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
MQTT connectivity for the Ikea VINDRIKTNING
2 |
3 |
4 | This repository contains an ESP8266 firmware, which adds MQTT to the Ikea VINDRIKTNING PM2.5 air quality sensor.
5 | The modification doesn't interfere with normal operation of the device in any way.
6 | The ESP8266 just adds another data sink beside the colored LEDs.
7 |
8 | 
9 |
10 | Home Assistant Autodiscovery is supported.
11 | Furthermore, the WifiManager library is used for on-the-fly configuration.
12 | Also, ArduinoOTA is used, so that firmware updates are possible even with a reassembled device.
13 |
14 | As the ESP8266 is 5V-tolerant, this should there shouldn't be any issues, however I haven't had time to test this for longer periods of time.
15 | Therefore, if the ESP burns out after a while, just add a voltage divider or something.
16 |
17 | ## Prerequisites
18 |
19 | To extend your air quality sensor, you will need
20 |
21 | - An ESP8266 with a 5v voltage regulator (e.g. a Wemos D1 Mini)
22 | - Some short dupont cables
23 | - A soldering iron
24 | - A long PH0 Screwdriver (e.g. Wera 118022)
25 |
26 | Fortunately, there is a lot of unused space in the enclosure, which is perfect for our ESP8266.
27 | Also, everything we need is accessible via easy to solder testpoints.
28 |
29 | ## Hardware
30 |
31 | To install the ESP8266, you need to unscrew the four visible screws in the back of the enclosure.
32 |
33 | Then, there are also three screws holding the tiny PCB in place. These aren't necessary to remove since you can solder
34 | in-place, however personally, I'd recommend taking the board out of there since it will be easier to solder without fear
35 | of accidentally melting some plastic.
36 |
37 | 
38 |
39 | As you can see in this image, you'll need to solder wires to GND, 5V and the Testpoint that is connected to TX of the
40 | Particle Sensor.
41 |
42 | Then just connect these Wires to GND, VIN (5V) and D2 (if you're using a Wemos D1 Mini).
43 |
44 | Done.
45 |
46 | ## Software
47 |
48 | The firmware can be built and flashed using the Arduino IDE.
49 |
50 | For this, you will need to add ESP8266 support to it by [using the Boards Manager](https://github.com/esp8266/Arduino#installing-with-boards-manager).
51 |
52 | Furthermore, you will also need to install the following libraries using the Library Manager:
53 |
54 | * ArduinoOTA 1.0.3
55 | * ArduinoJSON 6.10.1
56 | * PubSubClient 2.8.0
57 | * WiFiManager 0.15.0
58 |
59 |
60 | Just build, flash, and you're done.
61 |
62 | When connecting everything up, you should see an open Wi-Fi Access Point to configure your Wi-Fi and MQTT credentials.
63 |
64 | ## Low-Noise Mod
65 |
66 | **Note:** The intent of this section is only to document that this is possible. I don't "recommend" doing this nor do I advise against it.
67 |
68 | As you might've noticed, there's a fan in there, which is audible even multiple meters away.
69 |
70 | For some reason, the Ikea uC firmware decides to toggle the fan on and off every minute
71 | or so causing the noise it makes to change and therefore it constantly stays noticeable.
72 |
73 | Good thing is that the Fan does spin up fine with just 3.3V, which means that we can run it constantly from the
74 | voltage regulator of the D1 Mini.
75 |
76 | At 3.3V its noise is barely noticeable from 50 cm away.
77 |
78 | 
79 |
80 | Having the Fan not connected at all was also tried but proved to mess up all readings completely.
81 |
82 |
83 | This is of course a more invasive modification than just adding Wi-Fi data logging.
84 | Though, given that it is just a €10 device, I'm fine with that.
85 |
86 | To make soldering a bit easier, note that the whole outer metal part of the Micro USB connector of the D1 Mini is
87 | connected to GND.
88 |
89 | ## Misc
90 |
91 | The VINDRIKTNING consists of a custom(?) Cubic PM1006-like Sensor + another uC that does all that LED stuff, which talk
92 | via UART. The uC simply regularly polls the sensor and displays the results.
93 |
94 | Therefore, to add Wi-Fi connectivity, we just need to also listen to the TX of the Sensor and decode those messages.
95 | The Ikea uC will do all that polling stuff for us.
96 |
97 | As reported in #16, the transitions from Green to Yellow and Yellow to Red in the Ikea firmware are at around 30 and 100μg/m³.
98 |
99 | ## ToDo
100 |
101 | Reconfiguration of a provisioned device without having to OTAU a firmware that clears the settings would be nice.
102 |
103 |
104 | ## References and sources
105 |
106 | - [@haxfleisch](https://twitter.com/haxfleisch) for their teardown of the device.
107 | - [Gabriel Valky](https://github.com/gabonator) for the incredibly useful [LA104 custom firmware + tools](https://github.com/gabonator/LA104)
108 |
--------------------------------------------------------------------------------
/img/3.3v.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hypfer/esp8266-vindriktning-particle-sensor/83fd7c5034cc9737b954c5625426563492d83a2c/img/3.3v.jpg
--------------------------------------------------------------------------------
/img/board.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hypfer/esp8266-vindriktning-particle-sensor/83fd7c5034cc9737b954c5625426563492d83a2c/img/board.jpg
--------------------------------------------------------------------------------
/img/half-assembled.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hypfer/esp8266-vindriktning-particle-sensor/83fd7c5034cc9737b954c5625426563492d83a2c/img/half-assembled.jpg
--------------------------------------------------------------------------------
/platformio.ini:
--------------------------------------------------------------------------------
1 | ; PlatformIO Project Configuration File
2 | ;
3 | ; Build options: build flags, source filter
4 | ; Upload options: custom upload port, speed and extra flags
5 | ; Library options: dependencies, extra library storages
6 | ; Advanced options: extra scripting
7 | ;
8 | ; Please visit documentation for the other options and examples
9 | ; https://docs.platformio.org/page/projectconf.html
10 |
11 | [env:d1_mini]
12 | platform = espressif8266
13 | board = d1_mini
14 | framework = arduino
15 | lib_deps =
16 | bblanchon/ArduinoJson @ ^6.18.3
17 | knolleary/PubSubClient @ ^2.8
18 | tzapu/WiFiManager @ ^0.16.0
--------------------------------------------------------------------------------
/src/Config.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 | #include
5 |
6 | namespace Config {
7 | char mqtt_server[80] = "example.tld";
8 |
9 | char username[24] = "";
10 | char password[24] = "";
11 |
12 | void save() {
13 | DynamicJsonDocument json(512);
14 | json["mqtt_server"] = mqtt_server;
15 | json["username"] = username;
16 | json["password"] = password;
17 |
18 | File configFile = SPIFFS.open("/config.json", "w");
19 | if (!configFile) {
20 | return;
21 | }
22 |
23 | serializeJson(json, configFile);
24 | configFile.close();
25 | }
26 |
27 | void load() {
28 | if (SPIFFS.begin()) {
29 |
30 | if (SPIFFS.exists("/config.json")) {
31 | File configFile = SPIFFS.open("/config.json", "r");
32 |
33 | if (configFile) {
34 | const size_t size = configFile.size();
35 | std::unique_ptr buf(new char[size]);
36 |
37 | configFile.readBytes(buf.get(), size);
38 | DynamicJsonDocument json(512);
39 |
40 | if (DeserializationError::Ok == deserializeJson(json, buf.get())) {
41 | strcpy(mqtt_server, json["mqtt_server"]);
42 | strcpy(username, json["username"]);
43 | strcpy(password, json["password"]);
44 | }
45 | }
46 | }
47 | }
48 | }
49 | } // namespace Config
50 |
--------------------------------------------------------------------------------
/src/SerialCom.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | #include "Types.h"
6 |
7 | namespace SerialCom {
8 | constexpr static const uint8_t PIN_UART_RX = 4; // D2 on Wemos D1 Mini
9 | constexpr static const uint8_t PIN_UART_TX = 13; // UNUSED
10 |
11 | SoftwareSerial sensorSerial(PIN_UART_RX, PIN_UART_TX);
12 |
13 | uint8_t serialRxBuf[255];
14 | uint8_t rxBufIdx = 0;
15 |
16 | void setup() {
17 | sensorSerial.begin(9600);
18 | }
19 |
20 | void clearRxBuf() {
21 | // Clear everything for the next message
22 | memset(serialRxBuf, 0, sizeof(serialRxBuf));
23 | rxBufIdx = 0;
24 | }
25 |
26 | void parseState(particleSensorState_t& state) {
27 | /**
28 | * MSB DF 3 DF 4 LSB
29 | * uint16_t = xxxxxxxx xxxxxxxx
30 | */
31 | const uint16_t pm25 = (serialRxBuf[5] << 8) | serialRxBuf[6];
32 |
33 | Serial.printf("Received PM 2.5 reading: %d\n", pm25);
34 |
35 | state.measurements[state.measurementIdx] = pm25;
36 |
37 | state.measurementIdx = (state.measurementIdx + 1) % 5;
38 |
39 | if (state.measurementIdx == 0) {
40 | float avgPM25 = 0.0f;
41 |
42 | for (uint8_t i = 0; i < 5; ++i) {
43 | avgPM25 += state.measurements[i] / 5.0f;
44 | }
45 |
46 | state.avgPM25 = avgPM25;
47 | state.valid = true;
48 |
49 | Serial.printf("New Avg PM25: %d\n", state.avgPM25);
50 | }
51 |
52 | clearRxBuf();
53 | }
54 |
55 | bool isValidHeader() {
56 | bool headerValid = serialRxBuf[0] == 0x16 && serialRxBuf[1] == 0x11 && serialRxBuf[2] == 0x0B;
57 |
58 | if (!headerValid) {
59 | Serial.println("Received message with invalid header.");
60 | }
61 |
62 | return headerValid;
63 | }
64 |
65 | bool isValidChecksum() {
66 | uint8_t checksum = 0;
67 |
68 | for (uint8_t i = 0; i < 20; i++) {
69 | checksum += serialRxBuf[i];
70 | }
71 |
72 | if (checksum != 0) {
73 | Serial.printf("Received message with invalid checksum. Expected: 0. Actual: %d\n", checksum);
74 | }
75 |
76 | return checksum == 0;
77 | }
78 |
79 | void handleUart(particleSensorState_t& state) {
80 | if (!sensorSerial.available()) {
81 | return;
82 | }
83 |
84 | Serial.print("Receiving:");
85 | while (sensorSerial.available()) {
86 | serialRxBuf[rxBufIdx++] = sensorSerial.read();
87 | Serial.print(".");
88 |
89 | // Without this delay, receiving data breaks for reasons that are beyond me
90 | delay(15);
91 |
92 | if (rxBufIdx >= 64) {
93 | clearRxBuf();
94 | }
95 | }
96 | Serial.println("Done.");
97 |
98 | if (isValidHeader() && isValidChecksum()) {
99 | parseState(state);
100 |
101 | Serial.printf(
102 | "Current measurements: %d, %d, %d, %d, %d\n",
103 |
104 | state.measurements[0],
105 | state.measurements[1],
106 | state.measurements[2],
107 | state.measurements[3],
108 | state.measurements[4]
109 | );
110 | } else {
111 | clearRxBuf();
112 | }
113 | }
114 | } // namespace SerialCom
115 |
--------------------------------------------------------------------------------
/src/Types.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | struct particleSensorState_t {
4 | uint16_t avgPM25 = 0;
5 | uint16_t measurements[5] = {0, 0, 0, 0, 0};
6 | uint8_t measurementIdx = 0;
7 | boolean valid = false;
8 | };
9 |
--------------------------------------------------------------------------------
/src/esp8266-vindriktning-particle-sensor.ino:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | #include "Config.h"
10 | #include "SerialCom.h"
11 | #include "Types.h"
12 |
13 | particleSensorState_t state;
14 |
15 | uint8_t mqttRetryCounter = 0;
16 |
17 | WiFiManager wifiManager;
18 | WiFiClient wifiClient;
19 | PubSubClient mqttClient;
20 |
21 | WiFiManagerParameter custom_mqtt_server("server", "mqtt server", Config::mqtt_server, sizeof(Config::mqtt_server));
22 | WiFiManagerParameter custom_mqtt_user("user", "MQTT username", Config::username, sizeof(Config::username));
23 | WiFiManagerParameter custom_mqtt_pass("pass", "MQTT password", Config::password, sizeof(Config::password));
24 |
25 | uint32_t lastMqttConnectionAttempt = 0;
26 | const uint16_t mqttConnectionInterval = 60000; // 1 minute = 60 seconds = 60000 milliseconds
27 |
28 | uint32_t statusPublishPreviousMillis = 0;
29 | const uint16_t statusPublishInterval = 30000; // 30 seconds = 30000 milliseconds
30 |
31 | char identifier[24];
32 | #define FIRMWARE_PREFIX "esp8266-vindriktning-particle-sensor"
33 | #define AVAILABILITY_ONLINE "online"
34 | #define AVAILABILITY_OFFLINE "offline"
35 | char MQTT_TOPIC_AVAILABILITY[128];
36 | char MQTT_TOPIC_STATE[128];
37 | char MQTT_TOPIC_COMMAND[128];
38 |
39 | char MQTT_TOPIC_AUTOCONF_WIFI_SENSOR[128];
40 | char MQTT_TOPIC_AUTOCONF_PM25_SENSOR[128];
41 |
42 | bool shouldSaveConfig = false;
43 |
44 | void saveConfigCallback() {
45 | shouldSaveConfig = true;
46 | }
47 |
48 | void setup() {
49 | Serial.begin(115200);
50 | SerialCom::setup();
51 |
52 | Serial.println("\n");
53 | Serial.println("Hello from esp8266-vindriktning-particle-sensor");
54 | Serial.printf("Core Version: %s\n", ESP.getCoreVersion().c_str());
55 | Serial.printf("Boot Version: %u\n", ESP.getBootVersion());
56 | Serial.printf("Boot Mode: %u\n", ESP.getBootMode());
57 | Serial.printf("CPU Frequency: %u MHz\n", ESP.getCpuFreqMHz());
58 | Serial.printf("Reset reason: %s\n", ESP.getResetReason().c_str());
59 |
60 | delay(3000);
61 |
62 | snprintf(identifier, sizeof(identifier), "VINDRIKTNING-%X", ESP.getChipId());
63 | snprintf(MQTT_TOPIC_AVAILABILITY, 127, "%s/%s/status", FIRMWARE_PREFIX, identifier);
64 | snprintf(MQTT_TOPIC_STATE, 127, "%s/%s/state", FIRMWARE_PREFIX, identifier);
65 | snprintf(MQTT_TOPIC_COMMAND, 127, "%s/%s/command", FIRMWARE_PREFIX, identifier);
66 |
67 | snprintf(MQTT_TOPIC_AUTOCONF_PM25_SENSOR, 127, "homeassistant/sensor/%s/%s_pm25/config", FIRMWARE_PREFIX, identifier);
68 | snprintf(MQTT_TOPIC_AUTOCONF_WIFI_SENSOR, 127, "homeassistant/sensor/%s/%s_wifi/config", FIRMWARE_PREFIX, identifier);
69 |
70 | WiFi.hostname(identifier);
71 |
72 | Config::load();
73 |
74 | setupWifi();
75 | setupOTA();
76 | mqttClient.setServer(Config::mqtt_server, 1883);
77 | mqttClient.setKeepAlive(10);
78 | mqttClient.setBufferSize(2048);
79 | mqttClient.setCallback(mqttCallback);
80 |
81 | Serial.printf("Hostname: %s\n", identifier);
82 | Serial.printf("IP: %s\n", WiFi.localIP().toString().c_str());
83 |
84 | Serial.println("-- Current GPIO Configuration --");
85 | Serial.printf("PIN_UART_RX: %d\n", SerialCom::PIN_UART_RX);
86 |
87 | mqttReconnect();
88 | }
89 |
90 | void setupOTA() {
91 | ArduinoOTA.onStart([]() { Serial.println("Start"); });
92 | ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); });
93 | ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
94 | Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
95 | });
96 | ArduinoOTA.onError([](ota_error_t error) {
97 | Serial.printf("Error[%u]: ", error);
98 | if (error == OTA_AUTH_ERROR) {
99 | Serial.println("Auth Failed");
100 | } else if (error == OTA_BEGIN_ERROR) {
101 | Serial.println("Begin Failed");
102 | } else if (error == OTA_CONNECT_ERROR) {
103 | Serial.println("Connect Failed");
104 | } else if (error == OTA_RECEIVE_ERROR) {
105 | Serial.println("Receive Failed");
106 | } else if (error == OTA_END_ERROR) {
107 | Serial.println("End Failed");
108 | }
109 | });
110 |
111 | ArduinoOTA.setHostname(identifier);
112 |
113 | // This is less of a security measure and more a accidential flash prevention
114 | ArduinoOTA.setPassword(identifier);
115 | ArduinoOTA.begin();
116 | }
117 |
118 | void loop() {
119 | ArduinoOTA.handle();
120 | SerialCom::handleUart(state);
121 | mqttClient.loop();
122 |
123 | const uint32_t currentMillis = millis();
124 | if (currentMillis - statusPublishPreviousMillis >= statusPublishInterval) {
125 | statusPublishPreviousMillis = currentMillis;
126 |
127 | if (state.valid) {
128 | printf("Publish state\n");
129 | publishState();
130 | }
131 | }
132 |
133 | if (!mqttClient.connected() && currentMillis - lastMqttConnectionAttempt >= mqttConnectionInterval) {
134 | lastMqttConnectionAttempt = currentMillis;
135 | printf("Reconnect mqtt\n");
136 | mqttReconnect();
137 | }
138 | }
139 |
140 | void setupWifi() {
141 | wifiManager.setDebugOutput(false);
142 | wifiManager.setSaveConfigCallback(saveConfigCallback);
143 |
144 | wifiManager.addParameter(&custom_mqtt_server);
145 | wifiManager.addParameter(&custom_mqtt_user);
146 | wifiManager.addParameter(&custom_mqtt_pass);
147 |
148 | WiFi.hostname(identifier);
149 | wifiManager.autoConnect(identifier);
150 | mqttClient.setClient(wifiClient);
151 |
152 | strcpy(Config::mqtt_server, custom_mqtt_server.getValue());
153 | strcpy(Config::username, custom_mqtt_user.getValue());
154 | strcpy(Config::password, custom_mqtt_pass.getValue());
155 |
156 | if (shouldSaveConfig) {
157 | Config::save();
158 | } else {
159 | // For some reason, the read values get overwritten in this function
160 | // To combat this, we just reload the config
161 | // This is most likely a logic error which could be fixed otherwise
162 | Config::load();
163 | }
164 | }
165 |
166 | void resetWifiSettingsAndReboot() {
167 | wifiManager.resetSettings();
168 | delay(3000);
169 | ESP.restart();
170 | }
171 |
172 | void mqttReconnect() {
173 | for (uint8_t attempt = 0; attempt < 3; ++attempt) {
174 | if (mqttClient.connect(identifier, Config::username, Config::password, MQTT_TOPIC_AVAILABILITY, 1, true, AVAILABILITY_OFFLINE)) {
175 | mqttClient.publish(MQTT_TOPIC_AVAILABILITY, AVAILABILITY_ONLINE, true);
176 | publishAutoConfig();
177 |
178 | // Make sure to subscribe after polling the status so that we never execute commands with the default data
179 | mqttClient.subscribe(MQTT_TOPIC_COMMAND);
180 | break;
181 | }
182 | delay(5000);
183 | }
184 | }
185 |
186 | bool isMqttConnected() {
187 | return mqttClient.connected();
188 | }
189 |
190 | void publishState() {
191 | DynamicJsonDocument wifiJson(192);
192 | DynamicJsonDocument stateJson(604);
193 | char payload[256];
194 |
195 | wifiJson["ssid"] = WiFi.SSID();
196 | wifiJson["ip"] = WiFi.localIP().toString();
197 | wifiJson["rssi"] = WiFi.RSSI();
198 |
199 | stateJson["pm25"] = state.avgPM25;
200 |
201 | stateJson["wifi"] = wifiJson.as();
202 |
203 | serializeJson(stateJson, payload);
204 | mqttClient.publish(&MQTT_TOPIC_STATE[0], &payload[0], true);
205 | }
206 |
207 | void mqttCallback(char* topic, uint8_t* payload, unsigned int length) { }
208 |
209 | void publishAutoConfig() {
210 | char mqttPayload[2048];
211 | DynamicJsonDocument device(256);
212 | DynamicJsonDocument autoconfPayload(1024);
213 | StaticJsonDocument<64> identifiersDoc;
214 | JsonArray identifiers = identifiersDoc.to();
215 |
216 | identifiers.add(identifier);
217 |
218 | device["identifiers"] = identifiers;
219 | device["manufacturer"] = "Ikea";
220 | device["model"] = "VINDRIKTNING";
221 | device["name"] = identifier;
222 | device["sw_version"] = "2021.08.0";
223 |
224 | autoconfPayload["device"] = device.as();
225 | autoconfPayload["availability_topic"] = MQTT_TOPIC_AVAILABILITY;
226 | autoconfPayload["state_topic"] = MQTT_TOPIC_STATE;
227 | autoconfPayload["name"] = identifier + String(" WiFi");
228 | autoconfPayload["value_template"] = "{{value_json.wifi.rssi}}";
229 | autoconfPayload["unique_id"] = identifier + String("_wifi");
230 | autoconfPayload["unit_of_measurement"] = "dBm";
231 | autoconfPayload["json_attributes_topic"] = MQTT_TOPIC_STATE;
232 | autoconfPayload["json_attributes_template"] = "{\"ssid\": \"{{value_json.wifi.ssid}}\", \"ip\": \"{{value_json.wifi.ip}}\"}";
233 | autoconfPayload["icon"] = "mdi:wifi";
234 |
235 | serializeJson(autoconfPayload, mqttPayload);
236 | mqttClient.publish(&MQTT_TOPIC_AUTOCONF_WIFI_SENSOR[0], &mqttPayload[0], true);
237 |
238 | autoconfPayload.clear();
239 |
240 | autoconfPayload["device"] = device.as();
241 | autoconfPayload["availability_topic"] = MQTT_TOPIC_AVAILABILITY;
242 | autoconfPayload["state_topic"] = MQTT_TOPIC_STATE;
243 | autoconfPayload["name"] = identifier + String(" PM 2.5");
244 | autoconfPayload["unit_of_measurement"] = "μg/m³";
245 | autoconfPayload["value_template"] = "{{value_json.pm25}}";
246 | autoconfPayload["unique_id"] = identifier + String("_pm25");
247 | autoconfPayload["icon"] = "mdi:air-filter";
248 |
249 | serializeJson(autoconfPayload, mqttPayload);
250 | mqttClient.publish(&MQTT_TOPIC_AUTOCONF_PM25_SENSOR[0], &mqttPayload[0], true);
251 |
252 | autoconfPayload.clear();
253 | }
254 |
--------------------------------------------------------------------------------