diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2245c60 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: CI + +on: + push: + branches: + - '*' + tags-ignore: + - 'v*' + pull_request: + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - uses: actions/setup-python@v4 + with: + python-version: '3.11' + + - uses: pre-commit/action@v3.0.0 + + validate: + name: Validate for HACS + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/checkout@v3 + + - name: HACS validation + uses: hacs/action@main + with: + category: integration diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..5ce275d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,29 @@ +name: Release + +on: + release: + types: + - published + +permissions: + contents: write + +jobs: + release-zip: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Prepare release + run: | + cd ${{ github.workspace }}/custom_components/airmx + zip -r airmx.zip ./ + + - name: Upload zip + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: ${{ github.workspace }}/custom_components/airmx/airmx.zip + asset_name: airmx.zip + tag: ${{ github.ref }} + overwrite: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2a05812 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.iml +.mypy_cache +research +tools diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..8c46715 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,15 @@ +repos: + - repo: https://github.com/charliermarsh/ruff-pre-commit + rev: v0.0.280 + hooks: + - id: ruff + + - repo: https://github.com/psf/black + rev: 23.7.0 + hooks: + - id: black + + - repo: https://github.com/PyCQA/isort + rev: 5.12.0 + hooks: + - id: isort diff --git a/README.md b/README.md new file mode 100644 index 0000000..410b77b --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# Интеграция AIRMX и Tion Iris в Home Assistant +Инструкция в процессе разработки... diff --git a/airmx-addon/Dockerfile b/airmx-addon/Dockerfile new file mode 100644 index 0000000..d030178 --- /dev/null +++ b/airmx-addon/Dockerfile @@ -0,0 +1,12 @@ +ARG BUILD_FROM +FROM $BUILD_FROM + +WORKDIR / + +RUN apk add --no-cache python3 py3-pip mosquitto && \ + pip3 install flask==3.0.0 + +COPY rootfs / + +VOLUME /data +EXPOSE 80 1883 diff --git a/airmx-addon/README.md b/airmx-addon/README.md new file mode 100644 index 0000000..b4c79d7 --- /dev/null +++ b/airmx-addon/README.md @@ -0,0 +1,2 @@ +# Home Assistant Add-on: AIRMX +Аддон предоставляет замену китайским серверам i.airmx.cn и awm.airmx.cn, которые необходимы для управления увлажнителями AIRMX и TION Iris. diff --git a/airmx-addon/build.yaml b/airmx-addon/build.yaml new file mode 100644 index 0000000..610f925 --- /dev/null +++ b/airmx-addon/build.yaml @@ -0,0 +1,5 @@ +build_from: + aarch64: ghcr.io/home-assistant/aarch64-base:3.18 + amd64: ghcr.io/home-assistant/amd64-base:3.18 + armhf: ghcr.io/home-assistant/armhf-base:3.18 + armv7: ghcr.io/home-assistant/armv7-base:3.18 diff --git a/airmx-addon/config.yaml b/airmx-addon/config.yaml new file mode 100644 index 0000000..12b0666 --- /dev/null +++ b/airmx-addon/config.yaml @@ -0,0 +1,15 @@ +name: AIRMX +version: '0.0.1.dev1' +slug: airmx-addon +description: Local control AIRMX devices +url: https://github.com/dext0r/airmx +arch: + - aarch64 + - amd64 + - armhf + - armv7 +init: false +startup: system +ports: + 80/tcp: 25880 + 1883/tcp: 25883 diff --git a/airmx-addon/icon.png b/airmx-addon/icon.png new file mode 100644 index 0000000..a8840cd Binary files /dev/null and b/airmx-addon/icon.png differ diff --git a/airmx-addon/logo.png b/airmx-addon/logo.png new file mode 100644 index 0000000..a8840cd Binary files /dev/null and b/airmx-addon/logo.png differ diff --git a/airmx-addon/requirements.txt b/airmx-addon/requirements.txt new file mode 100644 index 0000000..5bd19d3 --- /dev/null +++ b/airmx-addon/requirements.txt @@ -0,0 +1 @@ +flask==3.0.0 diff --git a/airmx-addon/rootfs/etc/mosquitto/mosquitto.conf b/airmx-addon/rootfs/etc/mosquitto/mosquitto.conf new file mode 100644 index 0000000..675afbb --- /dev/null +++ b/airmx-addon/rootfs/etc/mosquitto/mosquitto.conf @@ -0,0 +1,8 @@ +allow_anonymous true +listener 1883 0.0.0.0 +log_dest stdout +log_type error +log_type warning +log_type notice +log_type information +log_timestamp_format %Y-%m-%d %H:%M:%S diff --git a/airmx-addon/rootfs/etc/services.d/i-airmx-cn/finish b/airmx-addon/rootfs/etc/services.d/i-airmx-cn/finish new file mode 100755 index 0000000..5a23d05 --- /dev/null +++ b/airmx-addon/rootfs/etc/services.d/i-airmx-cn/finish @@ -0,0 +1,12 @@ +#!/usr/bin/env bashio +# ============================================================================== +# Take down the S6 supervision tree when service fails +# s6-overlay docs: https://github.com/just-containers/s6-overlay +# ============================================================================== + +if [[ "$1" -ne 0 ]] && [[ "$1" -ne 256 ]]; then + bashio::log.warning "Halt add-on" + exec /run/s6/basedir/bin/halt +fi + +bashio::log.info "Service restart after closing" diff --git a/airmx-addon/rootfs/etc/services.d/i-airmx-cn/run b/airmx-addon/rootfs/etc/services.d/i-airmx-cn/run new file mode 100755 index 0000000..326637f --- /dev/null +++ b/airmx-addon/rootfs/etc/services.d/i-airmx-cn/run @@ -0,0 +1,2 @@ +#!/usr/bin/with-contenv bashio +exec /i-airmx-cn.py diff --git a/airmx-addon/rootfs/etc/services.d/mosquitto/finish b/airmx-addon/rootfs/etc/services.d/mosquitto/finish new file mode 100755 index 0000000..5a23d05 --- /dev/null +++ b/airmx-addon/rootfs/etc/services.d/mosquitto/finish @@ -0,0 +1,12 @@ +#!/usr/bin/env bashio +# ============================================================================== +# Take down the S6 supervision tree when service fails +# s6-overlay docs: https://github.com/just-containers/s6-overlay +# ============================================================================== + +if [[ "$1" -ne 0 ]] && [[ "$1" -ne 256 ]]; then + bashio::log.warning "Halt add-on" + exec /run/s6/basedir/bin/halt +fi + +bashio::log.info "Service restart after closing" diff --git a/airmx-addon/rootfs/etc/services.d/mosquitto/run b/airmx-addon/rootfs/etc/services.d/mosquitto/run new file mode 100755 index 0000000..2282c4d --- /dev/null +++ b/airmx-addon/rootfs/etc/services.d/mosquitto/run @@ -0,0 +1,2 @@ +#!/usr/bin/with-contenv bashio +exec mosquitto -c /etc/mosquitto/mosquitto.conf diff --git a/airmx-addon/rootfs/i-airmx-cn.py b/airmx-addon/rootfs/i-airmx-cn.py new file mode 100755 index 0000000..075b04b --- /dev/null +++ b/airmx-addon/rootfs/i-airmx-cn.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +import argparse +from dataclasses import asdict, dataclass, is_dataclass +from datetime import datetime +import json +from json import JSONDecodeError +import logging +import os.path +from typing import Any + +from flask import Flask, request +from werkzeug import exceptions as HTTPException + +DEVICE_STORE_PATH = "/data/devices.json" + +app = Flask(__name__) +app.logger.setLevel(logging.INFO) + + +@dataclass +class Device: + id: int + key: str + wifi_mac: str + ble_mac: str + type: int + ts: int + + +class EnhancedJSONEncoder(json.JSONEncoder): + def default(self, o: Any) -> Any: + if is_dataclass(o): + return asdict(o) + + return super().default(o) + + +def _load_devices(path: str) -> dict[int, Device]: + rv: dict[int, Device] = {} + if os.path.isfile(path): + with open(path, "r") as f: + try: + for item in json.load(f).values(): + device = Device(**item) + rv[device.id] = device + except JSONDecodeError: + app.logger.exception("Failed to load devices.json") + + return rv + + +devices: dict[int, Device] = _load_devices(DEVICE_STORE_PATH) + + +@app.route("/") +def root() -> str: + return "AIRMX addon\n" + + +@app.route("/aw") +def aw() -> dict[str, Any]: + if (path := request.args.get("path")) != "aw/GET/genId": + app.logger.error(f"Unsupported path {path}") + raise HTTPException.NotImplemented() + + params = json.loads(request.args.get("params", "")) + wifi_mac = int.from_bytes(bytearray.fromhex(params["mac"]), byteorder="little") + ble_mac = wifi_mac + 2 + device = Device( + id=int.from_bytes(bytearray.fromhex(params["mac"])[:2], byteorder="little"), + wifi_mac=wifi_mac.to_bytes(6, byteorder="big").hex(), + ble_mac=ble_mac.to_bytes(6, byteorder="big").hex(), + key=params["key"], + type=int(params["type"]), + ts=int(datetime.now().timestamp()), + ) + + match device.type: + case 21: # A3S_V2 / Iris + data = { + "awId": device.id, + "electrolysisLevel4OffTime": 1800, + "electrolysisLevel2OpenTime": 600, + "electrolysisLevel3OpenTime": 1200, + "electrolysisLevel4OpenTime": 1800, + "electrolysisLevel2OffTime": 600, + "electrolysisLevel1OpenTime": 60, + "electrolysisLevel3OffTime": 1200, + "electrolysisLevel1OffTime": 120, + } + case _: + app.logger.error(f"Unsupported device: {device}") + raise HTTPException.NotImplemented() + + app.logger.info(f"New device registered: {device}") + devices[device.id] = device + + with open(DEVICE_STORE_PATH, "w") as f: + json.dump(devices, f, cls=EnhancedJSONEncoder) + + return {"status": 200, "data": data} + + +@app.route("/gettime") +def gettime() -> dict[str, int]: + return {"time": int(datetime.now().timestamp())} + + +@app.route("/check/airwater/washCleanNotify") +def wash_clean_notify() -> dict[str, int]: + return {"status": 200} + + +@app.route("/_devices") +def get_devices() -> list[dict[str, str | int]]: + return [asdict(device) for device in sorted(devices.values(), key=lambda d: d.ts * -1)] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--port", default=80, type=int) + args = parser.parse_args() + + app.run(host="0.0.0.0", port=args.port, debug=False, use_reloader=False) diff --git a/airmx-esp-gate/README.md b/airmx-esp-gate/README.md new file mode 100644 index 0000000..44d875d --- /dev/null +++ b/airmx-esp-gate/README.md @@ -0,0 +1,6 @@ +# AIRMX Gate +Прошивка под ESP8266 для запуска точки доступа, к которой подключаются увлажнители. + +Весь трафик от увлажнителя будет перенаправлен в аддон на Home Assistant. + +Является необязательным компонентом, увлажнители можно подключать к домашнему роутеру напрямую и заворачивать их трафик через DNAT. diff --git a/airmx-esp-gate/TCPProxy.cpp b/airmx-esp-gate/TCPProxy.cpp new file mode 100644 index 0000000..e6c7d95 --- /dev/null +++ b/airmx-esp-gate/TCPProxy.cpp @@ -0,0 +1,266 @@ +#include "Arduino.h" +#include +#include + +#define TCP_PROXY_START_PORT 56000 +#define TCP_PROXY_MAX_CONNECTIONS 256 +#define TCP_PROXY_MAX_PORTMAP 2 + +// #define TCP_PROXY_DEBUG +// #define TCP_PROXY_DEBUG_CONNLIST + +#ifdef TCP_PROXY_DEBUG +#define DPRINT(...) Serial.print(__VA_ARGS__) +#define DPRINTLN(...) Serial.println(__VA_ARGS__) +#define DPRINTF(...) Serial.printf(__VA_ARGS__) +#else +#define DPRINT(...) +#define DPRINTLN(...) +#define DPRINTF(...) +#endif + +struct tcp_proxy_portmap { + uint16_t proxy_port; + uint16_t target_port; +}; + +struct tcp_pseudo_header { + uint32_t src; + uint32_t dest; + uint8_t reserved; + uint8_t protocol; + uint16_t tcp_length; +}; + +struct connection { + ip_addr_t client_addr; + uint16_t client_src_port; + uint16_t client_dest_port; + uint16_t proxy_src_port; + uint16_t target_port; +}; + +struct tcp_proxy { + struct raw_pcb *pcb; + uint16_t ignore_port; + ip_addr_t listen_addr; + ip_addr_t proxy_addr; + ip_addr_t target_addr; + tcp_proxy_portmap portmap[TCP_PROXY_MAX_PORTMAP]; +} config; + +connection connlist[TCP_PROXY_MAX_CONNECTIONS]; +uint16_t conn_idx; + +void update_checksum(uint8_t *pkt, ip_addr_t *src_addr, ip_addr_t *dest_addr, int length) { + struct tcp_pseudo_header pheader; + uint32_t chksum; + uint8_t *psum; + uint16_t finalsum; + + memset(&pheader, 0, sizeof(struct tcp_pseudo_header)); + + pheader.src = src_addr->addr; + pheader.dest = dest_addr->addr; + pheader.protocol = 6; + pheader.tcp_length = htons(length); + + pkt[16] = 0; // checksum + pkt[17] = 0; + chksum = 0; + psum = (uint8_t *)&pheader; + for (int i = 0; i < 12; i += 2) { + uint16_t chunk = (psum[0] << 8) | psum[1]; + chksum += chunk; + psum += 2; + } + + psum = (uint8_t *)pkt; + while (length > 1) { + uint16_t chunk = (*psum << 8) | *(psum + 1); + chksum += chunk; + psum += 2; + length -= 2; + } + + if (length > 0) { + uint16_t chunk = (uint16_t)(*psum) << 8; + chksum += chunk; + } + + finalsum = (chksum & 0xffff) + (chksum >> 16); + + while (chksum >> 16) { + chksum = (chksum & 0xffff) + (chksum >> 16); + } + + chksum = ~chksum; + finalsum = (uint16_t)chksum; + + pkt[16] = finalsum >> 8; + pkt[17] = finalsum & 0xff; +} + +static uint8_t handle_packet(void *arg, raw_pcb *pcb, pbuf *p, const ip_addr_t *addr) { + DPRINTLN("tcpproxy: handle packet"); + if (pcb == nullptr || p == nullptr || addr == nullptr) { + DPRINTLN("tcpproxy: skip packet"); + return 0; + } + + struct ip_hdr *pkt_ip_hdr = (struct ip_hdr *)p->payload; + if (pkt_ip_hdr == nullptr) { + DPRINTLN("tcpproxy: error 2"); + return 0; + } + + ip_addr_t pkt_src_addr; + ip_addr_t pkt_dest_addr; + ip_addr_copy(pkt_src_addr, pkt_ip_hdr->src); + ip_addr_copy(pkt_dest_addr, pkt_ip_hdr->dest); + + uint8_t *pkt = (uint8_t *)p->payload; + uint16_t pkt_src_port = (pkt[20] << 8) | pkt[21]; + uint16_t pkt_dest_port = (pkt[22] << 8) | pkt[23]; + + DPRINTF("tcpproxy: %s:%d", inet_ntoa(pkt_src_addr), pkt_src_port); + DPRINTF(" -> %s:%d \n", inet_ntoa(pkt_dest_addr), pkt_dest_port); + + if (pkt_dest_port == config.ignore_port || pkt_src_port == config.ignore_port) { + return 0; + } + + bool pkt_from_client = (pkt_src_addr.addr != config.target_addr.addr && pkt_dest_addr.addr == config.listen_addr.addr); + bool pkt_from_target = (pkt_src_addr.addr == config.target_addr.addr); + DPRINTF("tcpproxy: pkt_from_client %d, pkt_from_target %d\n", pkt_from_client ? 1 : 0, pkt_from_target ? 1 : 0); + if (!pkt_from_client && !pkt_from_target) { + return 0; + } + + pbuf_header(p, -PBUF_IP_HLEN); + connection *conn = NULL; + for (int i = 0; i <= TCP_PROXY_MAX_CONNECTIONS - 1; i++) { + connection *estb_conn = &connlist[i]; + +#ifdef TCP_PROXY_DEBUG_CONNLIST + DPRINTF("%d: %s:%d/%d -> %d/%d\n", + i, + inet_ntoa(estb_conn->client_addr), + estb_conn->client_src_port, + estb_conn->client_dest_port, + estb_conn->proxy_src_port, + estb_conn->target_port); +#endif + + if (pkt_from_client && estb_conn->client_addr.addr == pkt_src_addr.addr && estb_conn->client_src_port == pkt_src_port) { + conn = estb_conn; + break; + } + if (pkt_from_target && estb_conn->proxy_src_port == pkt_dest_port && estb_conn->target_port == pkt_src_port) { + conn = estb_conn; + break; + } + } + + if (!conn && pkt_from_client) { + DPRINTLN("tcpproxy: new connection"); + conn_idx++; + if (conn_idx >= TCP_PROXY_MAX_CONNECTIONS) { + conn_idx = 0; + } + + conn = &connlist[conn_idx]; + conn->client_addr = pkt_src_addr; + conn->client_src_port = pkt_src_port; + conn->proxy_src_port = TCP_PROXY_START_PORT + conn_idx; + + DPRINTF("tcpproxy: new [%d] %s:%d -> %d:%d\n", + conn_idx, + inet_ntoa(conn->client_addr), + conn->proxy_src_port, + conn->client_src_port, + pkt_dest_port); + } + + if (conn && pkt_from_client) { + conn->client_dest_port = pkt_dest_port; + + conn->target_port = pkt_dest_port; + for (int i = 0; i < TCP_PROXY_MAX_PORTMAP; i++) { + tcp_proxy_portmap *pmap = &config.portmap[i]; + if (pmap->proxy_port == pkt_dest_port) { + conn->target_port = pmap->target_port; + } + } + + if (conn->target_port == pkt_dest_port) { + DPRINTLN("tcpproxy: not in portmap"); + return 0; + } + + DPRINTF("tcpproxy: upd [%d]: %d -> %s:%d \n", + conn_idx, + conn->proxy_src_port, + inet_ntoa(config.target_addr), + conn->target_port); + } + + if (!conn) { + DPRINTLN("tcpproxy: ignoring packet, connection not found"); + return 0; + } + + ip_addr_t pkt_new_dest_addr = pkt_from_client ? config.target_addr : conn->client_addr; + ip_addr_t pkt_new_src_addr = pkt_from_client ? config.proxy_addr : config.listen_addr; + if (pkt_from_client) { + // source port + pkt[20] = conn->proxy_src_port >> 8; + pkt[21] = conn->proxy_src_port & 0xff; + // destination port + pkt[22] = conn->target_port >> 8; + pkt[23] = conn->target_port & 0xff; + } else { + // source port + pkt[20] = conn->client_dest_port >> 8; + pkt[21] = conn->client_dest_port & 0xff; + // destination port + pkt[22] = conn->client_src_port >> 8; + pkt[23] = conn->client_src_port & 0xff; + } + update_checksum((uint8_t *)p->payload, &pkt_new_src_addr, &pkt_new_dest_addr, p->len); + + uint16_t pkt_new_dest_port = (pkt[22] << 8) | pkt[23]; + DPRINTF("tcpproxy: send to %s:%d\n", inet_ntoa(pkt_new_dest_addr), pkt_new_dest_port); + raw_sendto(config.pcb, p, &pkt_new_dest_addr); + + pbuf_free(p); + return 1; +} + +void tcp_proxy_start(ip_addr_t listen_addr, ip_addr_t target_addr, uint16_t ignore_port) { + config.ignore_port = ignore_port; + config.listen_addr = listen_addr; + config.target_addr = target_addr; + + config.portmap[0].proxy_port = 80; + config.portmap[0].target_port = 25880; + config.portmap[1].proxy_port = 1883; + config.portmap[1].target_port = 25883; + + Serial.printf("tcpproxy started: listen_addr %s", inet_ntoa(config.listen_addr)); + Serial.printf(", target_addr %s\n", inet_ntoa(config.target_addr)); + + config.pcb = raw_new(IP_PROTO_TCP); + if (config.pcb == nullptr) { + Serial.println("tcpproxy: raw_new failed"); + return; + } + + raw_recv(config.pcb, handle_packet, NULL); + raw_bind(config.pcb, IP_ADDR_ANY); +} + +void tcp_proxy_set_proxy_addr(ip_addr_t addr) { + Serial.printf("tcpproxy: set proxy_addr %s\n", inet_ntoa(addr)); + config.proxy_addr = addr; +} \ No newline at end of file diff --git a/airmx-esp-gate/TCPProxy.h b/airmx-esp-gate/TCPProxy.h new file mode 100644 index 0000000..3a239fd --- /dev/null +++ b/airmx-esp-gate/TCPProxy.h @@ -0,0 +1,6 @@ +#ifndef TCPPROXY_H +#define TCPPROXY_H +void tcp_proxy_start(ip_addr_t listen_addr, ip_addr_t target_addr, uint16_t skip_port); +void tcp_proxy_set_proxy_addr(ip_addr_t addr); +#endif + diff --git a/airmx-esp-gate/WiFiManager.cpp b/airmx-esp-gate/WiFiManager.cpp new file mode 100644 index 0000000..e6239cc --- /dev/null +++ b/airmx-esp-gate/WiFiManager.cpp @@ -0,0 +1,4011 @@ +/** + * WiFiManager.cpp + * + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + +#include "WiFiManager.h" + +#if defined(ESP8266) || defined(ESP32) + +#ifdef ESP32 +uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; +#endif + +/** + * -------------------------------------------------------------------------------- + * WiFiManagerParameter + * -------------------------------------------------------------------------------- +**/ + +WiFiManagerParameter::WiFiManagerParameter() { + WiFiManagerParameter(""); +} + +WiFiManagerParameter::WiFiManagerParameter(const char *custom) { + _id = NULL; + _label = NULL; + _length = 0; + _value = nullptr; + _labelPlacement = WFM_LABEL_DEFAULT; + _customHTML = custom; +} + +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label) { + init(id, label, "", 0, "", WFM_LABEL_DEFAULT); +} + +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length) { + init(id, label, defaultValue, length, "", WFM_LABEL_DEFAULT); +} + +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom) { + init(id, label, defaultValue, length, custom, WFM_LABEL_DEFAULT); +} + +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { + init(id, label, defaultValue, length, custom, labelPlacement); +} + +void WiFiManagerParameter::init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { + _id = id; + _label = label; + _labelPlacement = labelPlacement; + _customHTML = custom; + _length = 0; + _value = nullptr; + setValue(defaultValue,length); +} + +WiFiManagerParameter::~WiFiManagerParameter() { + if (_value != NULL) { + delete[] _value; + } + _length=0; // setting length 0, ideally the entire parameter should be removed, or added to wifimanager scope so it follows +} + +// WiFiManagerParameter& WiFiManagerParameter::operator=(const WiFiManagerParameter& rhs){ +// Serial.println("copy assignment op called"); +// (*this->_value) = (*rhs._value); +// return *this; +// } + +// @note debug is not available in wmparameter class +void WiFiManagerParameter::setValue(const char *defaultValue, int length) { + if(!_id){ + // Serial.println("cannot set value of this parameter"); + return; + } + + // if(strlen(defaultValue) > length){ + // // Serial.println("defaultValue length mismatch"); + // // return false; //@todo bail + // } + + if(_length != length || _value == nullptr){ + _length = length; + if( _value != nullptr){ + delete[] _value; + } + _value = new char[_length + 1]; + } + + memset(_value, 0, _length + 1); // explicit null + + if (defaultValue != NULL) { + strncpy(_value, defaultValue, _length); + } +} +const char* WiFiManagerParameter::getValue() const { + // Serial.println(printf("Address of _value is %p\n", (void *)_value)); + return _value; +} +const char* WiFiManagerParameter::getID() const { + return _id; +} +const char* WiFiManagerParameter::getPlaceholder() const { + return _label; +} +const char* WiFiManagerParameter::getLabel() const { + return _label; +} +int WiFiManagerParameter::getValueLength() const { + return _length; +} +int WiFiManagerParameter::getLabelPlacement() const { + return _labelPlacement; +} +const char* WiFiManagerParameter::getCustomHTML() const { + return _customHTML; +} + +/** + * [addParameter description] + * @access public + * @param {[type]} WiFiManagerParameter *p [description] + */ +bool WiFiManager::addParameter(WiFiManagerParameter *p) { + + // check param id is valid, unless null + if(p->getID()){ + for (size_t i = 0; i < strlen(p->getID()); i++){ + if(!(isAlphaNumeric(p->getID()[i])) && !(p->getID()[i]=='_')){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] parameter IDs can only contain alpha numeric chars")); + #endif + return false; + } + } + } + + // init params if never malloc + if(_params == NULL){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("allocating params bytes:"),_max_params * sizeof(WiFiManagerParameter*)); + #endif + _params = (WiFiManagerParameter**)malloc(_max_params * sizeof(WiFiManagerParameter*)); + } + + // resize the params array by increment of WIFI_MANAGER_MAX_PARAMS + if(_paramsCount == _max_params){ + _max_params += WIFI_MANAGER_MAX_PARAMS; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("Updated _max_params:"),_max_params); + DEBUG_WM(WM_DEBUG_DEV,F("re-allocating params bytes:"),_max_params * sizeof(WiFiManagerParameter*)); + #endif + WiFiManagerParameter** new_params = (WiFiManagerParameter**)realloc(_params, _max_params * sizeof(WiFiManagerParameter*)); + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(WIFI_MANAGER_MAX_PARAMS); + // DEBUG_WM(_paramsCount); + // DEBUG_WM(_max_params); + #endif + if (new_params != NULL) { + _params = new_params; + } else { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] failed to realloc params, size not increased!")); + #endif + return false; + } + } + + _params[_paramsCount] = p; + _paramsCount++; + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Added Parameter:"),p->getID()); + #endif + return true; +} + +/** + * [getParameters description] + * @access public + */ +WiFiManagerParameter** WiFiManager::getParameters() { + return _params; +} + +/** + * [getParametersCount description] + * @access public + */ +int WiFiManager::getParametersCount() { + return _paramsCount; +} + +/** + * -------------------------------------------------------------------------------- + * WiFiManager + * -------------------------------------------------------------------------------- +**/ + +// constructors +WiFiManager::WiFiManager(Print& consolePort):_debugPort(consolePort){ + WiFiManagerInit(); +} + +WiFiManager::WiFiManager() { + WiFiManagerInit(); +} + +void WiFiManager::WiFiManagerInit(){ + setMenu(_menuIdsDefault); + if(_debug && _debugLevel >= WM_DEBUG_DEV) debugPlatformInfo(); + _max_params = WIFI_MANAGER_MAX_PARAMS; +} + +// destructor +WiFiManager::~WiFiManager() { + _end(); + // parameters + // @todo below belongs to wifimanagerparameter + if (_params != NULL){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("freeing allocated params!")); + #endif + free(_params); + _params = NULL; + } + + // remove event + // WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + #ifdef ESP32 + WiFi.removeEvent(wm_event_id); + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("unloading")); + #endif +} + +void WiFiManager::_begin(){ + if(_hasBegun) return; + _hasBegun = true; + // _usermode = WiFi.getMode(); + + #ifndef ESP32 + WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites + #endif +} + +void WiFiManager::_end(){ + _hasBegun = false; + if(_userpersistent) WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent + // if(_usermode != WIFI_OFF) WiFi.mode(_usermode); +} + +// AUTOCONNECT + +boolean WiFiManager::autoConnect() { + String ssid = getDefaultAPName(); + return autoConnect(ssid.c_str(), NULL); +} + +/** + * [autoConnect description] + * @access public + * @param {[type]} char const *apName [description] + * @param {[type]} char const *apPassword [description] + * @return {[type]} [description] + */ +boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("AutoConnect")); + #endif + + // bool wifiIsSaved = getWiFiIsSaved(); + + #ifdef ESP32 + setupHostname(true); + + if(_hostname != ""){ + // disable wifi if already on + if(WiFi.getMode() & WIFI_STA){ + WiFi.mode(WIFI_OFF); + int timeout = millis()+1200; + // async loop for mode change + while(WiFi.getMode()!= WIFI_OFF && millis()0){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Starting AP on channel:"),channel); + #endif + } + + // start soft AP with password or anonymous + // default channel is 1 here and in esplib, @todo just change to default remove conditionals + if (_apPassword != "") { + if(channel>0){ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),channel,_apHidden); + } + else{ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),1,_apHidden);//password option + } + } else { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("AP has anonymous access!")); + #endif + if(channel>0){ + ret = WiFi.softAP(_apName.c_str(),"",channel,_apHidden); + } + else{ + ret = WiFi.softAP(_apName.c_str(),"",1,_apHidden); + } + } + + if(_debugLevel >= WM_DEBUG_DEV) debugSoftAPConfig(); + + // @todo add softAP retry here to dela with unknown failures + + delay(500); // slight delay to make sure we get an AP IP + #ifdef WM_DEBUG_LEVEL + if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] There was a problem starting the AP")); + DEBUG_WM(F("AP IP address:"),WiFi.softAPIP()); + #endif + + // set ap hostname + #ifdef ESP32 + if(ret && _hostname != ""){ + bool res = WiFi.softAPsetHostname(_hostname.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("setting softAP Hostname:"),_hostname); + if(!res)DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] hostname: AP set failed!")); + DEBUG_WM(WM_DEBUG_DEV,F("hostname: AP: "),WiFi.softAPgetHostname()); + #endif + } + #endif + + return ret; +} + +/** + * [startWebPortal description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::startWebPortal() { + if(configPortalActive || webPortalActive) return; + connect = abort = false; + setupConfigPortal(); + webPortalActive = true; +} + +/** + * [stopWebPortal description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::stopWebPortal() { + if(!configPortalActive && !webPortalActive) return; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Stopping Web Portal")); + #endif + webPortalActive = false; + shutdownConfigPortal(); +} + +boolean WiFiManager::configPortalHasTimeout(){ + if(!configPortalActive) return false; + uint16_t logintvl = 30000; // how often to emit timeing out counter logging + + // handle timeout portal client check + if(_configPortalTimeout == 0 || (_apClientCheck && (WiFi_softap_num_stations() > 0))){ + // debug num clients every 30s + if(millis() - timer > logintvl){ + timer = millis(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("NUM CLIENTS: "),(String)WiFi_softap_num_stations()); + #endif + } + _configPortalStart = millis(); // kludge, bump configportal start time to skew timeouts + return false; + } + + // handle timeout webclient check + if(_webClientCheck && (_webPortalAccessed>_configPortalStart)>0) _configPortalStart = _webPortalAccessed; + + // handle timed out + if(millis() > _configPortalStart + _configPortalTimeout){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("config portal has timed out")); + #endif + return true; // timeout bail, else do debug logging + } + else if(_debug && _debugLevel > 0) { + // log timeout time remaining every 30s + if((millis() - timer) > logintvl){ + timer = millis(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal Timeout In"),(String)((_configPortalStart + _configPortalTimeout-millis())/1000) + (String)F(" seconds")); + #endif + } + } + + return false; +} + +void WiFiManager::setupHTTPServer(){ + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Starting Web Portal")); + #endif + + if(_httpPort != 80) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("http server started with custom port: "),_httpPort); // @todo not showing ip + #endif + } + + server.reset(new WM_WebServer(_httpPort)); + // This is not the safest way to reset the webserver, it can cause crashes on callbacks initilized before this and since its a shared pointer... + + if ( _webservercallback != NULL) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] _webservercallback calling")); + #endif + _webservercallback(); // @CALLBACK + } + // @todo add a new callback maybe, after webserver started, callback cannot override handlers, but can grab them first + + /* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */ + + // G macro workaround for Uri() bug https://github.com/esp8266/Arduino/issues/7102 + server->on(WM_G(R_root), std::bind(&WiFiManager::handleRoot, this)); + server->on(WM_G(R_wifi), std::bind(&WiFiManager::handleWifi, this, true)); + server->on(WM_G(R_wifinoscan), std::bind(&WiFiManager::handleWifi, this, false)); + server->on(WM_G(R_wifisave), std::bind(&WiFiManager::handleWifiSave, this)); + server->on(WM_G(R_info), std::bind(&WiFiManager::handleInfo, this)); + server->on(WM_G(R_param), std::bind(&WiFiManager::handleParam, this)); + server->on(WM_G(R_paramsave), std::bind(&WiFiManager::handleParamSave, this)); + server->on(WM_G(R_restart), std::bind(&WiFiManager::handleReset, this)); + server->on(WM_G(R_exit), std::bind(&WiFiManager::handleExit, this)); + server->on(WM_G(R_close), std::bind(&WiFiManager::handleClose, this)); + server->on(WM_G(R_erase), std::bind(&WiFiManager::handleErase, this, false)); + server->on(WM_G(R_status), std::bind(&WiFiManager::handleWiFiStatus, this)); + server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); + + server->on(WM_G(R_update), std::bind(&WiFiManager::handleUpdate, this)); + server->on(WM_G(R_updatedone), HTTP_POST, std::bind(&WiFiManager::handleUpdateDone, this), std::bind(&WiFiManager::handleUpdating, this)); + + server->begin(); // Web server start + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("HTTP server started")); + #endif +} + +void WiFiManager::setupDNSD(){ + dnsServer.reset(new DNSServer()); + + /* Setup the DNS server redirecting all the domains to the apIP */ + dnsServer->setErrorReplyCode(DNSReplyCode::NoError); + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM("dns server started port: ",DNS_PORT); + DEBUG_WM(WM_DEBUG_DEV,F("dns server started with ip: "),WiFi.softAPIP()); // @todo not showing ip + #endif + dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); +} + +void WiFiManager::setupConfigPortal() { + setupHTTPServer(); + _lastscan = 0; // reset network scan cache + if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async +} + +boolean WiFiManager::startConfigPortal() { + String ssid = getDefaultAPName(); + return startConfigPortal(ssid.c_str(), NULL); +} + +/** + * [startConfigPortal description] + * @access public + * @param {[type]} char const *apName [description] + * @param {[type]} char const *apPassword [description] + * @return {[type]} [description] + */ +boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { + _begin(); + + if(configPortalActive){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Starting Config Portal FAILED, is already running")); + #endif + return false; + } + + //setup AP + _apName = apName; // @todo check valid apname ? + _apPassword = apPassword; + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Starting Config Portal")); + #endif + + if(_apName == "") _apName = getDefaultAPName(); + + if(!validApPassword()) return false; + + // HANDLE issues with STA connections, shutdown sta if not connected, or else this will hang channel scanning and softap will not respond + if(_disableSTA || (!WiFi.isConnected() && _disableSTAConn)){ + // this fixes most ap problems, however, simply doing mode(WIFI_AP) does not work if sta connection is hanging, must `wifi_station_disconnect` + #ifdef WM_DISCONWORKAROUND + WiFi.mode(WIFI_AP_STA); + #endif + WiFi_Disconnect(); + WiFi_enableSTA(false); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Disabling STA")); + #endif + } + else { + // WiFi_enableSTA(true); + } + + // init configportal globals to known states + configPortalActive = true; + bool result = connect = abort = false; // loop flags, connect true success, abort true break + uint8_t state; + + _configPortalStart = millis(); + + // start access point + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Enabling AP")); + #endif + startAP(); + WiFiSetCountry(); + + // do AP callback if set + if ( _apcallback != NULL) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] _apcallback calling")); + #endif + _apcallback(this); + } + + // init configportal + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("setupConfigPortal")); + #endif + setupConfigPortal(); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("setupDNSD")); + #endif + setupDNSD(); + + + if(!_configPortalIsBlocking){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Config Portal Running, non blocking (processing)")); + if(_configPortalTimeout > 0) DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal Timeout In"),(String)(_configPortalTimeout/1000) + (String)F(" seconds")); + #endif + return result; // skip blocking loop + } + + // enter blocking loop, waiting for config + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients...")); + if(_configPortalTimeout > 0) DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal Timeout In"),(String)(_configPortalTimeout/1000) + (String)F(" seconds")); + #endif + + while(1){ + + // if timed out or abort, break + if(configPortalHasTimeout() || abort){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("configportal loop abort")); + #endif + shutdownConfigPortal(); + result = abort ? portalAbortResult : portalTimeoutResult; // false, false + if (_configportaltimeoutcallback != NULL) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] config portal timeout callback")); + #endif + _configportaltimeoutcallback(); // @CALLBACK + } + break; + } + + state = processConfigPortal(); + + // status change, break + // @todo what is this for, should be moved inside the processor + // I think.. this is to detect autoconnect by esp in background, there are also many open issues about autoreconnect not working + if(state != WL_IDLE_STATUS){ + result = (state == WL_CONNECTED); // true if connected + DEBUG_WM(WM_DEBUG_DEV,F("configportal loop break")); + break; + } + + if(!configPortalActive) break; + + yield(); // watchdog + } + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_NOTIFY,F("config portal exiting")); + #endif + return result; +} + +/** + * [process description] + * @access public + * @return bool connected + */ +boolean WiFiManager::process(){ + // process mdns, esp32 not required + #if defined(WM_MDNS) && defined(ESP8266) + MDNS.update(); + #endif + + if(webPortalActive || (configPortalActive && !_configPortalIsBlocking)){ + // if timed out or abort, break + if(_allowExit && (configPortalHasTimeout() || abort)){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("process loop abort")); + #endif + webPortalActive = false; + shutdownConfigPortal(); + if (_configportaltimeoutcallback != NULL) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] config portal timeout callback")); + #endif + _configportaltimeoutcallback(); // @CALLBACK + } + return false; + } + + uint8_t state = processConfigPortal(); // state is WL_IDLE or WL_CONNECTED/FAILED + return state == WL_CONNECTED; + } + return false; +} + +/** + * [processConfigPortal description] + * using esp wl_status enums as returns for now, should be fine + * returns WL_IDLE_STATUS or WL_CONNECTED/WL_CONNECT_FAILED upon connect/save flag + * + * @return {[type]} [description] + */ +uint8_t WiFiManager::processConfigPortal(){ + if(configPortalActive){ + //DNS handler + dnsServer->processNextRequest(); + } + + //HTTP handler + server->handleClient(); + + // Waiting for save... + if(connect) { + connect = false; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("processing save")); + #endif + if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. + + // skip wifi if no ssid + if(_ssid == ""){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("No ssid, skipping wifi save")); + #endif + } + else{ + // attempt sta connection to submitted _ssid, _pass + uint8_t res = connectWifi(_ssid, _pass, _connectonsave) == WL_CONNECTED; + if (res || (!_connectonsave)) { + #ifdef WM_DEBUG_LEVEL + if(!_connectonsave){ + DEBUG_WM(F("SAVED with no connect to new AP")); + } else { + DEBUG_WM(F("Connect to new AP [SUCCESS]")); + DEBUG_WM(F("Got IP Address:")); + DEBUG_WM(WiFi.localIP()); + } + #endif + + if ( _savewificallback != NULL) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] _savewificallback calling")); + #endif + _savewificallback(); // @CALLBACK + } + if(!_connectonsave) return WL_IDLE_STATUS; + if(_disableConfigPortal) shutdownConfigPortal(); + return WL_CONNECTED; // CONNECT SUCCESS + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); + #endif + } + + if (_shouldBreakAfterConfig) { + + // do save callback + // @todo this is more of an exiting callback than a save, clarify when this should actually occur + // confirm or verify data was saved to make this more accurate callback + if ( _savewificallback != NULL) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] WiFi/Param save callback")); + #endif + _savewificallback(); // @CALLBACK + } + if(_disableConfigPortal) shutdownConfigPortal(); + return WL_CONNECT_FAILED; // CONNECT FAIL + } + else if(_configPortalIsBlocking){ + // clear save strings + _ssid = ""; + _pass = ""; + // if connect fails, turn sta off to stabilize AP + WiFi_Disconnect(); + WiFi_enableSTA(false); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Processing - Disabling STA")); + #endif + } + else{ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal is non blocking - remaining open")); + #endif + } + } + + return WL_IDLE_STATUS; +} + +/** + * [shutdownConfigPortal description] + * @access public + * @return bool success (softapdisconnect) + */ +bool WiFiManager::shutdownConfigPortal(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("shutdownConfigPortal")); + #endif + + if(webPortalActive) return false; + + if(configPortalActive){ + //DNS handler + dnsServer->processNextRequest(); + } + + //HTTP handler + server->handleClient(); + + // @todo what is the proper way to shutdown and free the server up + // debug - many open issues aobut port not clearing for use with other servers + server->stop(); + server.reset(); + + WiFi.scanDelete(); // free wifi scan results + + if(!configPortalActive) return false; + + dnsServer->stop(); // free heap ? + dnsServer.reset(); + + // turn off AP + // @todo bug workaround + // https://github.com/esp8266/Arduino/issues/3793 + // [APdisconnect] set_config failed! *WM: disconnect configportal - softAPdisconnect failed + // still no way to reproduce reliably + + bool ret = false; + ret = WiFi.softAPdisconnect(false); + + #ifdef WM_DEBUG_LEVEL + if(!ret)DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); + DEBUG_WM(WM_DEBUG_VERBOSE,F("restoring usermode"),getModeString(_usermode)); + #endif + delay(1000); + WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372 + if(WiFi.status()==WL_IDLE_STATUS){ + WiFi.reconnect(); // restart wifi since we disconnected it in startconfigportal + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Reconnect, was idle")); + #endif + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("wifi status:"),getWLStatusString(WiFi.status())); + DEBUG_WM(WM_DEBUG_VERBOSE,F("wifi mode:"),getModeString(WiFi.getMode())); + #endif + configPortalActive = false; + DEBUG_WM(WM_DEBUG_VERBOSE,F("configportal closed")); + _end(); + return ret; +} + +// @todo refactor this up into seperate functions +// one for connecting to flash , one for new client +// clean up, flow is convoluted, and causes bugs +uint8_t WiFiManager::connectWifi(String ssid, String pass, bool connect) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Connecting as wifi client...")); + #endif + uint8_t retry = 1; + uint8_t connRes = (uint8_t)WL_NO_SSID_AVAIL; + + setSTAConfig(); + //@todo catch failures in set_config + + // make sure sta is on before `begin` so it does not call enablesta->mode while persistent is ON ( which would save WM AP state to eeprom !) + // WiFi.setAutoReconnect(false); + if(_cleanConnect) WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect + // @todo find out what status is when this is needed, can we detect it and handle it, say in between states or idle_status to avoid these + + // if retry without delay (via begin()), the IDF is still busy even after returning status + // E (5130) wifi:sta is connecting, return error + // [E][WiFiSTA.cpp:221] begin(): connect failed! + + while(retry <= _connectRetries && (connRes!=WL_CONNECTED)){ + if(_connectRetries > 1){ + if(_aggresiveReconn) delay(1000); // add idle time before recon + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Connect Wifi, ATTEMPT #"),(String)retry+" of "+(String)_connectRetries); + #endif + } + // if ssid argument provided connect to that + // NOTE: this also catches preload() _defaultssid @todo rework + if (ssid != "") { + wifiConnectNew(ssid,pass,connect); + // @todo connect=false seems to disconnect sta in begin() so not sure if _connectonsave is useful at all + // skip wait if not connecting + // if(connect){ + if(_saveTimeout > 0){ + connRes = waitForConnectResult(_saveTimeout); // use default save timeout for saves to prevent bugs in esp->waitforconnectresult loop + } + else { + connRes = waitForConnectResult(); + } + // } + } + else { + // connect using saved ssid if there is one + if (WiFi_hasAutoConnect()) { + wifiConnectDefault(); + connRes = waitForConnectResult(); + } + else { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("No wifi saved, skipping")); + #endif + } + } + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes)); + #endif + retry++; +} + +// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 +#ifdef NO_EXTRA_4K_HEAP + // do WPS, if WPS options enabled and not connected and no password was supplied + // @todo this seems like wrong place for this, is it a fallback or option? + if (_tryWPS && connRes != WL_CONNECTED && pass == "") { + startWPS(); + // should be connected at the end of WPS + connRes = waitForConnectResult(); + } +#endif + + if(connRes != WL_SCAN_COMPLETED){ + updateConxResult(connRes); + } + + return connRes; +} + +/** + * connect to a new wifi ap + * @since $dev + * @param String ssid + * @param String pass + * @return bool success + * @return connect only save if false + */ +bool WiFiManager::wifiConnectNew(String ssid, String pass,bool connect){ + bool ret = false; + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(WM_DEBUG_DEV,F("CONNECTED: "),WiFi.status() == WL_CONNECTED ? "Y" : "NO"); + DEBUG_WM(F("Connecting to NEW AP:"),ssid); + DEBUG_WM(WM_DEBUG_DEV,F("Using Password:"),pass); + #endif + WiFi_enableSTA(true,storeSTAmode); // storeSTAmode will also toggle STA on in default opmode (persistent) if true (default) + WiFi.persistent(true); + ret = WiFi.begin(ssid.c_str(), pass.c_str(), 0, NULL, connect); + WiFi.persistent(false); + #ifdef WM_DEBUG_LEVEL + if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] wifi begin failed")); + #endif + return ret; +} + +/** + * connect to stored wifi + * @since dev + * @return bool success + */ +bool WiFiManager::wifiConnectDefault(){ + bool ret = false; + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Connecting to SAVED AP:"),WiFi_SSID(true)); + DEBUG_WM(WM_DEBUG_DEV,F("Using Password:"),WiFi_psk(true)); + #endif + + ret = WiFi_enableSTA(true,storeSTAmode); + delay(500); // THIS DELAY ? + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("Mode after delay: "),getModeString(WiFi.getMode())); + if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] wifi enableSta failed")); + #endif + + ret = WiFi.begin(); + + #ifdef WM_DEBUG_LEVEL + if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] wifi begin failed")); + #endif + + return ret; +} + + +/** + * set sta config if set + * @since $dev + * @return bool success + */ +bool WiFiManager::setSTAConfig(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("STA static IP:"),_sta_static_ip); + #endif + bool ret = true; + if (_sta_static_ip) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Custom static IP/GW/Subnet/DNS")); + #endif + if(_sta_static_dns) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Custom static DNS")); + #endif + ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn, _sta_static_dns); + } + else { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet")); + #endif + ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn); + } + + #ifdef WM_DEBUG_LEVEL + if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] wifi config failed")); + else DEBUG_WM(F("STA IP set:"),WiFi.localIP()); + #endif + } + else { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("setSTAConfig static ip not set, skipping")); + #endif + } + return ret; +} + +// @todo change to getLastFailureReason and do not touch conxresult +void WiFiManager::updateConxResult(uint8_t status){ + // hack in wrong password detection + _lastconxresult = status; + #ifdef ESP8266 + if(_lastconxresult == WL_CONNECT_FAILED){ + if(wifi_station_get_connect_status() == STATION_WRONG_PASSWORD){ + _lastconxresult = WL_STATION_WRONG_PASSWORD; + } + } + #elif defined(ESP32) + // if(_lastconxresult == WL_CONNECT_FAILED){ + if(_lastconxresult == WL_CONNECT_FAILED || _lastconxresult == WL_DISCONNECTED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("lastconxresulttmp:"),getWLStatusString(_lastconxresulttmp)); + #endif + if(_lastconxresulttmp != WL_IDLE_STATUS){ + _lastconxresult = _lastconxresulttmp; + // _lastconxresulttmp = WL_IDLE_STATUS; + } + } + DEBUG_WM(WM_DEBUG_DEV,F("lastconxresult:"),getWLStatusString(_lastconxresult)); + #endif +} + + +uint8_t WiFiManager::waitForConnectResult() { + #ifdef WM_DEBUG_LEVEL + if(_connectTimeout > 0) DEBUG_WM(WM_DEBUG_DEV,_connectTimeout,F("ms connectTimeout set")); + #endif + return waitForConnectResult(_connectTimeout); +} + +/** + * waitForConnectResult + * @param uint16_t timeout in seconds + * @return uint8_t WL Status + */ +uint8_t WiFiManager::waitForConnectResult(uint32_t timeout) { + if (timeout == 0){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("connectTimeout not set, ESP waitForConnectResult...")); + #endif + return WiFi.waitForConnectResult(); + } + + unsigned long timeoutmillis = millis() + timeout; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,timeout,F("ms timeout, waiting for connect...")); + #endif + uint8_t status = WiFi.status(); + + while(millis() < timeoutmillis) { + status = WiFi.status(); + // @todo detect additional states, connect happens, then dhcp then get ip, there is some delay here, make sure not to timeout if waiting on IP + if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) { + return status; + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM (WM_DEBUG_VERBOSE,F(".")); + #endif + delay(100); + } + return status; +} + +// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 +#ifdef NO_EXTRA_4K_HEAP +void WiFiManager::startWPS() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("START WPS")); + #endif + #ifdef ESP8266 + WiFi.beginWPSConfig(); + #else + // @todo + #endif + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("END WPS")); + #endif +} +#endif + +String WiFiManager::getHTTPHead(String title){ + String page; + page += FPSTR(HTTP_HEAD_START); + page.replace(FPSTR(T_v), title); + page += FPSTR(HTTP_SCRIPT); + page += FPSTR(HTTP_STYLE); + page += _customHeadElement; + + if(_bodyClass != ""){ + String p = FPSTR(HTTP_HEAD_END); + p.replace(FPSTR(T_c), _bodyClass); // add class str + page += p; + } + else { + page += FPSTR(HTTP_HEAD_END); + } + + return page; +} + +void WiFiManager::HTTPSend(const String &content){ + server->send(200, FPSTR(HTTP_HEAD_CT), content); +} + +/** + * HTTPD handler for page requests + */ +void WiFiManager::handleRequest() { + _webPortalAccessed = millis(); + + // TESTING HTTPD AUTH RFC 2617 + // BASIC_AUTH will hold onto creds, hard to "logout", but convienent + // DIGEST_AUTH will require new auth often, and nonce is random + // bool authenticate(const char * username, const char * password); + // bool authenticateDigest(const String& username, const String& H1); + // void requestAuthentication(HTTPAuthMethod mode = BASIC_AUTH, const char* realm = NULL, const String& authFailMsg = String("") ); + + // 2.3 NO AUTH available + bool testauth = false; + if(!testauth) return; + + DEBUG_WM(WM_DEBUG_DEV,F("DOING AUTH")); + bool res = server->authenticate("admin","12345"); + if(!res){ + #ifndef WM_NOAUTH + server->requestAuthentication(HTTPAuthMethod::BASIC_AUTH); // DIGEST_AUTH + #endif + DEBUG_WM(WM_DEBUG_DEV,F("AUTH FAIL")); + } +} + +/** + * HTTPD CALLBACK root or redirect to captive portal + */ +void WiFiManager::handleRoot() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Root")); + #endif + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + handleRequest(); + String page = getHTTPHead(_title); // @token options @todo replace options with title + String str = FPSTR(HTTP_ROOT_MAIN); // @todo custom title + str.replace(FPSTR(T_t),_title); + str.replace(FPSTR(T_v),configPortalActive ? _apName : (getWiFiHostname() + " - " + WiFi.localIP().toString())); // use ip if ap is not active for heading @todo use hostname? + page += str; + page += FPSTR(HTTP_PORTAL_OPTIONS); + page += getMenuOut(); + reportStatus(page); + page += FPSTR(HTTP_END); + + HTTPSend(page); + if(_preloadwifiscan) WiFi_scanNetworks(_scancachetime,true); // preload wifiscan throttled, async + // @todo buggy, captive portals make a query on every page load, causing this to run every time in addition to the real page load + // I dont understand why, when you are already in the captive portal, I guess they want to know that its still up and not done or gone + // if we can detect these and ignore them that would be great, since they come from the captive portal redirect maybe there is a refferer +} + +/** + * HTTPD CALLBACK Wifi config page handler + */ +void WiFiManager::handleWifi(boolean scan) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Wifi")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi + if (scan) { + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(WM_DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh"))); + #endif + WiFi_scanNetworks(server->hasArg(F("refresh")),false); //wifiscan, force if arg refresh + page += getScanItemOut(); + } + String pitem = ""; + + pitem = FPSTR(HTTP_FORM_START); + pitem.replace(FPSTR(T_v), F("wifisave")); // set form action + page += pitem; + + pitem = FPSTR(HTTP_FORM_WIFI); + pitem.replace(FPSTR(T_v), WiFi_SSID()); + + if(_showPassword){ + pitem.replace(FPSTR(T_p), WiFi_psk()); + } + else if(WiFi_psk() != ""){ + pitem.replace(FPSTR(T_p),FPSTR(S_passph)); + } + else { + pitem.replace(FPSTR(T_p),""); + } + + page += pitem; + + page += getStaticOut(); + page += FPSTR(HTTP_FORM_WIFI_END); + if(_paramsInWifi && _paramsCount>0){ + page += FPSTR(HTTP_FORM_PARAM_HEAD); + page += getParamOut(); + } + page += FPSTR(HTTP_FORM_END); + page += FPSTR(HTTP_SCAN_LINK); + if(_showBack) page += FPSTR(HTTP_BACKBTN); + reportStatus(page); + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("Sent config page")); + #endif +} + +/** + * HTTPD CALLBACK Wifi param page handler + */ +void WiFiManager::handleParam(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Param")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleparam)); // @token titlewifi + + String pitem = ""; + + pitem = FPSTR(HTTP_FORM_START); + pitem.replace(FPSTR(T_v), F("paramsave")); + page += pitem; + + page += getParamOut(); + page += FPSTR(HTTP_FORM_END); + if(_showBack) page += FPSTR(HTTP_BACKBTN); + reportStatus(page); + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("Sent param page")); + #endif +} + + +String WiFiManager::getMenuOut(){ + String page; + + for(auto menuId :_menuIds ){ + if((String)_menutokens[menuId] == "param" && _paramsCount == 0) continue; // no params set, omit params from menu, @todo this may be undesired by someone, use only menu to force? + if((String)_menutokens[menuId] == "custom" && _customMenuHTML!=NULL){ + page += _customMenuHTML; + continue; + } + page += HTTP_PORTAL_MENU[menuId]; + delay(0); + } + + return page; +} + +// // is it possible in softap mode to detect aps without scanning +// bool WiFiManager::WiFi_scanNetworksForAP(bool force){ +// WiFi_scanNetworks(force); +// } + +void WiFiManager::WiFi_scanComplete(int networksFound){ + _lastscan = millis(); + _numNetworks = networksFound; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan ASYNC completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan ASYNC found:"),_numNetworks); + #endif +} + +bool WiFiManager::WiFi_scanNetworks(){ + return WiFi_scanNetworks(false,false); +} + +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime,bool async){ + return WiFi_scanNetworks(millis()-_lastscan > cachetime,async); +} +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ + return WiFi_scanNetworks(millis()-_lastscan > cachetime,false); +} +bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(WM_DEBUG_DEV,"scanNetworks async:",async == true); + // DEBUG_WM(WM_DEBUG_DEV,_numNetworks,(millis()-_lastscan )); + // DEBUG_WM(WM_DEBUG_DEV,"scanNetworks force:",force == true); + #endif + + // if 0 networks, rescan @note this was a kludge, now disabling to test real cause ( maybe wifi not init etc) + // enable only if preload failed? + if(_numNetworks == 0 && _autoforcerescan){ + DEBUG_WM(WM_DEBUG_DEV,"NO APs found forcing new scan"); + force = true; + } + + // if scan is empty or stale (last scantime > _scancachetime), this avoids fast reloading wifi page and constant scan delayed page loads appearing to freeze. + if(!_lastscan || (_lastscan>0 && (millis()-_lastscan > _scancachetime))){ + force = true; + } + + if(force){ + int8_t res; + _startscan = millis(); + if(async && _asyncScan){ + #ifdef ESP8266 + #ifndef WM_NOASYNC // no async available < 2.4.0 + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + #endif + using namespace std::placeholders; // for `_1` + WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); + #else + DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan SYNC started")); + res = WiFi.scanNetworks(); + #endif + #else + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + #endif + res = WiFi.scanNetworks(true); + #endif + return false; + } + else{ + DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan SYNC started")); + res = WiFi.scanNetworks(); + } + if(res == WIFI_SCAN_FAILED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] scan failed")); + #endif + } + else if(res == WIFI_SCAN_RUNNING){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] scan waiting")); + #endif + while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,"."); + #endif + delay(100); + } + _numNetworks = WiFi.scanComplete(); + } + else if(res >=0 ) _numNetworks = res; + _lastscan = millis(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + #endif + return true; + } + else { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Scan is cached"),(String)(millis()-_lastscan )+" ms ago"); + #endif + } + return false; +} + +String WiFiManager::WiFiManager::getScanItemOut(){ + String page; + + if(!_numNetworks) WiFi_scanNetworks(); // scan in case this gets called before any scans + + int n = _numNetworks; + if (n == 0) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("No networks found")); + #endif + page += FPSTR(S_nonetworks); // @token nonetworks + page += F("

"); + } + else { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(n,F("networks found")); + #endif + //sort networks + int indices[n]; + for (int i = 0; i < n; i++) { + indices[i] = i; + } + + // RSSI SORT + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) { + std::swap(indices[i], indices[j]); + } + } + } + + /* test std:sort + std::sort(indices, indices + n, [](const int & a, const int & b) -> bool + { + return WiFi.RSSI(a) > WiFi.RSSI(b); + }); + */ + + // remove duplicates ( must be RSSI sorted ) + if (_removeDuplicateAPs) { + String cssid; + for (int i = 0; i < n; i++) { + if (indices[i] == -1) continue; + cssid = WiFi.SSID(indices[i]); + for (int j = i + 1; j < n; j++) { + if (cssid == WiFi.SSID(indices[j])) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("DUP AP:"),WiFi.SSID(indices[j])); + #endif + indices[j] = -1; // set dup aps to index -1 + } + } + } + } + + // token precheck, to speed up replacements on large ap lists + String HTTP_ITEM_STR = FPSTR(HTTP_ITEM); + + // toggle icons with percentage + HTTP_ITEM_STR.replace("{qp}", FPSTR(HTTP_ITEM_QP)); + HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "" : "h"); + HTTP_ITEM_STR.replace("{qi}", FPSTR(HTTP_ITEM_QI)); + HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "h" : ""); + + // set token precheck flags + bool tok_r = HTTP_ITEM_STR.indexOf(FPSTR(T_r)) > 0; + bool tok_R = HTTP_ITEM_STR.indexOf(FPSTR(T_R)) > 0; + bool tok_e = HTTP_ITEM_STR.indexOf(FPSTR(T_e)) > 0; + bool tok_q = HTTP_ITEM_STR.indexOf(FPSTR(T_q)) > 0; + bool tok_i = HTTP_ITEM_STR.indexOf(FPSTR(T_i)) > 0; + + //display networks in page + for (int i = 0; i < n; i++) { + if (indices[i] == -1) continue; // skip dups + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("AP: "),(String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); + #endif + + int rssiperc = getRSSIasQuality(WiFi.RSSI(indices[i])); + uint8_t enc_type = WiFi.encryptionType(indices[i]); + + if (_minimumQuality == -1 || _minimumQuality < rssiperc) { + String item = HTTP_ITEM_STR; + if(WiFi.SSID(indices[i]) == ""){ + // Serial.println(WiFi.BSSIDstr(indices[i])); + continue; // No idea why I am seeing these, lets just skip them for now + } + item.replace(FPSTR(T_V), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding + item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]),true)); // ssid no encoding + if(tok_e) item.replace(FPSTR(T_e), encryptionTypeStr(enc_type)); + if(tok_r) item.replace(FPSTR(T_r), (String)rssiperc); // rssi percentage 0-100 + if(tok_R) item.replace(FPSTR(T_R), (String)WiFi.RSSI(indices[i])); // rssi db + if(tok_q) item.replace(FPSTR(T_q), (String)int(round(map(rssiperc,0,100,1,4)))); //quality icon 1-4 + if(tok_i){ + if (enc_type != WM_WIFIOPEN) { + item.replace(FPSTR(T_i), F("l")); + } else { + item.replace(FPSTR(T_i), ""); + } + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,item); + #endif + page += item; + delay(0); + } else { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Skipping , does not meet _minimumQuality")); + #endif + } + + } + page += FPSTR(HTTP_BR); + } + + return page; +} + +String WiFiManager::getIpForm(String id, String title, String value){ + String item = FPSTR(HTTP_FORM_LABEL); + item += FPSTR(HTTP_FORM_PARAM); + item.replace(FPSTR(T_i), id); + item.replace(FPSTR(T_n), id); + item.replace(FPSTR(T_p), FPSTR(T_t)); + // item.replace(FPSTR(T_p), default); + item.replace(FPSTR(T_t), title); + item.replace(FPSTR(T_l), F("15")); + item.replace(FPSTR(T_v), value); + item.replace(FPSTR(T_c), ""); + return item; +} + +String WiFiManager::getStaticOut(){ + String page; + if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields>=0) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("_staShowStaticFields")); + #endif + page += FPSTR(HTTP_FORM_STATIC_HEAD); + // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not + page += getIpForm(FPSTR(S_ip),FPSTR(S_staticip),(_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip + // WiFi.localIP().toString(); + page += getIpForm(FPSTR(S_gw),FPSTR(S_staticgw),(_sta_static_gw ? _sta_static_gw.toString() : "")); // @token staticgw + // WiFi.gatewayIP().toString(); + page += getIpForm(FPSTR(S_sn),FPSTR(S_subnet),(_sta_static_sn ? _sta_static_sn.toString() : "")); // @token subnet + // WiFi.subnetMask().toString(); + } + + if((_staShowDns || _sta_static_dns) && _staShowDns>=0){ + page += getIpForm(FPSTR(S_dns),FPSTR(S_staticdns),(_sta_static_dns ? _sta_static_dns.toString() : "")); // @token dns + } + + if(page!="") page += FPSTR(HTTP_BR); // @todo remove these, use css + + return page; +} + +String WiFiManager::getParamOut(){ + String page; + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("getParamOut"),_paramsCount); + #endif + + if(_paramsCount > 0){ + + String HTTP_PARAM_temp = FPSTR(HTTP_FORM_LABEL); + HTTP_PARAM_temp += FPSTR(HTTP_FORM_PARAM); + bool tok_I = HTTP_PARAM_temp.indexOf(FPSTR(T_I)) > 0; + bool tok_i = HTTP_PARAM_temp.indexOf(FPSTR(T_i)) > 0; + bool tok_n = HTTP_PARAM_temp.indexOf(FPSTR(T_n)) > 0; + bool tok_p = HTTP_PARAM_temp.indexOf(FPSTR(T_p)) > 0; + bool tok_t = HTTP_PARAM_temp.indexOf(FPSTR(T_t)) > 0; + bool tok_l = HTTP_PARAM_temp.indexOf(FPSTR(T_l)) > 0; + bool tok_v = HTTP_PARAM_temp.indexOf(FPSTR(T_v)) > 0; + bool tok_c = HTTP_PARAM_temp.indexOf(FPSTR(T_c)) > 0; + + char valLength[5]; + + for (int i = 0; i < _paramsCount; i++) { + //Serial.println((String)_params[i]->_length); + if (_params[i] == NULL || _params[i]->_length > 99999) { + // try to detect param scope issues, doesnt always catch but works ok + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] WiFiManagerParameter is out of scope")); + #endif + return ""; + } + } + + // add the extra parameters to the form + for (int i = 0; i < _paramsCount; i++) { + // label before or after, @todo this could be done via floats or CSS and eliminated + String pitem; + switch (_params[i]->getLabelPlacement()) { + case WFM_LABEL_BEFORE: + pitem = FPSTR(HTTP_FORM_LABEL); + pitem += FPSTR(HTTP_FORM_PARAM); + break; + case WFM_LABEL_AFTER: + pitem = FPSTR(HTTP_FORM_PARAM); + pitem += FPSTR(HTTP_FORM_LABEL); + break; + default: + // WFM_NO_LABEL + pitem = FPSTR(HTTP_FORM_PARAM); + break; + } + + // Input templating + // "
"; + // if no ID use customhtml for item, else generate from param string + if (_params[i]->getID() != NULL) { + if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); // T_I id number + if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); // T_i id name + if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); // T_n id name alias + if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); // T_p replace legacy placeholder token + if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getLabel()); // T_t title/label + snprintf(valLength, 5, "%d", _params[i]->getValueLength()); + if(tok_l)pitem.replace(FPSTR(T_l), valLength); // T_l value length + if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); // T_v value + if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // T_c meant for additional attributes, not html, but can stuff + } else { + pitem = _params[i]->getCustomHTML(); + } + + page += pitem; + } + } + + return page; +} + +void WiFiManager::handleWiFiStatus(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP WiFi status ")); + #endif + handleRequest(); + String page; + // String page = "{\"result\":true,\"count\":1}"; + #ifdef WM_JSTEST + page = FPSTR(HTTP_JS); + #endif + HTTPSend(page); +} + +/** + * HTTPD CALLBACK save form and redirect to WLAN config page again + */ +void WiFiManager::handleWifiSave() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP WiFi save ")); + DEBUG_WM(WM_DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + #endif + handleRequest(); + + //SAVE/connect here + _ssid = server->arg(F("s")).c_str(); + _pass = server->arg(F("p")).c_str(); + + if(_ssid == "" && _pass != ""){ + _ssid = WiFi_SSID(true); // password change, placeholder ssid, @todo compare pass to old?, confirm ssid is clean + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Detected WiFi password change")); + #endif + } + + #ifdef WM_DEBUG_LEVEL + String requestinfo = "SERVER_REQUEST\n----------------\n"; + requestinfo += "URI: "; + requestinfo += server->uri(); + requestinfo += "\nMethod: "; + requestinfo += (server->method() == HTTP_GET) ? "GET" : "POST"; + requestinfo += "\nArguments: "; + requestinfo += server->args(); + requestinfo += "\n"; + for (uint8_t i = 0; i < server->args(); i++) { + requestinfo += " " + server->argName(i) + ": " + server->arg(i) + "\n"; + } + + DEBUG_WM(WM_DEBUG_MAX,requestinfo); + #endif + + // set static ips from server args + if (server->arg(FPSTR(S_ip)) != "") { + //_sta_static_ip.fromString(server->arg(FPSTR(S_ip)); + String ip = server->arg(FPSTR(S_ip)); + optionalIPFromString(&_sta_static_ip, ip.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("static ip:"),ip); + #endif + } + if (server->arg(FPSTR(S_gw)) != "") { + String gw = server->arg(FPSTR(S_gw)); + optionalIPFromString(&_sta_static_gw, gw.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("static gateway:"),gw); + #endif + } + if (server->arg(FPSTR(S_sn)) != "") { + String sn = server->arg(FPSTR(S_sn)); + optionalIPFromString(&_sta_static_sn, sn.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("static netmask:"),sn); + #endif + } + if (server->arg(FPSTR(S_dns)) != "") { + String dns = server->arg(FPSTR(S_dns)); + optionalIPFromString(&_sta_static_dns, dns.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("static DNS:"),dns); + #endif + } + + if (_presavewificallback != NULL) { + _presavewificallback(); // @CALLBACK + } + + if(_paramsInWifi) doParamSave(); + + String page; + + if(_ssid == ""){ + page = getHTTPHead(FPSTR(S_titlewifisettings)); // @token titleparamsaved + page += FPSTR(HTTP_PARAMSAVED); + } + else { + page = getHTTPHead(FPSTR(S_titlewifisaved)); // @token titlewifisaved + page += FPSTR(HTTP_SAVED); + } + + if(_showBack) page += FPSTR(HTTP_BACKBTN); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); // @HTTPHEAD send cors + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("Sent wifi save page")); + #endif + + connect = true; //signal ready to connect/reset process in processConfigPortal +} + +void WiFiManager::handleParamSave() { + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Param save ")); + #endif + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + #endif + handleRequest(); + + doParamSave(); + + String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved + page += FPSTR(HTTP_PARAMSAVED); + if(_showBack) page += FPSTR(HTTP_BACKBTN); + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("Sent param save page")); + #endif +} + +void WiFiManager::doParamSave(){ + // @todo use new callback for before paramsaves, is this really needed? + if ( _presaveparamscallback != NULL) { + _presaveparamscallback(); // @CALLBACK + } + + //parameters + if(_paramsCount > 0){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Parameters")); + DEBUG_WM(WM_DEBUG_VERBOSE,FPSTR(D_HR)); + #endif + + for (int i = 0; i < _paramsCount; i++) { + if (_params[i] == NULL || _params[i]->_length > 99999) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] WiFiManagerParameter is out of scope")); + #endif + break; // @todo might not be needed anymore + } + //read parameter from server + String name = (String)FPSTR(S_parampre)+(String)i; + String value; + if(server->hasArg(name)) { + value = server->arg(name); + } else { + value = server->arg(_params[i]->getID()); + } + + //store it in params array + value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); + #endif + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,FPSTR(D_HR)); + #endif + } + + if ( _saveparamscallback != NULL) { + _saveparamscallback(); // @CALLBACK + } + +} + +/** + * HTTPD CALLBACK info page + */ +void WiFiManager::handleInfo() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Info")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo + reportStatus(page); + + uint16_t infos = 0; + + //@todo convert to enum or refactor to strings + //@todo wrap in build flag to remove all info code for memory saving + #ifdef ESP8266 + infos = 28; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("fchipid"), + F("idesize"), + F("flashsize"), + F("corever"), + F("bootver"), + F("cpufreq"), + F("freeheap"), + F("memsketch"), + F("memsmeter"), + F("lastreset"), + F("wifihead"), + F("conx"), + F("stassid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("autoconx"), + F("wifiaphead"), + F("apssid"), + F("apip"), + F("apbssid"), + F("apmac") + }; + + #elif defined(ESP32) + // add esp_chip_info ? + infos = 27; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("chiprev"), + F("idesize"), + F("flashsize"), + F("cpufreq"), + F("freeheap"), + F("memsketch"), + F("memsmeter"), + F("lastreset"), + F("temp"), + // F("hall"), + F("wifihead"), + F("conx"), + F("stassid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("apssid"), + F("wifiaphead"), + F("apip"), + F("apmac"), + F("aphost"), + F("apbssid") + }; + #endif + + for(size_t i=0; i"); + + page += F("

About


"); + page += getInfoData("aboutver"); + page += getInfoData("aboutarduinover"); + page += getInfoData("aboutidfver"); + page += getInfoData("aboutdate"); + page += F("
"); + + if(_showInfoUpdate){ + page += HTTP_PORTAL_MENU[8]; + page += HTTP_PORTAL_MENU[9]; + } + if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); + if(_showBack) page += FPSTR(HTTP_BACKBTN); + page += FPSTR(HTTP_HELP); + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("Sent info page")); + #endif +} + +String WiFiManager::getInfoData(String id){ + + String p; + if(id==F("esphead")){ + p = FPSTR(HTTP_INFO_esphead); + #ifdef ESP32 + p.replace(FPSTR(T_1), (String)ESP.getChipModel()); + #endif + } + else if(id==F("wifihead")){ + p = FPSTR(HTTP_INFO_wifihead); + p.replace(FPSTR(T_1),getModeString(WiFi.getMode())); + } + else if(id==F("uptime")){ + // subject to rollover! + p = FPSTR(HTTP_INFO_uptime); + p.replace(FPSTR(T_1),(String)(millis() / 1000 / 60)); + p.replace(FPSTR(T_2),(String)((millis() / 1000) % 60)); + } + else if(id==F("chipid")){ + p = FPSTR(HTTP_INFO_chipid); + p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); + } + #ifdef ESP32 + else if(id==F("chiprev")){ + p = FPSTR(HTTP_INFO_chiprev); + String rev = (String)ESP.getChipRevision(); + #ifdef _SOC_EFUSE_REG_H_ + String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S)&&EFUSE_RD_CHIP_VER_RESERVE_V); + p.replace(FPSTR(T_1),rev+"
"+revb); + #else + p.replace(FPSTR(T_1),rev); + #endif + } + #endif + #ifdef ESP8266 + else if(id==F("fchipid")){ + p = FPSTR(HTTP_INFO_fchipid); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipId()); + } + #endif + else if(id==F("idesize")){ + p = FPSTR(HTTP_INFO_idesize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipSize()); + } + else if(id==F("flashsize")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_flashsize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); + #elif defined ESP32 + p = FPSTR(HTTP_INFO_psrsize); + p.replace(FPSTR(T_1),(String)ESP.getPsramSize()); + #endif + } + else if(id==F("corever")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_corever); + p.replace(FPSTR(T_1),(String)ESP.getCoreVersion()); + #endif + } + #ifdef ESP8266 + else if(id==F("bootver")){ + p = FPSTR(HTTP_INFO_bootver); + p.replace(FPSTR(T_1),(String)system_get_boot_version()); + } + #endif + else if(id==F("cpufreq")){ + p = FPSTR(HTTP_INFO_cpufreq); + p.replace(FPSTR(T_1),(String)ESP.getCpuFreqMHz()); + } + else if(id==F("freeheap")){ + p = FPSTR(HTTP_INFO_freeheap); + p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); + } + else if(id==F("memsketch")){ + p = FPSTR(HTTP_INFO_memsketch); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + else if(id==F("memsmeter")){ + p = FPSTR(HTTP_INFO_memsmeter); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + else if(id==F("lastreset")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_lastreset); + p.replace(FPSTR(T_1),(String)ESP.getResetReason()); + #elif defined(ESP32) && defined(_ROM_RTC_H_) + // requires #include + p = FPSTR(HTTP_INFO_lastreset); + for(int i=0;i<2;i++){ + int reason = rtc_get_reset_reason(i); + String tok = (String)T_ss+(String)(i+1)+(String)T_es; + switch (reason) + { + //@todo move to array + case 1 : p.replace(tok,F("Vbat power on reset"));break; + case 3 : p.replace(tok,F("Software reset digital core"));break; + case 4 : p.replace(tok,F("Legacy watch dog reset digital core"));break; + case 5 : p.replace(tok,F("Deep Sleep reset digital core"));break; + case 6 : p.replace(tok,F("Reset by SLC module, reset digital core"));break; + case 7 : p.replace(tok,F("Timer Group0 Watch dog reset digital core"));break; + case 8 : p.replace(tok,F("Timer Group1 Watch dog reset digital core"));break; + case 9 : p.replace(tok,F("RTC Watch dog Reset digital core"));break; + case 10 : p.replace(tok,F("Instrusion tested to reset CPU"));break; + case 11 : p.replace(tok,F("Time Group reset CPU"));break; + case 12 : p.replace(tok,F("Software reset CPU"));break; + case 13 : p.replace(tok,F("RTC Watch dog Reset CPU"));break; + case 14 : p.replace(tok,F("for APP CPU, reseted by PRO CPU"));break; + case 15 : p.replace(tok,F("Reset when the vdd voltage is not stable"));break; + case 16 : p.replace(tok,F("RTC Watch dog reset digital core and rtc module"));break; + default : p.replace(tok,F("NO_MEAN")); + } + } + #endif + } + else if(id==F("apip")){ + p = FPSTR(HTTP_INFO_apip); + p.replace(FPSTR(T_1),WiFi.softAPIP().toString()); + } + else if(id==F("apmac")){ + p = FPSTR(HTTP_INFO_apmac); + p.replace(FPSTR(T_1),(String)WiFi.softAPmacAddress()); + } + #ifdef ESP32 + else if(id==F("aphost")){ + p = FPSTR(HTTP_INFO_aphost); + p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); + } + #endif + #ifndef WM_NOSOFTAPSSID + #ifdef ESP8266 + else if(id==F("apssid")){ + p = FPSTR(HTTP_INFO_apssid); + p.replace(FPSTR(T_1),htmlEntities(WiFi.softAPSSID())); + } + #endif + #endif + else if(id==F("apbssid")){ + p = FPSTR(HTTP_INFO_apbssid); + p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); + } + // softAPgetHostname // esp32 + // softAPSubnetCIDR + // softAPNetworkID + // softAPBroadcastIP + + else if(id==F("stassid")){ + p = FPSTR(HTTP_INFO_stassid); + p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); + } + else if(id==F("staip")){ + p = FPSTR(HTTP_INFO_staip); + p.replace(FPSTR(T_1),WiFi.localIP().toString()); + } + else if(id==F("stagw")){ + p = FPSTR(HTTP_INFO_stagw); + p.replace(FPSTR(T_1),WiFi.gatewayIP().toString()); + } + else if(id==F("stasub")){ + p = FPSTR(HTTP_INFO_stasub); + p.replace(FPSTR(T_1),WiFi.subnetMask().toString()); + } + else if(id==F("dnss")){ + p = FPSTR(HTTP_INFO_dnss); + p.replace(FPSTR(T_1),WiFi.dnsIP().toString()); + } + else if(id==F("host")){ + p = FPSTR(HTTP_INFO_host); + #ifdef ESP32 + p.replace(FPSTR(T_1),WiFi.getHostname()); + #else + p.replace(FPSTR(T_1),WiFi.hostname()); + #endif + } + else if(id==F("stamac")){ + p = FPSTR(HTTP_INFO_stamac); + p.replace(FPSTR(T_1),WiFi.macAddress()); + } + else if(id==F("conx")){ + p = FPSTR(HTTP_INFO_conx); + p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); + } + #ifdef ESP8266 + else if(id==F("autoconx")){ + p = FPSTR(HTTP_INFO_autoconx); + p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); + } + #endif + #if defined(ESP32) && !defined(WM_NOTEMP) + else if(id==F("temp")){ + // temperature is not calibrated, varying large offsets are present, use for relative temp changes only + p = FPSTR(HTTP_INFO_temp); + p.replace(FPSTR(T_1),(String)temperatureRead()); + p.replace(FPSTR(T_2),(String)((temperatureRead()+32)*1.8f)); + } + // else if(id==F("hall")){ + // p = FPSTR(HTTP_INFO_hall); + // p.replace(FPSTR(T_1),(String)hallRead()); // hall sensor reads can cause issues with adcs + // } + #endif + else if(id==F("aboutver")){ + p = FPSTR(HTTP_INFO_aboutver); + p.replace(FPSTR(T_1),FPSTR(WM_VERSION_STR)); + } + else if(id==F("aboutarduinover")){ + #ifdef VER_ARDUINO_STR + p = FPSTR(HTTP_INFO_aboutarduino); + p.replace(FPSTR(T_1),String(VER_ARDUINO_STR)); + #endif + } + // else if(id==F("aboutidfver")){ + // #ifdef VER_IDF_STR + // p = FPSTR(HTTP_INFO_aboutidf); + // p.replace(FPSTR(T_1),String(VER_IDF_STR)); + // #endif + // } + else if(id==F("aboutsdkver")){ + p = FPSTR(HTTP_INFO_sdkver); + #ifdef ESP32 + p.replace(FPSTR(T_1),(String)esp_get_idf_version()); + // p.replace(FPSTR(T_1),(String)system_get_sdk_version()); // deprecated + #else + p.replace(FPSTR(T_1),(String)system_get_sdk_version()); + #endif + } + else if(id==F("aboutdate")){ + p = FPSTR(HTTP_INFO_aboutdate); + p.replace(FPSTR(T_1),String(__DATE__ " " __TIME__)); + } + return p; +} + +/** + * HTTPD CALLBACK exit, closes configportal if blocking, if non blocking undefined + */ +void WiFiManager::handleExit() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Exit")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit + page += FPSTR(S_exiting); // @token exiting + // ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'}) + server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); // @HTTPHEAD send cache + HTTPSend(page); + delay(2000); + abort = true; +} + +/** + * HTTPD CALLBACK reset page + */ +void WiFiManager::handleReset() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP Reset")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset + page += FPSTR(S_resetting); //@token resetting + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("RESETTING ESP")); + #endif + delay(1000); + reboot(); +} + +/** + * HTTPD CALLBACK erase page + */ + +// void WiFiManager::handleErase() { +// handleErase(false); +// } +void WiFiManager::handleErase(boolean opt) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_NOTIFY,F("<- HTTP Erase")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase + + bool ret = erase(opt); + if (_resetcallback != NULL){ + _resetcallback(); // @CALLBACK + } + + if(ret) page += FPSTR(S_resetting); // @token resetting + else { + page += FPSTR(S_error); // @token erroroccur + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); + #endif + } + + page += FPSTR(HTTP_END); + HTTPSend(page); + + if(ret){ + delay(2000); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("RESETTING ESP")); + #endif + reboot(); + } +} + +/** + * HTTPD CALLBACK 404 + */ +void WiFiManager::handleNotFound() { + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + handleRequest(); + String message = FPSTR(S_notfound); // @token notfound + + bool verbose404 = false; // show info in 404 body, uri,method, args + if(verbose404){ + message += FPSTR(S_uri); // @token uri + message += server->uri(); + message += FPSTR(S_method); // @token method + message += ( server->method() == HTTP_GET ) ? FPSTR(S_GET) : FPSTR(S_POST); + message += FPSTR(S_args); // @token args + message += server->args(); + message += F("\n"); + + for ( uint8_t i = 0; i < server->args(); i++ ) { + message += " " + server->argName ( i ) + ": " + server->arg ( i ) + "\n"; + } + } + server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); // @HTTPHEAD send cache + server->sendHeader(F("Pragma"), F("no-cache")); + server->sendHeader(F("Expires"), F("-1")); + server->send ( 404, FPSTR(HTTP_HEAD_CT2), message ); +} + +/** + * HTTPD redirector + * Redirect to captive portal if we got a request for another domain. + * Return true in that case so the page handler do not try to handle the request again. + */ +boolean WiFiManager::captivePortal() { + + if(!_enableCaptivePortal || !configPortalActive) return false; // skip redirections if cp not enabled or not in ap mode + + String serverLoc = toStringIp(server->client().localIP()); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,"-> " + server->hostHeader()); + DEBUG_WM(WM_DEBUG_DEV,"serverLoc " + serverLoc); + #endif + + // fallback for ipv6 bug + if(serverLoc == "0.0.0.0"){ + if ((WiFi.status()) != WL_CONNECTED) + serverLoc = toStringIp(WiFi.softAPIP()); + else + serverLoc = toStringIp(WiFi.localIP()); + } + + if(_httpPort != 80) serverLoc += ":" + (String)_httpPort; // add port if not default + bool doredirect = serverLoc != server->hostHeader(); // redirect if hostheader not server ip, prevent redirect loops + + if (doredirect) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- Request redirected to captive portal")); + DEBUG_WM(WM_DEBUG_DEV,"serverLoc " + serverLoc); + #endif + server->sendHeader(F("Location"), (String)F("http://") + serverLoc, true); // @HTTPHEAD send redirect + server->send ( 302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server->client().stop(); // Stop is needed because we sent no content length + return true; + } + return false; +} + +void WiFiManager::stopCaptivePortal(){ + _enableCaptivePortal= false; + // @todo maybe disable configportaltimeout(optional), or just provide callback for user +} + +// HTTPD CALLBACK, handle close, stop captive portal, if not enabled undefined +void WiFiManager::handleClose(){ + DEBUG_WM(WM_DEBUG_VERBOSE,F("Disabling Captive Portal")); + stopCaptivePortal(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- HTTP close")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose + page += FPSTR(S_closing); // @token closing + HTTPSend(page); +} + +void WiFiManager::reportStatus(String &page){ + // updateConxResult(WiFi.status()); // @todo: this defeats the purpose of last result, update elsewhere or add logic here + DEBUG_WM(WM_DEBUG_DEV,F("[WIFI] reportStatus prev:"),getWLStatusString(_lastconxresult)); + DEBUG_WM(WM_DEBUG_DEV,F("[WIFI] reportStatus current:"),getWLStatusString(WiFi.status())); + String str; + if (WiFi_SSID() != ""){ + if (WiFi.status()==WL_CONNECTED){ + str = FPSTR(HTTP_STATUS_ON); + str.replace(FPSTR(T_i),WiFi.localIP().toString()); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + } + else { + str = FPSTR(HTTP_STATUS_OFF); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + if(_lastconxresult == WL_STATION_WRONG_PASSWORD){ + // wrong password + str.replace(FPSTR(T_c),"D"); // class + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFPW)); + } + else if(_lastconxresult == WL_NO_SSID_AVAIL){ + // connect failed, or ap not found + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFNOAP)); + } + else if(_lastconxresult == WL_CONNECT_FAILED){ + // connect failed + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); + } + else{ + str.replace(FPSTR(T_c),""); + str.replace(FPSTR(T_r),""); + } + } + } + else { + str = FPSTR(HTTP_STATUS_NONE); + } + page += str; +} + +// PUBLIC + +// METHODS + +/** + * reset wifi settings, clean stored ap password + */ + +/** + * [stopConfigPortal description] + * @return {[type]} [description] + */ +bool WiFiManager::stopConfigPortal(){ + if(_configPortalIsBlocking){ + abort = true; + return true; + } + return shutdownConfigPortal(); +} + +/** + * disconnect + * @access public + * @since $dev + * @return bool success + */ +bool WiFiManager::disconnect(){ + if(WiFi.status() != WL_CONNECTED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("Disconnecting: Not connected")); + #endif + return false; + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Disconnecting")); + #endif + return WiFi_Disconnect(); +} + +/** + * reboot the device + * @access public + */ +void WiFiManager::reboot(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Restarting")); + #endif + ESP.restart(); +} + +/** + * reboot the device + * @access public + */ +bool WiFiManager::erase(){ + return erase(false); +} + +bool WiFiManager::erase(bool opt){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM("Erasing"); + #endif + + #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) + // if opt true, do nvs erase + if(opt){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing NVS")); + #endif + esp_err_t err; + err = nvs_flash_init(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("nvs_flash_init: "),err!=ESP_OK ? (String)err : "Success"); + #endif + err = nvs_flash_erase(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("nvs_flash_erase: "), err!=ESP_OK ? (String)err : "Success"); + #endif + return err == ESP_OK; + } + #elif defined(ESP8266) && defined(spiffs_api_h) + if(opt){ + bool ret = false; + if(SPIFFS.begin()){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing SPIFFS")); + #endif + bool ret = SPIFFS.format(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("spiffs erase: "),ret ? "Success" : "ERROR"); + #endif + } else{ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("[ERROR] Could not start SPIFFS")); + #endif + } + return ret; + } + #else + (void)opt; + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing WiFi Config")); + #endif + return WiFi_eraseConfig(); +} + +/** + * [resetSettings description] + * ERASES STA CREDENTIALS + * @access public + */ +void WiFiManager::resetSettings() { +#ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("resetSettings")); + #endif + WiFi_enableSTA(true,true); // must be sta to disconnect erase + delay(500); // ensure sta is enabled + if (_resetcallback != NULL){ + _resetcallback(); // @CALLBACK + } + + #ifdef ESP32 + WiFi.disconnect(true,true); + #else + WiFi.persistent(true); + WiFi.disconnect(true); + WiFi.persistent(false); + #endif + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("SETTINGS ERASED")); + #endif +} + +// SETTERS + +/** + * [setTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setTimeout(unsigned long seconds) { + setConfigPortalTimeout(seconds); +} + +/** + * [setConfigPortalTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { + _configPortalTimeout = seconds * 1000; +} + +/** + * [setConnectTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConnectTimeout(unsigned long seconds) { + _connectTimeout = seconds * 1000; +} + +/** + * [setConnectRetries description] + * @access public + * @param {[type]} uint8_t numRetries [description] + */ +void WiFiManager::setConnectRetries(uint8_t numRetries){ + _connectRetries = constrain(numRetries,1,10); +} + +/** + * toggle _cleanconnect, always disconnect before connecting + * @param {[type]} bool enable [description] + */ +void WiFiManager::setCleanConnect(bool enable){ + _cleanConnect = enable; +} + +/** + * [setConnectTimeout description + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { + _saveTimeout = seconds * 1000; +} + +/** + * Set save portal connect on save option, + * if false, will only save credentials not connect + * @access public + * @param {[type]} bool connect [description] + */ +void WiFiManager::setSaveConnect(bool connect) { + _connectonsave = connect; +} + +/** + * [setDebugOutput description] + * @access public + * @param {[type]} boolean debug [description] + */ +void WiFiManager::setDebugOutput(boolean debug) { + _debug = debug; + if(_debug && _debugLevel == WM_DEBUG_DEV) debugPlatformInfo(); + if(_debug && _debugLevel >= WM_DEBUG_NOTIFY)DEBUG_WM((__FlashStringHelper *)WM_VERSION_STR," D:"+String(_debugLevel)); +} + +void WiFiManager::setDebugOutput(boolean debug, String prefix) { + _debugPrefix = prefix; + setDebugOutput(debug); +} + +void WiFiManager::setDebugOutput(boolean debug, wm_debuglevel_t level) { + _debugLevel = level; + // _debugPrefix = prefix; + setDebugOutput(debug); +} + + +/** + * [setAPStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _ap_static_ip = ip; + _ap_static_gw = gw; + _ap_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _sta_static_ip = ip; + _sta_static_gw = gw; + _sta_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @since $dev + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + * @param {[type]} IPAddress dns [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) { + setSTAStaticIPConfig(ip,gw,sn); + _sta_static_dns = dns; +} + +/** + * [setMinimumSignalQuality description] + * @access public + * @param {[type]} int quality [description] + */ +void WiFiManager::setMinimumSignalQuality(int quality) { + _minimumQuality = quality; +} + +/** + * [setBreakAfterConfig description] + * @access public + * @param {[type]} boolean shouldBreak [description] + */ +void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { + _shouldBreakAfterConfig = shouldBreak; +} + +/** + * setAPCallback, set a callback when softap is started + * @access public + * @param {[type]} void (*func)(WiFiManager* wminstance) + */ +void WiFiManager::setAPCallback( std::function func ) { + _apcallback = func; +} + +/** + * setWebServerCallback, set a callback after webserver is reset, and before routes are setup + * if we set webserver handlers before wm, they are used and wm is not by esp webserver + * on events cannot be overrided once set, and are not mutiples + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setWebServerCallback( std::function func ) { + _webservercallback = func; +} + +/** + * setSaveConfigCallback, set a save config callback after closing configportal + * @note calls only if wifi is saved or changed, or setBreakAfterConfig(true) + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveConfigCallback( std::function func ) { + _savewificallback = func; +} + +/** + * setPreSaveConfigCallback, set a callback to fire before saving wifi or params + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreSaveConfigCallback( std::function func ) { + _presavewificallback = func; +} + +/** + * setConfigResetCallback, set a callback to occur when a resetSettings() occurs + * @access public + * @param {[type]} void(*func)(void) + */ +void WiFiManager::setConfigResetCallback( std::function func ) { + _resetcallback = func; +} + +/** + * setSaveParamsCallback, set a save params callback on params save in wifi or params pages + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveParamsCallback( std::function func ) { + _saveparamscallback = func; +} + +/** + * setPreSaveParamsCallback, set a pre save params callback on params save prior to anything else + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreSaveParamsCallback( std::function func ) { + _presaveparamscallback = func; +} + +/** + * setPreOtaUpdateCallback, set a callback to fire before OTA update + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreOtaUpdateCallback( std::function func ) { + _preotaupdatecallback = func; +} + +/** + * setConfigPortalTimeoutCallback, set a callback to config portal is timeout + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setConfigPortalTimeoutCallback( std::function func ) { + _configportaltimeoutcallback = func; +} + +/** + * set custom head html + * custom element will be added to head, eg. new meta,style,script tag etc. + * @access public + * @param char element + */ +void WiFiManager::setCustomHeadElement(const char* html) { + _customHeadElement = html; +} + +/** + * set custom menu html + * custom element will be added to menu under custom menu item. + * @access public + * @param char element + */ +void WiFiManager::setCustomMenuHTML(const char* html) { + _customMenuHTML = html; +} + +/** + * toggle wifiscan hiding of duplicate ssid names + * if this is false, wifiscan will remove duplicat Access Points - defaut true + * @access public + * @param boolean removeDuplicates [true] + */ +void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { + _removeDuplicateAPs = removeDuplicates; +} + +/** + * toggle configportal blocking loop + * if enabled, then the configportal will enter a blocking loop and wait for configuration + * if disabled use with process() to manually process webserver + * @since $dev + * @access public + * @param boolean shoudlBlock [false] + */ +void WiFiManager::setConfigPortalBlocking(boolean shouldBlock) { + _configPortalIsBlocking = shouldBlock; +} + +/** + * toggle restore persistent, track internally + * sets ESP wifi.persistent so we can remember it and restore user preference on destruct + * there is no getter in esp8266 platform prior to https://github.com/esp8266/Arduino/pull/3857 + * @since $dev + * @access public + * @param boolean persistent [true] + */ +void WiFiManager::setRestorePersistent(boolean persistent) { + _userpersistent = persistent; + if(!persistent){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("persistent is off")); + #endif + } +} + +/** + * toggle showing static ip form fields + * if enabled, then the static ip, gateway, subnet fields will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowStaticFields(boolean alwaysShow){ + if(_disableIpFields) _staShowStaticFields = alwaysShow ? 1 : -1; + else _staShowStaticFields = alwaysShow ? 1 : 0; +} + +/** + * toggle showing dns fields + * if enabled, then the dns1 field will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowDnsFields(boolean alwaysShow){ + if(_disableIpFields) _staShowDns = alwaysShow ? 1 : -1; + _staShowDns = alwaysShow ? 1 : 0; +} + +/** + * toggle showing password in wifi password field + * if not enabled, placeholder will be S_passph + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowPassword(boolean show){ + _showPassword = show; +} + +/** + * toggle captive portal + * if enabled, then devices that use captive portal checks will be redirected to root + * if not you will automatically have to navigate to ip [192.168.4.1] + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setCaptivePortalEnable(boolean enabled){ + _enableCaptivePortal = enabled; +} + +/** + * toggle wifi autoreconnect policy + * if enabled, then wifi will autoreconnect automatically always + * On esp8266 we force this on when autoconnect is called, see notes + * On esp32 this is handled on SYSTEM_EVENT_STA_DISCONNECTED since it does not exist in core yet + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWiFiAutoReconnect(boolean enabled){ + _wifiAutoReconnect = enabled; +} + +/** + * toggle configportal timeout wait for station client + * if enabled, then the configportal will start timeout when no stations are connected to softAP + * disabled by default as rogue stations can keep it open if there is no auth + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setAPClientCheck(boolean enabled){ + _apClientCheck = enabled; +} + +/** + * toggle configportal timeout wait for web client + * if enabled, then the configportal will restart timeout when client requests come in + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWebPortalClientCheck(boolean enabled){ + _webClientCheck = enabled; +} + +/** + * toggle wifiscan percentages or quality icons + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setScanDispPerc(boolean enabled){ + _scanDispOptions = enabled; +} + +/** + * toggle configportal if autoconnect failed + * if enabled, then the configportal will be activated on autoconnect failure + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setEnableConfigPortal(boolean enable) +{ + _enableConfigPortal = enable; +} + +/** + * toggle configportal if autoconnect failed + * if enabled, then the configportal will be de-activated on wifi save + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setDisableConfigPortal(boolean enable) +{ + _disableConfigPortal = enable; +} + +/** + * set the hostname (dhcp client id) + * @since $dev + * @access public + * @param char* hostname 32 character hostname to use for sta+ap in esp32, sta in esp8266 + * @return bool false if hostname is not valid + */ +bool WiFiManager::setHostname(const char * hostname){ + //@todo max length 32 + _hostname = String(hostname); + return true; +} + +bool WiFiManager::setHostname(String hostname){ + //@todo max length 32 + _hostname = hostname; + return true; +} + +/** + * set the soft ao channel, ignored if channelsync is true and connected + * @param int32_t wifi channel, 0 to disable + */ +void WiFiManager::setWiFiAPChannel(int32_t channel){ + _apChannel = channel; +} + +/** + * set the soft ap hidden + * @param bool wifi ap hidden, default is false + */ +void WiFiManager::setWiFiAPHidden(bool hidden){ + _apHidden = hidden; +} + + +/** + * toggle showing erase wifi config button on info page + * @param boolean enabled + */ +void WiFiManager::setShowInfoErase(boolean enabled){ + _showInfoErase = enabled; +} + +/** + * toggle showing update upload web ota button on info page + * @param boolean enabled + */ +void WiFiManager::setShowInfoUpdate(boolean enabled){ + _showInfoUpdate = enabled; +} + +/** + * check if the config portal is running + * @return bool true if active + */ +bool WiFiManager::getConfigPortalActive(){ + return configPortalActive; +} + +/** + * [getConfigPortalActive description] + * @return bool true if active + */ +bool WiFiManager::getWebPortalActive(){ + return webPortalActive; +} + + +String WiFiManager::getWiFiHostname(){ + #ifdef ESP32 + return (String)WiFi.getHostname(); + #else + return (String)WiFi.hostname(); + #endif +} + +/** + * [setTitle description] + * @param String title, set app title + */ +void WiFiManager::setTitle(String title){ + _title = title; +} + +/** + * set menu items and order + * if param is present in menu , params will be removed from wifi page automatically + * eg. + * const char * menu[] = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * @since $dev + * @param uint8_t menu[] array of menu ids + */ +void WiFiManager::setMenu(const char * menu[], uint8_t size){ +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM(WM_DEBUG_DEV,"setmenu array"); + #endif + _menuIds.clear(); + for(size_t i = 0; i < size; i++){ + for(size_t j = 0; j < _nummenutokens; j++){ + if((String)menu[i] == (__FlashStringHelper *)(_menutokens[j])){ + if((String)menu[i] == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + delay(0); + } + delay(0); + } + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(getMenuOut()); + #endif +} + +/** + * setMenu with vector + * eg. + * std::vector menu = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * tokens can be found in _menutokens array in strings_en.h + * @shiftIncrement $dev + * @param {[type]} std::vector& menu [description] + */ +void WiFiManager::setMenu(std::vector& menu){ +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM(WM_DEBUG_DEV,"setmenu vector"); + #endif + _menuIds.clear(); + for(auto menuitem : menu ){ + for(size_t j = 0; j < _nummenutokens; j++){ + if((String)menuitem == (__FlashStringHelper *)(_menutokens[j])){ + if((String)menuitem == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + } + } + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(WM_DEBUG_DEV,getMenuOut()); + #endif +} + + +/** + * set params as sperate page not in wifi + * NOT COMPATIBLE WITH setMenu! + * @todo scan menuids and insert param after wifi or something, same for ota + * @param bool enable + * @since $dev + */ +void WiFiManager::setParamsPage(bool enable){ + _paramsInWifi = !enable; + setMenu(enable ? _menuIdsParams : _menuIdsDefault); +} + +// GETTERS + +/** + * get config portal AP SSID + * @since 0.0.1 + * @access public + * @return String the configportal ap name + */ +String WiFiManager::getConfigPortalSSID() { + return _apName; +} + +/** + * return the last known connection result + * logged on autoconnect and wifisave, can be used to check why failed + * get as readable string with getWLStatusString(getLastConxResult); + * @since $dev + * @access public + * @return bool return wl_status codes + */ +uint8_t WiFiManager::getLastConxResult(){ + return _lastconxresult; +} + +/** + * check if wifi has a saved ap or not + * @since $dev + * @access public + * @return bool true if a saved ap config exists + */ +bool WiFiManager::getWiFiIsSaved(){ + return WiFi_hasAutoConnect(); +} + +/** + * getDefaultAPName + * @since $dev + * @return string + */ +String WiFiManager::getDefaultAPName(){ + String hostString = String(WIFI_getChipId(),HEX); + hostString.toUpperCase(); + // char hostString[16] = {0}; + // sprintf(hostString, "%06X", ESP.getChipId()); + return _wifissidprefix + "_" + hostString; +} + +/** + * setCountry + * @since $dev + * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN + */ +void WiFiManager::setCountry(String cc){ + _wificountry = cc; +} + +/** + * setClass + * @param String str body class string + */ +void WiFiManager::setClass(String str){ + _bodyClass = str; +} + +/** + * setDarkMode + * @param bool enable, enable dark mode via invert class + */ +void WiFiManager::setDarkMode(bool enable){ + _bodyClass = enable ? "invert" : ""; +} + +/** + * setHttpPort + * @param uint16_t port webserver port number default 80 + */ +void WiFiManager::setHttpPort(uint16_t port){ + _httpPort = port; +} + + +bool WiFiManager::preloadWiFi(String ssid, String pass){ + _defaultssid = ssid; + _defaultpass = pass; + return true; +} + +// HELPERS + +/** + * getWiFiSSID + * @since $dev + * @param bool persistent + * @return String + */ +String WiFiManager::getWiFiSSID(bool persistent){ + return WiFi_SSID(persistent); +} + +/** + * getWiFiPass + * @since $dev + * @param bool persistent + * @return String + */ +String WiFiManager::getWiFiPass(bool persistent){ + return WiFi_psk(persistent); +} + +// DEBUG +// @todo fix DEBUG_WM(0,0); +template +void WiFiManager::DEBUG_WM(Generic text) { + DEBUG_WM(WM_DEBUG_NOTIFY,text,""); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) { + if(_debugLevel >= level) DEBUG_WM(level,text,""); +} + +template +void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { + DEBUG_WM(WM_DEBUG_NOTIFY,text,textb); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { + if(!_debug || _debugLevel < level) return; + + if(_debugLevel >= WM_DEBUG_MAX){ + #ifdef ESP8266 + // uint32_t free; + // uint16_t max; + // uint8_t frag; + // ESP.getHeapStats(&free, &max, &frag);// @todo Does not exist in 2.3.0 + // _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); + #elif defined ESP32 + // total_free_bytes; ///< Total free bytes in the heap. Equivalent to multi_free_heap_size(). + // total_allocated_bytes; ///< Total bytes allocated to data in the heap. + // largest_free_block; ///< Size of largest free block in the heap. This is the largest malloc-able size. + // minimum_free_bytes; ///< Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size(). + // allocated_blocks; ///< Number of (variable size) blocks allocated in the heap. + // free_blocks; ///< Number of (variable size) free blocks in the heap. + // total_blocks; ///< Total number of (variable size) blocks in the heap. + multi_heap_info_t info; + heap_caps_get_info(&info, MALLOC_CAP_INTERNAL); + uint32_t free = info.total_free_bytes; + uint16_t max = info.largest_free_block; + uint8_t frag = 100 - (max * 100) / free; + _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); + #endif + } + + _debugPort.print(_debugPrefix); + if(_debugLevel >= debugLvlShow) _debugPort.print("["+(String)level+"] "); + _debugPort.print(text); + if(textb){ + _debugPort.print(" "); + _debugPort.print(textb); + } + _debugPort.println(); +} + +/** + * [debugSoftAPConfig description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::debugSoftAPConfig(){ + + #ifdef ESP8266 + softap_config config; + wifi_softap_get_config(&config); + #if !defined(WM_NOCOUNTRY) + wifi_country_t country; + wifi_get_country(&country); + #endif + #elif defined(ESP32) + wifi_country_t country; + wifi_config_t conf_config; + esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK + wifi_ap_config_t config = conf_config.ap; + esp_wifi_get_country(&country); + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("SoftAP Configuration")); + DEBUG_WM(FPSTR(D_HR)); + DEBUG_WM(F("ssid: "),(char *) config.ssid); + DEBUG_WM(F("password: "),(char *) config.password); + DEBUG_WM(F("ssid_len: "),config.ssid_len); + DEBUG_WM(F("channel: "),config.channel); + DEBUG_WM(F("authmode: "),config.authmode); + DEBUG_WM(F("ssid_hidden: "),config.ssid_hidden); + DEBUG_WM(F("max_connection: "),config.max_connection); + #endif + #if !defined(WM_NOCOUNTRY) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("country: "),(String)country.cc); + #endif + DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); + DEBUG_WM(FPSTR(D_HR)); + #endif +} + +/** + * [debugPlatformInfo description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::debugPlatformInfo(){ + #ifdef ESP8266 + system_print_meminfo(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("[SYS] getCoreVersion(): "),ESP.getCoreVersion()); + DEBUG_WM(F("[SYS] system_get_sdk_version(): "),system_get_sdk_version()); + DEBUG_WM(F("[SYS] system_get_boot_version():"),system_get_boot_version()); + DEBUG_WM(F("[SYS] getFreeHeap(): "),(String)ESP.getFreeHeap()); + #endif + #elif defined(ESP32) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("[SYS] WM version: "), WM_VERSION_STR); + DEBUG_WM(F("[SYS] Arduino version: "), VER_ARDUINO_STR); + DEBUG_WM(F("[SYS] ESP SDK version: "), ESP.getSdkVersion()); + DEBUG_WM(F("[SYS] Free heap: "), ESP.getFreeHeap()); + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("[SYS] Chip ID:"),WIFI_getChipId()); + DEBUG_WM(F("[SYS] Chip Model:"), ESP.getChipModel()); + DEBUG_WM(F("[SYS] Chip Cores:"), ESP.getChipCores()); + DEBUG_WM(F("[SYS] Chip Rev:"), ESP.getChipRevision()); + #endif + #endif +} + +int WiFiManager::getRSSIasQuality(int RSSI) { + int quality = 0; + + if (RSSI <= -100) { + quality = 0; + } else if (RSSI >= -50) { + quality = 100; + } else { + quality = 2 * (RSSI + 100); + } + return quality; +} + +/** Is this an IP? */ +boolean WiFiManager::isIp(String str) { + for (size_t i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (c != '.' && (c < '0' || c > '9')) { + return false; + } + } + return true; +} + +/** IP to String? */ +String WiFiManager::toStringIp(IPAddress ip) { + String res = ""; + for (int i = 0; i < 3; i++) { + res += String((ip >> (8 * i)) & 0xFF) + "."; + } + res += String(((ip >> 8 * 3)) & 0xFF); + return res; +} + +boolean WiFiManager::validApPassword(){ + // check that ap password is valid, return false + if (_apPassword == NULL) _apPassword = ""; + if (_apPassword != "") { + if (_apPassword.length() < 8 || _apPassword.length() > 63) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); + #endif + _apPassword = ""; + return false; // @todo FATAL or fallback to empty , currently fatal, fail secure. + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("AccessPoint set password is VALID")); + DEBUG_WM(WM_DEBUG_DEV,"ap pass",_apPassword); + #endif + } + return true; +} + +/** + * encode htmlentities + * @since $dev + * @param string str string to replace entities + * @return string encoded string + */ +String WiFiManager::htmlEntities(String str, bool whitespace) { + str.replace("&","&"); + str.replace("<","<"); + str.replace(">",">"); + str.replace("'","'"); + if(whitespace) str.replace(" "," "); + // str.replace("-","–"); + // str.replace("\"","""); + // str.replace("/": "/"); + // str.replace("`": "`"); + // str.replace("=": "="); +return str; +} + +/** + * [getWLStatusString description] + * @access public + * @param {[type]} uint8_t status [description] + * @return {[type]} [description] + */ +String WiFiManager::getWLStatusString(uint8_t status){ + if(status <= 7) return WIFI_STA_STATUS[status]; + return FPSTR(S_NA); +} + +String WiFiManager::getWLStatusString(){ + uint8_t status = WiFi.status(); + if(status <= 7) return WIFI_STA_STATUS[status]; + return FPSTR(S_NA); +} + +String WiFiManager::encryptionTypeStr(uint8_t authmode) { +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM("enc_tye: ",authmode); + #endif + return AUTH_MODE_NAMES[authmode]; +} + +String WiFiManager::getModeString(uint8_t mode){ + if(mode <= 3) return WIFI_MODES[mode]; + return FPSTR(S_NA); +} + +bool WiFiManager::WiFiSetCountry(){ + if(_wificountry == "") return false; // skip not set + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("WiFiSetCountry to"),_wificountry); + #endif + +/* + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by eps_wifi_init + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_WIFI_ARG: invalid argument + * - others: refer to error codes in esp_err.h + */ + + // @todo move these definitions, and out of cpp `esp_wifi_set_country(&WM_COUNTRY_US)` + bool ret = true; + // ret = esp_wifi_set_bandwidth(WIFI_IF_AP,WIFI_BW_HT20); // WIFI_BW_HT40 + #ifdef ESP32 + esp_err_t err = ESP_OK; + // @todo check if wifi is init, no idea how, doesnt seem to be exposed atm ( check again it might be now! ) + if(WiFi.getMode() == WIFI_MODE_NULL){ + DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] cannot set country, wifi not init"); + } // exception if wifi not init! + // Assumes that _wificountry is set to one of the supported country codes : "01"(world safe mode) "AT","AU","BE","BG","BR", + // "CA","CH","CN","CY","CZ","DE","DK","EE","ES","FI","FR","GB","GR","HK","HR","HU", + // "IE","IN","IS","IT","JP","KR","LI","LT","LU","LV","MT","MX","NL","NO","NZ","PL","PT", + // "RO","SE","SI","SK","TW","US" + // If an invalid country code is passed, ESP_ERR_WIFI_ARG will be returned + // This also uses 802.11d mode, which matches the STA to the country code of the AP it connects to (meaning + // that the country code will be overridden if connecting to a "foreign" AP) + else { + #ifndef WM_NOCOUNTRY + err = esp_wifi_set_country_code(_wificountry.c_str(), true); + #else + DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] esp wifi set country is not available"); + err = true; + #endif + } + #ifdef WM_DEBUG_LEVEL + if(err){ + if(err == ESP_ERR_WIFI_NOT_INIT) DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_NOT_INIT"); + else if(err == ESP_ERR_INVALID_ARG) DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_ARG (invalid country code)"); + else if(err != ESP_OK)DEBUG_WM(WM_DEBUG_ERROR,"[ERROR] unknown error",(String)err); + } + #endif + ret = err == ESP_OK; + + #elif defined(ESP8266) && !defined(WM_NOCOUNTRY) + // if(WiFi.getMode() == WIFI_OFF); // exception if wifi not init! + if(_wificountry == "US") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_US); + else if(_wificountry == "JP") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_JP); + else if(_wificountry == "CN") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_CN); + #ifdef WM_DEBUG_LEVEL + else DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] country code not found")); + #endif + #endif + + #ifdef WM_DEBUG_LEVEL + if(ret) DEBUG_WM(WM_DEBUG_VERBOSE,F("[OK] esp_wifi_set_country: "),_wificountry); + else DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] esp_wifi_set_country failed")); + #endif + return ret; +} + +// set mode ignores WiFi.persistent +bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { + bool ret; + #ifdef ESP8266 + if((wifi_get_opmode() == (uint8) m ) && !persistent) { + return true; + } + ETS_UART_INTR_DISABLE(); + if(persistent) ret = wifi_set_opmode(m); + else ret = wifi_set_opmode_current(m); + ETS_UART_INTR_ENABLE(); + return ret; + #elif defined(ESP32) + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.mode(m); // @todo persistent check persistant mode, was eventually added to esp lib, but have to add version checking probably + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} +bool WiFiManager::WiFi_Mode(WiFiMode_t m) { + return WiFi_Mode(m,false); +} + +// sta disconnect without persistent +bool WiFiManager::WiFi_Disconnect() { + #ifdef ESP8266 + if((WiFi.getMode() & WIFI_STA) != 0) { + bool ret; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("WiFi station disconnect")); + #endif + ETS_UART_INTR_DISABLE(); // @todo possibly not needed + ret = wifi_station_disconnect(); + ETS_UART_INTR_ENABLE(); + return ret; + } + #elif defined(ESP32) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("WiFi station disconnect")); + #endif + return WiFi.disconnect(); // not persistent atm + #endif + return false; +} + +// toggle STA without persistent +bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { +#ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("WiFi_enableSTA"),(String) enable? "enable" : "disable"); + #endif + #ifdef ESP8266 + WiFiMode_t newMode; + WiFiMode_t currentMode = WiFi.getMode(); + bool isEnabled = (currentMode & WIFI_STA) != 0; + if(enable) newMode = (WiFiMode_t)(currentMode | WIFI_STA); + else newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); + + if((isEnabled != enable) || persistent) { + if(enable) { + #ifdef WM_DEBUG_LEVEL + if(persistent) DEBUG_WM(WM_DEBUG_DEV,F("enableSTA PERSISTENT ON")); + #endif + return WiFi_Mode(newMode,persistent); + } + else { + return WiFi_Mode(newMode,persistent); + } + } else { + return true; + } + #elif defined(ESP32) + bool ret; + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} + +bool WiFiManager::WiFi_enableSTA(bool enable) { + return WiFi_enableSTA(enable,false); +} + +bool WiFiManager::WiFi_eraseConfig() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_DEV,F("WiFi_eraseConfig")); + #endif + + #ifdef ESP8266 + #ifndef WM_FIXERASECONFIG + return ESP.eraseConfig(); + #else + // erase config BUG replacement + // https://github.com/esp8266/Arduino/pull/3635 + const size_t cfgSize = 0x4000; + size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; + + for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { + if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { + return false; + } + } + return true; + #endif + #elif defined(ESP32) + + bool ret; + WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! + WiFi.persistent(true); + ret = WiFi.disconnect(true,true); // disconnect(bool wifioff, bool eraseap) + delay(500); + WiFi.persistent(false); + return ret; + #endif +} + +uint8_t WiFiManager::WiFi_softap_num_stations(){ + #ifdef ESP8266 + return wifi_softap_get_station_num(); + #elif defined(ESP32) + return WiFi.softAPgetStationNum(); + #endif +} + +bool WiFiManager::WiFi_hasAutoConnect(){ + return WiFi_SSID(true) != ""; +} + +String WiFiManager::WiFi_SSID(bool persistent) const{ + + #ifdef ESP8266 + struct station_config conf; + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[33]; //ssid can be up to 32chars, => plus null term + memcpy(tmp, conf.ssid, sizeof(conf.ssid)); + tmp[32] = 0; //nullterm in case of 32 char ssid + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + if(persistent){ + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.ssid)); + } + else { + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_ap_record_t info; + if(!esp_wifi_sta_get_ap_info(&info)) { + return String(reinterpret_cast(info.ssid)); + } + return String(); + } + #endif +} + +String WiFiManager::WiFi_psk(bool persistent) const { + #ifdef ESP8266 + struct station_config conf; + + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[65]; //psk is 64 bytes hex => plus null term + memcpy(tmp, conf.password, sizeof(conf.password)); + tmp[64] = 0; //null term in case of 64 byte psk + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + // only if wifi is init + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.password)); + #endif +} + +#ifdef ESP32 + #ifdef WM_ARDUINOEVENTS + void WiFiManager::WiFiEvent(WiFiEvent_t event,arduino_event_info_t info){ + #else + void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ + #define wifi_sta_disconnected disconnected + #define ARDUINO_EVENT_WIFI_STA_DISCONNECTED SYSTEM_EVENT_STA_DISCONNECTED + #define ARDUINO_EVENT_WIFI_SCAN_DONE SYSTEM_EVENT_SCAN_DONE + #endif + if(!_hasBegun){ + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(WM_DEBUG_VERBOSE,"[ERROR] WiFiEvent, not ready"); + #endif + // Serial.println(F("\n[EVENT] WiFiEvent logging (wm debug not available)")); + // Serial.print(F("[EVENT] ID: ")); + // Serial.println(event); + return; + } + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(WM_DEBUG_VERBOSE,"[EVENT]",event); + #endif + if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: "),info.wifi_sta_disconnected.reason); + #endif + if(info.wifi_sta_disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.wifi_sta_disconnected.reason == WIFI_REASON_AUTH_FAIL){ + _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail + } else _lastconxresulttmp = WiFi.status(); + #ifdef WM_DEBUG_LEVEL + if(info.wifi_sta_disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(WM_DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: NO_AP_FOUND")); + if(info.wifi_sta_disconnected.reason == WIFI_REASON_ASSOC_FAIL){ + if(_aggresiveReconn) _connectRetries+=4; + DEBUG_WM(WM_DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: AUTH FAIL")); + } + #endif + #ifdef esp32autoreconnect + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting")); + #endif + WiFi.reconnect(); + #endif + } + else if(event == ARDUINO_EVENT_WIFI_SCAN_DONE && _asyncScan){ + uint16_t scans = WiFi.scanComplete(); + WiFi_scanComplete(scans); + } +} +#endif + +void WiFiManager::WiFi_autoReconnect(){ + #ifdef ESP8266 +WiFi.setAutoReconnect(_wifiAutoReconnect); + #elif defined(ESP32) + // if(_wifiAutoReconnect){ + // @todo move to seperate method, used for event listener now + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("ESP32 event handler enabled")); + #endif + using namespace std::placeholders; + if(wm_event_id == 0) wm_event_id = WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + // } + #endif +} + +// Called when /update is requested +void WiFiManager::handleUpdate() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("<- Handle update")); + #endif + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + String page = getHTTPHead(_title); // @token options + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_t), _title); + str.replace(FPSTR(T_v), configPortalActive ? _apName : (getWiFiHostname() + " - " + WiFi.localIP().toString())); // use ip if ap is not active for heading + page += str; + + page += FPSTR(HTTP_UPDATE); + page += FPSTR(HTTP_END); + + HTTPSend(page); + +} + +// upload via /u POST +void WiFiManager::handleUpdating(){ + // @todo + // cannot upload files in captive portal, file select is not allowed, show message with link or hide + // cannot upload if softreset after upload, maybe check for hard reset at least for dev, ERROR[11]: Invalid bootstrapping state, reset ESP8266 before updating + // add upload status to webpage somehow + // abort upload if error detected ? + // [x] supress cp timeout on upload, so it doesnt keep uploading? + // add progress handler for debugging + // combine route handlers into one callback and use argument or post checking instead of mutiple functions maybe, if POST process else server upload page? + // [x] add upload checking, do we need too check file? + // convert output to debugger if not moving to example + + // if (captivePortal()) return; // If captive portal redirect instead of displaying the page + bool error = false; + unsigned long _configPortalTimeoutSAV = _configPortalTimeout; // store cp timeout + _configPortalTimeout = 0; // disable timeout + + // handler for the file upload, get's the sketch bytes, and writes + // them through the Update object + HTTPUpload& upload = server->upload(); + + // UPLOAD START + if (upload.status == UPLOAD_FILE_START) { + // if(_debug) Serial.setDebugOutput(true); + uint32_t maxSketchSpace; + + // Use new callback for before OTA update + if (_preotaupdatecallback != NULL) { + _preotaupdatecallback(); // @CALLBACK + } + #ifdef ESP8266 + WiFiUDP::stopAll(); + maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; + #elif defined(ESP32) + // Think we do not need to stop WiFIUDP because we haven't started a listener + // maxSketchSpace = (ESP.getFlashChipSize() - 0x1000) & 0xFFFFF000; + // #define UPDATE_SIZE_UNKNOWN 0xFFFFFFFF // include update.h + maxSketchSpace = UPDATE_SIZE_UNKNOWN; + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,"[OTA] Update file: ", upload.filename.c_str()); + #endif + + // Update.onProgress(THandlerFunction_Progress fn); + // Update.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + // }); + + if (!Update.begin(maxSketchSpace)) { // start with max available size + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] OTA Update ERROR"), Update.getError()); + #endif + error = true; + Update.end(); // Not sure the best way to abort, I think client will keep sending.. + } + } + // UPLOAD WRITE + else if (upload.status == UPLOAD_FILE_WRITE) { + // Serial.print("."); + if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] OTA Update WRITE ERROR"), Update.getError()); + //Update.printError(Serial); // write failure + #endif + error = true; + } + } + // UPLOAD FILE END + else if (upload.status == UPLOAD_FILE_END) { + if (Update.end(true)) { // true to set the size to the current progress + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(WM_DEBUG_VERBOSE,F("\n\n[OTA] OTA FILE END bytes: "), upload.totalSize); + // Serial.printf("Updated: %u bytes\r\nRebooting...\r\n", upload.totalSize); + #endif + } + else { + // Update.printError(Serial); + error = true; + } + } + // UPLOAD ABORT + else if (upload.status == UPLOAD_FILE_ABORTED) { + Update.end(); + DEBUG_WM(F("[OTA] Update was aborted")); + error = true; + } + if(error) _configPortalTimeout = _configPortalTimeoutSAV; + delay(0); +} + +// upload and ota done, show status +void WiFiManager::handleUpdateDone() { + DEBUG_WM(WM_DEBUG_VERBOSE, F("<- Handle update done")); + // if (captivePortal()) return; // If captive portal redirect instead of displaying the page + + String page = getHTTPHead(FPSTR(S_options)); // @token options + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_t),_title); + str.replace(FPSTR(T_v), configPortalActive ? _apName : WiFi.localIP().toString()); // use ip if ap is not active for heading + page += str; + + if (Update.hasError()) { + page += FPSTR(HTTP_UPDATE_FAIL); + #ifdef ESP32 + page += "OTA Error: " + (String)Update.errorString(); + #else + page += "OTA Error: " + (String)Update.getError(); + #endif + DEBUG_WM(F("[OTA] update failed")); + } + else { + page += FPSTR(HTTP_UPDATE_SUCCESS); + DEBUG_WM(F("[OTA] update ok")); + } + page += FPSTR(HTTP_END); + + HTTPSend(page); + + delay(1000); // send page + if (!Update.hasError()) { + ESP.restart(); + } +} + +#endif diff --git a/airmx-esp-gate/WiFiManager.h b/airmx-esp-gate/WiFiManager.h new file mode 100644 index 0000000..2954943 --- /dev/null +++ b/airmx-esp-gate/WiFiManager.h @@ -0,0 +1,854 @@ +/** + * WiFiManager.h + * + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + + +#ifndef WiFiManager_h +#define WiFiManager_h + +#if defined(ESP8266) || defined(ESP32) + +#ifdef ESP8266 +#include +#endif + +#include + +// #define WM_MDNS // includes MDNS, also set MDNS with sethostname +// #define WM_FIXERASECONFIG // use erase flash fix +// #define WM_ERASE_NVS // esp32 erase(true) will erase NVS +// #define WM_RTC // esp32 info page will include reset reasons + +// #define WM_JSTEST // build flag for enabling js xhr tests +// #define WIFI_MANAGER_OVERRIDE_STRINGS // build flag for using own strings include + +#ifdef ARDUINO_ESP8266_RELEASE_2_3_0 +#warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" +// @todo check failing on platform = espressif8266@1.7.3 +#define WM_NOASYNC // esp8266 no async scan wifi +#define WM_NOCOUNTRY // esp8266 no country +#define WM_NOAUTH // no httpauth +#define WM_NOSOFTAPSSID // no softapssid() @todo shim +#endif + +// #ifdef CONFIG_IDF_TARGET_ESP32S2 +// #warning ESP32S2 +// #endif + +// #ifdef CONFIG_IDF_TARGET_ESP32C3 +// #warning ESP32C3 +// #endif + +// #ifdef CONFIG_IDF_TARGET_ESP32S3 +// #warning ESP32S3 +// #endif + +#if defined(ARDUINO_ESP32S3_DEV) || defined(CONFIG_IDF_TARGET_ESP32S3) +#warning "WM_NOTEMP" +#define WM_NOTEMP // disabled temp sensor, have to determine which chip we are on +#endif + +// #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. + +// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, @DEPRECATED +// autoreconnect is WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 + +#define WM_WEBSERVERSHIM // use webserver shim lib + +#define WM_G(string_literal) (String(FPSTR(string_literal)).c_str()) + +#ifdef ESP8266 + + extern "C" { + #include "user_interface.h" + } + #include + #include + + #ifdef WM_MDNS + #include + #endif + + #define WIFI_getChipId() ESP.getChipId() + #define WM_WIFIOPEN ENC_TYPE_NONE + +#elif defined(ESP32) + + #include + #include + #include + + #define WIFI_getChipId() (uint32_t)ESP.getEfuseMac() + #define WM_WIFIOPEN WIFI_AUTH_OPEN + + #ifndef WEBSERVER_H + #ifdef WM_WEBSERVERSHIM + #include + #else + #include + // Forthcoming official ? probably never happening + // https://github.com/esp8266/ESPWebServer + #endif + #endif + + #ifdef WM_ERASE_NVS + #include + #include + #endif + + #ifdef WM_MDNS + #include + #endif + + #ifdef WM_RTC + #ifdef ESP_IDF_VERSION_MAJOR // IDF 4+ + #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 + #include "esp32/rom/rtc.h" + #elif CONFIG_IDF_TARGET_ESP32S2 + #include "esp32s2/rom/rtc.h" + #elif CONFIG_IDF_TARGET_ESP32C3 + #include "esp32c3/rom/rtc.h" + #elif CONFIG_IDF_TARGET_ESP32S3 + #include "esp32s3/rom/rtc.h" + #else + #error Target CONFIG_IDF_TARGET is not supported + #endif + #else // ESP32 Before IDF 4.0 + #include "rom/rtc.h" + #endif + #endif + +#else +#endif + +#include +#include + + +// Include wm strings vars +// Pass in strings env override via WM_STRINGS_FILE +#ifndef WM_STRINGS_FILE +#define WM_STRINGS_FILE "wm_strings_en.h" // this includes constants as dependency +#endif +#include WM_STRINGS_FILE + +// prep string concat vars +#define WM_STRING2(x) #x +#define WM_STRING(x) WM_STRING2(x) + +// #include +#ifdef ESP_IDF_VERSION + // #pragma message "ESP_IDF_VERSION_MAJOR = " WM_STRING(ESP_IDF_VERSION_MAJOR) + // #pragma message "ESP_IDF_VERSION_MINOR = " WM_STRING(ESP_IDF_VERSION_MINOR) + // #pragma message "ESP_IDF_VERSION_PATCH = " WM_STRING(ESP_IDF_VERSION_PATCH) + #define VER_IDF_STR WM_STRING(ESP_IDF_VERSION_MAJOR) "." WM_STRING(ESP_IDF_VERSION_MINOR) "." WM_STRING(ESP_IDF_VERSION_PATCH) +#else + #define VER_IDF_STR "Unknown" +#endif + +#ifdef Arduino_h + #ifdef ESP32 + // #include "esp_arduino_version.h" // esp32 arduino > 2.x + #endif + // esp_get_idf_version + #ifdef ESP_ARDUINO_VERSION + // #pragma message "ESP_ARDUINO_VERSION_MAJOR = " WM_STRING(ESP_ARDUINO_VERSION_MAJOR) + // #pragma message "ESP_ARDUINO_VERSION_MINOR = " WM_STRING(ESP_ARDUINO_VERSION_MINOR) + // #pragma message "ESP_ARDUINO_VERSION_PATCH = " WM_STRING(ESP_ARDUINO_VERSION_PATCH) + #ifdef ESP_ARDUINO_VERSION_MAJOR + #define VER_ARDUINO_STR WM_STRING(ESP_ARDUINO_VERSION_MAJOR) "." WM_STRING(ESP_ARDUINO_VERSION_MINOR) "." WM_STRING(ESP_ARDUINO_VERSION_PATCH) + #else + #define VER_ARDUINO_STR "Unknown" + #endif + #else + #include + // #pragma message "ESP_ARDUINO_VERSION_GIT = " WM_STRING(ARDUINO_ESP32_GIT_VER)// 0x46d5afb1 + // #pragma message "ESP_ARDUINO_VERSION_DESC = " WM_STRING(ARDUINO_ESP32_GIT_DESC) // 1.0.6 + // #pragma message "ESP_ARDUINO_VERSION_REL = " WM_STRING(ARDUINO_ESP32_RELEASE) //"1_0_6" + #ifdef ESP_ARDUINO_VERSION_MAJOR + #define VER_ARDUINO_STR WM_STRING(ESP_ARDUINO_VERSION_MAJOR) "." WM_STRING(ESP_ARDUINO_VERSION_MINOR) "." WM_STRING(ESP_ARDUINO_VERSION_PATCH) + #else + #define VER_ARDUINO_STR "Unknown" + #endif + #endif +#else +#define VER_ARDUINO_STR "Unknown" +#endif + +// #pragma message "VER_IDF_STR = " WM_STRING(VER_IDF_STR) +// #pragma message "VER_ARDUINO_STR = " WM_STRING(VER_ARDUINO_STR) + +#ifndef WIFI_MANAGER_MAX_PARAMS + #define WIFI_MANAGER_MAX_PARAMS 5 // params will autoincrement and realloc by this amount when max is reached +#endif + +#define WFM_LABEL_BEFORE 1 +#define WFM_LABEL_AFTER 2 +#define WFM_NO_LABEL 0 +#define WFM_LABEL_DEFAULT 1 + +class WiFiManagerParameter { + public: + /** + Create custom parameters that can be added to the WiFiManager setup web page + @id is used for HTTP queries and must not contain spaces nor other special characters + */ + WiFiManagerParameter(); + WiFiManagerParameter(const char *custom); + WiFiManagerParameter(const char *id, const char *label); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); + ~WiFiManagerParameter(); + // WiFiManagerParameter& operator=(const WiFiManagerParameter& rhs); + + const char *getID() const; + const char *getValue() const; + const char *getLabel() const; + const char *getPlaceholder() const; // @deprecated, use getLabel + int getValueLength() const; + int getLabelPlacement() const; + virtual const char *getCustomHTML() const; + void setValue(const char *defaultValue, int length); + + protected: + void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); + + private: + WiFiManagerParameter& operator=(const WiFiManagerParameter&); + const char *_id; + const char *_label; + char *_value; + int _length; + int _labelPlacement; + protected: + const char *_customHTML; + friend class WiFiManager; +}; + + + // debugging + typedef enum { + WM_DEBUG_SILENT = 0, // debug OFF but still compiled for runtime + WM_DEBUG_ERROR = 1, // error only + WM_DEBUG_NOTIFY = 2, // default stable,INFO + WM_DEBUG_VERBOSE = 3, // move verbose info + WM_DEBUG_DEV = 4, // development useful debugging info + WM_DEBUG_MAX = 5 // MAX extra dev auditing, var dumps etc (MAX+1 will print timing,mem and frag info) + } wm_debuglevel_t; + +class WiFiManager +{ + public: + WiFiManager(Print& consolePort); + WiFiManager(); + ~WiFiManager(); + void WiFiManagerInit(); + + // auto connect to saved wifi, or custom, and start config portal on failures + boolean autoConnect(); + boolean autoConnect(char const *apName, char const *apPassword = NULL); + + //manually start the config portal, autoconnect does this automatically on connect failure + boolean startConfigPortal(); // auto generates apname + boolean startConfigPortal(char const *apName, char const *apPassword = NULL); + + //manually stop the config portal if started manually, stop immediatly if non blocking, flag abort if blocking + bool stopConfigPortal(); + + //manually start the web portal, autoconnect does this automatically on connect failure + void startWebPortal(); + + //manually stop the web portal if started manually + void stopWebPortal(); + + // Run webserver processing, if setConfigPortalBlocking(false) + boolean process(); + + // get the AP name of the config portal, so it can be used in the callback + String getConfigPortalSSID(); + int getRSSIasQuality(int RSSI); + + // erase wifi credentials + void resetSettings(); + + // reboot esp + void reboot(); + + // disconnect wifi, without persistent saving or erasing + bool disconnect(); + + // erase esp + bool erase(); + bool erase(bool opt); + + //adds a custom parameter, returns false on failure + bool addParameter(WiFiManagerParameter *p); + + //returns the list of Parameters + WiFiManagerParameter** getParameters(); + + // returns the Parameters Count + int getParametersCount(); + + // SET CALLBACKS + + //called after AP mode and config portal has started + void setAPCallback( std::function func ); + + //called after webserver has started + void setWebServerCallback( std::function func ); + + //called when settings reset have been triggered + void setConfigResetCallback( std::function func ); + + //called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) + void setSaveConfigCallback( std::function func ); + + //called when saving params-in-wifi or params before anything else happens (eg wifi) + void setPreSaveConfigCallback( std::function func ); + + //called when saving params before anything else happens + void setPreSaveParamsCallback( std::function func ); + + //called when saving either params-in-wifi or params page + void setSaveParamsCallback( std::function func ); + + //called just before doing OTA update + void setPreOtaUpdateCallback( std::function func ); + + //called when config portal is timeout + void setConfigPortalTimeoutCallback( std::function func ); + + //sets timeout before AP,webserver loop ends and exits even if there has been no setup. + //useful for devices that failed to connect at some point and got stuck in a webserver loop + //in seconds setConfigPortalTimeout is a new name for setTimeout, ! not used if setConfigPortalBlocking + void setConfigPortalTimeout(unsigned long seconds); + void setTimeout(unsigned long seconds); // @deprecated, alias + + //sets timeout for which to attempt connecting, useful if you get a lot of failed connects + void setConnectTimeout(unsigned long seconds); + + // sets number of retries for autoconnect, force retry after wait failure exit + void setConnectRetries(uint8_t numRetries); // default 1 + + //sets timeout for which to attempt connecting on saves, useful if there are bugs in esp waitforconnectloop + void setSaveConnectTimeout(unsigned long seconds); + + // lets you disable automatically connecting after save from webportal + void setSaveConnect(bool connect = true); + + // toggle debug output + void setDebugOutput(boolean debug); + void setDebugOutput(boolean debug, String prefix); // log line prefix, default "*wm:" + void setDebugOutput(boolean debug, wm_debuglevel_t level ); // log line prefix, default "*wm:" + + //set min quality percentage to include in scan, defaults to 8% if not specified + void setMinimumSignalQuality(int quality = 8); + + //sets a custom ip /gateway /subnet configuration + void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + + //sets config for a static IP + void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + + //sets config for a static IP with DNS + void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); + + //if this is set, it will exit after config, even if connection is unsuccessful. + void setBreakAfterConfig(boolean shouldBreak); + + // if this is set, portal will be blocking and wait until save or exit, + // is false user must manually `process()` to handle config portal, + // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal + void setConfigPortalBlocking(boolean shouldBlock); + + //add custom html at inside for all pages + void setCustomHeadElement(const char* html); + + //if this is set, customise style + void setCustomMenuHTML(const char* html); + + //if this is true, remove duplicated Access Points - defaut true + void setRemoveDuplicateAPs(boolean removeDuplicates); + + //setter for ESP wifi.persistent so we can remember it and restore user preference, as WIFi._persistent is protected + void setRestorePersistent(boolean persistent); + + //if true, always show static net inputs, IP, subnet, gateway, else only show if set via setSTAStaticIPConfig + void setShowStaticFields(boolean alwaysShow); + + //if true, always show static dns, esle only show if set via setSTAStaticIPConfig + void setShowDnsFields(boolean alwaysShow); + + // toggle showing the saved wifi password in wifi form, could be a security issue. + void setShowPassword(boolean show); + + //if false, disable captive portal redirection + void setCaptivePortalEnable(boolean enabled); + + //if false, timeout captive portal even if a STA client connected to softAP (false), suggest disabling if captiveportal is open + void setAPClientCheck(boolean enabled); + + //if true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open + void setWebPortalClientCheck(boolean enabled); + + // if true, enable autoreconnecting + void setWiFiAutoReconnect(boolean enabled); + + // if true, wifiscan will show percentage instead of quality icons, until we have better templating + void setScanDispPerc(boolean enabled); + + // if true (default) then start the config portal from autoConnect if connection failed + void setEnableConfigPortal(boolean enable); + + // if true (default) then stop the config portal from autoConnect when wifi is saved + void setDisableConfigPortal(boolean enable); + + // set a custom hostname, sets sta and ap dhcp client id for esp32, and sta for esp8266 + bool setHostname(const char * hostname); + bool setHostname(String hostname); + + // show erase wifi onfig button on info page, true + void setShowInfoErase(boolean enabled); + + // show OTA upload button on info page + void setShowInfoUpdate(boolean enabled); + + // set ap channel + void setWiFiAPChannel(int32_t channel); + + // set ap hidden + void setWiFiAPHidden(bool hidden); // default false + + // clean connect, always disconnect before connecting + void setCleanConnect(bool enable); // default false + + // set custom menu items and order, vector or arr + // see _menutokens for ids + void setMenu(std::vector& menu); + void setMenu(const char* menu[], uint8_t size); + + // set the webapp title, default WiFiManager + void setTitle(String title); + + // add params to its own menu page and remove from wifi, NOT TO BE COMBINED WITH setMenu! + void setParamsPage(bool enable); + + // get last connection result, includes autoconnect and wifisave + uint8_t getLastConxResult(); + + // get a status as string + String getWLStatusString(uint8_t status); + String getWLStatusString(); + + // get wifi mode as string + String getModeString(uint8_t mode); + + // check if the module has a saved ap to connect to + bool getWiFiIsSaved(); + + // helper to get saved password, if persistent get stored, else get current if connected + String getWiFiPass(bool persistent = true); + + // helper to get saved ssid, if persistent get stored, else get current if connected + String getWiFiSSID(bool persistent = true); + + // debug output the softap config + void debugSoftAPConfig(); + + // debug output platform info and versioning + void debugPlatformInfo(); + + // helper for html + String htmlEntities(String str, bool whitespace = false); + + // set the country code for wifi settings, CN + void setCountry(String cc); + + // set body class (invert), may be used for hacking in alt classes + void setClass(String str); + + // set dark mode via invert class + void setDarkMode(bool enable); + + // get default ap esp uses , esp_chipid etc + String getDefaultAPName(); + + // set port of webserver, 80 + void setHttpPort(uint16_t port); + + // check if config portal is active (true) + bool getConfigPortalActive(); + + // check if web portal is active (true) + bool getWebPortalActive(); + + // to preload autoconnect for test fixtures or other uses that skip esp sta config + bool preloadWiFi(String ssid, String pass); + + // get hostname helper + String getWiFiHostname(); + + + std::unique_ptr dnsServer; + + #if defined(ESP32) && defined(WM_WEBSERVERSHIM) + using WM_WebServer = WebServer; + #else + using WM_WebServer = ESP8266WebServer; + #endif + + std::unique_ptr server; + + private: + // vars + std::vector _menuIds; + std::vector _menuIdsParams = {"wifi","param","info","exit"}; + std::vector _menuIdsUpdate = {"wifi","param","info","update","exit"}; + std::vector _menuIdsDefault = {"wifi","info","exit","sep","update"}; + + // ip configs @todo struct ? + IPAddress _ap_static_ip; + IPAddress _ap_static_gw; + IPAddress _ap_static_sn; + IPAddress _sta_static_ip; + IPAddress _sta_static_gw; + IPAddress _sta_static_sn; + IPAddress _sta_static_dns; + + unsigned long _configPortalStart = 0; // ms config portal start time (updated for timeouts) + unsigned long _webPortalAccessed = 0; // ms last web access time + uint8_t _lastconxresult = WL_IDLE_STATUS; // store last result when doing connect operations + int _numNetworks = 0; // init index for numnetworks wifiscans + unsigned long _lastscan = 0; // ms for timing wifi scans + unsigned long _startscan = 0; // ms for timing wifi scans + unsigned long _startconn = 0; // ms for timing wifi connects + + // defaults + const byte DNS_PORT = 53; + String _apName = "no-net"; + String _apPassword = ""; + String _ssid = ""; // var temp ssid + String _pass = ""; // var temp psk + String _defaultssid = ""; // preload ssid + String _defaultpass = ""; // preload pass + + // options flags + unsigned long _configPortalTimeout = 0; // ms close config portal loop if set (depending on _cp/webClientCheck options) + unsigned long _connectTimeout = 0; // ms stop trying to connect to ap if set + unsigned long _saveTimeout = 0; // ms stop trying to connect to ap on saves, in case bugs in esp waitforconnectresult + + WiFiMode_t _usermode = WIFI_STA; // Default user mode + String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid + int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. + bool _cleanConnect = false; // disconnect before connect in connectwifi, increases stability on connects + bool _connectonsave = true; // connect to wifi when saving creds + bool _disableSTA = false; // disable sta when starting ap, always + bool _disableSTAConn = false; // disable sta when starting ap, if sta is not connected ( stability ) + bool _channelSync = false; // use same wifi sta channel when starting ap + int32_t _apChannel = 0; // default channel to use for ap, 0 for auto + bool _apHidden = false; // store softap hidden value + uint16_t _httpPort = 80; // port for webserver + // uint8_t _retryCount = 0; // counter for retries, probably not needed if synchronous + uint8_t _connectRetries = 1; // number of sta connect retries, force reconnect, wait loop (connectimeout) does not always work and first disconnect bails + bool _aggresiveReconn = true; // use an agrressive reconnect strategy, WILL delay conxs + // on some conn failure modes will add delays and many retries to work around esp and ap bugs, ie, anti de-auth protections + // https://github.com/tzapu/WiFiManager/issues/1067 + bool _allowExit = true; // allow exit in nonblocking, else user exit/abort calls will be ignored including cptimeout + + #ifdef ESP32 + wifi_event_id_t wm_event_id = 0; + static uint8_t _lastconxresulttmp; // tmp var for esp32 callback + #endif + + #ifndef WL_STATION_WRONG_PASSWORD + uint8_t WL_STATION_WRONG_PASSWORD = 7; // @kludge define a WL status for wrong password + #endif + + // parameter options + int _minimumQuality = -1; // filter wifiscan ap by this rssi + int _staShowStaticFields = 0; // ternary 1=always show static ip fields, 0=only if set, -1=never(cannot change ips via web!) + int _staShowDns = 0; // ternary 1=always show dns, 0=only if set, -1=never(cannot change dns via web!) + boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan + boolean _showPassword = false; // show or hide saved password on wifi form, might be a security issue! + boolean _shouldBreakAfterConfig = false; // stop configportal on save failure + boolean _configPortalIsBlocking = true; // configportal enters blocking loop + boolean _enableCaptivePortal = true; // enable captive portal redirection + boolean _userpersistent = true; // users preffered persistence to restore + boolean _wifiAutoReconnect = true; // there is no platform getter for this, we must assume its true and make it so + boolean _apClientCheck = false; // keep cp alive if ap have station + boolean _webClientCheck = true; // keep cp alive if web have client + boolean _scanDispOptions = false; // show percentage in scans not icons + boolean _paramsInWifi = true; // show custom parameters on wifi page + boolean _showInfoErase = true; // info page erase button + boolean _showInfoUpdate = true; // info page update button + boolean _showBack = false; // show back button + boolean _enableConfigPortal = true; // FOR autoconnect - start config portal if autoconnect failed + boolean _disableConfigPortal = true; // FOR autoconnect - stop config portal if cp wifi save + String _hostname = ""; // hostname for esp8266 for dhcp, and or MDNS + + const char* _customHeadElement = ""; // store custom head element html from user isnide + const char* _customMenuHTML = ""; // store custom head element html from user inside <> + String _bodyClass = ""; // class to add to body + String _title = FPSTR(S_brand); // app title - default WiFiManager + + // internal options + + // wifiscan notes + // currently disabled due to issues with caching, sometimes first scan is empty esp32 wifi not init yet race, or portals hit server nonstop flood + // The following are background wifi scanning optimizations + // experimental to make scans faster, preload scans after starting cp, and visiting home page, so when you click wifi its already has your list + // ideally we would add async and xhr here but I am holding off on js requirements atm + // might be slightly buggy since captive portals hammer the home page, @todo workaround this somehow. + // cache time helps throttle this + // async enables asyncronous scans, so they do not block anything + // the refresh button bypasses cache + // no aps found is problematic as scans are always going to want to run, leading to page load delays + // + // These settings really only make sense with _preloadwifiscan true + // but not limited to, we could run continuous background scans on various page hits, or xhr hits + // which would be better coupled with asyncscan + // atm preload is only done on root hit and startcp + // + // preload scanning causes AP to delay showing for users, but also caches and lets the cp load faster once its open + // my scan takes 7-10 seconds + public: + boolean _preloadwifiscan = false; // preload wifiscan if true + unsigned int _scancachetime = 30000; // ms cache time for preload scans + boolean _asyncScan = false; // perform wifi network scan async + + private: + + boolean _autoforcerescan = false; // automatically force rescan if scan networks is 0, ignoring cache + + boolean _disableIpFields = false; // modify function of setShow_X_Fields(false), forces ip fields off instead of default show if set, eg. _staShowStaticFields=-1 + + String _wificountry = ""; // country code, @todo define in strings lang + + // wrapper functions for handling setting and unsetting persistent for now. + bool esp32persistent = false; + bool _hasBegun = false; // flag wm loaded,unloaded + void _begin(); + void _end(); + + void setupConfigPortal(); + bool shutdownConfigPortal(); + bool setupHostname(bool restart); + +#ifdef NO_EXTRA_4K_HEAP + boolean _tryWPS = false; // try WPS on save failure, unsupported + void startWPS(); +#endif + + bool startAP(); + void setupDNSD(); + void setupHTTPServer(); + + uint8_t connectWifi(String ssid, String pass, bool connect = true); + bool setSTAConfig(); + bool wifiConnectDefault(); + bool wifiConnectNew(String ssid, String pass,bool connect = true); + + uint8_t waitForConnectResult(); + uint8_t waitForConnectResult(uint32_t timeout); + void updateConxResult(uint8_t status); + + // webserver handlers +public: + void handleNotFound(); +private: + void HTTPSend(const String &content); + void handleRoot(); + void handleWifi(boolean scan); + void handleWifiSave(); + void handleInfo(); + void handleReset(); + + void handleExit(); + void handleClose(); + // void handleErase(); + void handleErase(boolean opt); + void handleParam(); + void handleWiFiStatus(); + void handleRequest(); + void handleParamSave(); + void doParamSave(); + + boolean captivePortal(); + boolean configPortalHasTimeout(); + uint8_t processConfigPortal(); + void stopCaptivePortal(); + // OTA Update handler + void handleUpdate(); + void handleUpdating(); + void handleUpdateDone(); + + + // wifi platform abstractions + bool WiFi_Mode(WiFiMode_t m); + bool WiFi_Mode(WiFiMode_t m,bool persistent); + bool WiFi_Disconnect(); + bool WiFi_enableSTA(bool enable); + bool WiFi_enableSTA(bool enable,bool persistent); + bool WiFi_eraseConfig(); + uint8_t WiFi_softap_num_stations(); + bool WiFi_hasAutoConnect(); + void WiFi_autoReconnect(); + String WiFi_SSID(bool persistent = true) const; + String WiFi_psk(bool persistent = true) const; + bool WiFi_scanNetworks(); + bool WiFi_scanNetworks(bool force,bool async); + bool WiFi_scanNetworks(unsigned int cachetime,bool async); + bool WiFi_scanNetworks(unsigned int cachetime); + void WiFi_scanComplete(int networksFound); + bool WiFiSetCountry(); + + #ifdef ESP32 + + // check for arduino or system event system, handle esp32 arduino v2 and IDF + #if defined(ESP_ARDUINO_VERSION) && defined(ESP_ARDUINO_VERSION_VAL) + + #define WM_ARDUINOVERCHECK ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0) + #define WM_ARDUINOVERCHECK_204 ESP_ARDUINO_VERSION <= ESP_ARDUINO_VERSION_VAL(2, 0, 5) + + #ifdef WM_ARDUINOVERCHECK + #define WM_ARDUINOEVENTS + #else + #define WM_NOSOFTAPSSID + #define WM_NOCOUNTRY + #endif + + #ifdef WM_ARDUINOVERCHECK_204 + #define WM_DISCONWORKAROUND + #endif + + #else + #define WM_NOCOUNTRY + #endif + + #ifdef WM_NOCOUNTRY + #warning "ESP32 set country unavailable" + #endif + + + #ifdef WM_ARDUINOEVENTS + void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info); + #else + void WiFiEvent(WiFiEvent_t event, system_event_info_t info); + #endif + #endif + + // output helpers + String getParamOut(); + String getIpForm(String id, String title, String value); + String getScanItemOut(); + String getStaticOut(); + String getHTTPHead(String title); + String getMenuOut(); + //helpers + boolean isIp(String str); + String toStringIp(IPAddress ip); + boolean validApPassword(); + String encryptionTypeStr(uint8_t authmode); + void reportStatus(String &page); + String getInfoData(String id); + + // flags + boolean connect = false; + boolean abort = false; + boolean reset = false; + boolean configPortalActive = false; + + + // these are state flags for portal mode, we are either in webportal mode(STA) or configportal mode(AP) + // these are mutually exclusive as STA+AP mode is not supported due to channel restrictions and stability + // if we decide to support this, these checks will need to be replaced with something client aware to check if client origin is ap or web + // These state checks are critical and used for internal function checks + boolean webPortalActive = false; + boolean portalTimeoutResult = false; + + boolean portalAbortResult = false; + boolean storeSTAmode = true; // option store persistent STA mode in connectwifi + int timer = 0; // timer for debug throttle for numclients, and portal timeout messages + + // WiFiManagerParameter + int _paramsCount = 0; + int _max_params; + WiFiManagerParameter** _params = NULL; + + boolean _debug = true; + String _debugPrefix = FPSTR(S_debugPrefix); + + wm_debuglevel_t debugLvlShow = WM_DEBUG_VERBOSE; // at which level start showing [n] level tags + + // build debuglevel support + // @todo use DEBUG_ESP_x? + + // Set default debug level + #ifndef WM_DEBUG_LEVEL + #define WM_DEBUG_LEVEL WM_DEBUG_NOTIFY + #endif + + // override debug level OFF + #ifdef WM_NODEBUG + #undef WM_DEBUG_LEVEL + #endif + + #ifdef WM_DEBUG_LEVEL + uint8_t _debugLevel = (uint8_t)WM_DEBUG_LEVEL; + #else + uint8_t _debugLevel = 0; // default debug level + #endif + + // @todo use DEBUG_ESP_PORT ? + #ifdef WM_DEBUG_PORT + Print& _debugPort = WM_DEBUG_PORT; + #else + Print& _debugPort = Serial; // debug output stream ref + #endif + + template + void DEBUG_WM(Generic text); + + template + void DEBUG_WM(wm_debuglevel_t level,Generic text); + template + void DEBUG_WM(Generic text,Genericb textb); + template + void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); + + // callbacks + // @todo use cb list (vector) maybe event ids, allow no return value + std::function _apcallback; + std::function _webservercallback; + std::function _savewificallback; + std::function _presavewificallback; + std::function _presaveparamscallback; + std::function _saveparamscallback; + std::function _resetcallback; + std::function _preotaupdatecallback; + std::function _configportaltimeoutcallback; + + template + auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { + return obj->fromString(s); + } + auto optionalIPFromString(...) -> bool { + // DEBUG_WM("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work."); + return false; + } + +}; + +#endif + +#endif diff --git a/airmx-esp-gate/airmx-esp-gate.ino b/airmx-esp-gate/airmx-esp-gate.ino new file mode 100644 index 0000000..0297523 --- /dev/null +++ b/airmx-esp-gate/airmx-esp-gate.ino @@ -0,0 +1,93 @@ +#include "WiFiManager.h" // https://github.com/tzapu/WiFiManager +#include // https://github.com/vshymanskyy/Preferences +#include "TCPProxy.h" + +#define RESET_PIN 4 // D2 +#define LED_PIN 2 // D4 +#define VERSION "v1" + +uint16_t httpPort = 8888; +const char* prefsNamespace = "airmx-gate"; +WiFiManagerParameter haAddressParam("ha_addr", "Home Assistant IP"); +WiFiManagerParameter apSSIDParam("ap_ssid", "Access Point SSID"); +WiFiManagerParameter apPasswordParam("ap_password", "Access Point Password"); +WiFiEventHandler onStationModeGotIPHandler; + +Preferences prefs; +WiFiManager wm; +IPAddress haAddress; + +void setup() { + Serial.begin(115200); + + wm.setConfigResetCallback(configResetCallback); + pinMode(RESET_PIN, INPUT_PULLUP); + if (digitalRead(RESET_PIN) == LOW) { + wm.resetSettings(); + + pinMode(LED_PIN, OUTPUT); + digitalWrite(LED_PIN, LOW); + return; + } + + Serial.println(); + wm.setDebugOutput(true, WM_DEBUG_DEV); + wm.setAPCallback(configModeCallback); + wm.setSaveConfigCallback(saveConfigCallback); + wm.setTitle("AIRMX Gate " VERSION); + wm.setBreakAfterConfig(true); + wm.setHttpPort(8888); + + prefs.begin(prefsNamespace); + haAddress = prefs.getULong(haAddressParam.getID()); + haAddressParam.setValue(haAddress.toString().c_str(), 15); + apSSIDParam.setValue(prefs.getString(apSSIDParam.getID(), "miaoxin").c_str(), 16); + apPasswordParam.setValue(prefs.getString(apPasswordParam.getID(), "miaoxin666").c_str(), 16); + wm.addParameter(&haAddressParam); + wm.addParameter(&apSSIDParam); + wm.addParameter(&apPasswordParam); + prefs.end(); + + onStationModeGotIPHandler = WiFi.onStationModeGotIP(WiFiGotIP); + + wm.autoConnect(apSSIDParam.getValue(), apPasswordParam.getValue()); + wm.startConfigPortal(apSSIDParam.getValue(), apPasswordParam.getValue()); +} + +void loop() { + wm.process(); +} + +void configModeCallback(WiFiManager* myWiFiManager) { + if (haAddress) { + tcp_proxy_start(WiFi.softAPIP(), haAddress, httpPort); + } else { + Serial.println("No HA address, skipping proxy start"); + } +} + +void saveConfigCallback() { + Serial.println("Saving config"); + + prefs.begin(prefsNamespace); + IPAddress haAddress; + haAddress.fromString(haAddressParam.getValue()); + prefs.putULong(haAddressParam.getID(), haAddress); + if (strlen(apPasswordParam.getValue()) >= 8) { + prefs.putString(apSSIDParam.getID(), apSSIDParam.getValue()); + prefs.putString(apPasswordParam.getID(), apPasswordParam.getValue()); + } + prefs.end(); + + ESP.restart(); +} + +void configResetCallback() { + prefs.begin(prefsNamespace); + prefs.clear(); + prefs.end(); +} + +void WiFiGotIP(const WiFiEventStationModeGotIP& event) { + tcp_proxy_set_proxy_addr(WiFi.localIP()); +} diff --git a/airmx-esp-gate/build/esp8266.esp8266.nodemcu/.gitignore b/airmx-esp-gate/build/esp8266.esp8266.nodemcu/.gitignore new file mode 100644 index 0000000..4a60f24 --- /dev/null +++ b/airmx-esp-gate/build/esp8266.esp8266.nodemcu/.gitignore @@ -0,0 +1,2 @@ +*.elf +*.map \ No newline at end of file diff --git a/airmx-esp-gate/build/esp8266.esp8266.nodemcu/airmx-esp-gate.ino.bin b/airmx-esp-gate/build/esp8266.esp8266.nodemcu/airmx-esp-gate.ino.bin new file mode 100644 index 0000000..720ac5b Binary files /dev/null and b/airmx-esp-gate/build/esp8266.esp8266.nodemcu/airmx-esp-gate.ino.bin differ diff --git a/airmx-esp-gate/wm_consts_en.h b/airmx-esp-gate/wm_consts_en.h new file mode 100644 index 0000000..c81c49d --- /dev/null +++ b/airmx-esp-gate/wm_consts_en.h @@ -0,0 +1,265 @@ +/** + * wm_consts.h + * internal const strings/tokens + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix" + * @version 0.0.0 + * @license MIT + */ + +#ifndef _WM_CONSTS_H +#define _WM_CONSTS_H + + +// ----------------------------------------------------------------------------------------------- +// TOKENS + +const char WM_VERSION_STR[] PROGMEM = "v2.0.15-rc.1"; + +static const char _wifi_token[] PROGMEM = "wifi"; +static const char _wifinoscan_token[] PROGMEM = "wifinoscan"; +static const char _info_token[] PROGMEM = "info"; +static const char _param_token[] PROGMEM = "param"; +static const char _close_token[] PROGMEM = "close"; +static const char _restart_token[] PROGMEM = "restart"; +static const char _exit_token[] PROGMEM = "exit"; +static const char _erase_token[] PROGMEM = "erase"; +static const char _update_token[] PROGMEM = "update"; +static const char _sep_token[] PROGMEM = "sep"; +static const char _custom_token[] PROGMEM = "custom"; +static PGM_P _menutokens[] PROGMEM = { + _wifi_token, + _wifinoscan_token, + _info_token, + _param_token, + _close_token, + _restart_token, + _exit_token, + _erase_token, + _update_token, + _sep_token, + _custom_token +}; +const uint8_t _nummenutokens = (sizeof(_menutokens) / sizeof(PGM_P)); + + +const char R_root[] PROGMEM = "/"; +const char R_wifi[] PROGMEM = "/wifi"; +const char R_wifinoscan[] PROGMEM = "/0wifi"; +const char R_wifisave[] PROGMEM = "/wifisave"; +const char R_info[] PROGMEM = "/info"; +const char R_param[] PROGMEM = "/param"; +const char R_paramsave[] PROGMEM = "/paramsave"; +const char R_restart[] PROGMEM = "/restart"; +const char R_exit[] PROGMEM = "/exit"; +const char R_close[] PROGMEM = "/close"; +const char R_erase[] PROGMEM = "/erase"; +const char R_status[] PROGMEM = "/status"; +const char R_update[] PROGMEM = "/update"; +const char R_updatedone[] PROGMEM = "/u"; + + +//Strings +const char S_ip[] PROGMEM = "ip"; +const char S_gw[] PROGMEM = "gw"; +const char S_sn[] PROGMEM = "sn"; +const char S_dns[] PROGMEM = "dns"; + + + +//Tokens +//@todo consolidate and reduce +const char T_ss[] PROGMEM = "{"; // token start sentinel +const char T_es[] PROGMEM = "}"; // token end sentinel +const char T_1[] PROGMEM = "{1}"; // @token 1 +const char T_2[] PROGMEM = "{2}"; // @token 2 +const char T_3[] PROGMEM = "{3}"; // @token 2 +const char T_v[] PROGMEM = "{v}"; // @token v +const char T_V[] PROGMEM = "{V}"; // @token v +const char T_I[] PROGMEM = "{I}"; // @token I +const char T_i[] PROGMEM = "{i}"; // @token i +const char T_n[] PROGMEM = "{n}"; // @token n +const char T_p[] PROGMEM = "{p}"; // @token p +const char T_t[] PROGMEM = "{t}"; // @token t +const char T_l[] PROGMEM = "{l}"; // @token l +const char T_c[] PROGMEM = "{c}"; // @token c +const char T_e[] PROGMEM = "{e}"; // @token e +const char T_q[] PROGMEM = "{q}"; // @token q +const char T_r[] PROGMEM = "{r}"; // @token r +const char T_R[] PROGMEM = "{R}"; // @token R +const char T_h[] PROGMEM = "{h}"; // @token h + +// http +const char HTTP_HEAD_CL[] PROGMEM = "Content-Length"; +const char HTTP_HEAD_CT[] PROGMEM = "text/html"; +const char HTTP_HEAD_CT2[] PROGMEM = "text/plain"; +const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; +const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; + +const char * const WIFI_STA_STATUS[] PROGMEM +{ + "WL_IDLE_STATUS", // 0 STATION_IDLE + "WL_NO_SSID_AVAIL", // 1 STATION_NO_AP_FOUND + "WL_SCAN_COMPLETED", // 2 + "WL_CONNECTED", // 3 STATION_GOT_IP + "WL_CONNECT_FAILED", // 4 STATION_CONNECT_FAIL, STATION_WRONG_PASSWORD(NI) + "WL_CONNECTION_LOST", // 5 + "WL_DISCONNECTED", // 6 + "WL_STATION_WRONG_PASSWORD" // 7 KLUDGE +}; + +#ifdef ESP32 +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "OPEN", + "WEP", + "WPA_PSK", + "WPA2_PSK", + "WPA_WPA2_PSK", + "WPA2_ENTERPRISE", + "MAX" +}; +#elif defined(ESP8266) +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "", + "", + "WPA_PSK", // 2 ENC_TYPE_TKIP + "", + "WPA2_PSK", // 4 ENC_TYPE_CCMP + "WEP", // 5 ENC_TYPE_WEP + "", + "OPEN", //7 ENC_TYPE_NONE + "WPA_WPA2_PSK", // 8 ENC_TYPE_AUTO +}; +#endif + +const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; + + +#ifdef ESP32 +// as 2.5.2 +// typedef struct { +// char cc[3]; /**< country code string */ +// uint8_t schan; /**< start channel */ +// uint8_t nchan; /**< total channel number */ +// int8_t max_tx_power; /**< This field is used for getting WiFi maximum transmitting power, call esp_wifi_set_max_tx_power to set the maximum transmitting power. */ +// wifi_country_policy_t policy; /**< country policy */ +// } wifi_country_t; +const wifi_country_t WM_COUNTRY_US{"US",1,11,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +#elif defined(ESP8266) && !defined(WM_NOCOUNTRY) +// typedef struct { +// char cc[3]; /**< country code string */ +// uint8_t schan; /**< start channel */ +// uint8_t nchan; /**< total channel number */ +// uint8_t policy; /**< country policy */ +// } wifi_country_t; +const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; +#endif + + +/* +* ESP32 WiFi Events + +0 SYSTEM_EVENT_WIFI_READY < ESP32 WiFi ready +1 SYSTEM_EVENT_SCAN_DONE < ESP32 finish scanning AP +2 SYSTEM_EVENT_STA_START < ESP32 station start +3 SYSTEM_EVENT_STA_STOP < ESP32 station stop +4 SYSTEM_EVENT_STA_CONNECTED < ESP32 station connected to AP +5 SYSTEM_EVENT_STA_DISCONNECTED < ESP32 station disconnected from AP +6 SYSTEM_EVENT_STA_AUTHMODE_CHANGE < the auth mode of AP connected by ESP32 station changed +7 SYSTEM_EVENT_STA_GOT_IP < ESP32 station got IP from connected AP +8 SYSTEM_EVENT_STA_LOST_IP < ESP32 station lost IP and the IP is reset to 0 +9 SYSTEM_EVENT_STA_WPS_ER_SUCCESS < ESP32 station wps succeeds in enrollee mode +10 SYSTEM_EVENT_STA_WPS_ER_FAILED < ESP32 station wps fails in enrollee mode +11 SYSTEM_EVENT_STA_WPS_ER_TIMEOUT < ESP32 station wps timeout in enrollee mode +12 SYSTEM_EVENT_STA_WPS_ER_PIN < ESP32 station wps pin code in enrollee mode +13 SYSTEM_EVENT_AP_START < ESP32 soft-AP start +14 SYSTEM_EVENT_AP_STOP < ESP32 soft-AP stop +15 SYSTEM_EVENT_AP_STACONNECTED < a station connected to ESP32 soft-AP +16 SYSTEM_EVENT_AP_STADISCONNECTED < a station disconnected from ESP32 soft-AP +17 SYSTEM_EVENT_AP_STAIPASSIGNED < ESP32 soft-AP assign an IP to a connected station +18 SYSTEM_EVENT_AP_PROBEREQRECVED < Receive probe request packet in soft-AP interface +19 SYSTEM_EVENT_GOT_IP6 < ESP32 station or ap or ethernet interface v6IP addr is preferred +20 SYSTEM_EVENT_ETH_START < ESP32 ethernet start +21 SYSTEM_EVENT_ETH_STOP < ESP32 ethernet stop +22 SYSTEM_EVENT_ETH_CONNECTED < ESP32 ethernet phy link up +23 SYSTEM_EVENT_ETH_DISCONNECTED < ESP32 ethernet phy link down +24 SYSTEM_EVENT_ETH_GOT_IP < ESP32 ethernet got IP from connected AP +25 SYSTEM_EVENT_MAX + + +typedef enum { + ARDUINO_EVENT_WIFI_READY = 0, + ARDUINO_EVENT_WIFI_SCAN_DONE, + ARDUINO_EVENT_WIFI_STA_START, + ARDUINO_EVENT_WIFI_STA_STOP, + ARDUINO_EVENT_WIFI_STA_CONNECTED, + ARDUINO_EVENT_WIFI_STA_DISCONNECTED, + ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE, + ARDUINO_EVENT_WIFI_STA_GOT_IP, + ARDUINO_EVENT_WIFI_STA_GOT_IP6, + ARDUINO_EVENT_WIFI_STA_LOST_IP, + ARDUINO_EVENT_WIFI_AP_START, + ARDUINO_EVENT_WIFI_AP_STOP, + ARDUINO_EVENT_WIFI_AP_STACONNECTED, + ARDUINO_EVENT_WIFI_AP_STADISCONNECTED, + ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED, + ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED, + ARDUINO_EVENT_WIFI_AP_GOT_IP6, + ARDUINO_EVENT_WIFI_FTM_REPORT, + ARDUINO_EVENT_ETH_START, + ARDUINO_EVENT_ETH_STOP, + ARDUINO_EVENT_ETH_CONNECTED, + ARDUINO_EVENT_ETH_DISCONNECTED, + ARDUINO_EVENT_ETH_GOT_IP, + ARDUINO_EVENT_ETH_GOT_IP6, + ARDUINO_EVENT_WPS_ER_SUCCESS, + ARDUINO_EVENT_WPS_ER_FAILED, + ARDUINO_EVENT_WPS_ER_TIMEOUT, + ARDUINO_EVENT_WPS_ER_PIN, + ARDUINO_EVENT_WPS_ER_PBC_OVERLAP, + ARDUINO_EVENT_SC_SCAN_DONE, + ARDUINO_EVENT_SC_FOUND_CHANNEL, + ARDUINO_EVENT_SC_GOT_SSID_PSWD, + ARDUINO_EVENT_SC_SEND_ACK_DONE, + ARDUINO_EVENT_PROV_INIT, + ARDUINO_EVENT_PROV_DEINIT, + ARDUINO_EVENT_PROV_START, + ARDUINO_EVENT_PROV_END, + ARDUINO_EVENT_PROV_CRED_RECV, + ARDUINO_EVENT_PROV_CRED_FAIL, + ARDUINO_EVENT_PROV_CRED_SUCCESS, + ARDUINO_EVENT_MAX +} arduino_event_id_t; + +typedef union { + wifi_event_sta_scan_done_t wifi_scan_done; + wifi_event_sta_authmode_change_t wifi_sta_authmode_change; + wifi_event_sta_connected_t wifi_sta_connected; + wifi_event_sta_disconnected_t wifi_sta_disconnected; + wifi_event_sta_wps_er_pin_t wps_er_pin; + wifi_event_sta_wps_fail_reason_t wps_fail_reason; + wifi_event_ap_probe_req_rx_t wifi_ap_probereqrecved; + wifi_event_ap_staconnected_t wifi_ap_staconnected; + wifi_event_ap_stadisconnected_t wifi_ap_stadisconnected; + wifi_event_ftm_report_t wifi_ftm_report; + ip_event_ap_staipassigned_t wifi_ap_staipassigned; + ip_event_got_ip_t got_ip; + ip_event_got_ip6_t got_ip6; + smartconfig_event_got_ssid_pswd_t sc_got_ssid_pswd; + esp_eth_handle_t eth_connected; + wifi_sta_config_t prov_cred_recv; + wifi_prov_sta_fail_reason_t prov_fail_reason; +} arduino_event_info_t; + +*/ + +#endif \ No newline at end of file diff --git a/airmx-esp-gate/wm_strings_en.h b/airmx-esp-gate/wm_strings_en.h new file mode 100644 index 0000000..4b53160 --- /dev/null +++ b/airmx-esp-gate/wm_strings_en.h @@ -0,0 +1,275 @@ +/** + * wm_strings_en.h + * engligh strings for + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + +#ifndef _WM_STRINGS_EN_H_ +#define _WM_STRINGS_EN_H_ + + +#ifndef WIFI_MANAGER_OVERRIDE_STRINGS +// !!! ABOVE WILL NOT WORK if you define in your sketch, must be build flag, if anyone one knows how to order includes to be able to do this it would be neat.. I have seen it done.. + +// strings files must include a consts file! +#include "wm_consts_en.h" // include constants, tokens, routes + +const char WM_LANGUAGE[] PROGMEM = "en-US"; // i18n lang code + +const char HTTP_HEAD_START[] PROGMEM = "" +"" +"" +"" +"" +"{v}"; + +const char HTTP_SCRIPT[] PROGMEM = ""; // @todo add button states, disable on click , show ack , spinner etc + +const char HTTP_HEAD_END[] PROGMEM = "
"; // {c} = _bodyclass +// example of embedded logo, base64 encoded inline, No styling here +// const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; +const char HTTP_ROOT_MAIN[] PROGMEM = "

{t}

{v}

"; + +const char * const HTTP_PORTAL_MENU[] PROGMEM = { +"

\n", // MENU_WIFI +"

\n", // MENU_WIFINOSCAN +"

\n", // MENU_INFO +"

\n",//MENU_PARAM +"

\n", // MENU_CLOSE +"

\n",// MENU_RESTART +"

\n", // MENU_EXIT +"

\n", // MENU_ERASE +"

\n",// MENU_UPDATE +"

" // MENU_SEP +}; + +// const char HTTP_PORTAL_OPTIONS[] PROGMEM = strcat(HTTP_PORTAL_MENU[0] , HTTP_PORTAL_MENU[3] , HTTP_PORTAL_MENU[7]); +const char HTTP_PORTAL_OPTIONS[] PROGMEM = ""; +const char HTTP_ITEM_QI[] PROGMEM = ""; // rssi icons +const char HTTP_ITEM_QP[] PROGMEM = "
{r}%
"; // rssi percentage {h} = hidden showperc pref +const char HTTP_ITEM[] PROGMEM = "
{v}{qi}{qp}
"; // {q} = HTTP_ITEM_QI, {r} = HTTP_ITEM_QP +// const char HTTP_ITEM[] PROGMEM = "
{v} {R} {r}% {q} {e}
"; // test all tokens + +const char HTTP_FORM_START[] PROGMEM = "
"; +const char HTTP_FORM_WIFI[] PROGMEM = "

"; +const char HTTP_FORM_WIFI_END[] PROGMEM = ""; +const char HTTP_FORM_STATIC_HEAD[] PROGMEM = "

"; +const char HTTP_FORM_END[] PROGMEM = "

"; +const char HTTP_FORM_LABEL[] PROGMEM = ""; +const char HTTP_FORM_PARAM_HEAD[] PROGMEM = "

"; +const char HTTP_FORM_PARAM[] PROGMEM = "
\n"; // do not remove newline! + +const char HTTP_SCAN_LINK[] PROGMEM = "
"; +const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; +const char HTTP_PARAMSAVED[] PROGMEM = "
Saved
"; +const char HTTP_END[] PROGMEM = "
"; +const char HTTP_ERASEBTN[] PROGMEM = "
"; +const char HTTP_UPDATEBTN[] PROGMEM = "
"; +const char HTTP_BACKBTN[] PROGMEM = "

"; + +const char HTTP_STATUS_ON[] PROGMEM = "
Connected to {v}
with IP {i}
"; +const char HTTP_STATUS_OFF[] PROGMEM = "
Not connected to {v}{r}
"; // {c=class} {v=ssid} {r=status_off} +const char HTTP_STATUS_OFFPW[] PROGMEM = "
Authentication failure"; // STATION_WRONG_PASSWORD, no eps32 +const char HTTP_STATUS_OFFNOAP[] PROGMEM = "
AP not found"; // WL_NO_SSID_AVAIL +const char HTTP_STATUS_OFFFAIL[] PROGMEM = "
Could not connect"; // WL_CONNECT_FAILED +const char HTTP_STATUS_NONE[] PROGMEM = "
No AP set
"; +const char HTTP_BR[] PROGMEM = "
"; + +const char HTTP_STYLE[] PROGMEM = ""; + +#ifndef WM_NOHELP +const char HTTP_HELP[] PROGMEM = + "

Available pages


" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "
PageFunction
/Menu page.
/wifiShow WiFi scan results and enter WiFi configuration.(/0wifi noscan)
/wifisaveSave WiFi configuration information and configure device. Needs variables supplied.
/paramParameter page
/infoInformation page
/uOTA Update
/closeClose the captiveportal popup, config portal will remain active
/exitExit Config portal, config portal will close
/restartReboot the device
/eraseErase WiFi configuration and reboot device. Device will not reconnect to a network until new WiFi configuration data is entered.
" + "

Github https://github.com/tzapu/WiFiManager."; +#else +const char HTTP_HELP[] PROGMEM = ""; +#endif + +const char HTTP_UPDATE[] PROGMEM = "Upload new firmware

* May not function inside captive portal, open in browser http://192.168.4.1"; +const char HTTP_UPDATE_FAIL[] PROGMEM = "
Update failed!
Reboot device and try again
"; +const char HTTP_UPDATE_SUCCESS[] PROGMEM = "
Update successful.
Device rebooting now...
"; + +#ifdef WM_JSTEST +const char HTTP_JS[] PROGMEM = +""; +#endif + +// Info html +// @todo remove html elements from progmem, repetetive strings +#ifdef ESP32 + const char HTTP_INFO_esphead[] PROGMEM = "

esp32


"; + const char HTTP_INFO_chiprev[] PROGMEM = "
Chip rev
{1}
"; + const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
CPU0: {1}
CPU1: {2}
"; + const char HTTP_INFO_aphost[] PROGMEM = "
Access point hostname
{1}
"; + const char HTTP_INFO_psrsize[] PROGMEM = "
PSRAM Size
{1} bytes
"; + const char HTTP_INFO_temp[] PROGMEM = "
Temperature
{1} C° / {2} F°
"; + const char HTTP_INFO_hall[] PROGMEM = "
Hall
{1}
"; +#else + const char HTTP_INFO_esphead[] PROGMEM = "

esp8266


"; + const char HTTP_INFO_fchipid[] PROGMEM = "
Flash chip ID
{1}
"; + const char HTTP_INFO_corever[] PROGMEM = "
Core version
{1}
"; + const char HTTP_INFO_bootver[] PROGMEM = "
Boot version
{1}
"; + const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
{1}
"; + const char HTTP_INFO_flashsize[] PROGMEM = "
Real flash size
{1} bytes
"; +#endif + +const char HTTP_INFO_memsmeter[] PROGMEM = "
"; +const char HTTP_INFO_memsketch[] PROGMEM = "
Memory - Sketch size
Used / Total bytes
{1} / {2}"; +const char HTTP_INFO_freeheap[] PROGMEM = "
Memory - Free heap
{1} bytes available
"; +const char HTTP_INFO_wifihead[] PROGMEM = "

WiFi


"; +const char HTTP_INFO_uptime[] PROGMEM = "
Uptime
{1} mins {2} secs
"; +const char HTTP_INFO_chipid[] PROGMEM = "
Chip ID
{1}
"; +const char HTTP_INFO_idesize[] PROGMEM = "
Flash size
{1} bytes
"; +const char HTTP_INFO_sdkver[] PROGMEM = "
SDK version
{1}
"; +const char HTTP_INFO_cpufreq[] PROGMEM = "
CPU frequency
{1}MHz
"; +const char HTTP_INFO_apip[] PROGMEM = "
Access point IP
{1}
"; +const char HTTP_INFO_apmac[] PROGMEM = "
Access point MAC
{1}
"; +const char HTTP_INFO_apssid[] PROGMEM = "
Access point SSID
{1}
"; +const char HTTP_INFO_apbssid[] PROGMEM = "
BSSID
{1}
"; +const char HTTP_INFO_stassid[] PROGMEM = "
Station SSID
{1}
"; +const char HTTP_INFO_staip[] PROGMEM = "
Station IP
{1}
"; +const char HTTP_INFO_stagw[] PROGMEM = "
Station gateway
{1}
"; +const char HTTP_INFO_stasub[] PROGMEM = "
Station subnet
{1}
"; +const char HTTP_INFO_dnss[] PROGMEM = "
DNS Server
{1}
"; +const char HTTP_INFO_host[] PROGMEM = "
Hostname
{1}
"; +const char HTTP_INFO_stamac[] PROGMEM = "
Station MAC
{1}
"; +const char HTTP_INFO_conx[] PROGMEM = "
Connected
{1}
"; +const char HTTP_INFO_autoconx[] PROGMEM = "
Autoconnect
{1}
"; + +const char HTTP_INFO_aboutver[] PROGMEM = "
WiFiManager
{1}
"; +const char HTTP_INFO_aboutarduino[] PROGMEM = "
Arduino
{1}
"; +const char HTTP_INFO_aboutsdk[] PROGMEM = "
ESP-SDK/IDF
{1}
"; +const char HTTP_INFO_aboutdate[] PROGMEM = "
Build date
{1}
"; + +const char S_brand[] PROGMEM = "WiFiManager"; +const char S_debugPrefix[] PROGMEM = "*wm:"; +const char S_y[] PROGMEM = "Yes"; +const char S_n[] PROGMEM = "No"; +const char S_enable[] PROGMEM = "Enabled"; +const char S_disable[] PROGMEM = "Disabled"; +const char S_GET[] PROGMEM = "GET"; +const char S_POST[] PROGMEM = "POST"; +const char S_NA[] PROGMEM = "Unknown"; +const char S_passph[] PROGMEM = "********"; +const char S_titlewifisaved[] PROGMEM = "Credentials saved"; +const char S_titlewifisettings[] PROGMEM = "Settings saved"; +const char S_titlewifi[] PROGMEM = "Config ESP"; +const char S_titleinfo[] PROGMEM = "Info"; +const char S_titleparam[] PROGMEM = "Setup"; +const char S_titleparamsaved[] PROGMEM = "Setup saved"; +const char S_titleexit[] PROGMEM = "Exit"; +const char S_titlereset[] PROGMEM = "Reset"; +const char S_titleerase[] PROGMEM = "Erase"; +const char S_titleclose[] PROGMEM = "Close"; +const char S_options[] PROGMEM = "options"; +const char S_nonetworks[] PROGMEM = "No networks found. Refresh to scan again."; +const char S_staticip[] PROGMEM = "Static IP"; +const char S_staticgw[] PROGMEM = "Static gateway"; +const char S_staticdns[] PROGMEM = "Static DNS"; +const char S_subnet[] PROGMEM = "Subnet"; +const char S_exiting[] PROGMEM = "Exiting"; +const char S_resetting[] PROGMEM = "Module will reset in a few seconds."; +const char S_closing[] PROGMEM = "You can close the page, portal will continue to run"; +const char S_error[] PROGMEM = "An error occured"; +const char S_notfound[] PROGMEM = "File not found\n\n"; +const char S_uri[] PROGMEM = "URI: "; +const char S_method[] PROGMEM = "\nMethod: "; +const char S_args[] PROGMEM = "\nArguments: "; +const char S_parampre[] PROGMEM = "param_"; + +// debug strings +const char D_HR[] PROGMEM = "--------------------"; + + +// softap ssid default prefix +#ifdef ESP8266 + const char S_ssidpre[] PROGMEM = "ESP"; +#elif defined(ESP32) + const char S_ssidpre[] PROGMEM = "ESP32"; +#else + const char S_ssidpre[] PROGMEM = "WM"; +#endif + +// END WIFI_MANAGER_OVERRIDE_STRINGS +#endif + +#endif diff --git a/custom_components/airmx/__init__.py b/custom_components/airmx/__init__.py new file mode 100644 index 0000000..4f9bfb6 --- /dev/null +++ b/custom_components/airmx/__init__.py @@ -0,0 +1,65 @@ +import logging +from typing import Any + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import CONF_ID, CONF_MODEL, EVENT_HOMEASSISTANT_STOP +from homeassistant.core import HomeAssistant +from homeassistant.helpers.json import JSONEncoder +from homeassistant.helpers.storage import Store + +from .airwater.const import AirWaterModel +from .airwater.device import STORAGE_VERSION, AirWaterDevice, AirWaterSettingsStore +from .const import CONF_MQTT_HOST, CONF_MQTT_PORT, CONF_SIGN_KEY, DEVICES, DOMAIN, PLATFORMS, SETTING_STORES + +_LOGGER = logging.getLogger(__name__) + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + device_id = entry.data[CONF_ID] + settings_store = AirWaterSettingsStore( + hass, + STORAGE_VERSION, + f"{DOMAIN}.airwater_{device_id}", + encoder=JSONEncoder, + ) + device = AirWaterDevice( + hass, + device_id, + AirWaterModel(entry.data[CONF_MODEL]), + settings_store, + entry.data[CONF_SIGN_KEY], + entry.data[CONF_MQTT_HOST], + entry.data[CONF_MQTT_PORT], + ) + await device.async_setup() + + hass.data.setdefault(DOMAIN, {SETTING_STORES: {}, DEVICES: {}}) + hass.data[DOMAIN][DEVICES][entry.entry_id] = device + hass.data[DOMAIN][SETTING_STORES][entry.entry_id] = settings_store + + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + + entry.async_on_unload(hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, device.async_stop)) + entry.async_on_unload(entry.add_update_listener(_async_entry_update_listener)) + + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + device: AirWaterDevice = hass.data[DOMAIN][DEVICES][entry.entry_id] + await device.async_stop() + + if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): + hass.data[DOMAIN][DEVICES].pop(entry.entry_id) + + return unload_ok + + +async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + settings_store: Store[Any] | None = hass.data.get(DOMAIN, {}).get(SETTING_STORES, {}).get(entry.entry_id) + if settings_store: + await settings_store.async_remove() + + +async def _async_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: + await hass.config_entries.async_reload(entry.entry_id) diff --git a/custom_components/airmx/airwater/ble.py b/custom_components/airmx/airwater/ble.py new file mode 100755 index 0000000..0ff26c8 --- /dev/null +++ b/custom_components/airmx/airwater/ble.py @@ -0,0 +1,81 @@ +import asyncio +from contextlib import suppress +from dataclasses import dataclass +import logging + +from bleak import BleakClient, BleakError, BLEDevice +from bleak.backends.characteristic import BleakGATTCharacteristic + +_LOGGER = logging.getLogger(__name__) + +PACKET_SIZE = 16 +NOTIFICATION_UUID = "22210002-554a-4546-5542-46534450464d" +COMMAND_UUID = "22210001-554a-4546-5542-46534450464d" + + +@dataclass +class BindAPRequest: + ssid: str + password: str + + @property + def as_bytes(self) -> bytes: + data = b"" + data += len(self.ssid).to_bytes() + data += self.ssid.encode() + data += len(self.password).to_bytes() + data += self.password.encode() + return data + + +class AirWaterBLEConnector: + _bind_ap_done = False + + def _notification_handler(self, _: BleakGATTCharacteristic, data: bytearray) -> None: + _LOGGER.debug("< %s", data.hex()) + if data != b"\x00\x11\x00\x15\x01": + _LOGGER.error(f"Unexpected data: {data.hex()}") + else: + self._bind_ap_done = True + + async def bind_ap(self, device: BLEDevice, ssid: str, password: str) -> None: + _LOGGER.debug(f"Connecting to {device}...") + + async with BleakClient(device) as client: + await client.start_notify(NOTIFICATION_UUID, self._notification_handler) + + request = BindAPRequest(ssid, password).as_bytes + request_size = len(request) + packet_count = int(request_size / PACKET_SIZE) + if request_size % 16 > 0: + packet_count += 1 + + for seq in range(0, packet_count): + csum = (seq + 1 << 4) + packet_count + + packet = b"" + packet += seq.to_bytes() + packet += csum.to_bytes() + packet += b"\x00\x15" + + f = seq * PACKET_SIZE + s = seq * PACKET_SIZE + PACKET_SIZE + packet += request[f:s] + + _LOGGER.debug("> %s", packet.hex()) + await client.write_gatt_char(COMMAND_UUID, packet, response=True) + + for _ in range(0, 60): + await asyncio.sleep(0.3) + if self._bind_ap_done: + break + + if not self._bind_ap_done: + raise Exception("AP binding timeout") + + ack_packet = (seq + 1).to_bytes() + b"\x11\x00\x16" + _LOGGER.debug("> %s", ack_packet.hex()) + await client.write_gatt_char(COMMAND_UUID, packet, response=True) + + with suppress(BleakError): + await client.stop_notify(NOTIFICATION_UUID) diff --git a/custom_components/airmx/airwater/const.py b/custom_components/airmx/airwater/const.py new file mode 100644 index 0000000..4333f06 --- /dev/null +++ b/custom_components/airmx/airwater/const.py @@ -0,0 +1,56 @@ +from enum import IntEnum, IntFlag, StrEnum + + +class AirWaterFeature(IntFlag): + HEATER = 1 + + +class AirWaterModel(StrEnum): + A2 = "AirWater A2" + A3 = "AirWater A3" + A3S = "AirWater A3S" + A3S_V2 = "A3S_V2" + A5 = "AirWater A5" + + @property + def human_readable(self) -> str: + if self == self.A3S_V2: + return "AirWater A3S_V2 / Tion Iris" + + return self + + @property + def features(self) -> int: + if self in [self.A2, self.A5]: + return AirWaterFeature.HEATER + + return 0 + + +class AirWaterCommand(IntEnum): + CONTROL = 1000 + STATUS_INFO = 1001 + SET = 1002 + SET_INFO = 1003 + GET_STATUS = 1008 + STERILIZATION = 1011 + STERILIZATION_INFO = 1012 + + +class AirWaterMode(IntEnum): + MANUAL = 0 + AUTO = 1 + SLEEP = 2 + MALFUNCTION = 5 + + +class WaterType(IntEnum): + FILTERED = 1 + TAP = 2 + + @property + def cleaning_time(self) -> int: + if self == self.FILTERED: + return 300 + + return 150 diff --git a/custom_components/airmx/airwater/device.py b/custom_components/airmx/airwater/device.py new file mode 100644 index 0000000..301a882 --- /dev/null +++ b/custom_components/airmx/airwater/device.py @@ -0,0 +1,371 @@ +import dataclasses +from datetime import datetime, timedelta +import hashlib +import json +import logging +from typing import Any, Callable, Self, cast + +from homeassistant.core import CALLBACK_TYPE, Event, HassJob, HomeAssistant +from homeassistant.helpers.event import async_track_time_interval +from homeassistant.helpers.storage import Store +from homeassistant.util.json import json_loads_object +import paho.mqtt.client as mqtt + +from ..mqtt.client import MQTTClient +from .const import AirWaterCommand, AirWaterMode, AirWaterModel, WaterType + +_LOGGER = logging.getLogger(__name__) + +AVAILABILITY_TIMEOUT = timedelta(seconds=30) +UPDATE_INTERVAL = 600 +UPDATE_DURATION = 10 +NULL_VALUE = 99999 +STORAGE_VERSION = 1 + +CommandData = dict[str, int | str] +CommandType = dict[str, int | str | CommandData] +AirWaterSettingsStoreData = dict[str, int | str] + + +def _get_bool_from_command_data(data: CommandData, key: str, default: bool = False) -> bool: + return bool(data.get(key, int(default))) + + +def _get_float_from_command_data(data: CommandData, key: str) -> float | None: + value = int(data.get(key, NULL_VALUE)) + if value == NULL_VALUE: + return None + + return value / 100 + + +def _get_int_from_command_data(data: CommandData, key: str, default: int = 0) -> int: + return int(data.get(key, default)) + + +@dataclasses.dataclass +class AirWaterDeviceSettings: + water_type: WaterType = WaterType.TAP + target_humidity: int = 45 + heater: bool = True + proximity_sensor: bool = True + auto_shake: bool = True + + # unknown fields + clean_notify: bool = True + electrolysis: int = 0 + electrolysis_level: int = 0 + + @classmethod + def from_command_data(cls, data: CommandData) -> Self: + return cls( + target_humidity=int(data.get("hThreshold", 0)), + heater=_get_bool_from_command_data(data, "powerHeat"), + proximity_sensor=_get_bool_from_command_data(data, "pirLock"), + auto_shake=_get_bool_from_command_data(data, "autoShakeEnable"), + clean_notify=_get_bool_from_command_data(data, "cleanNotify"), + electrolysis=_get_bool_from_command_data(data, "electrolysis"), + electrolysis_level=_get_bool_from_command_data(data, "electrolysisLevel"), + ) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> Self: + return cls( + water_type=WaterType(data["water_type"]), + target_humidity=int(data["target_humidity"]), + heater=bool(data["heater"]), + proximity_sensor=bool(data["proximity_sensor"]), + auto_shake=bool(data["auto_shake"]), + clean_notify=bool(data["clean_notify"]), + electrolysis=int(data["electrolysis"]), + electrolysis_level=int(data["electrolysis_level"]), + ) + + @property + def as_command_data(self) -> CommandData: + return { + "hThreshold": self.target_humidity, + "powerHeat": int(self.heater), + "pirLock": int(self.proximity_sensor), + "autoShakeEnable": int(self.auto_shake), + "cleanNotify" "": int(self.clean_notify), + "electrolysis": int(self.electrolysis), + "electrolysisLevel": int(self.electrolysis_level), + } + + def with_changes(self, **changes: Any) -> Self: + return dataclasses.replace(self, **changes) + + +class AirWaterSettingsStore(Store[AirWaterSettingsStoreData]): + pass + + +@dataclasses.dataclass +class AirWaterDeviceStatus: + power: bool = False + mode: AirWaterMode = AirWaterMode.AUTO + fan_speed: int = 0 + child_lock: bool = False + uv: bool = True + anion: bool = True + target_humidity: int = 0 + water_level: int = 0 + internal_sensor_humidity: float | None = None + internal_sensor_temperature: float | None = None + remote_sensor_online: bool = False + remote_sensor_rssi: int = -100 + remote_sensor_humidity: float | None = None + remote_sensor_temperature: float | None = None + need_cleaning: bool = False + heater: bool = False + wud: int = 0 + malfunction: bool = False + firmware_version: str | None = None + + # unknown fields + electrolysis: int = 0 + wet_film: int | None = None + + @classmethod + def from_command_data(cls, data: CommandData) -> Self: + status = cls( + power=_get_bool_from_command_data(data, "power"), + mode=AirWaterMode(_get_int_from_command_data(data, "mode")), + fan_speed=_get_int_from_command_data(data, "cadr"), + child_lock=_get_bool_from_command_data(data, "lock"), + uv=_get_bool_from_command_data(data, "uv"), + anion=_get_bool_from_command_data(data, "anion"), + target_humidity=_get_int_from_command_data(data, "hThreshold"), + water_level=_get_int_from_command_data(data, "water"), + internal_sensor_humidity=_get_float_from_command_data(data, "h0"), + internal_sensor_temperature=_get_float_from_command_data(data, "t0"), + remote_sensor_online=_get_bool_from_command_data(data, "gooseOnline"), + remote_sensor_rssi=_get_int_from_command_data(data, "bleSignal", -100), + remote_sensor_humidity=_get_float_from_command_data(data, "h"), + remote_sensor_temperature=_get_float_from_command_data(data, "t"), + need_cleaning=_get_bool_from_command_data(data, "isNeedClean"), + heater=_get_bool_from_command_data(data, "powerHeatStatus"), + wud=_get_int_from_command_data(data, "WUD"), + firmware_version=str(data.get("version")) if "version" in data else None, + electrolysis=_get_int_from_command_data(data, "electrolysis"), + wet_film=_get_int_from_command_data(data, "wetFilm"), + ) + + if status.mode == AirWaterMode.MALFUNCTION: + status.mode = AirWaterMode.AUTO + status.malfunction = True + + if status.remote_sensor_online: + if not status.remote_sensor_temperature or not status.remote_sensor_temperature: + status.remote_sensor_online = False + + return status + + @property + def as_command_data(self) -> CommandData: + return { + "power": int(self.power), + "mode": self.mode, + "cadr": self.fan_speed, + "lock": int(self.child_lock), + "uv": int(self.uv), + "anion": int(self.anion), + } + + def with_changes(self, **changes: Any) -> Self: + return dataclasses.replace(self, **changes) + + +class AirWaterDevice: + _settings: AirWaterDeviceSettings + _unsub_subscribe_for_updates: CALLBACK_TYPE | None = None + + def __init__( + self, + hass: HomeAssistant, + device_id: int, + model: AirWaterModel, + settings_store: AirWaterSettingsStore, + sign_key: str, + mqtt_host: str, + mqtt_port: int, + ): + self.id = device_id + self.model = model + self.last_state_report: dict[Any, dict[Any, Any]] = {} + + self._hass = hass + self._mqttc = MQTTClient(hass, mqtt_host, mqtt_port, f"aw_{device_id}", sign_key) + self._mqttc.subscribe_topics = [f"airwater/01/0/1/1/{self.id}"] + self._mqttc.on_message = HassJob(self._async_handle_mqtt_message) + self._mqttc.on_connect = HassJob(self._async_subscribe_for_updates) + self._mqttc.on_disconnect = HassJob(self._async_notify) + self._sign_key = sign_key + self._status = AirWaterDeviceStatus() + self._settings_store = settings_store + self._listeners: list[Callable[[], None]] = [] + self._last_update: datetime | None = None + + async def async_setup(self) -> None: + self._settings = await self._async_load_settings() + await self._mqttc.async_connect() + self._unsub_subscribe_for_updates = async_track_time_interval( + self._hass, self._async_subscribe_for_updates, timedelta(seconds=UPDATE_DURATION) + ) + await self._async_subscribe_for_updates() + + async def async_stop(self, _: Event | None = None) -> None: + if self._unsub_subscribe_for_updates: + self._unsub_subscribe_for_updates() + + await self._mqttc.async_disconnect() + + @property + def name(self) -> str: + return f"{self.model.value} {self.id}" + + @property + def available(self) -> bool: + if not self._mqttc.connected or not self._last_update: + return False + + if datetime.now() - self._last_update >= AVAILABILITY_TIMEOUT: + return False + + return True + + @property + def status(self) -> AirWaterDeviceStatus: + return self._status + + @property + def settings(self) -> AirWaterDeviceSettings: + return self._settings + + async def async_turn_on(self) -> None: + await self._async_control(self.status.with_changes(power=True)) + + async def async_turn_off(self) -> None: + await self._async_control(self.status.with_changes(power=False)) + + async def async_set_mode(self, mode: AirWaterMode) -> None: + await self._async_control(self.status.with_changes(mode=mode)) + + async def async_set_target_humidity(self, humidity: int) -> None: + await self._async_set(self.settings.with_changes(target_humidity=humidity)) + + async def async_set_fan_speed(self, speed: int) -> None: + await self._async_control(self.status.with_changes(fan_speed=speed, mode=AirWaterMode.MANUAL)) + + async def async_set_child_lock_on(self) -> None: + await self._async_control(self.status.with_changes(child_lock=True)) + + async def async_set_child_lock_off(self) -> None: + await self._async_control(self.status.with_changes(child_lock=False)) + + async def async_set_anion_on(self) -> None: + await self._async_control(self.status.with_changes(anion=True)) + + async def async_set_anion_off(self) -> None: + await self._async_control(self.status.with_changes(anion=False)) + + async def async_set_heater_on(self) -> None: + await self._async_set(self.settings.with_changes(heater=True)) + + async def async_set_heater_off(self) -> None: + await self._async_set(self.settings.with_changes(heater=False)) + + async def async_set_proximity_sensor_on(self) -> None: + await self._async_set(self.settings.with_changes(proximity_sensor=True)) + + async def async_set_proximity_sensor_off(self) -> None: + await self._async_set(self.settings.with_changes(proximity_sensor=False)) + + async def async_set_water_type(self, water_type: WaterType) -> None: + await self._async_update_settings(self.settings.with_changes(water_type=water_type)) + await self._async_subscribe_for_updates() + + async def async_send_command(self, command: AirWaterCommand, data: CommandData) -> None: + await self._mqttc.async_publish( + f"airwater/01/1/0/1/{self.id}", + self._get_signed_command(command, data), + ) + + def async_add_listener(self, cb: Callable[[], None]) -> Callable[[], None]: + """Add a listener to notify when data is updated.""" + + def unsub() -> None: + self._listeners.remove(cb) + + self._listeners.append(cb) + return unsub + + async def _async_handle_mqtt_message(self, message: mqtt.MQTTMessage) -> None: + state_report = cast(CommandType, json_loads_object(cast(bytes, message.payload))) + self._last_update = datetime.now() + self.last_state_report[state_report["cmdId"]] = state_report + + match state_report["cmdId"]: + case AirWaterCommand.STATUS_INFO: + await self._async_handle_new_status(cast(CommandData, state_report["data"])) + case AirWaterCommand.SET_INFO: + await self._async_handle_new_settings(cast(CommandData, state_report["data"])) + case _: + _LOGGER.error(f"Unknown command: {state_report['cmdId']}") + + self._async_notify() + + def _async_notify(self) -> None: + """Notify all listeners that data has been updated.""" + for listener in self._listeners: + listener() + + async def _async_control(self, new_status: AirWaterDeviceStatus) -> None: + await self.async_send_command(AirWaterCommand.CONTROL, new_status.as_command_data) + + async def _async_set(self, new_settings: AirWaterDeviceSettings) -> None: + await self.async_send_command(AirWaterCommand.SET, new_settings.as_command_data) + + async def _async_subscribe_for_updates(self, _: datetime | None = None) -> None: + self._async_notify() + + if self._mqttc.connected: + await self.async_send_command( + AirWaterCommand.GET_STATUS, + { + "cleanTime": self._settings.water_type.cleaning_time, + "water_type": int(self._settings.water_type), + "frequencyTime": UPDATE_INTERVAL, + "durationTime": UPDATE_DURATION, + }, + ) + + async def _async_handle_new_status(self, data: CommandData) -> None: + self._status = AirWaterDeviceStatus.from_command_data(data) + await self._async_update_settings(self.settings.with_changes(target_humidity=self._status.target_humidity)) + + async def _async_handle_new_settings(self, data: CommandData) -> None: + await self._async_update_settings(AirWaterDeviceSettings.from_command_data(data)) + + async def _async_update_settings(self, settings: AirWaterDeviceSettings) -> None: + if self._settings != settings: + self._settings = settings + self._settings_store.async_delay_save(lambda: dataclasses.asdict(self._settings), 10) + + async def _async_load_settings(self) -> AirWaterDeviceSettings: + if (restored := await self._settings_store.async_load()) is None: + return AirWaterDeviceSettings() + + return AirWaterDeviceSettings.from_dict(restored) + + def _get_signed_command(self, command: AirWaterCommand, data: CommandData) -> bytes: + def _dump(v: Any) -> str: + return json.dumps(v, separators=(",", ":")) + + cmd: CommandType = {"cmdId": int(command), "time": int(datetime.now().timestamp()), "data": data} + + to_sign = _dump(cmd)[1:-1] + cmd["sig"] = hashlib.md5(f"{to_sign},{self._sign_key}".encode()).hexdigest() + + return _dump(cmd).encode() diff --git a/custom_components/airmx/binary_sensor.py b/custom_components/airmx/binary_sensor.py new file mode 100644 index 0000000..4a82c74 --- /dev/null +++ b/custom_components/airmx/binary_sensor.py @@ -0,0 +1,65 @@ +from homeassistant.components.binary_sensor import ( + BinarySensorDeviceClass, + BinarySensorEntity, + BinarySensorEntityDescription, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import EntityCategory +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .airwater.device import AirWaterDevice +from .const import ATTR_MALFUNCTION, ATTR_NEED_CLEANING, ATTR_UV, DEVICES, DOMAIN +from .entity import AirWaterEntity + +BINARY_SENSOR_TYPES = ( + BinarySensorEntityDescription( + key=ATTR_UV, + translation_key=ATTR_UV, + icon="mdi:lightbulb", + entity_category=EntityCategory.DIAGNOSTIC, + ), + BinarySensorEntityDescription( + key=ATTR_NEED_CLEANING, + translation_key=ATTR_NEED_CLEANING, + icon="mdi:hand-wash-outline", + device_class=BinarySensorDeviceClass.PROBLEM, + entity_category=EntityCategory.DIAGNOSTIC, + ), + BinarySensorEntityDescription( + key=ATTR_MALFUNCTION, + translation_key=ATTR_MALFUNCTION, + icon="mdi:alert-outline", + device_class=BinarySensorDeviceClass.PROBLEM, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + device: AirWaterDevice = hass.data[DOMAIN][DEVICES][entry.entry_id] + entities: list[BinarySensorEntity] = [] + + for description in BINARY_SENSOR_TYPES: + entities.append(AirWaterGenericBinarySensor(device, entry, description)) + + async_add_entities(entities) + + +class AirWaterGenericBinarySensor(AirWaterEntity, BinarySensorEntity): + def __init__(self, device: AirWaterDevice, entry: ConfigEntry, description: BinarySensorEntityDescription) -> None: + super().__init__(device, entry) + self.entity_description = description + + @property + def unique_id(self) -> str: + return f"{super().unique_id}_{self.entity_description.key}" + + @property + def is_on(self) -> bool | None: + return bool(getattr(self._device.status, self.entity_description.key)) diff --git a/custom_components/airmx/config_flow.py b/custom_components/airmx/config_flow.py new file mode 100644 index 0000000..b70ae47 --- /dev/null +++ b/custom_components/airmx/config_flow.py @@ -0,0 +1,202 @@ +from dataclasses import dataclass +import logging +from typing import Self + +from bleak import BLEDevice +from homeassistant import data_entry_flow +from homeassistant.components import bluetooth +from homeassistant.config_entries import ConfigFlow +from homeassistant.const import CONF_DEVICE, CONF_ID, CONF_MODEL, CONF_PASSWORD +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.device_registry import format_mac +from homeassistant.helpers.selector import SelectOptionDict, SelectSelector, SelectSelectorConfig, SelectSelectorMode +from homeassistant.helpers.typing import ConfigType +import voluptuous as vol + +from .airwater.ble import AirWaterBLEConnector +from .airwater.const import AirWaterModel +from .const import CONF_MQTT_HOST, CONF_MQTT_PORT, CONF_SIGN_KEY, CONF_SSID, DOMAIN + +_LOGGER = logging.getLogger(__name__) + +ADDON_HOSTNAME = "a06532c7-airmx-addon" +ADDON_MQTT_PORT = 25883 + + +@dataclass +class AirWaterBLEDevice: + model: AirWaterModel + device: BLEDevice + + @property + def address(self) -> str: + return self.device.address + + +@dataclass +class AirWaterDeviceInfo: + id: int + ble_mac: str + sign_key: str + model: AirWaterModel | None = None + + @classmethod + def from_dict(cls, data: ConfigType) -> Self: + return cls(id=data["id"], sign_key=data["key"], ble_mac=format_mac(data["ble_mac"]).upper()) + + @property + def name(self) -> str: + if self.model: + return f"{self.ble_mac} ({self.model.human_readable})" + + return self.ble_mac + + +class FlowHandler(ConfigFlow, domain=DOMAIN): + def __init__(self) -> None: + self._registered_devices: dict[int, AirWaterDeviceInfo] = {} + self._discovered_devices: dict[str, AirWaterBLEDevice] = {} + self._data: ConfigType = {} + + for ble_device in bluetooth.async_get_scanner(self.hass).discovered_devices: + if ble_device.name is not None: + try: + device = AirWaterBLEDevice(model=AirWaterModel(ble_device.name), device=ble_device) + self._discovered_devices[device.address] = device + except ValueError: + pass + + async def async_step_user(self, user_input: ConfigType | None = None) -> data_entry_flow.FlowResult: + return self.async_show_menu(step_id="user", menu_options=["addon", "manual", "bind_ap"]) + + async def async_step_addon(self, user_input: ConfigType | None = None) -> data_entry_flow.FlowResult: + if user_input is not None: + self._data[CONF_ID] = int(user_input[CONF_ID]) + return await self.async_step_select_model() + + http = async_get_clientsession(self.hass) + try: + devices_response = await http.get(f"http://{ADDON_HOSTNAME}/_devices") + devices_response.raise_for_status() + devices: list[AirWaterDeviceInfo] = [AirWaterDeviceInfo.from_dict(d) for d in await devices_response.json()] + except Exception as e: + _LOGGER.exception(e) + return self.async_abort(reason="addon_connection_error") + + if not devices: + return self.async_abort(reason="wifi_device_not_found") + + options: list[SelectOptionDict] = [] + for device in devices: + if ble_device := self._discovered_devices.get(device.ble_mac): + device.model = ble_device.model + + self._registered_devices[device.id] = device + + options.append(SelectOptionDict(value=str(device.id), label=device.name)) + + schema = vol.Schema( + { + vol.Required(CONF_ID): SelectSelector( + SelectSelectorConfig(mode=SelectSelectorMode.LIST, options=options), + ) + } + ) + return self.async_show_form(step_id="addon", data_schema=schema) + + async def async_step_select_model(self, user_input: ConfigType | None = None) -> data_entry_flow.FlowResult: + device = self._registered_devices[self._data[CONF_ID]] + if user_input is not None: + device.model = AirWaterModel(user_input[CONF_MODEL]) + + if device.model: + self._data.update( + { + CONF_MODEL: device.model, + CONF_SIGN_KEY: device.sign_key, + CONF_MQTT_HOST: ADDON_HOSTNAME, + CONF_MQTT_PORT: ADDON_MQTT_PORT, + } + ) + return self._create_or_update_config_entry(self._data) + + schema = vol.Schema({vol.Required(CONF_MODEL): self._model_selector}) + return self.async_show_form( + step_id="select_model", + data_schema=schema, + description_placeholders={"device": device.name}, + ) + + async def async_step_manual(self, user_input: ConfigType | None = None) -> data_entry_flow.FlowResult: + if user_input is not None: + return self._create_or_update_config_entry(user_input) + + schema = vol.Schema( + { + vol.Required(CONF_MODEL): self._model_selector, + vol.Required(CONF_ID): cv.positive_int, + vol.Required(CONF_SIGN_KEY): cv.string, + vol.Required(CONF_MQTT_HOST, default=ADDON_HOSTNAME): cv.string, + vol.Required(CONF_MQTT_PORT, default=ADDON_MQTT_PORT): cv.positive_int, + } + ) + return self.async_show_form(step_id="manual", data_schema=schema) + + async def async_step_bind_ap(self, user_input: ConfigType | None = None) -> data_entry_flow.FlowResult: + devices: dict[str, BLEDevice] = {} + for device in bluetooth.async_get_scanner(self.hass).discovered_devices: + if device.name is not None: + try: + AirWaterModel(device.name) + devices[device.address] = device + except ValueError: + pass + + if not devices: + return self.async_abort(reason="ble_device_not_found") + + if user_input is not None: + try: + device = devices[user_input[CONF_DEVICE]] + except KeyError: + return self.async_abort(reason="ble_device_not_found") + + await AirWaterBLEConnector().bind_ap(device, user_input[CONF_SSID], user_input[CONF_PASSWORD]) + + return self.async_abort(reason="bind_ap_done") + + schema = vol.Schema( + { + vol.Required(CONF_DEVICE): SelectSelector( + SelectSelectorConfig( + mode=SelectSelectorMode.DROPDOWN, + options=[ + SelectOptionDict(value=d.address, label=f"{d.name}: {d.address}") for d in devices.values() + ], + ), + ), + vol.Required(CONF_SSID): cv.string, + vol.Required(CONF_PASSWORD): cv.string, + } + ) + return self.async_show_form(step_id="bind_ap", data_schema=schema) + + @property + def _model_selector(self) -> SelectSelector: + return SelectSelector( + SelectSelectorConfig( + mode=SelectSelectorMode.DROPDOWN, + options=[SelectOptionDict(value=m, label=m.human_readable) for m in AirWaterModel.__members__.values()], + ), + ) + + def _create_or_update_config_entry(self, data: ConfigType) -> data_entry_flow.FlowResult: + title = f"{data[CONF_MODEL]}: {data[CONF_ID]}" + + for entry in self.hass.config_entries.async_entries(DOMAIN): + if entry.data[CONF_ID] == data[CONF_ID]: + self.hass.config_entries.async_update_entry(entry, title=title, data=data) + return self.async_abort(reason="updated_entry") + + return self.async_create_entry(title=title, data=data) diff --git a/custom_components/airmx/const.py b/custom_components/airmx/const.py new file mode 100644 index 0000000..588524f --- /dev/null +++ b/custom_components/airmx/const.py @@ -0,0 +1,42 @@ +from homeassistant.const import Platform + +DOMAIN = "airmx" + +PLATFORMS = [ + Platform.BINARY_SENSOR, + Platform.HUMIDIFIER, + Platform.NUMBER, + Platform.SELECT, + Platform.SENSOR, + Platform.SWITCH, +] + +DEVICES = "devices" +SETTING_STORES = "settings_stores" + +CONF_MQTT_HOST = "mqtt_host" +CONF_MQTT_PORT = "mqtt_port" +CONF_SIGN_KEY = "sign_key" +CONF_SSID = "ssid" + +ATTR_ANION = "anion" +ATTR_CHILD_LOCK = "child_lock" +ATTR_COMMAND = "command" +ATTR_FAN_SPEED = "fan_speed" +ATTR_HEATER = "heater" +ATTR_HUMIDITY = "humidity" +ATTR_MALFUNCTION = "malfunction" +ATTR_NEED_CLEANING = "need_cleaning" +ATTR_PROXIMITY_SENSOR = "proximity_sensor" +ATTR_REMOTE_SENSOR_RSSI = "remote_sensor_rssi" +ATTR_STATUS = "status" +ATTR_UV = "uv" +ATTR_WATER_LEVEL = "water_level" +ATTR_WATER_TYPE = "water_type" +ATTR_WUD = "wud" + +MODE_MANUAL = "manual" + +SERVICE_SEND_COMMAND = "send_command" +ATTR_COMMAND_ID = "command_id" +ATTR_COMMAND_DATA = "command_data" diff --git a/custom_components/airmx/diagnostics.py b/custom_components/airmx/diagnostics.py new file mode 100644 index 0000000..1c9ff9f --- /dev/null +++ b/custom_components/airmx/diagnostics.py @@ -0,0 +1,16 @@ +from typing import Any + +from homeassistant.components.diagnostics import async_redact_data +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant + +from .airwater.device import AirWaterDevice +from .const import CONF_SIGN_KEY, DEVICES, DOMAIN + +TO_REDACT = {CONF_SIGN_KEY} + + +async def async_get_config_entry_diagnostics(hass: HomeAssistant, entry: ConfigEntry) -> dict[str, dict[str, Any]]: + device: AirWaterDevice = hass.data[DOMAIN][DEVICES][entry.entry_id] + data = {"entry": async_redact_data(entry.as_dict(), TO_REDACT), "last_state_report": device.last_state_report} + return data diff --git a/custom_components/airmx/entity.py b/custom_components/airmx/entity.py new file mode 100644 index 0000000..248bf7c --- /dev/null +++ b/custom_components/airmx/entity.py @@ -0,0 +1,35 @@ +from homeassistant.config_entries import ConfigEntry +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity import Entity + +from .airwater.device import AirWaterDevice +from .const import DOMAIN + + +class AirWaterEntity(Entity): + _attr_should_poll = False + _attr_has_entity_name = True + + def __init__(self, device: AirWaterDevice, entry: ConfigEntry) -> None: + self._device = device + self._entry = entry + + @property + def unique_id(self) -> str: + return f"airwater_{self._device.id}" + + @property + def available(self) -> bool: + return self._device.available + + @property + def device_info(self) -> DeviceInfo | None: + return DeviceInfo( + identifiers={(DOMAIN, f"airwater_{self._device.id}")}, + name=self._device.name, + manufacturer="AIRMX", + model=self._device.model.human_readable, + ) + + async def async_added_to_hass(self) -> None: + self.async_on_remove(self._device.async_add_listener(self.async_write_ha_state)) diff --git a/custom_components/airmx/humidifier.py b/custom_components/airmx/humidifier.py new file mode 100644 index 0000000..d70b3ae --- /dev/null +++ b/custom_components/airmx/humidifier.py @@ -0,0 +1,114 @@ +import json +import logging +from typing import Any + +from homeassistant.components.humidifier import ( + MODE_AUTO, + MODE_NORMAL, + HumidifierDeviceClass, + HumidifierEntity, + HumidifierEntityFeature, +) +from homeassistant.components.humidifier.const import MODE_SLEEP +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import ATTR_ENTITY_ID +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import config_validation as cv, device_registry as dr, entity_platform +from homeassistant.helpers.entity_platform import AddEntitiesCallback +import voluptuous as vol + +from .airwater.const import AirWaterCommand, AirWaterMode +from .airwater.device import AirWaterDevice +from .const import ATTR_COMMAND_DATA, ATTR_COMMAND_ID, DEVICES, DOMAIN, MODE_MANUAL, SERVICE_SEND_COMMAND +from .entity import AirWaterEntity + +_LOGGER = logging.getLogger(__name__) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + device: AirWaterDevice = hass.data[DOMAIN][DEVICES][entry.entry_id] + async_add_entities([AirWaterHumidifier(device, entry)]) + + platform = entity_platform.async_get_current_platform() + platform.async_register_entity_service( + SERVICE_SEND_COMMAND, + vol.Schema( + { + vol.Required(ATTR_ENTITY_ID): cv.entity_id, + vol.Required(ATTR_COMMAND_ID): vol.Coerce(int), + vol.Required(ATTR_COMMAND_DATA): cv.string, + } + ), + "async_send_command", + ) + + +class AirWaterHumidifier(AirWaterEntity, HumidifierEntity): + _attr_name = None + _attr_device_class = HumidifierDeviceClass.HUMIDIFIER + _attr_supported_features = HumidifierEntityFeature.MODES + _attr_available_modes = [MODE_AUTO, MODE_MANUAL, MODE_SLEEP] + _attr_translation_key = "humidifier" + + @property + def is_on(self) -> bool | None: + return self._device.status.power + + @property + def current_humidity(self) -> int | None: + for value in [self._device.status.remote_sensor_humidity, self._device.status.internal_sensor_humidity]: + if value is not None: + return int(value) + + return None + + @property + def target_humidity(self) -> int | None: + if self.mode == MODE_MANUAL: + return None + + return self._device.status.target_humidity + + @property + def mode(self) -> str | None: + return { + AirWaterMode.SLEEP: MODE_SLEEP, + AirWaterMode.MANUAL: MODE_NORMAL, + }.get(self._device.status.mode, MODE_AUTO) + + async def async_turn_on(self, **kwargs: Any) -> None: + await self._device.async_turn_on() + + async def async_turn_off(self, **kwargs: Any) -> None: + await self._device.async_turn_off() + + async def async_set_humidity(self, humidity: int) -> None: + await self._device.async_set_target_humidity(humidity) + + async def async_set_mode(self, mode: str) -> None: + await self._device.async_set_mode( + { + MODE_SLEEP: AirWaterMode.SLEEP, + MODE_NORMAL: AirWaterMode.MANUAL, + }.get(mode, AirWaterMode.AUTO) + ) + + async def async_send_command(self, command_id: int, command_data: str) -> None: + await self._device.async_send_command(AirWaterCommand(command_id), json.loads(command_data)) + + @callback + def async_write_ha_state(self) -> None: + super().async_write_ha_state() + + if self.device_info and self.device_info.get("sw_version") != self._device.status.firmware_version: + self._update_device_info() + + def _update_device_info(self) -> None: + device_registry = dr.async_get(self.hass) + device = device_registry.async_get_device({(DOMAIN, self.unique_id)}) + if device: + device_registry.async_update_device(device.id, sw_version=self._device.status.firmware_version) diff --git a/custom_components/airmx/manifest.json b/custom_components/airmx/manifest.json new file mode 100644 index 0000000..36e8051 --- /dev/null +++ b/custom_components/airmx/manifest.json @@ -0,0 +1,12 @@ +{ + "domain": "airmx", + "name": "AIRMX", + "codeowners": ["@dext0r"], + "config_flow": true, + "dependencies": ["bluetooth_adapters"], + "documentation": "https://github.com/dext0r/airmx", + "integration_type": "device", + "iot_class": "local_push", + "requirements": ["paho-mqtt"], + "version": "0.0.1.dev1" +} diff --git a/custom_components/airmx/mqtt/client.py b/custom_components/airmx/mqtt/client.py new file mode 100644 index 0000000..6d7e3a8 --- /dev/null +++ b/custom_components/airmx/mqtt/client.py @@ -0,0 +1,107 @@ +import asyncio +import logging +from typing import Any, Coroutine + +from homeassistant.core import HassJob, HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError +import paho.mqtt.client as mqtt + +_LOGGER = logging.getLogger(__name__) + + +class MQTTClient: + def __init__( + self, + hass: HomeAssistant, + host: str, + port: int = 1883, + username: str | None = None, + password: str | None = None, + ): + self._hass = hass + self._client = mqtt.Client() + self._client.on_connect = self._mqtt_on_connect + self._client.on_message = self._mqtt_on_message + self._client.on_disconnect = self._mqtt_on_disconnect + self._host = host + self._port = port + self._lock = asyncio.Lock() + + self.subscribe_topics: list[str] = [] + self.on_message: HassJob[[mqtt.MQTTMessage], Coroutine[Any, Any, None] | None] | None = None + self.on_connect: HassJob[[], Coroutine[Any, Any, None] | None] | None = None + self.on_disconnect: HassJob[[], Coroutine[Any, Any, None] | None] | None = None + + if username and password: + self._client.username_pw_set(username, password) + + async def async_connect(self) -> None: + result: int | None = None + + try: + result = await self._hass.async_add_executor_job(self._client.connect, self._host, self._port) + except OSError as err: + _LOGGER.error(f"Failed to connect to MQTT server due to exception: {err}") + + if result is not None and result != 0: + _LOGGER.error("Failed to connect to MQTT server: %s", mqtt.error_string(result)) + + self._client.loop_start() + + async def async_disconnect(self) -> None: + async with self._lock: + await self._hass.async_add_executor_job(lambda: self._client.disconnect()) + + async def async_publish(self, topic: str, payload: bytes) -> None: + async with self._lock: + msg_info = await self._hass.async_add_executor_job(self._client.publish, topic, payload) + + _LOGGER.debug(f"Transmitting message on {topic}: {payload!r}") + self._raise_on_error(msg_info.rc) + + @property + def connected(self) -> bool: + return self._client.is_connected() + + def _mqtt_on_connect( + self, + _mqttc: mqtt.Client, + _userdata: None, + _flags: dict[str, int], + result_code: int, + _properties: mqtt.Properties | None = None, + ) -> None: + _LOGGER.info(f"Connected to MQTT server ({result_code})") + + for topic in self.subscribe_topics: + _LOGGER.info(f"Subscribe to {topic}") + self._client.subscribe(topic) + + if self.on_connect: + self._hass.async_run_hass_job(self.on_connect) + + def _mqtt_on_disconnect( + self, + _mqttc: mqtt.Client, + _userdata: None, + result_code: int, + _properties: mqtt.Properties | None = None, + ) -> None: + _LOGGER.info(f"Disconnected from MQTT server ({result_code})") + + if self.on_disconnect: + self._hass.async_run_hass_job(self.on_disconnect) + + def _mqtt_on_message(self, _mqttc: mqtt.Client, _userdata: None, msg: mqtt.MQTTMessage) -> None: + self._hass.loop.call_soon_threadsafe(self._mqtt_handle_message, msg) + + @callback + def _mqtt_handle_message(self, msg: mqtt.MQTTMessage) -> None: + _LOGGER.debug(f"Received from MQTT: {msg.payload!r}") + if self.on_message: + self._hass.async_run_hass_job(self.on_message, msg) + + @staticmethod + def _raise_on_error(result_code: int) -> None: + if result_code and (message := mqtt.error_string(result_code)): + raise HomeAssistantError(f"Error talking to MQTT: {message}") diff --git a/custom_components/airmx/number.py b/custom_components/airmx/number.py new file mode 100644 index 0000000..6f1fe90 --- /dev/null +++ b/custom_components/airmx/number.py @@ -0,0 +1,38 @@ +from homeassistant.components.number import NumberEntity +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import PERCENTAGE +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .airwater.device import AirWaterDevice +from .const import ATTR_FAN_SPEED, DEVICES, DOMAIN +from .entity import AirWaterEntity + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + device: AirWaterDevice = hass.data[DOMAIN][DEVICES][entry.entry_id] + async_add_entities([AirWaterFanSpeedEntity(device, entry)]) + + +class AirWaterFanSpeedEntity(AirWaterEntity, NumberEntity): + _attr_translation_key = ATTR_FAN_SPEED + _attr_icon = "mdi:fan" + _attr_native_unit_of_measurement = PERCENTAGE + _attr_native_min_value = 0 + _attr_native_max_value = 100 + _attr_native_step = 1 + + @property + def unique_id(self) -> str: + return f"{super().unique_id}_{self._attr_translation_key}" + + @property + def native_value(self) -> float: + return self._device.status.fan_speed + + async def async_set_native_value(self, value: float) -> None: + await self._device.async_set_fan_speed(int(value)) diff --git a/custom_components/airmx/select.py b/custom_components/airmx/select.py new file mode 100644 index 0000000..be6bbe5 --- /dev/null +++ b/custom_components/airmx/select.py @@ -0,0 +1,51 @@ +from homeassistant.components.select import SelectEntity +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import EntityCategory +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .airwater.const import WaterType as AirWaterWaterType +from .airwater.device import AirWaterDevice +from .const import ATTR_WATER_TYPE, DEVICES, DOMAIN +from .entity import AirWaterEntity + +WATER_TYPE_TAP = "tap" +WATER_TYPE_FILTERED = "filtered" + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + device: AirWaterDevice = hass.data[DOMAIN][DEVICES][entry.entry_id] + async_add_entities([AirWaterWaterTypeEntity(device, entry)]) + + +class AirWaterWaterTypeEntity(AirWaterEntity, SelectEntity): + _attr_translation_key = ATTR_WATER_TYPE + _attr_icon = "mdi:hand-water" + _attr_entity_category = EntityCategory.CONFIG + + @property + def unique_id(self) -> str: + return f"{super().unique_id}_{self._attr_translation_key}" + + @property + def current_option(self) -> str | None: + return { + AirWaterWaterType.TAP: WATER_TYPE_TAP, + AirWaterWaterType.FILTERED: WATER_TYPE_FILTERED, + }[self._device.settings.water_type] + + @property + def options(self) -> list[str]: + return [WATER_TYPE_TAP, WATER_TYPE_FILTERED] + + async def async_select_option(self, option: str) -> None: + await self._device.async_set_water_type( + { + WATER_TYPE_TAP: AirWaterWaterType.TAP, + WATER_TYPE_FILTERED: AirWaterWaterType.FILTERED, + }[option] + ) diff --git a/custom_components/airmx/sensor.py b/custom_components/airmx/sensor.py new file mode 100644 index 0000000..1e567b6 --- /dev/null +++ b/custom_components/airmx/sensor.py @@ -0,0 +1,125 @@ +from dataclasses import asdict +from typing import Any, Mapping, cast + +from homeassistant.components.sensor import SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import ( + ATTR_TEMPERATURE, + PERCENTAGE, + SIGNAL_STRENGTH_DECIBELS_MILLIWATT, + EntityCategory, + UnitOfTemperature, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .airwater.device import AirWaterDevice +from .const import ATTR_REMOTE_SENSOR_RSSI, ATTR_STATUS, ATTR_WATER_LEVEL, ATTR_WUD, DEVICES, DOMAIN +from .entity import AirWaterEntity + +SENSOR_TYPES = ( + SensorEntityDescription( + key=ATTR_REMOTE_SENSOR_RSSI, + translation_key=ATTR_REMOTE_SENSOR_RSSI, + native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, + device_class=SensorDeviceClass.SIGNAL_STRENGTH, + state_class=SensorStateClass.MEASUREMENT, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + ), + SensorEntityDescription( + key=ATTR_WATER_LEVEL, + translation_key=ATTR_WATER_LEVEL, + native_unit_of_measurement=PERCENTAGE, + icon="mdi:cup-water", + state_class=SensorStateClass.MEASUREMENT, + entity_category=EntityCategory.DIAGNOSTIC, + ), + SensorEntityDescription( + key=ATTR_WUD, + translation_key=ATTR_WUD, + icon="mdi:liquid-spot", + state_class=SensorStateClass.MEASUREMENT, + entity_category=EntityCategory.DIAGNOSTIC, + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + device: AirWaterDevice = hass.data[DOMAIN][DEVICES][entry.entry_id] + entities: list[SensorEntity] = [ + AirWaterTemperatureSensor(device, entry), + AirWaterStatusSensor(device, entry), + ] + + for description in SENSOR_TYPES: + entities.append(AirWaterGenericSensor(device, entry, description)) + + async_add_entities(entities) + + +class AirWaterGenericSensor(AirWaterEntity, SensorEntity): + def __init__(self, device: AirWaterDevice, entry: ConfigEntry, description: SensorEntityDescription) -> None: + super().__init__(device, entry) + self.entity_description = description + + @property + def unique_id(self) -> str: + return f"{super().unique_id}_{self.entity_description.key}" + + @property + def native_value(self) -> int: + return cast(int, getattr(self._device.status, self.entity_description.key)) + + +class AirWaterTemperatureSensor(AirWaterEntity, SensorEntity): + entity_description = SensorEntityDescription( + key=ATTR_TEMPERATURE, + translation_key=ATTR_TEMPERATURE, + native_unit_of_measurement=UnitOfTemperature.CELSIUS, + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ) + + @property + def unique_id(self) -> str: + return f"{super().unique_id}_{self.entity_description.key}" + + @property + def native_value(self) -> float | None: + for value in [self._device.status.remote_sensor_temperature, self._device.status.internal_sensor_temperature]: + if value is not None: + return round(value, 1) + + return None + + +class AirWaterStatusSensor(AirWaterEntity, SensorEntity): + entity_description = SensorEntityDescription( + key=ATTR_STATUS, + translation_key=ATTR_STATUS, + icon="mdi:information-outline", + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + ) + + @property + def unique_id(self) -> str: + return f"{super().unique_id}_{self.entity_description.key}" + + @property + def native_value(self) -> str: + return "" + + @property + def extra_state_attributes(self) -> Mapping[str, Any] | None: + attrs = {} + for prefix, data in (("status", self._device.status), ("settings", self._device.settings)): + for key, value in asdict(data).items(): # type: ignore + attrs[f"{prefix}.{key}"] = value + + return attrs diff --git a/custom_components/airmx/services.yaml b/custom_components/airmx/services.yaml new file mode 100644 index 0000000..85180e5 --- /dev/null +++ b/custom_components/airmx/services.yaml @@ -0,0 +1,17 @@ +send_command: + fields: + entity_id: + required: true + selector: + entity: + integration: airmx + domain: humidifier + command_id: + required: true + selector: + text: + type: number + command_data: + required: true + selector: + text: diff --git a/custom_components/airmx/switch.py b/custom_components/airmx/switch.py new file mode 100644 index 0000000..e716518 --- /dev/null +++ b/custom_components/airmx/switch.py @@ -0,0 +1,125 @@ +from dataclasses import dataclass +import logging +from typing import Any + +from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import EntityCategory +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .airwater.const import AirWaterFeature +from .airwater.device import AirWaterDevice +from .const import ATTR_ANION, ATTR_CHILD_LOCK, ATTR_HEATER, ATTR_PROXIMITY_SENSOR, DEVICES, DOMAIN +from .entity import AirWaterEntity + +_LOGGER = logging.getLogger(__name__) + + +@dataclass +class AirWaterSwitchDescriptionMixin: + feature: int | None + setting: bool + method_on: str + method_off: str + icon_on: str + icon_off: str + + +@dataclass +class AirWaterSwitchDescription(SwitchEntityDescription, AirWaterSwitchDescriptionMixin): + ... + + +SWITCH_TYPES = ( + AirWaterSwitchDescription( + key=ATTR_ANION, + translation_key=ATTR_ANION, + icon_on="mdi:atom", + icon_off="mdi:atom", + feature=None, + setting=False, + method_on="async_set_anion_on", + method_off="async_set_anion_off", + entity_category=EntityCategory.CONFIG, + ), + AirWaterSwitchDescription( + key=ATTR_CHILD_LOCK, + translation_key=ATTR_CHILD_LOCK, + icon_on="mdi:lock-outline", + icon_off="mdi:lock-open-outline", + feature=None, + setting=False, + method_on="async_set_child_lock_on", + method_off="async_set_child_lock_off", + entity_category=EntityCategory.CONFIG, + ), + AirWaterSwitchDescription( + key=ATTR_HEATER, + translation_key=ATTR_HEATER, + icon_on="mdi:radiator", + icon_off="mdi:radiator-off", + feature=AirWaterFeature.HEATER, + setting=True, + method_on="async_set_heater_on", + method_off="async_set_heater_off", + entity_category=EntityCategory.CONFIG, + ), + AirWaterSwitchDescription( + key=ATTR_PROXIMITY_SENSOR, + translation_key=ATTR_PROXIMITY_SENSOR, + icon_on="mdi:motion-sensor", + icon_off="mdi:motion-sensor-off", + feature=None, + setting=True, + method_on="async_set_proximity_sensor_on", + method_off="async_set_proximity_sensor_off", + entity_category=EntityCategory.CONFIG, + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + device: AirWaterDevice = hass.data[DOMAIN][DEVICES][entry.entry_id] + entities: list[SwitchEntity] = [] + + for description in SWITCH_TYPES: + if description.feature is None or bool(device.model.features & description.feature): + entities.append(AirWaterGenericSwitch(device, entry, description)) + + async_add_entities(entities) + + +class AirWaterGenericSwitch(AirWaterEntity, SwitchEntity): + entity_description: AirWaterSwitchDescription + + def __init__(self, device: AirWaterDevice, entry: ConfigEntry, description: AirWaterSwitchDescription) -> None: + super().__init__(device, entry) + self.entity_description = description + + @property + def unique_id(self) -> str: + return f"{super().unique_id}_{self.entity_description.key}" + + @property + def is_on(self) -> bool | None: + if self.entity_description.setting: + return bool(getattr(self._device.settings, self.entity_description.key)) + + return bool(getattr(self._device.status, self.entity_description.key)) + + @property + def icon(self) -> str: + return self.entity_description.icon_on if self.is_on else self.entity_description.icon_off + + async def async_turn_on(self, **kwargs: Any) -> None: + method = getattr(self._device, self.entity_description.method_on) + await method() + + async def async_turn_off(self, **kwargs: Any) -> None: + method = getattr(self._device, self.entity_description.method_off) + await method() diff --git a/custom_components/airmx/translations/en.json b/custom_components/airmx/translations/en.json new file mode 100644 index 0000000..ed2e974 --- /dev/null +++ b/custom_components/airmx/translations/en.json @@ -0,0 +1,132 @@ +{ + "config": { + "abort": { + "addon_connection_error": "Failed to get devices from AIRMX addon", + "wifi_device_not_found": "Device was not found during discovery, check the AIRMX addon logs", + "ble_device_not_found": "Device was not found during BLE discovery, please try again later", + "bind_ap_done": "Binding to the Access Point completed", + "updated_entry": "Device configuration updated" + }, + "step": { + "user": { + "menu_options": { + "addon": "Automatic setup (AIRMX addon required)", + "manual": "Manual setup", + "bind_ap": "Bind device to the Access Point" + } + }, + "addon": { + "title": "Select device" + }, + "select_model": { + "title": "Select model", + "description": "Select model of device {device}", + "data": { + "model": "Model" + } + }, + "manual": { + "title": "Manual setup", + "data": { + "model": "Model", + "id": "ID", + "sign_key": "Key", + "mqtt_host": "MQTT host", + "mqtt_port": "MQTT port" + } + }, + "bind_ap": { + "title": "Bind device to AP", + "data": { + "device": "Device", + "ssid": "SSID", + "password": "Password" + } + } + } + }, + "entity": { + "binary_sensor": { + "need_cleaning": { + "name": "Need cleaning" + }, + "uv": { + "name": "UV sterilization" + }, + "malfunction": { + "name": "Malfunction" + } + }, + "humidifier": { + "humidifier": { + "state_attributes": { + "mode": { + "state": { + "manual": "Manual" + } + } + } + } + }, + "number": { + "fan_speed": { + "name": "Fan speed" + } + }, + "select": { + "water_type": { + "name": "Water type", + "state": { + "tap": "Tap", + "filtered": "Filtered" + } + } + }, + "sensor": { + "remote_sensor_rssi": { + "name": "Remote sensor RSSI" + }, + "status": { + "name": "Status" + }, + "water_level": { + "name": "Water level" + }, + "wud": { + "name": "WUD" + } + }, + "switch": { + "anion": { + "name": "Ionization" + }, + "child_lock": { + "name": "Child lock" + }, + "heater": { + "name": "Heater" + }, + "proximity_sensor": { + "name": "Proximity sensor" + } + } + }, + "services": { + "send_command": { + "name": "Send command", + "description": "Send any commmand to a humidifier. For debug purposes only.", + "fields": { + "entity_id": { + "name": "Entity ID", + "description": "Name of the airmx entity." + }, + "id": { + "name": "Command ID" + }, + "data": { + "name": "Command data" + } + } + } + } +} diff --git a/custom_components/airmx/translations/ru.json b/custom_components/airmx/translations/ru.json new file mode 100644 index 0000000..f442bed --- /dev/null +++ b/custom_components/airmx/translations/ru.json @@ -0,0 +1,114 @@ +{ + "config": { + "abort": { + "addon_connection_error": "Ошибка получения списка устройства от аддона AIRMX", + "wifi_device_not_found": "Устройство не найдено, проверьте журналы аддона AIRMX", + "ble_device_not_found": "Устройство не найдено во время BLE обнаружения, попробуйте ещё раз позже", + "bind_ap_done": "Привязка к точке доступа выполнена успешно", + "updated_entry": "Конфигурация устройства обновлена" + }, + "step": { + "user": { + "menu_options": { + "addon": "Автоматическая настройка (требуется аддон AIRMX)", + "manual": "Ручная настройка", + "bind_ap": "Привязать устройство к точке доступа" + } + }, + "addon": { + "title": "Выберите устройство" + }, + "select_model": { + "title": "Выберите модель", + "description": "Выберите модель устройства {device}", + "data": { + "model": "Модель" + } + }, + "manual": { + "title": "Ручная настройка", + "data": { + "model": "Модель", + "id": "ID", + "sign_key": "Ключ", + "mqtt_host": "Хост MQTT", + "mqtt_port": "Порт MQTT" + } + }, + "bind_ap": { + "title": "Привязка к точке доступа", + "data": { + "device": "Устройство", + "ssid": "SSID", + "password": "Пароль" + } + } + } + }, + "entity": { + "binary_sensor": { + "need_cleaning": { + "name": "Требуется очистка" + }, + "uv": { + "name": "УФ стерилизация" + }, + "malfunction": { + "name": "Неисправность" + } + }, + "humidifier": { + "humidifier": { + "state_attributes": { + "mode": { + "state": { + "manual": "Ручной" + } + } + } + } + }, + "number": { + "fan_speed": { + "name": "Скорость вентилятора" + } + }, + "select": { + "water_type": { + "name": "Тип воды", + "state": { + "tap": "Обычная", + "filtered": "Фильтрованная" + } + } + }, + "sensor": { + "remote_sensor_rssi": { + "name": "Уровень сигнала выносного датчика" + }, + "status": { + "name": "Состояние" + }, + "water_level": { + "name": "Уровень воды" + }, + "wud": { + "name": "WUD" + } + }, + "switch": { + "anion": { + "name": "Ионизация" + }, + "child_lock": { + "name": "Блокировка управления" + }, + "heater": { + "name": "Нагреватель" + }, + "proximity_sensor": { + "name": "Датчик приближения" + } + } + } +} diff --git a/hacs.json b/hacs.json new file mode 100644 index 0000000..a1c0d5a --- /dev/null +++ b/hacs.json @@ -0,0 +1,7 @@ +{ + "homeassistant": "2023.11", + "name": "AIRMX", + "render_readme": true, + "zip_release": true, + "filename": "airmx.zip" +} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..50afb82 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,30 @@ +[tool.black] +line-length = 120 + +[tool.ruff] +line-length = 120 + +[tool.isort] +profile = "black" +line_length = 120 +force_sort_within_sections = true +combine_as_imports = true +known_first_party = ["custom_components.airmx"] +skip_glob = [".venv*/*"] + +[tool.mypy] +python_version = 3.11 +follow_imports_for_stubs = true +local_partial_types = true +strict_equality = true +warn_redundant_casts = true +warn_unused_ignores = true +check_untyped_defs = true +disallow_incomplete_defs = true +disallow_subclassing_any = true +disallow_any_generics = true +disallow_untyped_calls = true +disallow_untyped_decorators = true +disallow_untyped_defs = true +warn_return_any = true +warn_unreachable = true diff --git a/repository.yaml b/repository.yaml new file mode 100644 index 0000000..08d9468 --- /dev/null +++ b/repository.yaml @@ -0,0 +1,3 @@ +name: AIRMX +url: https://github.com/dext0r/airmx +maintainer: '@dext0r' diff --git a/requirements_dev.txt b/requirements_dev.txt new file mode 100644 index 0000000..b95fe81 --- /dev/null +++ b/requirements_dev.txt @@ -0,0 +1,7 @@ +mypy==1.7.1 +ruff==0.1.6 +isort==5.12.0 +black==23.11.0 + +types-paho-mqtt==1.6.0.7 +voluptuous-stubs==0.1.1