├── .clang-format
├── .gitignore
├── .gitlab-ci.yml
├── .travis.yml
├── .vscode
└── extensions.json
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── ISSUE_TEMPLATE.md
├── LICENSE
├── PULL_REQUEST_TEMPLATE.md
├── README.md
├── diagrams
├── nodemcu_pir_sensor.fzz
└── nodemcu_pir_sensor.svg
├── lib
└── readme.txt
├── platformio.ini
└── src
├── main.cpp
└── setup-template.h
/.clang-format:
--------------------------------------------------------------------------------
1 | ColumnLimit: 0
2 | IndentWidth: 2
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .pioenvs
2 | .piolibdeps
3 | .clang_complete
4 | .gcc-flags.json
5 | .vscode/.browse.c_cpp.db*
6 | .vscode/c_cpp_properties.json
7 | .vscode/launch.json
8 | .vscode/settings.json
9 | src/setup.h
10 |
--------------------------------------------------------------------------------
/.gitlab-ci.yml:
--------------------------------------------------------------------------------
1 | image: python:2
2 |
3 | stages:
4 | - build
5 |
6 | # Change pip's cache directory to be inside the project directory since we can
7 | # only cache local items.
8 | variables:
9 | PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache"
10 |
11 | # Pip's cache doesn't store the python packages
12 | # https://pip.pypa.io/en/stable/reference/pip_install/#caching
13 | #
14 | # If you want to also cache the installed packages, you have to install
15 | # them in a virtualenv and cache it as well.
16 | cache:
17 | paths:
18 | - .cache/pip
19 | - venv/
20 | - ~/.platformio
21 |
22 | before_script:
23 | - python -V # Print out python version for debugging
24 | - pip install -U platformio
25 | - platformio update
26 |
27 | run:
28 | stage: build
29 | script:
30 | - mv src/setup-template.h src/setup.h
31 | - platformio run
32 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python:
3 | - "2.7"
4 |
5 | sudo: false
6 | cache:
7 | directories:
8 | - "~/.platformio"
9 |
10 | install:
11 | - pip install -U platformio
12 | - platformio update
13 |
14 | script:
15 | - mv src/setup-template.h src/setup.h
16 | - platformio run
17 |
--------------------------------------------------------------------------------
/.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 | }
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Contributing
2 | You are welcome to edit, fork and create pull requests as you like.
3 |
4 | - If you make a change, make sure to refer to any issues that it fixes.
5 | - Make sure you have used linters and tested what you have added/changed works.
6 | - Any pull request will be verified by the bots, so make sure you fix any issues the bots find.
7 | - I, and any other users I approve will be able to merge your changes so be patient.
8 |
--------------------------------------------------------------------------------
/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ## Description of issue
2 |
3 | ## How to reproduce issue (if applicable)
4 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ## Description
2 |
3 |
4 | ## Related issues this fixes
5 |
6 |
7 | ## Example entry for HASS `configuration.yaml` (if applicable):
8 |
9 |
10 | ## Checklist:
11 | - [ ] Change is tested and works on my device.
12 | - [ ] Linters have been run.
13 | - [ ] Code is ready for merge (You can set the title to WIP to stop merge early)
14 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ESP8266 MQTT PIR Sensor [](https://travis-ci.org/timmo001/ESP8266-MQTT-PIR-Sensor)
2 | ESP8266 MQTT PIR Sensor. Compatible with Home Assistant's MQTT `sensor` and `binary_sensor`
3 |
4 | ## Hardware Example
5 | 
6 |
7 | ## Software Setup
8 | - Using Atom or VS Code, install [Platform IO](https://platformio.org/platformio-ide)
9 | - Once setup, install the `esp8266` embedded platform
10 | - Rename `src/setup-template.h` to `src/setup.h` and add your network, MQTT and lighting setup information. Take note of the `deviceName` you set. You will need this later to subscribe to MQTT messages.
11 | - Build the project (Ctrl+Alt+B) and check for any errors
12 |
13 | > If the build produces an error referencing dependencies, You will need to manually install these libraries:
14 | - ArduinoJson
15 | - PubSubClient
16 | - Upload to your board of choice (Ctrl+Alt+U). This project was created specifically for the `NodeMCU` but can be configured to work with another WiFi board with some tinkering.
17 |
18 | ## Example Home Assistant Configuration
19 | This example creates a `binary_sensor` with an automation to brighten a `light_group`, if another light sensor is below a threshold and a someone is home, then dimming the lights after 10 minutes if the PIR does not detect movement. This will only occur if the lights are still on.
20 |
21 | ```yaml
22 | binary_sensor:
23 | platform: mqtt
24 | name: Kitchen PIR
25 | state_topic: sensor/pir001
26 | payload_on: 1
27 | payload_off: 0
28 |
29 | automation:
30 | - alias: Kitchen Motion Detected
31 | trigger:
32 | - platform: state
33 | entity_id: binary_sensor.kitchen_pir
34 | to: 'on'
35 | condition:
36 | - condition: state
37 | entity_id: group.phones
38 | state: home
39 | - condition: numeric_state
40 | entity_id: sensor.sn1_ldr
41 | below: '450'
42 | action:
43 | - alias: Wake Kitchen lights
44 | data:
45 | entity_id: group.kitchen
46 | brightness_pct: 80
47 | service: light.turn_on
48 |
49 | - alias: 'Reset kitchen lights 10 minutes after last movement'
50 | trigger:
51 | platform: state
52 | entity_id: binary_sensor.kitchen_pir
53 | to: 'off'
54 | for:
55 | minutes: 10
56 | condition:
57 | - condition: state
58 | entity_id: group.phones
59 | state: home
60 | - condition: numeric_state
61 | entity_id: sensor.sn1_ldr
62 | below: '450'
63 | - condition: state
64 | entity_id: light.kitchen_room_lights
65 | state: 'on'
66 | action:
67 | service: homeassistant.turn_on
68 | entity_id: scene.reset_kitchen_lights
69 | ```
70 |
--------------------------------------------------------------------------------
/diagrams/nodemcu_pir_sensor.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/timmo001/ESP8266-MQTT-PIR-Sensor/06f55a1eaba11013c5cda4a622277f9d550dc1d3/diagrams/nodemcu_pir_sensor.fzz
--------------------------------------------------------------------------------
/diagrams/nodemcu_pir_sensor.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/lib/readme.txt:
--------------------------------------------------------------------------------
1 |
2 | This directory is intended for the project specific (private) libraries.
3 | PlatformIO will compile them to static libraries and link to executable file.
4 |
5 | The source code of each library should be placed in separate directory, like
6 | "lib/private_lib/[here are source files]".
7 |
8 | For example, see how can be organized `Foo` and `Bar` libraries:
9 |
10 | |--lib
11 | | |
12 | | |--Bar
13 | | | |--docs
14 | | | |--examples
15 | | | |--src
16 | | | |- Bar.c
17 | | | |- Bar.h
18 | | | |- library.json (optional, custom build options, etc) http://docs.platformio.org/page/librarymanager/config.html
19 | | |
20 | | |--Foo
21 | | | |- Foo.c
22 | | | |- Foo.h
23 | | |
24 | | |- readme.txt --> THIS FILE
25 | |
26 | |- platformio.ini
27 | |--src
28 | |- main.c
29 |
30 | Then in `src/main.c` you should use:
31 |
32 | #include
33 | #include
34 |
35 | // rest H/C/CPP code
36 |
37 | PlatformIO will find your libraries automatically, configure preprocessor's
38 | include paths and build them.
39 |
40 | More information about PlatformIO Library Dependency Finder
41 | - http://docs.platformio.org/page/librarymanager/ldf.html
42 |
--------------------------------------------------------------------------------
/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 | ; http://docs.platformio.org/page/projectconf.html
10 |
11 | [env:nodemcuv2]
12 | platform = espressif8266
13 | board = nodemcuv2
14 | framework = arduino
15 | lib_deps = ArduinoJson, PubSubClient
16 | monitor_baud = 9600
17 |
--------------------------------------------------------------------------------
/src/main.cpp:
--------------------------------------------------------------------------------
1 | using namespace std;
2 |
3 | #include "setup.h"
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | /****************************************FOR JSON***************************************/
10 | const int BUFFER_SIZE = JSON_OBJECT_SIZE(10);
11 | #define MQTT_MAX_PACKET_SIZE 512
12 |
13 | /******************************** OTHER GLOBALS *******************************/
14 | long state = -1;
15 |
16 | WiFiClient espClient;
17 | PubSubClient client(espClient);
18 |
19 | void setup_wifi() {
20 | delay(10);
21 | Serial.print("Connecting to SSID: ");
22 | Serial.println(WIFI_SSID);
23 |
24 | // We start by connecting to a WiFi network
25 | WiFi.mode(WIFI_STA);
26 | WiFi.hostname(DEVICE_NAME);
27 |
28 | if (WiFi.status() != WL_CONNECTED) { // FIX FOR USING 2.3.0 CORE (only .begin if not connected)
29 | WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
30 | }
31 |
32 | while (WiFi.status() != WL_CONNECTED) {
33 | delay(500);
34 | Serial.print(".");
35 | }
36 |
37 | Serial.println("");
38 | Serial.println("WiFi connected");
39 | Serial.print("IP address: ");
40 | Serial.println(WiFi.localIP());
41 | }
42 |
43 | void sendState() {
44 | StaticJsonBuffer jsonBuffer;
45 |
46 | // const char *payload = (char *)state;
47 | char payload[1];
48 | sprintf(payload, "%d", state);
49 |
50 | char combinedArray[sizeof(MQTT_STATE_TOPIC_PREFIX) + sizeof(DEVICE_NAME)];
51 | sprintf(combinedArray, "%s%s", MQTT_STATE_TOPIC_PREFIX, DEVICE_NAME); // with word space
52 | client.publish(combinedArray, payload, true);
53 | }
54 |
55 | void reconnect() {
56 | // Loop until we're reconnected
57 | while (!client.connected()) {
58 | Serial.print("Attempting MQTT connection...");
59 | // Attempt to connect
60 | if (client.connect(DEVICE_NAME, MQTT_USER, MQTT_PASSWORD)) {
61 | Serial.println("connected");
62 |
63 | char combinedArray[sizeof(MQTT_STATE_TOPIC_PREFIX) + sizeof(DEVICE_NAME) + 4];
64 | sprintf(combinedArray, "%s%s/set", MQTT_STATE_TOPIC_PREFIX, DEVICE_NAME); // with word space
65 | client.subscribe(combinedArray);
66 |
67 | sendState();
68 | } else {
69 | Serial.print("failed, rc=");
70 | Serial.print(client.state());
71 | Serial.println(" try again in 5 seconds");
72 | // Wait 5 seconds before retrying
73 | delay(5000);
74 | }
75 | }
76 | }
77 |
78 | void updateState() {
79 | long newState = digitalRead(SENSOR_PIN);
80 | if (newState != state) {
81 | if (newState == HIGH) {
82 | Serial.println("Motion detected");
83 | digitalWrite(LED_BUILTIN, LOW); // Turn the status LED on
84 | } else {
85 | Serial.println("No Motion");
86 | digitalWrite(LED_BUILTIN, HIGH); // Turn the status LED off
87 | }
88 | state = newState;
89 | sendState();
90 | }
91 | delay(50);
92 | }
93 |
94 | void setup() {
95 | Serial.begin(9600);
96 |
97 | setup_wifi();
98 |
99 | client.setServer(MQTT_SERVER, MQTT_PORT);
100 |
101 | //OTA SETUP
102 | ArduinoOTA.setPort(OTA_PORT);
103 | ArduinoOTA.setHostname(DEVICE_NAME); // Hostname defaults to esp8266-[ChipID]
104 | ArduinoOTA.setPassword((const char *)OTA_PASSWORD); // No authentication by default
105 |
106 | ArduinoOTA.onStart([]() { Serial.println("Starting"); });
107 | ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); });
108 | ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
109 | Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
110 | });
111 | ArduinoOTA.onError([](ota_error_t error) {
112 | Serial.print("Error[%u]: " + error);
113 | if (error == OTA_AUTH_ERROR)
114 | Serial.println("Auth Failed");
115 | else if (error == OTA_BEGIN_ERROR)
116 | Serial.println("Begin Failed");
117 | else if (error == OTA_CONNECT_ERROR)
118 | Serial.println("Connect Failed");
119 | else if (error == OTA_RECEIVE_ERROR)
120 | Serial.println("Receive Failed");
121 | else if (error == OTA_END_ERROR)
122 | Serial.println("End Failed");
123 | });
124 | ArduinoOTA.begin();
125 |
126 | Serial.println("Ready");
127 |
128 | pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output (So it doesnt float as a LED is on this pin)
129 | pinMode(SENSOR_PIN, INPUT); // Declare sensor as input
130 | }
131 |
132 | void loop() {
133 | if (!client.connected()) {
134 | reconnect();
135 | }
136 | if (WiFi.status() != WL_CONNECTED) {
137 | delay(1);
138 | Serial.print("WIFI Disconnected. Attempting reconnection.");
139 | setup_wifi();
140 | return;
141 | }
142 | client.loop(); // Check MQTT
143 | ArduinoOTA.handle(); // Check OTA Firmware Updates
144 |
145 | updateState();
146 | }
--------------------------------------------------------------------------------
/src/setup-template.h:
--------------------------------------------------------------------------------
1 | using namespace std;
2 |
3 | #define WIFI_SSID "SSID"
4 | #define WIFI_PASSWORD "PASSWORD"
5 |
6 | #define MQTT_SERVER "DOMAIN_OR_IP"
7 | #define MQTT_USER "USERNAME"
8 | #define MQTT_PASSWORD "PASSWORD"
9 | #define MQTT_PORT 1883
10 | #define MQTT_STATE_TOPIC_PREFIX "sensor/" // e.g. sensor/ and sensor//set
11 | #define DEVICE_NAME "pir001"
12 |
13 | #define OTA_PASSWORD "PASSWORD" // The password you will need to enter to upload remotely via the ArduinoIDE
14 | #define OTA_PORT 8266
15 |
16 | #define SENSOR_PIN D8
17 |
--------------------------------------------------------------------------------