/*
  xdrv_74_esp32_thread.ino - Thread network support for Tasmota

  Copyright (C) 2026  ricolehn

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifdef ESP32
#ifdef USE_THREAD
/*********************************************************************************************\
 * Thread (IEEE 802.15.4) network support for ESP32-C6 and ESP32-C5
 *
 * The device joins an existing Thread network. It needs the Active Operational Dataset of that
 * network as hex string, as exported by the Thread Border Router (Home Assistant: Settings -
 * System - Network - Thread, or `ot-ctl dataset active -x` on an OpenThread Border Router).
 *
 * While Wi-Fi is enabled, Thread runs alongside as end device. After `Wifi 0` Thread is the network
 * of the device: webserver and Matter are reachable over Thread (IPv6 only), and the device may
 * become a router of the Thread mesh. Switching between both takes a restart.
 *
 * Matter announces its services by SRP to the Border Router, see Berry module `thread`.
 *
 * Thread               - Show Thread state
 * ThreadDataset <hex>  - Store the Active Operational Dataset and restart
 * ThreadDataset 0      - Erase the Thread network credentials and restart
\*********************************************************************************************/

#define XDRV_74                    74

#ifndef CONFIG_OPENTHREAD_ENABLED
#error "USE_THREAD needs a framework with OpenThread, see [thread_flags] in platformio_tasmota32.ini"
#endif
#ifndef USE_IPV6
#error "USE_THREAD needs USE_IPV6"
#endif

#include "esp_coexist.h"
#include "esp_openthread.h"
#include "esp_openthread_lock.h"
#include "esp_openthread_netif_glue.h"
#include "esp_vfs_eventfd.h"
#include "openthread/dataset.h"
#include "openthread/instance.h"
#include "openthread/ip6.h"
#include "openthread/link.h"
#include "openthread/logging.h"
#include "openthread/srp_client.h"
#include "openthread/srp_client_buffers.h"
#include "openthread/thread.h"
#include "openthread/thread_ftd.h"

// OpenThread runs in its own task. Other tasks call its API only while holding its lock.
const TickType_t THREAD_LOCK_TICKS = pdMS_TO_TICKS(500);

struct {
  // Copy of the OpenThread state, updated every second
  otIp6Address ip6_global;                   // Off-mesh routable address, reachable from the home network
  otIp6Address ip6_mesh;                     // Mesh-local EID
  otIp6Address ip6_local;                    // Link-local address
  otExtAddress ext_address;
  otExtendedPanId ext_pan_id;
  char network_name[OT_NETWORK_NAME_MAX_SIZE +1];
  uint16_t pan_id;
  uint16_t rloc16;
  uint8_t channel;
  otDeviceRole role;
  otSrpClientItemState srp_state;
  bool commissioned;                         // Active Operational Dataset is present

  otError srp_error;                         // Last SRP update error, set by the OpenThread task
  volatile esp_err_t stop_error;             // Set when the OpenThread task stopped
  volatile bool running;                     // OpenThread task runs
  bool network;                              // Thread is the network of the device (Wi-Fi disabled at start)
} Thread;

/*********************************************************************************************/

void ThreadTask(void *arg) {
  Thread.stop_error = esp_openthread_launch_mainloop();  // Returns on a fatal error only
  Thread.running = false;
  vTaskDelete(nullptr);
}

void ThreadStart(void) {
  // Configure OpenThread and join the network. Runs before the OpenThread task starts.
  esp_openthread_lock_acquire(portMAX_DELAY);
  otInstance *ot = esp_openthread_get_instance();
#if CONFIG_OPENTHREAD_LOG_LEVEL_DYNAMIC
  otLoggingSetLevel(CONFIG_LOG_DEFAULT_LEVEL);
#endif

  // Matter uses the extended address in hex as host name
  uint16_t size;
  char *host_name = otSrpClientBuffersGetHostNameString(ot, &size);
  ToHex_P(otLinkGetExtendedAddress(ot)->m8, OT_EXT_ADDRESS_SIZE, host_name, size);
  otSrpClientSetHostName(ot, host_name);
  otSrpClientEnableAutoHostAddress(ot);
  otSrpClientSetCallback(ot, [](otError error, const otSrpClientHostInfo *, const otSrpClientService *, const otSrpClientService *removed, void *) {
    Thread.srp_error = error;
    while (removed) {                        // Services removed by thread.srp_remove() are done now
      const otSrpClientService *next = removed->mNext;
      otSrpClientBuffersFreeService(esp_openthread_get_instance(), (otSrpClientBuffersServiceEntry*)removed);
      removed = next;
    }
  }, nullptr);

  // As network of the device it may route for the mesh. Alongside Wi-Fi it shares the radio, so end device only.
  Thread.network = !Settings->flag4.network_wifi;
  otThreadSetRouterEligible(ot, Thread.network);
  if (otDatasetIsCommissioned(ot) &&
      ((otIp6SetEnabled(ot, true) != OT_ERROR_NONE) || (otThreadSetEnabled(ot, true) != OT_ERROR_NONE))) {
    AddLog(LOG_LEVEL_ERROR, PSTR("THR: Join failed"));
  }
  esp_openthread_lock_release();
}

void ThreadInit(void) {
  esp_openthread_platform_config_t config = {};
  config.radio_config.radio_mode = RADIO_MODE_NATIVE;
  config.host_config.host_connection_mode = HOST_CONNECTION_MODE_NONE;
  config.port_config.storage_partition_name = "nvs";
  config.port_config.netif_queue_size = 10;
  config.port_config.task_queue_size = 10;

  esp_vfs_eventfd_config_t eventfd_config = { .max_fds = 3 };  // OpenThread radio, task queue and netif
  esp_err_t err = esp_vfs_eventfd_register(&eventfd_config);
  if (ESP_ERR_INVALID_STATE == err) { err = ESP_OK; }          // Already registered
  if ((ESP_OK == err) && !Network.begin()) { err = ESP_FAIL; }  // Network interfaces and events, also without Wi-Fi
  if (ESP_OK == err) { err = esp_openthread_init(&config); }
  if (ESP_OK == err) {
    esp_netif_config_t netif_config = ESP_NETIF_DEFAULT_OPENTHREAD();
    esp_netif_t *netif = esp_netif_new(&netif_config);
    err = (netif) ? esp_netif_attach(netif, esp_openthread_netif_glue_init(&config)) : ESP_ERR_NO_MEM;
  }
  if (ESP_OK == err) {
#if CONFIG_ESP_COEX_SW_COEXIST_ENABLE
    esp_coex_wifi_i154_enable();             // Share the radio with Wi-Fi
#endif
    ThreadStart();
    Thread.running = true;
    if (xTaskCreate(ThreadTask, "ot_main", CONFIG_OPENTHREAD_TASK_SIZE, nullptr, CONFIG_OPENTHREAD_TASK_PRIORITY, nullptr) != pdPASS) {
      Thread.running = false;
      err = ESP_ERR_NO_MEM;
    }
  }
  if (err != ESP_OK) {
    AddLog(LOG_LEVEL_ERROR, PSTR("THR: Start failed (%s)"), esp_err_to_name(err));
  }
}

char* ThreadIp6Str(const void *ip6, char *out) {
  // out needs OT_IP6_ADDRESS_STRING_SIZE, empty if the address is unspecified
  out[0] = '\0';
  if (!otIp6IsAddressUnspecified((const otIp6Address*)ip6)) {
    otIp6AddressToString((const otIp6Address*)ip6, out, OT_IP6_ADDRESS_STRING_SIZE);
  }
  return out;
}

void ThreadEverySecond(void) {
  if (!Thread.running) {
    if (Thread.stop_error != ESP_OK) {
      AddLog(LOG_LEVEL_ERROR, PSTR("THR: Stopped (%s)"), esp_err_to_name(Thread.stop_error));
      Thread.stop_error = ESP_OK;
      Thread.role = OT_DEVICE_ROLE_DISABLED;
    }
    return;
  }
  if (!esp_openthread_lock_acquire(THREAD_LOCK_TICKS)) { return; }
  otInstance *ot = esp_openthread_get_instance();
  otDeviceRole role = otThreadGetDeviceRole(ot);
  otIp6Address ip6_global = {};
  for (const otNetifAddress *addr = otIp6GetUnicastAddresses(ot); addr; addr = addr->mNext) {
    if (addr->mPreferred && !addr->mMeshLocal &&
        ((OT_ADDRESS_ORIGIN_SLAAC == addr->mAddressOrigin) || (OT_ADDRESS_ORIGIN_DHCPV6 == addr->mAddressOrigin))) {
      ip6_global = addr->mAddress;
      break;
    }
  }
  Thread.ip6_mesh = *otThreadGetMeshLocalEid(ot);
  Thread.ip6_local = *otThreadGetLinkLocalIp6Address(ot);
  Thread.ext_address = *otLinkGetExtendedAddress(ot);
  Thread.ext_pan_id = *otThreadGetExtendedPanId(ot);
  strlcpy(Thread.network_name, otThreadGetNetworkName(ot), sizeof(Thread.network_name));
  Thread.pan_id = otLinkGetPanId(ot);
  Thread.rloc16 = otThreadGetRloc16(ot);
  Thread.channel = otLinkGetChannel(ot);
  Thread.srp_state = otSrpClientGetHostInfo(ot)->mState;
  Thread.commissioned = otDatasetIsCommissioned(ot);
  otError srp_error = Thread.srp_error;
  Thread.srp_error = OT_ERROR_NONE;
  esp_openthread_lock_release();

  if (role != Thread.role) {
    Thread.role = role;
    AddLog(LOG_LEVEL_INFO, PSTR("THR: Role %s"), otThreadDeviceRoleToString(role));
  }
  if (memcmp(&ip6_global, &Thread.ip6_global, sizeof(ip6_global))) {
    Thread.ip6_global = ip6_global;
    char ip6[OT_IP6_ADDRESS_STRING_SIZE];
    AddLog(LOG_LEVEL_INFO, PSTR("THR: " D_JSON_IP6_GLOBAL " %s"), ThreadIp6Str(&ip6_global, ip6));
  }
  if (srp_error != OT_ERROR_NONE) {
    AddLog(LOG_LEVEL_INFO, PSTR("THR: SRP %s"), otThreadErrorToString(srp_error));
  }

  // Thread takes over the network with `Wifi 0` and hands it back with `Wifi 1`, both from a fresh start
  if (Thread.commissioned && (Thread.network == Settings->flag4.network_wifi) && !TasmotaGlobal.restart_flag) {
    AddLog(LOG_LEVEL_INFO, PSTR("THR: Network change, restart"));
    TasmotaGlobal.restart_flag = 2;
  }
}

bool ThreadIsNetwork(void) {
  // Thread is the network of the device and attached to the mesh
  return Thread.network && (Thread.role >= OT_DEVICE_ROLE_CHILD);
}

/*********************************************************************************************\
 * Commands
\*********************************************************************************************/

const char kThreadCommands[] PROGMEM = "Thread|"  // Prefix
  "|Dataset";

void (* const ThreadCommand[])(void) PROGMEM = {
  &CmndThread, &CmndThreadDataset };

void CmndThread(void) {
  if (!Thread.running) {
    ResponseCmndError();
    return;
  }
  if (!Thread.commissioned) {
    ResponseCmndChar_P(PSTR("No dataset"));
    return;
  }
  char ext_pan_id[2 * OT_EXT_PAN_ID_SIZE +1];
  char ext_address[2 * OT_EXT_ADDRESS_SIZE +1];
  char ip6_global[OT_IP6_ADDRESS_STRING_SIZE];
  char ip6_mesh[OT_IP6_ADDRESS_STRING_SIZE];
  char ip6_local[OT_IP6_ADDRESS_STRING_SIZE];
  Response_P(PSTR("{\"%s\":{\"Role\":\"%s\",\"Network\":\"%s\",\"Channel\":%d,\"PanId\":\"0x%04X\",\"ExtPanId\":\"%s\","
                  "\"ExtAddress\":\"%s\",\"Rloc16\":\"0x%04X\",\"" D_JSON_IP6_GLOBAL "\":\"%s\",\"IP6Mesh\":\"%s\",\""
                  D_JSON_IP6_LOCAL "\":\"%s\",\"Srp\":\"%s\"}}"),
    XdrvMailbox.command, otThreadDeviceRoleToString(Thread.role), EscapeJSONString(Thread.network_name).c_str(),
    Thread.channel, Thread.pan_id, ToHex_P(Thread.ext_pan_id.m8, OT_EXT_PAN_ID_SIZE, ext_pan_id, sizeof(ext_pan_id)),
    ToHex_P(Thread.ext_address.m8, OT_EXT_ADDRESS_SIZE, ext_address, sizeof(ext_address)), Thread.rloc16,
    ThreadIp6Str(&Thread.ip6_global, ip6_global), ThreadIp6Str(&Thread.ip6_mesh, ip6_mesh),
    ThreadIp6Str(&Thread.ip6_local, ip6_local), otSrpClientItemStateToString(Thread.srp_state));
}

void CmndThreadDataset(void) {
  // ThreadDataset <hex> - Store the Active Operational Dataset and restart
  // ThreadDataset 0     - Erase the Thread network credentials and restart
  if (!Thread.running) {
    ResponseCmndError();
    return;
  }
  if (!XdrvMailbox.data_len) {
    ResponseCmndChar((Thread.commissioned) ? Thread.network_name : PSTR("No dataset"));
    return;
  }
  bool erase = (1 == XdrvMailbox.data_len) && ('0' == XdrvMailbox.data[0]);
  otOperationalDatasetTlvs tlvs;
  otOperationalDataset dataset;
  if (!erase) {
    int32_t length = XdrvMailbox.data_len / 2;
    if ((XdrvMailbox.data_len & 1) || (length > (int32_t)sizeof(tlvs.mTlvs)) ||
        (HexToBytes(XdrvMailbox.data, tlvs.mTlvs, sizeof(tlvs.mTlvs)) != length)) {
      ResponseCmndChar_P(PSTR("Invalid hex"));
      return;
    }
    tlvs.mLength = length;
    const otOperationalDatasetComponents &has = dataset.mComponents;
    if ((otDatasetParseTlvs(&tlvs, &dataset) != OT_ERROR_NONE) || !has.mIsActiveTimestampPresent ||
        !has.mIsNetworkKeyPresent || !has.mIsNetworkNamePresent || !has.mIsExtendedPanIdPresent ||
        !has.mIsMeshLocalPrefixPresent || !has.mIsPanIdPresent || !has.mIsChannelPresent) {
      ResponseCmndChar_P(PSTR("Incomplete dataset"));
      return;
    }
  }
  otError error = OT_ERROR_BUSY;
  if (esp_openthread_lock_acquire(THREAD_LOCK_TICKS)) {
    otInstance *ot = esp_openthread_get_instance();
    otThreadSetEnabled(ot, false);
    otIp6SetEnabled(ot, false);
    error = (erase) ? otInstanceErasePersistentInfo(ot) : otDatasetSetActiveTlvs(ot, &tlvs);
    esp_openthread_lock_release();
    TasmotaGlobal.restart_flag = 2;          // Join with the stored dataset, also if storing failed
  }
  if (error != OT_ERROR_NONE) {
    ResponseCmndChar(otThreadErrorToString(error));
  } else if (erase) {
    ResponseCmndDone();
  } else {
    ResponseCmndChar(dataset.mNetworkName.m8);  // Never the network key
  }
}

/*********************************************************************************************\
 * Berry module `thread`
 *
 * thread.info([key:string]) -> map, or the value of key
 * thread.srp_add(service:string, proto:string, port:int, txt:map, instance:string [, subtypes:list]) -> bool
 * thread.srp_remove(service:string, proto:string, instance:string) -> bool
\*********************************************************************************************/

#ifdef USE_BERRY
extern "C" {
  // Service names, subtype labels and TXT data of Matter fit well into the SRP client buffers
  const uint32_t THREAD_SRP_NAME_SIZE = 96;
  const uint32_t THREAD_SRP_TXT_SIZE = 64;
  const uint32_t THREAD_SRP_SUBTYPES = 6;

  static otSrpClientService *ThreadSrpFind(otInstance *ot, const char *name, const char *instance_name) {
    for (const otSrpClientService *service = otSrpClientGetServices(ot); service; service = service->mNext) {
      if (!strcmp(service->mName, name) && !strcmp(service->mInstanceName, instance_name)) {
        return (otSrpClientService*)service;
      }
    }
    return nullptr;
  }

  static void ThreadSrpDrop(otInstance *ot, otSrpClientService *service) {
    // Forget a service without telling the server, its entry is free right away
    otSrpClientClearService(ot, service);
    otSrpClientBuffersFreeService(ot, (otSrpClientBuffersServiceEntry*)service);
  }

  int be_thread_info(bvm *vm) {
    if ((be_top(vm) >= 1) && be_isstring(vm, 1)) {  // Value of this key only
      be_pushnil(vm);
      be_pushvalue(vm, 1);
    } else {
      be_newobject(vm, "map");
    }
    be_map_insert_bool(vm, "up", ThreadIsNetwork());
    if (Thread.commissioned) {
      char text[OT_IP6_ADDRESS_STRING_SIZE];
      be_map_insert_str(vm, "role", otThreadDeviceRoleToString(Thread.role));
      be_map_insert_str(vm, "network", Thread.network_name);
      be_map_insert_str(vm, "extaddr", ToHex_P(Thread.ext_address.m8, OT_EXT_ADDRESS_SIZE, text, sizeof(text)));
      if (*ThreadIp6Str(&Thread.ip6_global, text)) { be_map_insert_str(vm, "ip6", text); }
      if (*ThreadIp6Str(&Thread.ip6_mesh, text)) { be_map_insert_str(vm, "ip6mesh", text); }
      if (*ThreadIp6Str(&Thread.ip6_local, text)) { be_map_insert_str(vm, "ip6local", text); }
    }
    be_pop(vm, 1);
    be_return(vm);
  }

  // Register a service with the SRP server of the Thread network, or update it.
  // `false` if Thread is not the network of the device or the service does not fit.
  int be_thread_srp_add(bvm *vm) {
    int32_t top = be_top(vm);
    if ((top < 5) || !be_isstring(vm, 1) || !be_isstring(vm, 2) || !be_isint(vm, 3) || !be_ismapinstance(vm, 4) ||
        !be_isstring(vm, 5) || ((top >= 6) && !be_isnil(vm, 6) && !be_islistinstance(vm, 6))) {
      be_raise(vm, "value_error", "wrong or missing arguments");
    }
    // Encode everything before taking the OpenThread lock, as Berry may raise while converting values
    char name[THREAD_SRP_NAME_SIZE];         // "_service._proto" and the subtype labels, each null terminated
    uint32_t name_len = snprintf_P(name, sizeof(name), PSTR("%s.%s"), be_tostring(vm, 1), be_tostring(vm, 2)) +1;
    bool fits = (name_len <= sizeof(name));
    uint32_t label_offset[THREAD_SRP_SUBTYPES];
    uint32_t labels = 0;
    if ((top >= 6) && be_islistinstance(vm, 6)) {
      be_getmember(vm, 6, ".p");
      be_pushiter(vm, -1);
      while (fits && be_iter_hasnext(vm, -2)) {
        be_iter_next(vm, -2);
        const char *label = be_tostring(vm, -1);
        uint32_t len = strlen(label) +1;
        fits = (labels < THREAD_SRP_SUBTYPES) && (name_len + len <= sizeof(name));
        if (fits) {
          memcpy(&name[name_len], label, len);
          label_offset[labels++] = name_len;
          name_len += len;
        }
        be_pop(vm, 1);
      }
      be_pop(vm, 2);
    }
    uint8_t txt[THREAD_SRP_TXT_SIZE];        // Entries of a length byte and "key=value"
    uint32_t txt_len = 0;
    be_getmember(vm, 4, ".p");
    be_pushiter(vm, -1);
    while (fits && be_iter_hasnext(vm, -2)) {
      be_iter_next(vm, -2);
      const char *key = be_tostring(vm, -2);
      const char *value = be_tostring(vm, -1);
      int32_t room = sizeof(txt) - txt_len -1;   // After the length byte, with room for the terminating null
      int32_t len = (room > 0) ? snprintf_P((char*)&txt[txt_len +1], room, PSTR("%s=%s"), key, value) : -1;
      fits = (len >= 0) && (len < room);
      if (fits) {
        txt[txt_len] = len;
        txt_len += len +1;
      }
      be_pop(vm, 2);
    }
    be_pop(vm, 2);
    uint16_t port = be_toint(vm, 3);
    const char *instance_name = be_tostring(vm, 5);

    bool added = false;
    if (fits && Thread.network && Thread.running && esp_openthread_lock_acquire(THREAD_LOCK_TICKS)) {
      otInstance *ot = esp_openthread_get_instance();
      otSrpClientService *previous = ThreadSrpFind(ot, name, instance_name);
      if (previous) { ThreadSrpDrop(ot, previous); }   // Registered again below with the new data
      otSrpClientBuffersServiceEntry *entry = otSrpClientBuffersAllocateService(ot);
      if (entry) {
        uint16_t name_size, instance_size, txt_size, labels_size;
        char *entry_name = otSrpClientBuffersGetServiceEntryServiceNameString(entry, &name_size);
        char *entry_instance = otSrpClientBuffersGetServiceEntryInstanceNameString(entry, &instance_size);
        uint8_t *entry_txt = otSrpClientBuffersGetServiceEntryTxtBuffer(entry, &txt_size);
        const char **entry_labels = otSrpClientBuffersGetSubTypeLabelsArray(entry, &labels_size);
        if ((name_len <= name_size) && (strlen(instance_name) < instance_size) && (txt_len <= txt_size) && (labels < labels_size)) {
          memcpy(entry_name, name, name_len);
          strcpy(entry_instance, instance_name);
          memcpy(entry_txt, txt, txt_len);
          entry->mTxtEntry.mValueLength = txt_len;
          for (uint32_t i = 0; i < labels; i++) {
            entry_labels[i] = &entry_name[label_offset[i]];  // The array is null terminated after allocation
          }
          entry->mService.mPort = port;
          added = (OT_ERROR_NONE == otSrpClientAddService(ot, &entry->mService));
        }
        if (!added) { otSrpClientBuffersFreeService(ot, entry); }
      }
      esp_openthread_lock_release();
    }
    be_pushbool(vm, added);
    be_return(vm);
  }

  // Remove a service from the SRP server. Returns `true` if the service was registered.
  int be_thread_srp_remove(bvm *vm) {
    if ((be_top(vm) < 3) || !be_isstring(vm, 1) || !be_isstring(vm, 2) || !be_isstring(vm, 3)) {
      be_raise(vm, "value_error", "wrong or missing arguments");
    }
    char name[THREAD_SRP_NAME_SIZE];
    snprintf_P(name, sizeof(name), PSTR("%s.%s"), be_tostring(vm, 1), be_tostring(vm, 2));
    const char *instance_name = be_tostring(vm, 3);

    bool found = false;
    if (Thread.running && esp_openthread_lock_acquire(THREAD_LOCK_TICKS)) {
      otInstance *ot = esp_openthread_get_instance();
      otSrpClientService *service = ThreadSrpFind(ot, name, instance_name);
      if (service) {
        found = true;
        if (OT_SRP_CLIENT_ITEM_STATE_TO_ADD == service->mState) {
          ThreadSrpDrop(ot, service);        // Not sent to the server, so nothing to remove there
        } else if ((service->mState != OT_SRP_CLIENT_ITEM_STATE_TO_REMOVE) && (service->mState != OT_SRP_CLIENT_ITEM_STATE_REMOVING)) {
          otSrpClientRemoveService(ot, service);  // Its entry is freed by the SRP callback
        }
      }
      esp_openthread_lock_release();
    }
    be_pushbool(vm, found);
    be_return(vm);
  }
}
#endif  // USE_BERRY

/*********************************************************************************************\
 * Interface
\*********************************************************************************************/

bool Xdrv74(uint32_t function) {
  bool result = false;

  switch (function) {
    case FUNC_EVERY_SECOND:
      ThreadEverySecond();
      break;
#ifdef USE_WEBSERVER
    case FUNC_WEB_SENSOR:
      if (Thread.commissioned) {
        WSContentSend_P(PSTR("{s}Thread{m}%s (%s){e}"), otThreadDeviceRoleToString(Thread.role), HtmlEscape(Thread.network_name).c_str());
      }
      break;
#endif  // USE_WEBSERVER
    case FUNC_COMMAND:
      result = DecodeCommand(kThreadCommands, ThreadCommand);
      break;
    case FUNC_INIT:
      ThreadInit();
      break;
    case FUNC_ACTIVE:
      result = true;
      break;
  }
  return result;
}

#endif  // USE_THREAD
#endif  // ESP32
