├── LICENSE ├── README.md ├── ac_controller └── ac_controller.ino └── relay_server └── relay_server.ino /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 | I wrote this ESP32 code to control EdgeStar AP14001HS portable air conditioners 2 | using the relay outputs from a Nest thermostat. 3 | 4 | See https://pmarks.net/ac for an overview of the project. 5 | -------------------------------------------------------------------------------- /ac_controller/ac_controller.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define ARRAY_SIZE(array) ((sizeof(array))/(sizeof(array[0]))) 6 | 7 | const char WIFI_SSID[] = "redacted"; 8 | const char WIFI_PASS[] = "redacted"; 9 | const char SERVER_IP[] = "192.168.4.1"; 10 | const int SERVER_PORT = 4533; 11 | 12 | const int IR_LED_PIN = 23; 13 | const int IR_KHZ = 38; 14 | 15 | // AP14001HS IR codes 16 | const uint16_t IR_0 = 625; // stable range is 590-700 17 | const uint16_t IR_1 = 1500; // stable range is 1130-1900ish 18 | // IR_STOP is a delay to allow playing codes back-to-back. 19 | // Test procedure: 20 | // - Go to COOL and set temperature to 88. 21 | // - Send "88->80->80->88", pause 1 second, and loop forever. 22 | // With IR_STOP=1100, this loses sync after about a minute. 23 | // With IR_STOP=1500, this ran for ~45 minutes (several hundred 24 | // cycles) at which point it missed an entire sequence of codes, 25 | // which seems like a different kind of bug. 26 | const uint16_t IR_STOP = IR_1; 27 | const uint16_t IR_FAN_SPEED[] = { 28 | IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, 29 | IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, 30 | IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_0, IR_0, IR_1, IR_0, IR_0, IR_0, 31 | IR_1, IR_0, IR_1, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, IR_0, 32 | IR_0, IR_1, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, 33 | IR_STOP 34 | }; 35 | const uint16_t IR_POWER[] = { 36 | IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, 37 | IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, 38 | IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_0, IR_0, IR_1, IR_0, IR_0, IR_0, 39 | IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, IR_0, 40 | IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, 41 | IR_STOP 42 | }; 43 | const uint16_t IR_MODE[] = { 44 | IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, 45 | IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, 46 | IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_0, IR_0, IR_0, IR_0, 47 | IR_1, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, 48 | IR_0, IR_1, IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, 49 | IR_STOP 50 | }; 51 | const uint16_t IR_UP[] = { 52 | IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, 53 | IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, 54 | IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_0, IR_0, IR_1, IR_0, IR_0, IR_0, 55 | IR_1, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, IR_0, 56 | IR_0, IR_1, IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, 57 | IR_STOP 58 | }; 59 | const uint16_t IR_DOWN[] = { 60 | IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, 61 | IR_0, IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, 62 | IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, IR_0, IR_0, IR_0, IR_0, 63 | IR_0, IR_0, IR_1, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_0, IR_1, 64 | IR_0, IR_1, IR_0, IR_1, IR_0, IR_0, IR_0, IR_1, IR_0, IR_1, IR_0, IR_1, IR_0, 65 | IR_STOP 66 | }; 67 | 68 | // It seems that I can't use "enum" from an .ino file 69 | #define ACMode int 70 | const ACMode MODE_COOL = 0; 71 | const ACMode MODE_DEHU = 1; // Not used much. 72 | const ACMode MODE_FAN = 2; 73 | const ACMode MODE_HEAT = 3; 74 | // The A/C cycles through this many modes when we send irMode() 75 | const ACMode MODE_CYCLES = 4; 76 | 77 | // In some contexts, we can treat "OFF" as an extra virtual mode. 78 | const ACMode MODE_OFF = 4; 79 | const ACMode MODE_COUNT = 5; 80 | 81 | // More virtual modes; printable but not counted. 82 | const ACMode MODE_INVALID = 5; 83 | const ACMode MODE_COOL_IDLE = 6; 84 | const ACMode MODE_HEAT_IDLE = 7; 85 | 86 | const char* const MODE_NAMES[] = { 87 | "COOL", "DEHU", "FAN", "HEAT", "OFF", "INVALID", "COOL_IDLE", "HEAT_IDLE" 88 | }; 89 | 90 | struct ACState { 91 | // When cool_temp is negative, we synchronize the temperature range 92 | // to 18..27. For ironclad temperature control, we could reset this 93 | // whenever resyncAndSetActiveMode() runs, but it's actually useful 94 | // to let it float, so the user can manually raise the set point 95 | // (up to 23..32) so smaller rooms don't get too cold. 96 | int heat_temp = -1; 97 | int cool_temp = -1; 98 | 99 | ACMode active_mode = MODE_INVALID; 100 | ACMode memory_mode = MODE_INVALID; 101 | }; 102 | 103 | template 104 | void serialPrintf(const char* format, Args ... args) { 105 | char buf[256] = ""; 106 | snprintf(buf, sizeof(buf), format, args ...); 107 | Serial.print(buf); 108 | } 109 | 110 | template 111 | [[noreturn]] void panic(const char* format, Args ... args) { 112 | serialPrintf(format, args ...); 113 | while (true) { 114 | digitalWrite(2, HIGH); 115 | delay(500); 116 | digitalWrite(2, LOW); 117 | delay(500); 118 | } 119 | } 120 | 121 | // Longer than any other delays. 122 | const unsigned long FOREVER_MS = 86400*1000; 123 | 124 | struct Delay { 125 | bool en = false; 126 | unsigned long start_time; 127 | int duration = -1; 128 | 129 | void start(int duration0 = -1) { 130 | duration = duration0; 131 | start_time = millis(); 132 | en = true; 133 | } 134 | 135 | bool justFired() { 136 | if (duration < 0) panic("undefined duration!\n"); 137 | if (en && elapsed() >= duration) { 138 | en = false; 139 | return true; 140 | } 141 | return false; 142 | } 143 | 144 | int elapsed() { 145 | if (!en) return FOREVER_MS; 146 | // Keep the start_time fresh to avoid wraparound. 147 | const unsigned long now = millis(); 148 | if (now - start_time > FOREVER_MS) { 149 | start_time = now - FOREVER_MS; 150 | } 151 | return now - start_time; 152 | } 153 | }; 154 | 155 | // Do a full mode sync every 3 hours. 156 | const int RESYNC_MS = 3*3600*1000; 157 | 158 | // AP14001HS temperature limits, in F and C. 159 | // We only support celsius because: 160 | // - Temperature changes require fewer clicks 161 | // - Cycling through modes will corrupt fahrenheit temperatures, 162 | // reducing the value by 0-2 degrees. I'm guessing the device 163 | // is using C internally, with lossy F->C->F conversion. 164 | // 165 | // Alas, if you remove power from the AP14001HS while it's running, 166 | // it reboots to fahrenheit, with no way to recover automatically, 167 | // The best we can do is "fail safe" by shifting the ranges from 168 | // 18..27C -> 75..84F (cool), and 18..25C -> 61..70F (heat). 169 | // 170 | // Sync procedure: if you see "F", press in the temperature dial 171 | // and power cycle the controller. 172 | const int COOL_MIN_F = 61; 173 | const int COOL_MAX_F = 89; 174 | const int COOL_MIN_C = 16; 175 | const int COOL_MAX_C = 32; 176 | const int HEAT_MIN_F = 61; 177 | const int HEAT_MAX_F = 77; 178 | const int HEAT_MIN_C = 16; 179 | const int HEAT_MAX_C = 25; 180 | 181 | // Temperatures below/above a reasonable human's thermostat settings, 182 | // so we can send fewer clicks in the common case. 183 | // (For heat, just use Min/Max, because the range is smaller.) 184 | const int COOL_RUN_TEMP = 18; 185 | const int COOL_IDLE_TEMP = 27; 186 | 187 | int comparableSeq(uint16_t sent_qseq, uint16_t qseq, int rseq) { 188 | if (0 <= rseq && rseq <= 0xf) { 189 | if (qseq == sent_qseq - 1) { 190 | return 0x10 | rseq; 191 | } else if (qseq == sent_qseq) { 192 | return 0x20 | rseq; 193 | } 194 | } 195 | return 0x00; 196 | } 197 | 198 | // I'm using an INL-3APD80 photodiode in photovoltaic mode, 199 | // "PIN --->|--- GND", in parallel with a 10nF capacitor. 200 | const int PHOTO_PIN = 33; 201 | // Time between analog reads; lag occurs around <= 25us. 202 | const int READ_US = 50; 203 | // 50us*2000 = 100ms pre-read, because the act of reading 204 | // seems to disturb the measured value. 205 | const int SKIP_COUNT = 2000; 206 | // 50us*2000 = 100ms read, to average out the noise. 207 | // Raising this to 20000 (1000ms) makes it possible to run 208 | // without the 10nF capacitor. 209 | const int READ_COUNT = 2000; 210 | 211 | int filteredRead() { 212 | int sum = 0; 213 | const unsigned long start = micros(); 214 | for (int i = 0; i < SKIP_COUNT + READ_COUNT; i++) { 215 | const int val = analogRead(PHOTO_PIN); 216 | if (i >= SKIP_COUNT) { 217 | sum += val; 218 | } 219 | const int target_us = ((i + 1) * READ_US) + random(READ_US / 5); 220 | const int wait = target_us - (micros() - start); 221 | if (wait > 0) { 222 | delayMicroseconds(wait); 223 | } 224 | } 225 | return sum; 226 | } 227 | 228 | void cycleMode(ACMode* m) { 229 | if (!(MODE_COOL <= *m && *m < MODE_CYCLES)) { 230 | panic("Can't cycle from mode %d\n", *m); 231 | } 232 | *m = (*m + 1) % MODE_CYCLES; 233 | } 234 | 235 | // This defines the minimum separation between light levels. 236 | const float STEP_FACTOR = 1.05; 237 | int stepUp(int val) { 238 | return val * STEP_FACTOR; 239 | } 240 | int stepDn(int val) { 241 | return val * (1 / STEP_FACTOR); 242 | } 243 | 244 | IRsend irsend(IR_LED_PIN); 245 | 246 | void irPower() { 247 | irsend.sendRaw(IR_POWER, ARRAY_SIZE(IR_POWER), IR_KHZ); 248 | } 249 | 250 | void irMode() { 251 | irsend.sendRaw(IR_MODE, ARRAY_SIZE(IR_MODE), IR_KHZ); 252 | } 253 | 254 | int irTemp(int old_temp, int new_temp, bool* first=nullptr) { 255 | serialPrintf("Changing temp: %d -> %d\n", old_temp, new_temp); 256 | bool first_default = true; 257 | if (first == nullptr) { 258 | first = &first_default; 259 | } 260 | int t = old_temp; 261 | while (t < new_temp) { 262 | irsend.sendRaw(IR_UP, ARRAY_SIZE(IR_UP), IR_KHZ); 263 | if (*first) { 264 | *first = false; 265 | } else { 266 | t++; 267 | } 268 | } 269 | while (t > new_temp) { 270 | irsend.sendRaw(IR_DOWN, ARRAY_SIZE(IR_DOWN), IR_KHZ); 271 | if (*first) { 272 | *first = false; 273 | } else { 274 | t--; 275 | } 276 | } 277 | return new_temp; // for convenience 278 | } 279 | 280 | // When this returns, the A/C will be off, 281 | // and we'll know the luma value for "off". 282 | int measureOffLuma() { 283 | const int luma1 = filteredRead(); 284 | serialPrintf("Before POWER: luma=%d\n", luma1); 285 | irPower(); // mystery on/off 286 | const int luma2 = filteredRead(); 287 | if (luma2 > stepUp(luma1)) { 288 | serialPrintf("After POWER: luma=%d (on!)\n", luma2); 289 | irPower(); 290 | return luma1; 291 | } else if (luma2 < stepDn(luma1)) { 292 | serialPrintf("After POWER: luma=%d (off!)\n", luma2); 293 | return luma2; 294 | } else { 295 | serialPrintf("After POWER: luma=%d (no effect!)\n", luma2); 296 | irPower(); // Better to shout an even number of POWERs into the void. 297 | panic("POWER didn't seem to do anything.\n"); 298 | } 299 | } 300 | 301 | int maxIndex(const std::vector& vals) { 302 | int max_val = INT_MIN; 303 | int max_index = 0; 304 | for (int i = 0; i < vals.size(); i++) { 305 | if (vals[i] > max_val) { 306 | max_val = vals[i]; 307 | max_index = i; 308 | } 309 | } 310 | return max_index; 311 | } 312 | 313 | int lumaOrder(ACMode mode) { 314 | switch (mode) { 315 | case MODE_OFF: return 1; 316 | case MODE_HEAT: return 2; 317 | case MODE_FAN: return 3; 318 | case MODE_COOL: return 4; 319 | default: panic("Mode %d has no luma order\n", mode); 320 | } 321 | } 322 | 323 | bool orderOk(ACMode old_mode, int old_luma, ACMode new_mode, int new_luma) { 324 | if (old_mode == new_mode) { 325 | panic("orderOk requires different modes\n"); 326 | } 327 | const bool old_is_lo = lumaOrder(old_mode) < lumaOrder(new_mode); 328 | const ACMode lo_mode = old_is_lo ? old_mode : new_mode; 329 | const ACMode hi_mode = old_is_lo ? new_mode : old_mode; 330 | const int lo_luma = old_is_lo ? old_luma : new_luma; 331 | const int hi_luma = old_is_lo ? new_luma : old_luma; 332 | if (!(lo_luma < hi_luma)) { 333 | serialPrintf("Modes %s (luma=%d) and %s (luma=%d) out of order\n", 334 | MODE_NAMES[lo_mode], lo_luma, MODE_NAMES[hi_mode], hi_luma); 335 | return false; 336 | } 337 | if (!(stepUp(lo_luma) < hi_luma)) { 338 | serialPrintf("Modes %s (luma=%d) and %s (luma=%d) are too close\n", 339 | MODE_NAMES[lo_mode], lo_luma, MODE_NAMES[hi_mode], hi_luma); 340 | return false; 341 | } 342 | return true; 343 | } 344 | 345 | // XXX maybe force a resync instead?? 346 | void orderOkOrPanic(ACMode old_mode, int old_luma, ACMode new_mode, int new_luma) { 347 | if (!orderOk(old_mode, old_luma, new_mode, new_luma)) { 348 | panic("Transition from %s -> %s violated luma order!\n", 349 | MODE_NAMES[old_mode], MODE_NAMES[new_mode]); 350 | } 351 | } 352 | 353 | // This must be called immediately after measureOffLuma(). 354 | // When we return, the A/C will be in the mode select menu for 355 | // the next several seconds, pointing at the returned mode. 356 | ACMode synchronizeMode(int off_luma) { 357 | std::vector lumas; 358 | while (lumas.size() < MODE_CYCLES) { 359 | irMode(); 360 | const int l = filteredRead(); 361 | serialPrintf("Sampled luma=%d for mystery mode %d\n", l, lumas.size()); 362 | lumas.push_back(l); 363 | } 364 | 365 | // "Cool" is the brightest value. 366 | const int cool_idx = maxIndex(lumas); 367 | 368 | const std::vector mode_lumas = { 369 | lumas[cool_idx], 370 | lumas[(cool_idx + 1) % MODE_CYCLES], 371 | lumas[(cool_idx + 2) % MODE_CYCLES], 372 | lumas[(cool_idx + 3) % MODE_CYCLES], 373 | off_luma 374 | }; 375 | 376 | bool all_ok = true; 377 | for (int i = 0; i < MODE_COUNT; i++) { 378 | serialPrintf("Mode %4s has luma=%d\n", MODE_NAMES[i], mode_lumas[i]); 379 | for (int j = i+1; j < MODE_COUNT; j++) { 380 | if (i != MODE_DEHU && j != MODE_DEHU) { 381 | all_ok &= orderOk(i, mode_lumas[i], j, mode_lumas[j]); 382 | } 383 | } 384 | } 385 | if (!all_ok) { 386 | // Try to restore the initial mode before dying. 387 | irMode(); 388 | panic("Mode order seems wrong -- check photodiode polarity?\n"); 389 | } 390 | 391 | // Which mode was lit initially? 392 | const ACMode init_mode = (MODE_CYCLES - cool_idx) % MODE_CYCLES; 393 | 394 | // Which mode is lit now? 395 | const ACMode out = (init_mode + MODE_CYCLES - 1) % MODE_CYCLES; 396 | 397 | return out; 398 | } 399 | 400 | // Caller should update resync_d. 401 | void resyncAndSetActiveMode(ACMode new_mode, ACState* acs) { 402 | bool leave_power_off = false; 403 | switch (new_mode) { 404 | case MODE_OFF: 405 | // To sync into OFF, just turn the fan on+off. 406 | new_mode = MODE_FAN; 407 | leave_power_off = true; 408 | break; 409 | case MODE_HEAT: 410 | case MODE_COOL: 411 | case MODE_FAN: 412 | break; 413 | default: 414 | panic("mode %d not supported here\n", new_mode); 415 | } 416 | const int off_luma = measureOffLuma(); 417 | acs->active_mode = synchronizeMode(off_luma); 418 | while (acs->active_mode != new_mode) { 419 | irMode(); 420 | cycleMode(&acs->active_mode); 421 | } 422 | 423 | applyActiveMode(true, acs); 424 | 425 | if (leave_power_off) { 426 | irPower(); 427 | acs->active_mode = MODE_OFF; 428 | } else { 429 | const int on_luma = filteredRead(); 430 | orderOkOrPanic(MODE_OFF, off_luma, new_mode, on_luma); 431 | } 432 | } 433 | 434 | void applyActiveMode(bool in_menu, ACState* acs) { 435 | if (in_menu) { 436 | // On the AP14001HS, when I cycle through modes, stop on FAN, 437 | // and then press POWER (1 or 3 times), it sometimes starts 438 | // either with the fan on low, or the compressor 439 | // (but not the exhaust) running. I've been able to reproduce 440 | // this with delay(<=800), but not with delay(>=900), 441 | // so 1000 seems like a safe value. 442 | delay(1000); 443 | } 444 | irPower(); 445 | acs->memory_mode = acs->active_mode; 446 | 447 | bool first = true; 448 | switch (acs->active_mode) { 449 | case MODE_HEAT: 450 | if (acs->heat_temp < 0) { 451 | // Clamp to min F, but hope that we're in C mode. 452 | irTemp(HEAT_MAX_F, HEAT_MIN_F, &first); 453 | acs->heat_temp = HEAT_MIN_C; 454 | } 455 | acs->heat_temp = irTemp(acs->heat_temp, HEAT_MAX_C, &first); 456 | break; 457 | case MODE_COOL: 458 | if (acs->cool_temp < 0) { 459 | // Clamp to max F, but hope that we're in C mode. 460 | irTemp(COOL_MIN_F, COOL_MAX_F, &first); 461 | acs->cool_temp = COOL_MAX_C; 462 | } 463 | acs->cool_temp = irTemp(acs->cool_temp, COOL_RUN_TEMP, &first); 464 | break; 465 | case MODE_FAN: 466 | break; 467 | default: 468 | panic("mode %d not supported here\n", acs->active_mode); 469 | } 470 | } 471 | 472 | void powerOff(ACState* acs) { 473 | const int on_luma = filteredRead(); 474 | irPower(); 475 | const int off_luma = filteredRead(); 476 | orderOkOrPanic(acs->memory_mode, on_luma, MODE_OFF, off_luma); 477 | acs->active_mode = MODE_OFF; 478 | } 479 | 480 | struct ProtocolState { 481 | WiFiUDP udp; 482 | 483 | // Sequencing algorithm: 484 | // - Every couple seconds, the client sends a query (Q) containing 485 | // a randomly-initialized query sequence number (qseq). 486 | // - The server immediately responds with a response (R) containing 487 | // "R qseq rseq mode", where qseq is copied from the query, and 488 | // rseq is 0. 489 | // - When the server wants to fast-push a new mode, it sends another 490 | // packet with rseq incremented. 491 | // - The client will only accept responses with the current or 492 | // previous qseq, and (qseq, rseq) must grow lexicographically. 493 | uint16_t sent_qseq; 494 | 495 | // Initialized after connecting to WiFi. 496 | uint16_t recvd_qseq; 497 | int recvd_rseq; 498 | }; 499 | 500 | void sendUDP(struct ProtocolState* prs) { 501 | char buf[16]; 502 | const int buf_len = sprintf(buf, "Q %04x", ++prs->sent_qseq); 503 | prs->udp.beginPacket(SERVER_IP, SERVER_PORT); 504 | prs->udp.write(reinterpret_cast(buf), buf_len); 505 | prs->udp.endPacket(); 506 | } 507 | 508 | ACMode receiveUDP(struct ProtocolState* prs) { 509 | ACMode out = MODE_INVALID; 510 | while (prs->udp.parsePacket() > 0) { 511 | char buf[32]; 512 | const int buf_len = prs->udp.read(buf, ARRAY_SIZE(buf)-1); 513 | if (buf_len < 0) continue; 514 | buf[buf_len] = '\0'; 515 | char buf_type; 516 | uint16_t buf_qseq; 517 | int buf_rseq; 518 | char buf_mode[ARRAY_SIZE(buf)]; 519 | if (std::sscanf(buf, "%c %04" SCNx16 " %1x %s", 520 | &buf_type, &buf_qseq, &buf_rseq, buf_mode) != 4) { 521 | serialPrintf("packet malformed\n"); 522 | continue; 523 | } 524 | if (buf_type != 'R') { 525 | serialPrintf("packet type '%c'\n"); 526 | continue; 527 | } 528 | const int last_cmp_seq = comparableSeq(prs->sent_qseq, prs->recvd_qseq, prs->recvd_rseq); 529 | const int this_cmp_seq = comparableSeq(prs->sent_qseq, buf_qseq, buf_rseq); 530 | if (!(this_cmp_seq > last_cmp_seq)) { 531 | serialPrintf("packet late or misordered\n"); 532 | continue; 533 | } 534 | if (buf_qseq == prs->sent_qseq) { 535 | const int missed_responses = ((buf_qseq - prs->recvd_qseq) & 0xFFFF) - 1; 536 | if (missed_responses > 0) { 537 | serialPrintf("Recovered after %d missed responses\n", missed_responses); 538 | } 539 | } 540 | prs->recvd_qseq = buf_qseq; 541 | prs->recvd_rseq = buf_rseq; 542 | 543 | // TODO: Read entire response. 544 | switch (buf_mode[0]) { 545 | case 'H': 546 | out = MODE_HEAT; 547 | break; 548 | case 'C': 549 | out = MODE_COOL; 550 | break; 551 | case 'F': 552 | out = MODE_FAN; 553 | break; 554 | case 'O': 555 | out = MODE_OFF; 556 | break; 557 | } 558 | } 559 | return out; 560 | } 561 | 562 | void setup() { 563 | Serial.begin(115200); 564 | 565 | // Underclocking to 80 MHz breaks IR transmission. 566 | // 160 MHz isn't obviously broken, but it's not worth the risk. 567 | serialPrintf("CPU: %d MHz\n", getCpuFrequencyMhz()); 568 | 569 | analogSetAttenuation(ADC_0db); 570 | randomSeed(analogRead(PHOTO_PIN)); 571 | pinMode(2, OUTPUT); 572 | irsend.begin(); 573 | } 574 | 575 | void loop() { 576 | static ACState acs; 577 | static ProtocolState prs; 578 | static Delay resync_d; 579 | static Delay active_mode_d; 580 | static Delay compressor_idle_d; 581 | static Delay wifi_connecting_d; 582 | static Delay wifi_reconnect_d; 583 | static Delay next_udp_d; 584 | static int last_compressor_idle_ms = FOREVER_MS; 585 | static ACMode want_mode = MODE_INVALID; 586 | 587 | static bool init = true; 588 | if (init) { 589 | wifi_reconnect_d.start(0); 590 | active_mode_d.start(); // Hold INVALID for a bit. 591 | init = false; 592 | } 593 | 594 | // Use lambdas to avoid passing lots of variables. 595 | auto transition_hold_time = [&]() { 596 | if (acs.active_mode == want_mode) { 597 | return 0; 598 | } 599 | switch (acs.active_mode) { 600 | case MODE_INVALID: 601 | // After a power failure, wait 5 seconds for the A/C to settle. 602 | return 5*1000; 603 | case MODE_HEAT_IDLE: 604 | case MODE_COOL_IDLE: { 605 | // If the compressor was idle for less than 10 minutes 606 | // during the last cycle, then try to cover the entire 607 | // idle gap with fan noise. 608 | // (I'm not sure if this is useful in heat mode.) 609 | static const int IDLE_THRESHOLD_MS = 600*1000; 610 | if (want_mode == MODE_OFF && 611 | last_compressor_idle_ms < IDLE_THRESHOLD_MS) { 612 | return IDLE_THRESHOLD_MS * 3 / 2; // 150% 613 | } 614 | } // fallthrough 615 | case MODE_HEAT: 616 | case MODE_COOL: 617 | // Keep the compressor on/off for 3 minutes. 618 | // The bare minimum is ~20s, to exit the temperature menu. 619 | return 180*1000; 620 | default: 621 | return 0; 622 | } 623 | }; 624 | auto print_next_transition = [&]() { 625 | const int t = transition_hold_time() - active_mode_d.elapsed(); 626 | if (t > 0) { 627 | serialPrintf("Transition from %s -> %s in %d ms\n", 628 | MODE_NAMES[acs.active_mode], MODE_NAMES[want_mode], t); 629 | } 630 | }; 631 | 632 | resync_d.elapsed(); // Don't let this get too old. 633 | 634 | if (wifi_reconnect_d.justFired()) { 635 | serialPrintf("Connecting to %s\n", WIFI_SSID); 636 | WiFi.begin(WIFI_SSID, WIFI_PASS); 637 | wifi_connecting_d.start(10000); 638 | } 639 | if (wifi_connecting_d.justFired()) { 640 | WiFi.disconnect(); 641 | wifi_reconnect_d.start(10000); 642 | serialPrintf("WiFi's dead; reconnect in %d ms...\n", wifi_reconnect_d.duration); 643 | want_mode = MODE_OFF; 644 | } 645 | if (wifi_reconnect_d.en) { 646 | // ignoring WiFi. 647 | } else if (WiFi.status() == WL_CONNECTED) { 648 | if (wifi_connecting_d.en) { 649 | serialPrintf("WiFi connected.\n"); 650 | wifi_connecting_d.en = false; 651 | prs.recvd_qseq = prs.sent_qseq = esp_random(); 652 | prs.recvd_rseq = 0; 653 | next_udp_d.start(0); 654 | } 655 | if (next_udp_d.justFired()) { 656 | const int missed_responses = (prs.sent_qseq - prs.recvd_qseq) & 0xFFFF; 657 | if (missed_responses > 0) { 658 | serialPrintf("UDP timeout #%d\n", missed_responses); 659 | } 660 | if (missed_responses >= 5) { 661 | serialPrintf("Too many UDP timeouts; killing WiFi.\n"); 662 | wifi_connecting_d.start(0); 663 | } else { 664 | sendUDP(&prs); 665 | next_udp_d.start(random(1900, 2100)); // Query again (or timeout) in 2 seconds. 666 | } 667 | } 668 | const ACMode new_mode = receiveUDP(&prs); 669 | if (new_mode != MODE_INVALID) { 670 | // Blip to indicate WiFi ok. 671 | digitalWrite(2, HIGH); 672 | delay(1); 673 | digitalWrite(2, LOW); 674 | 675 | if (new_mode != want_mode) { 676 | want_mode = new_mode; 677 | print_next_transition(); 678 | } 679 | } 680 | } else if (!wifi_connecting_d.en) { 681 | // WiFi died sometime after a successful connection. 682 | wifi_connecting_d.start(0); 683 | } 684 | 685 | if (active_mode_d.elapsed() >= transition_hold_time() && 686 | acs.active_mode != want_mode) { 687 | serialPrintf("Executing transition: %s -> %s\n", 688 | MODE_NAMES[acs.active_mode], MODE_NAMES[want_mode]); 689 | switch (acs.active_mode) { 690 | case MODE_INVALID: 691 | resync_d.start(0); 692 | // fallthrough 693 | case MODE_OFF: 694 | // Switching from OFF -> (*) is a good time to stop and sync. 695 | if (resync_d.justFired()) { 696 | resyncAndSetActiveMode(want_mode, &acs); 697 | resync_d.start(RESYNC_MS); 698 | } else { 699 | const int off_luma = filteredRead(); 700 | acs.active_mode = acs.memory_mode; 701 | bool in_menu = false; 702 | while (acs.active_mode != want_mode) { 703 | irMode(); 704 | if (!in_menu) { 705 | in_menu = true; 706 | } else { 707 | cycleMode(&acs.active_mode); 708 | } 709 | } 710 | applyActiveMode(in_menu, &acs); 711 | const int on_luma = filteredRead(); 712 | orderOkOrPanic(MODE_OFF, off_luma, acs.active_mode, on_luma); 713 | } 714 | break; 715 | // HEAT and COOL need to idle before doing anything else. 716 | case MODE_HEAT: 717 | acs.heat_temp = irTemp(acs.heat_temp, HEAT_MIN_C); 718 | acs.active_mode = MODE_HEAT_IDLE; 719 | compressor_idle_d.start(); 720 | break; 721 | case MODE_COOL: 722 | acs.cool_temp = irTemp(acs.cool_temp, COOL_IDLE_TEMP); 723 | acs.active_mode = MODE_COOL_IDLE; 724 | compressor_idle_d.start(); 725 | break; 726 | case MODE_HEAT_IDLE: 727 | if (resync_d.justFired()) { 728 | resyncAndSetActiveMode(want_mode, &acs); 729 | resync_d.start(RESYNC_MS); 730 | } else if (want_mode == MODE_HEAT) { 731 | // Fast idle->heat transition. 732 | acs.heat_temp = irTemp(acs.heat_temp, HEAT_MAX_C); 733 | acs.active_mode = MODE_HEAT; 734 | } else { 735 | powerOff(&acs); 736 | } 737 | break; 738 | case MODE_COOL_IDLE: 739 | if (resync_d.justFired()) { 740 | resyncAndSetActiveMode(want_mode, &acs); 741 | resync_d.start(RESYNC_MS); 742 | } else if (want_mode == MODE_COOL) { 743 | // Fast idle->cool transition. 744 | acs.cool_temp = irTemp(acs.cool_temp, COOL_RUN_TEMP); 745 | acs.active_mode = MODE_COOL; 746 | } else { 747 | powerOff(&acs); 748 | } 749 | break; 750 | case MODE_FAN: 751 | powerOff(&acs); 752 | break; 753 | } 754 | if (acs.active_mode == MODE_HEAT || acs.active_mode == MODE_COOL) { 755 | last_compressor_idle_ms = compressor_idle_d.elapsed(); 756 | } 757 | active_mode_d.start(); 758 | serialPrintf("Mode is now %s\n", MODE_NAMES[acs.active_mode]); 759 | print_next_transition(); 760 | } 761 | 762 | delay(1); // saves 20mA @ 240MHz 763 | } 764 | -------------------------------------------------------------------------------- /relay_server/relay_server.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | const char WIFI_SSID[] = "redacted"; 7 | const char WIFI_PASS[] = "redacted"; 8 | const int SERVER_PORT = 4533; 9 | 10 | #define ARRAY_SIZE(array) ((sizeof(array))/(sizeof(array[0]))) 11 | 12 | template 13 | void serialPrintf(const char* format, Args ... args) { 14 | char buf[256] = ""; 15 | snprintf(buf, sizeof(buf), format, args ...); 16 | Serial.print(buf); 17 | } 18 | 19 | // Assuming the USB port is "down": 20 | // - Pin 18: right connector, orange, labeled "O" on the thermostat. 21 | // "heat pump changeover valve" energized (active low) for cooling mode, 22 | // deenergized for heating mode. 23 | // - Pin 19: right connector, yellow, labeled "Y1" on the thermostat. 24 | // "compressor relay stage 1" energized (active low) to activate 25 | // the heat pump compressor, otherwise off. 26 | const int OPTO_PINS[] = {18, 19}; 27 | int opto_count = 0; 28 | int opto_lo[ARRAY_SIZE(OPTO_PINS)] = {0}; 29 | unsigned int opto_sample_millis = 0; 30 | std::deque opto_queue; 31 | 32 | void OptoSample() { 33 | for (int i = 0; i < ARRAY_SIZE(OPTO_PINS); i++) { 34 | if (!digitalRead(OPTO_PINS[i])) { 35 | opto_lo[i]++; 36 | } 37 | } 38 | opto_count++; 39 | } 40 | 41 | int ReduceOptoSamples() { 42 | int out_bits = 0; 43 | for (int i = 0; i < ARRAY_SIZE(OPTO_PINS); i++) { 44 | // Set bit 'i' if >75% of samples are low (AC waveform present.) 45 | if (opto_lo[i]*4 > opto_count*3) { 46 | out_bits |= (1 << i); 47 | } 48 | opto_lo[i] = 0; 49 | } 50 | opto_count = 0; 51 | return out_bits; 52 | } 53 | 54 | // Returns true if the queue contains 10 identical samples. 55 | // Each sample is based on 25ms of AC waveform, so 250ms total. 56 | bool RotateOptoQueue(int sample) { 57 | static const int MAX_SIZE = 10; 58 | while (opto_queue.size() >= MAX_SIZE) { 59 | opto_queue.pop_front(); 60 | } 61 | opto_queue.push_back(sample); 62 | int count_same = 0; 63 | for (int v : opto_queue) { 64 | if (v == opto_queue[0]) { 65 | count_same++; 66 | } 67 | } 68 | return count_same == MAX_SIZE; 69 | } 70 | 71 | bool DoOptoStuff() { 72 | const unsigned long now = millis(); 73 | if (opto_sample_millis != now) { 74 | OptoSample(); 75 | opto_sample_millis = now; 76 | if (opto_count >= 25 /* milliseconds */) { 77 | return RotateOptoQueue(ReduceOptoSamples()); 78 | } 79 | } 80 | return false; // no new value 81 | } 82 | 83 | struct IP4Port { 84 | IP4Port(IPAddress ip0, uint16_t port0) { 85 | ip = ip0; 86 | port = port0; 87 | } 88 | IPAddress ip; 89 | uint16_t port; 90 | }; 91 | 92 | struct IP4PortCmp { 93 | bool operator()(const IP4Port& a, const IP4Port& b) { 94 | // Endian doesn't matter, as long as the order is consistent. 95 | if (a.ip != b.ip) { 96 | return a.ip < b.ip; 97 | } 98 | return a.port < b.port; 99 | } 100 | }; 101 | 102 | struct Seqs { 103 | uint16_t qseq; 104 | int rseq = -1; 105 | }; 106 | 107 | std::map clients; 108 | unsigned long cleanup_millis = millis(); 109 | 110 | WiFiUDP udp; 111 | 112 | String send_mode = "OFF"; 113 | 114 | void sendUDP(const struct IP4Port& dest, const struct Seqs& cs) { 115 | char buf[32]; 116 | const int buf_len = sprintf(buf, "R %04x %x %s", 117 | cs.qseq, cs.rseq, send_mode.c_str()); 118 | udp.beginPacket(dest.ip, dest.port); 119 | udp.write(reinterpret_cast(buf), buf_len); 120 | udp.endPacket(); 121 | } 122 | 123 | void pokeAllClients(bool actually_send) { 124 | for (auto it = clients.begin(); it != clients.end();) { 125 | const IP4Port& client = it->first; 126 | Seqs* cs = &it->second; 127 | if (++cs->rseq < 5) { 128 | if (actually_send) { 129 | sendUDP(client, *cs); 130 | } 131 | ++it; 132 | } else { 133 | serialPrintf("Dropping client: %s %d\n", 134 | client.ip.toString().c_str(), client.port); 135 | it = clients.erase(it); 136 | } 137 | } 138 | } 139 | 140 | void setup() { 141 | Serial.begin(115200); 142 | serialPrintf("Hello from relay_server\n"); 143 | 144 | setCpuFrequencyMhz(80); // saves 35mA 145 | serialPrintf("CPU: %d MHz\n", getCpuFrequencyMhz()); 146 | 147 | pinMode(2, OUTPUT); 148 | 149 | for (int pin : OPTO_PINS) { 150 | pinMode(pin, INPUT_PULLUP); 151 | } 152 | 153 | WiFi.softAP(WIFI_SSID, WIFI_PASS); 154 | IPAddress myIP = WiFi.softAPIP(); 155 | Serial.print("AP IP address: "); 156 | Serial.println(myIP); 157 | 158 | udp.begin(SERVER_PORT); 159 | } 160 | 161 | void loop() { 162 | bool blink = false; 163 | 164 | if (DoOptoStuff()) { 165 | String new_mode; 166 | switch (opto_queue[0]) { 167 | case 0x2: // Y1 active, O inactive 168 | new_mode = "HEAT"; 169 | break; 170 | case 0x3: // Y1 active, O active 171 | new_mode = "COOL"; 172 | break; 173 | default: // Y1 inactive 174 | new_mode = "OFF"; 175 | break; 176 | } 177 | if (new_mode != send_mode) { 178 | serialPrintf("Changing from %s->%s\n", 179 | send_mode.c_str(), new_mode.c_str()); 180 | send_mode = new_mode; 181 | pokeAllClients(true); 182 | } 183 | } 184 | 185 | while (udp.parsePacket() > 0) { 186 | char buf[32]; 187 | const int buf_len = udp.read(buf, ARRAY_SIZE(buf)-1); 188 | if (buf_len < 0) continue; 189 | buf[buf_len] = '\0'; 190 | char buf_type; 191 | uint16_t buf_qseq; 192 | char buf_ignore; 193 | if (std::sscanf(buf, "%c %04" SCNx16 "%c", &buf_type, &buf_qseq, &buf_ignore) != 2) { 194 | serialPrintf("packet malformed\n"); 195 | continue; 196 | } 197 | if (buf_type != 'Q') { 198 | serialPrintf("packet with type '%c'\n", buf_type); 199 | continue; 200 | } 201 | const IP4Port client(udp.remoteIP(), udp.remotePort()); 202 | Seqs* cs = &clients[client]; 203 | if (cs->rseq < 0) { 204 | serialPrintf("New client: %s %d\n", 205 | client.ip.toString().c_str(), client.port); 206 | } else if (((cs->qseq - buf_qseq) & 0xFFFF) < 10) { 207 | serialPrintf("packet out of order: %04x->%04x\n", cs->qseq, buf_qseq); 208 | continue; 209 | } 210 | cs->qseq = buf_qseq; 211 | cs->rseq = 0; 212 | sendUDP(client, *cs); 213 | blink = true; 214 | } 215 | 216 | const unsigned long now = millis(); 217 | if (now - cleanup_millis >= 10000) { 218 | pokeAllClients(false); 219 | cleanup_millis = now; 220 | } 221 | 222 | if (blink) digitalWrite(2, HIGH); 223 | delay(1); // saves 5mA @ 80MHz 224 | if (blink) digitalWrite(2, LOW); 225 | } 226 | --------------------------------------------------------------------------------