// CommissionerNode - one half of real Thread commissioning.
//
// This board forms a network and then acts as the COMMISSIONER: it admits
// new devices that present the right joining passphrase (PSKd). Flash
// JoinerNode (the other half) to a second board - the joiner needs NO
// network credentials in its sketch, just the PSKd.
//
//   Commissioner serial:                Joiner serial:
//   role -> leader                      joining with PSKd "J01NME"...
//   commissioner active                 join OK!
//   (joiner appears in child table)     role -> child
//
// The PSKd below must match the one in JoinerNode (6..32 chars, uppercase
// letters/digits, no I, O, Q or Z).

#include <NiusThread.h>

static const char *kPskd = "J01NME";

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();
  Thread.setNetwork("ArduinoNRF", 25, 0xBEEF, kNetworkKey);
  Thread.start();
  Serial.println("CommissionerNode: forming network...");
}

void loop() {
  static ThreadClass::Role lastRole = ThreadClass::ROLE_DISABLED;
  static bool commissionerRequested = false;
  static bool joinerWindowOpen = false;

  Thread.process();

  if (Thread.role() != lastRole) {
    lastRole = Thread.role();
    Serial.print("role -> ");
    Serial.println(Thread.roleString());
  }

  // Once attached, become the Commissioner; once active, open the joiner
  // window so any device with our PSKd may join (10-minute window).
  if (!commissionerRequested && Thread.isAttached()) {
    commissionerRequested = (Thread.commissionerStart() == ThreadClass::THREAD_OK);
    if (commissionerRequested) {
      Serial.println("petitioning to become commissioner...");
    }
  }

  if (commissionerRequested && !joinerWindowOpen && Thread.commissionerActive()) {
    if (Thread.commissionerAddJoiner(kPskd, 600) == ThreadClass::THREAD_OK) {
      joinerWindowOpen = true;
      Serial.print("commissioner active - joiners with PSKd \"");
      Serial.print(kPskd);
      Serial.println("\" may join for the next 10 min");
    }
  }
}
