// FormNetwork - the "hello world" of NiusThread.
//
// Flash this same sketch to one, two, or more ArduinoNRF boards:
//   * The first board promotes itself to LEADER within a few seconds.
//   * Every other board joins the mesh as CHILD (and may later be promoted
//     to ROUTER by the leader).
//
// Open each board's serial monitor at 115200 and watch the role change:
//
//   Thread node starting, EUI-64: F4-CE-...
//   role -> detached
//   role -> leader      rloc16=0x2C00     <- first board
//   role -> child       rloc16=0x2C01    <- second board
//
// All boards must share the same network parameters below.

#include <NiusThread.h>

// The credentials of your mesh. Make your own key for anything real!
static const char    *kNetworkName = "ArduinoNRF";
static const uint8_t  kChannel     = 11;      // 802.15.4 channel, 11..26
static const uint16_t kPanId       = 0xBEEF;
static const uint8_t  kNetworkKey[16] = {
    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
    0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
};

void setup() {
  Serial.begin(115200);
  while (!Serial && millis() < 3000) {}

  Thread.begin();

  uint8_t eui[8];
  Thread.getEui64(eui);
  Serial.print("Thread node starting, EUI-64: ");
  for (int i = 0; i < 8; i++) {
    if (eui[i] < 0x10) Serial.print('0');
    Serial.print(eui[i], HEX);
    if (i < 7) Serial.print('-');
  }
  Serial.println();

  Thread.setNetwork(kNetworkName, kChannel, kPanId, kNetworkKey);
  Thread.start();
}

void loop() {
  static ThreadClass::Role lastRole = ThreadClass::ROLE_DISABLED;

  Thread.process();  // keep the stack running - call this every loop()

  if (Thread.role() != lastRole) {
    lastRole = Thread.role();
    Serial.print("role -> ");
    Serial.print(Thread.roleString());
    Serial.print("      rloc16=0x");
    Serial.println(Thread.rloc16(), HEX);
  }
}
