espressif / esp-matter

Espressif's SDK for Matter
Apache License 2.0
644 stars 150 forks source link

API to get local fabricId/NodeId list? (CON-1266) #1018

Closed jonsmirl closed 1 month ago

jonsmirl commented 1 month ago

It there an API to get the local fabricId/NodeId list? Just for the local node, not a remote one.

This doesn't work....

    endpoint_t *root = endpoint::get(device.getNode(), 0);
    cluster_t *cluster = esp_matter::cluster::get(root, OperationalCredentials::Id);
    attribute_t *attr = attribute::get(cluster, OperationalCredentials::Attributes::Fabrics::Id);
    esp_matter_attr_val_t val;
    err = attribute::get_val(attr, &val);
    ESP_LOGI(TAG, "array err %d size %d count %d", err, val.val.a.s, val.val.a.n);

I (2103) debug_cluster: array err 0 size 0 count 0
wqx6 commented 1 month ago

You can try to iterate the Fabric Table of the server instance

FabricTable &fabricTable = Server::GetInstance().GetFabricTable();
for (auto iter = fabricTable.begin(); iter != fabricTable.end(); ++iter) {
       printf("FabricId 0x%llx NodeId 0x%llx", iter->GetFabricId(), iter->GetNodeId());
}
jonsmirl commented 1 month ago

Example of how to use this....

This has to be run after CHIP reports getting both the IPv4 and the IPv6 addresses.

oid Cluster_WebServer::enable_host(bool enable)
{
    char host_name[32] = "";

    chip::FabricTable &fabricTable = chip::Server::GetInstance().GetFabricTable();
    for (auto iter = fabricTable.begin(); iter != fabricTable.end(); ++iter)
    {
        uint64_t node_id = iter->GetNodeId();
        // find node ids which begin with 0xAB0DE
        // pick off the id number and use it for the websever MDNS name 'lowpan-xxx.local'
        if (iter->GetVendorId() == LOWPAN_VENDOR_ID)
        {
            uint64_t node_id = iter->GetNodeId() & 0xFFFFFFFFull;
            snprintf(host_name, sizeof(host_name), "lowpan-%llx", node_id);
            esp_netif_t *intf = esp_netif_get_default_netif();
            mdns_ip_addr_t addr4, addr6;
            addr4.addr.type = ESP_IPADDR_TYPE_V4;
            esp_netif_ip_info_t info;
            esp_netif_get_ip_info(intf, &info);
            addr4.addr.u_addr.ip4 = info.ip;
            addr6.addr.type = ESP_IPADDR_TYPE_V6;
            esp_netif_get_ip6_linklocal(intf, &addr6.addr.u_addr.ip6);
            addr4.next = &addr6;
            addr6.next = NULL;

            // create MDNS record for the web server at 'lowpan-xxx.local'
            ESP_ERROR_CHECK(mdns_delegate_hostname_add(host_name, &addr4));
            ESP_ERROR_CHECK(mdns_service_add_for_host("web", "_http", "_tcp", host_name, 80, NULL, 0));
            strncat(host_name, ".local", sizeof(host_name) - strlen(host_name) - 1);
            esp_matter_attr_val_t val = esp_matter_char_str(host_name, strlen(host_name));
            ESP_ERROR_CHECK(attribute::update(0, cluster_webserver::Id, cluster_webserver::attribute::hostname::Id, &val));
            break;
        }
    }
}