Receive commands
When someone moves a switch, slider or button, or an automation or the assistant sends a value, your handler runs with the datastream's key and the new value.
One handler per key
void onLight(String key, String value) {
digitalWrite(LED_BUILTIN, value == "1" ? HIGH : LOW);
}
void onFanSpeed(String key, String value) {
analogWrite(FAN_PIN, constrain(value.toInt(), 0, 255));
}
void onAnyOther(String key, String value) {
Serial.println(key + " = " + value);
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
MaxwellTrack.onWrite("light", onLight);
MaxwellTrack.onWrite("fan_speed", onFanSpeed);
MaxwellTrack.onWrite(onAnyOther); // every key without its own handler
MaxwellTrack.begin(DEVICE_ID, AUTH_TOKEN, WIFI_SSID, WIFI_PASS);
}A per-key handler takes priority over the general one. Values always arrive as text: a switch sends 1 or 0, a slider its number.
Report the real state back
After acting, write the state back to the same key. The dashboard switch then shows what the hardware is actually doing, also after a restart or a reconnect.
bool relayOn = false;
void onRelay(String key, String value) {
relayOn = value.toInt() != 0;
digitalWrite(RELAY_PIN, relayOn ? HIGH : LOW);
MaxwellTrack.write("relay", relayOn ? 1 : 0);
}
void onConnection(bool online) {
if (online) MaxwellTrack.write("relay", relayOn ? 1 : 0);
}
void setup() {
MaxwellTrack.onWrite("relay", onRelay);
MaxwellTrack.onConnectionChange(onConnection);
MaxwellTrack.begin(DEVICE_ID, AUTH_TOKEN, WIFI_SSID, WIFI_PASS);
}Delivery
Commands are delivered while the device is connected. Handlers run inside run(), so keep them short and never block in them.
Something unclear or out of date on this page? Tell support.
