Search code examples
esp32mac-address

While using painlessMesh for ESP32, how is nodeId calculated based on the MAC adress?


In the documentation for painlessMesh, we can found this statement:

Return the nodeId of the node that we are running on.

On the ESP hardware nodeId is uniquely calculated from the MAC address of the node.

I would like to know how exacly is this nodeId calculated?

For instance, these are my ESP32 MAC address and nodeId. What is the formula to go from the first one to the second?

ESP32 Number
MAC address 78:E3:6D:18:FE:68
nodeId 1830354537

I have tried converting the MAC address to decimal base, and still can't arrive to the nodeId value.


Solution

  • painlessMesh simply uses the lower 32 bits of the MAC address as the nodeId.

    In the case of 78:E3:6D:18:FE:68, it uses 6D:18:FE:68 in network order.

    So:

    (0x6d << 24) + (0x18 << 16) + (0xFE << 8) + 0x68
    

    which in decimal is 1830354537

    painlessMesh is open source, so you can simply look at its source code to see how it does this:

    inline uint32_t encodeNodeId(const uint8_t *hwaddr) {
      using namespace painlessmesh::logger;
      Log(GENERAL, "encodeNodeId():\n");
      uint32_t value = 0;
    
      value |= hwaddr[2] << 24;  // Big endian (aka "network order"):
      value |= hwaddr[3] << 16;
      value |= hwaddr[4] << 8;
      value |= hwaddr[5];
      return value;
    }