数年前にESP8266で作ったリモコンがたまに不調になったりして寿命が近そうな気がしてきたので Raspberry Pi Pico W で新たに作り直してみた。
今までと同じ仕様で作るには、WiFi/MQTT/MDNS(Query含む)/OTAなどの機能が必要であったが、Arduinoのボードマネジャーとして下記を利用するだけでOKであったことと少しだけ修正したライブラリもあったりもしたが開発のしやすさは素晴らしすぎる!!
https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json
詳細は下記を参照のこと。
Arduino-Pico
ESPのWiFiライブラリをPicoWへ移植してるようなので、ESPからPicoWへの移行を考えてる人には超お勧めだ。
なお、我が家でしか使えない物を公開する意味ってあるのかな?とも思ったが自身の忘備録かねて皆様の何かの参考にでもなれば幸いである。
【初期化操作】
3個のボタンを同時に押しながら電源を入れると初期化され、APモード(192.168.4.1)で起動する。
スマホなどから”picow-xxxxxx”にWiFi接続(初期パスワードは接続名と同じ)後、ブラウザで”192.168.4.1″を開くと設定画面が表示される。
接続先APのPASSWORD設定を行なった後[Apply]で保存し[Reboot]で再起動するとSTAモードで起動しWiFi接続が成功するまで繰り返す。
【通常操作】
・ボタン短押し(3秒未満)...シャッターを閉じる。
・ボタン長押し(3秒以上)...シャッターを開ける。
・割り当てされたIPアドレス或いは”picow-xxxxxx.local”をブラウザで開くと設定画面が表示される。
【接続管理】
WiFi/MQTTへの接続/再接続は自動で行なう。
【LED】
1.0秒毎に点滅...APモード
0.2秒毎に点滅...WiFi/MQTT未接続
消灯...シャッター全閉
点滅...シャッター開閉度(100-0%)に応じて消灯/点灯の割合が変化
点灯...シャッター全開
【外観】

TW5-3-7B プラスチックケース:W50 x D70 x 27.5(mm)

※タカチのプラケースの基板取付の下(4mm)にタクトSWがおさまるのはリモコン用途を意識しているのかな?
【基板】

※基板のタクトSWの中心穴は、ボタン用の穴あけ位置をドリルなどでマークするのに便利!!
【USB-Cコネクタ】

5個/セット DIY OEM Type C メスソケット – 2ピン ヘッダー ケーブル ピッチ=2.0mm ラッチマウントタイプ DC 5V 電源
※ CC1/2のプルダウンがないのでUSB-A to C変換ケーブル等を利用すること。
【設定画面】黒塗りがスゴ!!(笑)
【別途インストールが必要なArduinoライブラリ】
ArduinoMqttClient
【ライブラリの修正箇所】
[…/libraries/ArduinoMqttClient/src/MqttClient.h]
|
1 |
#define MQTT_CLIENT_STD_FUNCTION_CALLBACK |
※コメントを外す
[…/Arduino15/packages/rp2040/hardware/rp2040/6.3.0/libraries/ArduinoOTA/ArduinoOTA.cpp]
|
1 2 |
//#include <SimpleMDNS.h> #include <LEAmDNS.h> |
※インクルードを入れ替える
【ファームウェア】
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
/* ShutterSwitch-PicoW.ino - Shutter Switch Controller for Raspberry Pi Pico W Copyright (c) 2026 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Boards Manager: https://arduino-pico.readthedocs.io/ ---------------------------------------------------- Flash Size: "2MB (Sketch 1MB, FS: 1MB) WiFi Resion: "Japan" ---------------------------------------------------- AP Mode: 192.168.4.1 */ #include "wlan.h" #define LED_WIFI_OFFLINE_INTERVAL 200 #define LED_APMODE_INTERVAL 1000 #define LED_PERCENT_INTERVAL 1000 #define BUTTON_LONG_PUSH_TIME 3000 #define SHUTTER_NO_MAX 3 #define elementsof(a) (int)(sizeof(a)/sizeof(*a)) static const uint8_t GPIO_BTNS[] = { 11, 6, 2 }; static const uint8_t GPIO_LEDS[] = { 19, 22, 28 }; static const char CMD_STOP[] = "STOP"; /* unsupported */ static const char CMD_DOWN_FORCE[] = "DOWN_FORCE"; /* unsupported */ static const char CMD_DOWN[] = "DOWN"; static const char CMD_UP[] = "UP"; static const char TOPIC_CONTROL[] = "/home/garage/shutter/control/"; static const char TOPIC_STATE [] = "/home/garage/shutter/state/"; static const char TOPIC_QUERY [] = "/home/garage/shutter/query/0"; static WLan wlan; static uint8_t percent[3] = { 100, 100, 100 }; static uint8_t led_mask; static uint8_t led_data; static int getStartShutterNo(void) { return 1; } static String getTopicAll(const char *topic) { String rv = topic; rv += '#'; return rv; } static String getTopic(const char *topic, int no) { String rv = topic; rv += no; return rv; } static void command(const char *cmd, int no) { wlan.mqtt_publish(getTopic(TOPIC_CONTROL, no + getStartShutterNo()), cmd, strlen(cmd)); } static void message(WLan& wlan, const String& topic, const void* payload, size_t size) { (void)wlan; if (topic.startsWith(TOPIC_STATE)) { int no = topic.substring(strlen(TOPIC_STATE)).toInt(); if (no <= SHUTTER_NO_MAX) { no -= getStartShutterNo(); if ((no >= 0) && (no < elementsof(percent))) { uint8_t val = String((const char*)payload, size).toInt(); percent[no] = val; } } } } static void notify(WLan& wlan, WLan::NOTIFY status) { switch (status) { case WLan::NOTIFY::WIFI_CONNECTED: break; case WLan::NOTIFY::WIFI_DISCONNECTED: break; case WLan::NOTIFY::MQTT_CONNECTED: wlan.mqtt_message(message); wlan.mqtt_subscribe(getTopicAll(TOPIC_STATE)); wlan.mqtt_publish(TOPIC_QUERY); break; case WLan::NOTIFY::MQTT_DISCONNECTED: break; } } static void display_led(bool on, int no = -1) { if ((no >= 0) && (no < elementsof(GPIO_LEDS))) { uint8_t bit = 1 << no; if (on) led_data |= bit; else led_data &= ~bit; if ((led_mask & bit) == 0) digitalWrite(GPIO_LEDS[no], on ? LOW : HIGH); } else { for (int i = 0; i < elementsof(GPIO_LEDS); ++i) display_led(on, i); } } static void control_led(bool mask, bool on, int no = -1) { if ((no >= 0) && (no < elementsof(GPIO_LEDS))) { uint8_t bit = 1 << no; if (mask) led_mask |= bit; else { led_mask &= ~bit; on = led_data & bit; } digitalWrite(GPIO_LEDS[no], on ? LOW : HIGH); } else { for (int i = 0; i < elementsof(GPIO_LEDS); ++i) control_led(mask, on, i); } } static uint8_t button_status(void) { uint8_t rv = 0; for (int i = 0; i < elementsof(GPIO_BTNS); ++i) { if (digitalRead(GPIO_BTNS[i]) == LOW) rv |= 1 << i; } return rv; } static void control(void) { static struct { uint32_t pushed; uint8_t status; } btns[elementsof(GPIO_BTNS)]; for (int i = 0; i < elementsof(btns); ++i) { if (digitalRead(GPIO_BTNS[i]) == LOW) { switch (btns[i].status) { case 0: btns[i].pushed = millis(); btns[i].status = 1; control_led(true, false, i); break; case 1: if (millis() - btns[i].pushed >= BUTTON_LONG_PUSH_TIME) { command(CMD_UP, i); control_led(true, true, i); delay(100); control_led(false, false, i); btns[i].status = 2; } break; } } else { if ((btns[i].status == 1) && (millis() - btns[i].pushed >= 20)) { command(CMD_DOWN, i); control_led(true, true, i); delay(100); } control_led(false, false, i); btns[i].status = 0; } } } void setup() { /* Setup GPIO */ for (int i = 0; i < elementsof(GPIO_BTNS); ++i) pinMode(GPIO_BTNS[i], INPUT_PULLUP); for (int i = 0; i < elementsof(GPIO_LEDS); ++i) pinMode(GPIO_LEDS[i], OUTPUT_12MA); /* Setup wlan */ wlan.notify(notify); wlan.begin(button_status() == 7); /* Setup Serial (USB) */ Serial.begin(115200); while (!Serial && (millis() < 1000)) delay(10); } void loop() { if (wlan.run()) { /* WiFi+MQTT Connected */ control(); uint32_t t = millis() % LED_PERCENT_INTERVAL; for (int i = 0; i < elementsof(GPIO_LEDS); ++i) display_led(t >= (uint32_t)percent[i] * LED_PERCENT_INTERVAL / 100, i); } else { /* WiFi+MQTT Disonnected or AP Mode */ display_led((millis() / (wlan.apmode() ? LED_APMODE_INTERVAL : LED_WIFI_OFFLINE_INTERVAL)) & 1); } } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 |
/* wlan.h - WiFi Management Library for Raspberry Pi Pico W Copyright (c) 2026 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Boards Manager: https://arduino-pico.readthedocs.io/ ---------------------------------------------------- Flash Size: "2MB (Sketch 1MB, FS: 1MB) WiFi Resion: "Japan" ---------------------------------------------------- */ #pragma once #include <algorithm> #include <vector> #include <map> #include <functional> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <time.h> #include <Arduino.h> #include <EEPROM.h> #include <LEAmDNS.h> #include <ArduinoOTA.h> /* ArduinoOTA.cpp: #include <SimpleMDNS.h> --> <LEAmDNS.h> */ #include <ArduinoMqttClient.h> /* MqttClient.h: #define MQTT_CLIENT_STD_FUNCTION_CALLBACK */ #include "wsta.h" class WLan : public WSta { public: typedef enum struct NOTIFY { WIFI_CONNECTED, WIFI_DISCONNECTED, MQTT_CONNECTED, MQTT_DISCONNECTED, }; typedef std::function<void(WLan& wlan, NOTIFY status)> notify_t; typedef std::function<void(WLan& wlan, const String& topic, const void* payload, size_t size)> mqtt_message_t; WLan(bool led = true) : WSta(led) { _mqtt_client = new MqttClient(_wifiClient); _mqtt_broker.connected = false; memset(&_uptime, 0, sizeof(_uptime)); } virtual ~WLan(void) { end(); delete _mqtt_client; WSta::~WSta(); } void begin(bool init = false) { EEPROM.begin(4096); EEPROM.get<decltype(_conf)>(0, _conf); if (init || (_conf.mark != CONF_CHECK_MARK)) { memset(&_conf, 0, sizeof(_conf)); _conf.mark = CONF_CHECK_MARK; _conf.dhcp = true; strncpy(_conf.sys_password, udn(), sizeof(_conf.sys_password)); EEPROM.put<decltype(_conf)>(0, _conf); EEPROM.commit(); } if (!IPAddress(_conf.subnet).isSet()) memcpy(_conf.subnet, &IPAddress(255, 255, 255, 0)[0], sizeof(_conf.subnet)); if (_conf.mqtt_port == 0) _conf.mqtt_port = 1883; /* Check AP Mode */ if ((_ap_mode = !*_conf.ssid)) beginAP(); } void end(void) { if (_ap_mode) endAP(); else disconnected(); } bool apmode(void) { return _ap_mode; } void notify(notify_t callback) { _notify = callback; } void mqtt_auth(const String& username, const String& password) { _mqtt_client->setUsernamePassword(username, password); } void mqtt_keepalive_interval(uint32_t interval) { _mqtt_client->setKeepAliveInterval(interval); } void mqtt_connection_timeout(uint32_t timeout) { _mqtt_client->setConnectionTimeout(timeout); } void mqtt_tx_payload_size(uint16_t size) { _mqtt_client->setTxPayloadSize(size); } void mqtt_clean_session(bool clean) { _mqtt_client->setCleanSession(clean); } void mqtt_will_message(const String& topic, const void* payload = nullptr, size_t size = 0, bool retain = false, uint8_t qos = 0) { _mqtt_client->beginWill(topic, size, retain, qos); if (payload && size) _mqtt_client->write((uint8_t*)payload, size); _mqtt_client->endWill(); } void mqtt_publish(const String& topic, const void* payload = nullptr, size_t size = 0, bool retain = false, uint8_t qos = 0, bool dup = false) { _mqtt_client->beginMessage(topic, size, retain, qos, dup); if (payload && size) _mqtt_client->write((uint8_t*)payload, size); _mqtt_client->endMessage(); } void mqtt_subscribe(const String& topic, uint8_t qos = 0) { _mqtt_client->subscribe(topic, qos); } void mqtt_message(mqtt_message_t callback) { _mqtt_client->onMessage ( [this, callback] (MqttClient* client, int messageSize) { String topic = client->messageTopic(); if (callback) { char payload[messageSize]; client->read((uint8_t*)payload, messageSize); callback(*this, topic, payload, messageSize); } } ); } bool run(void) { uptime(); if (_ap_mode) { http_server(); connect_led(true); } else if (WSta::run()) { http_server(); mqtt_client(); ArduinoOTA.handle(); return !*_conf.mqtt_host || _mqtt_client->connected(); } return false; } uint64_t uptime(void) { uint32_t t = millis(); _uptime.msec += t - _uptime.save; _uptime.save = t; return _uptime.msec; } const char* udn(void) { if (*_udn == 0) { /* Creating Unique Device Name */ uint8_t mac[WL_MAC_ADDR_LENGTH]; WiFi.macAddress(mac); #if defined(ARDUINO_RASPBERRY_PI_PICO_2W) snprintf(_udn, sizeof(_udn), "pico2w-%02x%02x%02x", mac[WL_MAC_ADDR_LENGTH - 3], mac[WL_MAC_ADDR_LENGTH - 2], mac[WL_MAC_ADDR_LENGTH - 1]); #else snprintf(_udn, sizeof(_udn), "picow-%02x%02x%02x", mac[WL_MAC_ADDR_LENGTH - 3], mac[WL_MAC_ADDR_LENGTH - 2], mac[WL_MAC_ADDR_LENGTH - 1]); #endif } return _udn; } protected: virtual void wifi_connected(void) { if (_notify) _notify(*this, NOTIFY::WIFI_CONNECTED); } virtual void wifi_disconnected(void) { if (_notify) _notify(*this, NOTIFY::WIFI_DISCONNECTED); } virtual void mqtt_connected(void) { if (_notify) _notify(*this, NOTIFY::MQTT_CONNECTED); } virtual void mqtt_disconnected(void) { if (_notify) _notify(*this, NOTIFY::MQTT_DISCONNECTED); } private: static constexpr const uint32_t CONF_CHECK_MARK = 0xCAFEBABE; static constexpr const uint16_t HTTP_SERVER_PORT = 80; static constexpr const char* HTTP_GET = "GET"; static constexpr const char* HTTP_POST = "POST"; static constexpr const char* CONTENT_TYPE = "Content-Type:"; static constexpr const char* CONTENT_LENGTH = "Content-Length:"; static constexpr const char* URLENCODED = "application/x-www-form-urlencoded"; static constexpr const char* URL_SETTING = "/"; static constexpr const char* STA_SSID = "ssid"; static constexpr const char* STA_PSWD = "pswd"; static constexpr const char* STA_DHCP = "dhcp"; static constexpr const char* STA_LOCAL_IP = "local_ip"; static constexpr const char* STA_SUBNET = "subnet"; static constexpr const char* STA_GATEWAY = "gateway"; static constexpr const char* STA_DNS_SERVER = "dns_server"; static constexpr const char* AP_LOCAL_IP = "ap_local_ip"; static constexpr const char* AP_SUBNET = "ap_subnet"; static constexpr const char* MQTT_HOST = "mqtt_host"; static constexpr const char* MQTT_PORT = "mqtt_port"; static constexpr const char* SNTP_SERVER = "sntp_server"; static constexpr const char* SNTP_TZNAME = "sntp_tzname"; static constexpr const char* SYS_PASSWORD = "sys_password"; static constexpr const char* SUBMIT = "submit"; static constexpr const char* SUBMIT_RESCAN = "rescan"; static constexpr const char* SUBMIT_APPLY = "apply"; static constexpr const char* SUBMIT_REBOOT = "reboot"; typedef struct { uint32_t mark; char ssid[32]; char pswd[64]; bool dhcp; uint8_t local_ip [4]; uint8_t subnet [4]; uint8_t gateway [4]; uint8_t dns_server[4]; char mqtt_host[32]; uint16_t mqtt_port; char sntp_server[32]; char sntp_tzname[32]; char sys_password[32]; } net_conf_t; typedef struct { String name; IPAddress addr; uint16_t port; bool connected; } mqtt_broker_t; typedef struct { uint32_t save; uint64_t msec; } uptime_t; WiFiServer _http_server; WiFiClient _wifiClient; MqttClient *_mqtt_client; bool _ap_mode; net_conf_t _conf; char _udn[16]; uptime_t _uptime; mqtt_broker_t _mqtt_broker; notify_t _notify; void beginAP(void) { WiFi.beginAP(udn(), _conf.sys_password); _http_server.begin(HTTP_SERVER_PORT); } void endAP(void) { _http_server.stop(); WiFi.disconnectAP(); } void connect(void) override { if (*_conf.ssid) { WiFi.disconnect(); if (_conf.dhcp) WiFi.config(IPAddress(), IPAddress(), IPAddress(), IPAddress()); else WiFi.config(IPAddress(_conf.local_ip), IPAddress(_conf.dns_server), IPAddress(_conf.gateway), IPAddress(_conf.subnet)); WiFi.beginNoBlock(_conf.ssid, _conf.pswd); } } void connected(uint32_t conn_time) override { (void)conn_time; if (*_conf.sntp_server) { NTP.begin(_conf.sntp_server); if (*_conf.sntp_tzname) { setenv("TZ", _conf.sntp_tzname, 1); tzset(); } } _http_server.begin(HTTP_SERVER_PORT); _mqtt_client->setId(udn()); ArduinoOTA.setHostname(udn()); ArduinoOTA.setPassword(_conf.sys_password); ArduinoOTA.begin(); wifi_connected(); } void disconnected(void) override { wifi_disconnected(); if (_mqtt_broker.connected) mqtt_disconnected(); _mqtt_broker.connected = false; ArduinoOTA.end(); _mqtt_client->stop(); _http_server.stop(); sntp_stop(); } bool query_mqtt_Broker(void) { _mqtt_broker.addr.clear(); if (*_conf.mqtt_host) { _mqtt_broker.addr.fromString(_conf.mqtt_host); if (_mqtt_broker.addr.isSet()) { /* Fixed IP Address */ _mqtt_broker.name = _mqtt_broker.addr.toString(); _mqtt_broker.port = _conf.mqtt_port; } else { // MDNS Query Service (MQTT) int index = MDNS.queryService("mqtt", "tcp"); if (index) { if ((strcmp(_conf.mqtt_host, "*") == 0) || (strcmp(_conf.mqtt_host, "*.local") == 0)) index = 0; else { /* Fixed Host Name */ while (--index >= 0) { if (strcasecmp(MDNS.answerHostname(index), _conf.mqtt_host) == 0) break; } } if (index >= 0) { _mqtt_broker.name = MDNS.answerHostname(index); _mqtt_broker.addr = MDNS.answerIP(index); _mqtt_broker.port = MDNS.answerPort(index); } } MDNS.removeQuery(); } } return _mqtt_broker.addr.isSet(); } void mqtt_client(void) { if (_mqtt_client->connected()) _mqtt_client->poll(); else if (_mqtt_broker.connected) { _mqtt_broker.connected = false; mqtt_disconnected(); _mqtt_client->stop(); } else if (query_mqtt_Broker()) { if (_mqtt_client->connect(_mqtt_broker.addr, _mqtt_broker.port)) { _mqtt_broker.connected = true; mqtt_connected(); } } } static void strncpy(char* dst, const char* src, size_t len) { if (len) { ::strncpy(dst, src, len); dst[len - 1] = 0; } } static void appendf(String& str, const char* format, ...) { va_list ap; va_start(ap, format); while (1) { const char* p = strchr(format, '%'); if (p) { str += String(format, (size_t)p - (size_t)format); switch (p[1]) { case '%': str += '%'; break; case 'd': str += va_arg(ap, int); break; case 'u': str += va_arg(ap, unsigned int); break; case 's': str += va_arg(ap, const char*); break; case '\0': --p; /* fall through */ default : str += "<%"; if (p[2]) str += p[2]; str += '>'; break; } format = &p[2]; } else { str += format; break; } } va_end(ap); } static String urlencoded(const String& str) { String rv = str; int pos; rv.replace('+', ' '); while ((pos = rv.indexOf('%')) >= 0) { char h = rv[pos + 1]; char l = rv[pos + 2]; h = (h >= 'a' ? h - 'a' + 10 : (h >= 'A' ? h - 'A' + 10 : h - '0')); l = (l >= 'a' ? l - 'a' + 10 : (l >= 'A' ? l - 'A' + 10 : l - '0')); char c = (h << 4) + l; rv = rv.substring(0, pos) + c + rv.substring(pos + 3); } return rv; } void http_server(void) { WiFiClient client = _http_server.accept(); if (!client) return; // Wait for the client to send data for (uint32_t t = millis(); !client.available(); delay(1)) { if (!client.connected() || (millis() - t >= 1000)) { client.stop(); return; } } // Read HTTP Header String method, url, http, type, str; std::map<String, String> params; int length = -1; char buf[256]; do { str = client.readStringUntil('\r'); client.read(); /* skip '\n' */ if (method.length() == 0) { int pos = str.indexOf(' '); if (pos > 0) { method = str.substring(0, pos); method.trim(); url = str.substring(pos + 1); url.trim(); pos = url.indexOf(' '); if (pos > 0) { http = str.substring(pos + 1); http.trim(); url = url.substring(0, pos); } } else method = "UNKNOWN"; } else if (str.startsWith(CONTENT_TYPE)) { type = str.substring(strlen(CONTENT_TYPE)); type.trim(); } else if (str.startsWith(CONTENT_LENGTH)) length = str.substring(strlen(CONTENT_LENGTH)).toInt(); } while (str.length()); /* Parse URL Parameters */ int pos = url.indexOf('?'); if (pos > 0) { str = url.substring(pos + 1); url = url.substring(0, pos); while (str.length()) { pos = str.indexOf('&'); String key, val; if (pos >= 0) { key = str.substring(0, pos); str = str.substring(pos + 1); } else { key = str; str = ""; } pos = key.indexOf('='); if (pos >= 0) { val = urlencoded(key.substring(pos + 1)); key = urlencoded(key.substring(0, pos)); params[key] = val; } } } /* Parse POST Parameters */ if (method.equals(HTTP_POST) && type.equals(URLENCODED) && (length > 0)) { int l, m, r; l = 0; while (length > 0) { int n = client.read(buf + l, min(length, (int)sizeof(buf) - l)); if (n <= 0) break; length -= n; n += l; l = r = 0; m = -1; while (r < n) { char c = buf[r++]; if (c == '=') m = r; if ((c == '&') || ((r == n) && (length == 0))) { if (m >= 0) { String key = urlencoded(String(buf + l, m - l - 1)); String val = urlencoded(String(buf + m, r - m - (c == '&'))); params[key] = val; } l = r; m = -1; } } n -= l; memcpy(buf, buf + l, n); l = n; } } /* Setting Form Parameters */ if (url.equals(URL_SETTING)) { String submit = params[SUBMIT]; if (submit.equals(SUBMIT_REBOOT)) rp2040.reboot(); else if (submit.equals(SUBMIT_APPLY)) { /* Data Save to EEPROM */ for (int i = 0;; ++i) { String ssid = STA_SSID; String pswd = STA_PSWD; ssid += i; pswd += i; if (!params.contains(ssid)) break; ssid = params[ssid]; pswd = params[pswd]; if (pswd.length()) { strncpy(_conf.ssid, ssid.c_str(), sizeof(_conf.ssid)); strncpy(_conf.pswd, pswd.c_str(), sizeof(_conf.pswd)); break; } } IPAddress local_ip, subnet, gateway, dns_server; local_ip.fromString(params[STA_LOCAL_IP]); subnet.fromString(params[STA_SUBNET]); gateway.fromString(params[STA_GATEWAY]); dns_server.fromString(params[STA_DNS_SERVER]); _conf.dhcp = params[STA_DHCP].toInt(); memcpy(_conf.local_ip, &local_ip[0], sizeof(_conf.local_ip)); memcpy(_conf.subnet, &subnet[0], sizeof(_conf.subnet)); memcpy(_conf.gateway, &gateway[0], sizeof(_conf.gateway)); memcpy(_conf.dns_server, &dns_server[0], sizeof(_conf.dns_server)); strncpy(_conf.mqtt_host, params[MQTT_HOST].c_str(), sizeof(_conf.mqtt_host)); _conf.mqtt_port = params[MQTT_PORT].toInt(); strncpy(_conf.sntp_server, params[SNTP_SERVER].c_str(), sizeof(_conf.sntp_server)); strncpy(_conf.sntp_tzname, params[SNTP_TZNAME].c_str(), sizeof(_conf.sntp_tzname)); if (params[SYS_PASSWORD].length()) strncpy(_conf.sys_password, params[SYS_PASSWORD].c_str(), sizeof(_conf.sys_password)); EEPROM.put<decltype(_conf)>(0, _conf); EEPROM.commit(); } } // Build a simple HTML response String html = "<!DOCTYPE html><html><body>"; html += "<h1>"; html += udn(); html += " — WiFi Setting</h1>"; appendf(html, "<form action='%s' method='post'>", URL_SETTING); /* Scan Network */ struct ap_t { String ssid; int rssi; }; std::vector<struct ap_t> scan; int count = WiFi.scanNetworks(); for (int i = 0; i < count; ++i) { const char* ssid = WiFi.SSID(i); int rssi = WiFi.RSSI(i); if (*ssid) { bool found = false; for (auto& ap : scan) { if (ap.ssid.equals(ssid)) { if (ap.rssi < rssi) ap.rssi = rssi; found = true; break; } } if (!found) scan.push_back({ ssid, rssi }); } } std::sort(scan.begin(), scan.end(), [](ap_t& a, ap_t& b) { return a.rssi > b.rssi; }); /* Access Point */ html += "<h3>Access Point</h3>"; html += "<table border='1' cellpadding='6'>"; html += "<tr><th>SSID</th><th>PASSWORD</th><th>RSSI</th></tr>"; int index = 0; for (auto& ap : scan) { appendf(html, "<tr>" "<td><input type='text' name='%s%d' value='%s' readonly>%s</td>" "<td><input type='text' name='%s%d' value=''></td>" "<td>%d</td>" "</tr>", STA_SSID, index, ap.ssid.c_str(), ap.ssid.equals(_conf.ssid) ? "<" : "", STA_PSWD, index, ap.rssi); ++index; } appendf(html, "<tr>" "<td><input type='text' name='%s%d' value=''></td>" "<td><input type='text' name='%s%d' value=''></td>" "<td></td>" "</tr>", STA_SSID, index, STA_PSWD, index); html += "</table>"; /* IP Config */ html += "<p><h3>IP Config</h3>"; html += "<table border='1' cellpadding='6'>"; appendf(html, "<tr>" "<td>DHCP</td>" "<td><select name='%s'><option value='0'%s>Disabled</option><option value='1'%s>Enabled</option></select></td>" "<td align='center'>%s</td>" "</tr>", STA_DHCP, !_conf.dhcp ? " selected" : "", _conf.dhcp ? " selected" : "", _ap_mode ? "AP Mode" : "STA Mode"); appendf(html, "<tr>" "<td>Local IP</td>" "<td><input type='text' name='%s' value='%s'></td>" "<td>%s</td>" "</tr>", STA_LOCAL_IP, IPAddress(_conf.local_ip).toString().c_str(), _ap_mode ? WiFi.softAPIP().toString().c_str() : WiFi.localIP().toString().c_str()); appendf(html, "<tr>" "<td>Subnet</td>" "<td><input type='text' name='%s' value='%s'></td>" "<td>%s</td>" "</tr>", STA_SUBNET, IPAddress(_conf.subnet).toString().c_str(), _ap_mode ? "255.255.255.0" : WiFi.subnetMask().toString().c_str()); appendf(html, "<tr>" "<td>Gateway</td>" "<td><input type='text' name='%s' value='%s''></td>" "<td>%s</td>" "</tr>", STA_GATEWAY, IPAddress(_conf.gateway).toString().c_str(), _ap_mode ? WiFi.softAPIP().toString().c_str() : WiFi.gatewayIP().toString().c_str()); appendf(html, "<tr>" "<td>DNS Server</td>" "<td><input type='text' name='%s' value='%s'></td>" "<td>%s</td>" "</tr>", STA_DNS_SERVER, IPAddress(_conf.dns_server).toString().c_str(), _ap_mode ? WiFi.softAPIP().toString().c_str() : WiFi.dnsIP().toString().c_str()); appendf(html, "<tr>" "<td>MAC Address</td>" "<td></td>" "<td>%s</td>" "</tr>", _ap_mode ? WiFi.softAPmacAddress().c_str() : WiFi.macAddress().c_str()); html += "</table>"; /* MQTT Broker */ html += "<p><h3>MQTT Broker</h3>"; html += "<table border='1' cellpadding='6'>"; str = ""; if ((!_mqtt_broker.name.equals(_mqtt_broker.addr.toString())) && (!_mqtt_broker.name.equals(_conf.mqtt_host))) str = " (" + _mqtt_broker.name + ")"; appendf(html, "<tr>" "<td>Host</td>" "<td><input type='text' name='%s' value='%s'></td>" "<td>%s%s</td>" "</tr>", MQTT_HOST, _conf.mqtt_host, _mqtt_broker.addr.toString().c_str(), str.c_str()); appendf(html, "<tr>" "<td>Port</td>" "<td><input type='text' name='%s' value='%u'></td>" "<td>%u</td>" "</tr>", MQTT_PORT, _conf.mqtt_port, _mqtt_broker.port); html += "</table>"; /* SNTP Server */ html += "<p><h3>SNTP Server</h3>"; html += "<table border='1' cellpadding='6'>"; str = ""; if (*_conf.sntp_server) { time_t t = time(NULL); struct tm lt = *localtime(&t); snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d", lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday, lt.tm_hour, lt.tm_min, lt.tm_sec); str += buf; } appendf(html, "<tr>" "<td>Host</td>" "<td><input type='text' name='%s' value='%s'></td>" "<td>%s</td>" "</tr>", SNTP_SERVER, _conf.sntp_server, str.c_str()); appendf(html, "<tr>" "<td>TZ Name</td>" "<td><input type='text' name='%s' value='%s'></td>" "<td>Proleptic Format</td>" "</tr>", SNTP_TZNAME, _conf.sntp_tzname); html += "</table>"; /* System */ html += "<p><h3>System</h3>"; html += "<table border='1' cellpadding='6'>"; appendf(html, "<tr>" "<td>CPU Frequency</td>" "<td>%u MHz</td>" "</tr>", (unsigned int)(rp2040.f_cpu() / 1000000)); switch (rp2040.getResetReason()) { case RP2040::PWRON_RESET: str = "Power on" ; break; case RP2040::RUN_PIN_RESET: str = "GPIO Pin" ; break; case RP2040::SOFT_RESET: str = "Software" ; break; case RP2040::WDT_RESET: str = "Watch dog"; break; case RP2040::DEBUG_RESET: str = "Debug" ; break; case RP2040::GLITCH_RESET: str = "Glitch" ; break; case RP2040::BROWNOUT_RESET: str = "Brownout" ; break; default: str = "Unknown" ; break; } appendf(html, "<tr>" "<td>Reset Reason</td>" "<td>%s</td>" "</tr>", str.c_str()); str = ""; str += rp2040.getFreeHeap(); for (int len = str.length(); len > 3; len -= 3) str = str.substring(0, len - 3) + ',' + str.substring(len - 3); appendf(html, "<tr>" "<td>Free Heap Memory</td>" "<td>%s Bytes</td>" "</tr>", str.c_str()); unsigned long t = uptime() / 1000; snprintf(buf, sizeof(buf), "%lu days, %02lu:%02lu:%02lu", t / (24 * 60 * 60), t / (60 * 60) % 24, t / ( 1 * 60) % 60, t % 60); appendf(html, "<tr>" "<td>Uptime</td>" "<td>%s</td>" "</tr>", buf); appendf(html, "<tr>" "<td>AP/OTA Password</td>" "<td><input type='text' name='%s' value=''></td>" "</tr>", SYS_PASSWORD); html += "</table>"; /* Submit Button's */ html += "<p><span style='margin-right: 1em;'></span>"; appendf(html, "<button type='submit' name='%s' value='%s'>Rescan</button>", SUBMIT, SUBMIT_RESCAN); html += "<span style='margin-right: 1em;'></span>"; appendf(html, "<button type='submit' name='%s' value='%s'>Apply</button>", SUBMIT, SUBMIT_APPLY); html += "<span style='margin-right: 1em;'></span>"; appendf(html, "<button type='submit' name='%s' value='%s'>Reboot</button>", SUBMIT, SUBMIT_REBOOT); html += "</form></body></html>"; // Send HTTP response client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.print("Content-Length: "); client.println(html.length()); client.println("Connection: close"); client.println(); client.print(html); delay(10); client.stop(); } }; |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
/* wsta.h - WiFi STA Library for Raspberry Pi Pico W Copyright (c) 2026 Sasapea's Lab. All right reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <stdint.h> #include <stdbool.h> #include <Arduino.h> #include <WiFi.h> class WSta { public: static void builtin_led(bool on) { static bool status; if (status != on) digitalWrite(PIN_LED, status = on); } void connect_led(bool connected) { if (_led) builtin_led(millis() / (connected ? LED_BLINK_ONLINE : LED_BLINK_OFFLINE) & 1); } WSta(bool led = true) : _led(led) { pinMode(PIN_LED, OUTPUT); } virtual ~WSta(void) { } uint8_t status(void) { uint8_t rv = WiFi.status(); if (_fixed) { if (_delay) { if ((rv == WL_CONNECTED) && (millis() - _delay < WIFI_LINK_TIMEOUT)) rv = _wlstat; else _delay = 0; } else if (rv == WL_CONNECTED) { if (_wlstat != WL_CONNECTED) { _delay = millis(); rv = _wlstat; } } } connect_led(_wlstat == WL_CONNECTED); return _wlstat = rv; } bool run(void) { uint8_t rv = status(); switch (rv) { case WL_IDLE_STATUS: case WL_DISCONNECTED: case WL_CONNECT_FAILED: case WL_CONNECTION_LOST: rv = WL_DISCONNECTED; break; case WL_CONNECTED: break; default: rv = _status; break; } if (_status != rv) { switch (rv) { case WL_DISCONNECTED: if (_status == WL_CONNECTED) disconnected(); if ((_start = millis()) == 0) --_start; connect(); _fixed = WiFi.localIP().isSet(); _wlstat = WL_NO_SHIELD; _delay = 0; break; case WL_CONNECTED: connected(millis() - _start); _start = 0; break; default: break; } _status = rv; } else if (_start) { if (millis() - _start >= WIFI_CONN_TIMEOUT) { _start = 0; _status = WL_NO_SHIELD; } } return rv == WL_CONNECTED; } virtual void connect(void) { } virtual void connected([[maybe_unused]] uint32_t conn_time) { } virtual void disconnected(void) { } private: static constexpr uint32_t WIFI_CONN_TIMEOUT = 20000; static constexpr uint32_t WIFI_LINK_TIMEOUT = 10000; static constexpr uint32_t LED_BLINK_OFFLINE = 200; static constexpr uint32_t LED_BLINK_ONLINE = 1000; bool _led = true; bool _fixed = false; uint8_t _status = WL_NO_SHIELD; uint8_t _wlstat = WL_NO_SHIELD; uint32_t _delay = 0; uint32_t _start = 0; }; |



