     static const PROGMEM u1_t devaddr[] = DEVADDR;
     static_assert(sizeof(settings.DevAddr) == sizeof(devaddr), "DEVADDR needs to be 4 bytes");
     _memcpy(settings.DevAddr, devaddr, sizeof(settings.DevAddr));
+    settings.flags |= FLAG_DEV_ADDR_SET;
+    debugLogData("Setting DevAddr", settings.DevAddr, sizeof(settings.DevAddr));
+    write = true;
+  #endif
+  #if defined(NWKSKEY)
+    static const PROGMEM u1_t nwkskey[] = NWKSKEY;
+    static_assert(sizeof(settings.NwkSKey) == sizeof(nwkskey), "NWKSKEY needs to be 16 bytes");
+    _memcpy(settings.NwkSKey, nwkskey, sizeof(settings.NwkSKey));
+    settings.flags |= FLAG_NWK_SKEY_SET;
+    debugLogData("Setting NwkSKey", settings.NwkSKey, sizeof(settings.NwkSKey));
+    write = true;
   #endif
   #if defined(APPSKEY)
     static const PROGMEM u1_t appskey[] = APPSKEY;
     static_assert(sizeof(settings.AppSKey) == sizeof(appskey), "APPSKEY needs to be 16 bytes");
     _memcpy(settings.AppSKey, appskey, sizeof(settings.AppSKey));
-  #endif
-  #if defined(NWKSKEY)
-    static const PROGMEM u1_t nwkskey[] = NWKSKEY;
-    static_assert(sizeof(settings.NwkSKey) == sizeof(nwkskey), "NWKSKEY needs to be 16 bytes");
-    _memcpy(settings.NwkSKey, nwkskey, sizeof(settings.NwkSKey));
-  #endif
-  #if defined(DEVADDR) && defined(APPSKEY) && defined(NWKSKEY)
-    settings.flags |= FLAG_SESSION_VARS_SET;
+    settings.flags |= FLAG_APP_SKEY_SET;
+    debugLogData("Setting AppSKey", settings.AppSKey, sizeof(settings.AppSKey));
     write = true;
   #endif
 

  u1_t AppEUI[8];
#define FLAG_DEV_EUI_SET (1 << 3)
  u1_t DevEUI[8];
} PersistentSettings;

PersistentSettings settings;

  }
}

#define AssignSessionCallback(key, flag) \
void assign##key##Callback(uint8_t data[], uint16_t len) { \
  debugLogData("assign" #key, data, len); \
  if (len==sizeof(settings.key)) {        \
    memcpy(settings.key, data, sizeof(settings.key)); \
    saveSettingBytes(offset(settings, key), settings.key, sizeof(settings.key)); \
    settings.flags |= flag; \
    saveSettingValue(offset(settings, flags), settings.flags); \
    if ((settings.flags & FLAG_SESSION_VARS_SET)==FLAG_SESSION_VARS_SET) { \
      loraSetSessionKeys(settings.seq_no, settings.AppSKey, settings.NwkSKey, settings.DevAddr); \
    } \
  } \
}

AssignSessionCallback(DevAddr, FLAG_DEV_ADDR_SET)
AssignSessionCallback(NwkSKey, FLAG_NWK_SKEY_SET)
AssignSessionCallback(AppSKey, FLAG_APP_SKEY_SET)

#define AssignAppCallback(key, flag) \
void assign##key##Callback(uint8_t data[], uint16_t len) { \
