Zum Inhalt

homekit_demo.tc

HomeKit Demo — Temperature sensor + Humidity sensor + Switch

Source on GitHub

// HomeKit Demo — Temperature sensor + Humidity sensor + Switch
// Exposes 2 read-only sensor values and 1 controllable switch to Apple Home
//
// All HomeKit globals are float — no x10 scaling needed.
// Upload compiled .tcb, then navigate to http://<device>/tc_ui
// Scan QR code at http://<device>/hk with iPhone to pair

// --- globals bound to HomeKit (native float values) ---
float temperature;   // current temp (e.g. 22.5)
float humidity;      // current humidity (e.g. 55.0)
float sw_state;      // switch on/off (1.0 = on, 0.0 = off)

// --- local simulation state ---
float sim_temp;      // simulation base temp
float sim_hum;       // simulation base humidity
int sw_btn;          // local button state (0/1)
int last_power;      // track last tasm_power to avoid redundant writes
int tick;

// Called by HomeKit when Apple Home sends a command (e.g. toggle switch)
void HomeKitWrite(int dev, int var, float val) {
    if (dev == 2 && var == 0) {
        sw_state = val;
        if (val > 0.0) {
            sw_btn = 1;
        } else {
            sw_btn = 0;
        }
    }
}

// WebUI: display sensors + switch control
void WebUI() {
    webSlider(sim_temp, 15, 35, "Temperature");
    webSlider(sim_hum, 20, 90, "Humidity");
    webButton(sw_btn, "Switch");
}

void EverySecond() {
    tick = tick + 1;

    // Simulate small fluctuations around base values
    int wobble_i;
    wobble_i = (tick * 7) % 11 - 5;  // -5..+5
    float wobble;
    wobble = (float)wobble_i / 10.0;  // -0.5..+0.5
    temperature = sim_temp + wobble;
    humidity = sim_hum + wobble;

    // Sync web button (0/1) <-> HomeKit global (float)
    if (sw_state > 0.0 && sw_btn == 0) {
        sw_btn = 1;
    }
    if (sw_state == 0.0 && sw_btn > 0) {
        sw_btn = 0;
    }
    sw_state = (float)sw_btn;

    // Only write tasm_power when it actually changes
    if (sw_btn != last_power) {
        tasm_power = sw_btn;
        last_power = sw_btn;
    }
}

int main() {
    sim_temp = 22.5;
    sim_hum = 55.0;
    sw_state = 0.0;
    sw_btn = 0;
    last_power = -1;
    tick = 0;

    temperature = sim_temp;
    humidity = sim_hum;

    webPageLabel(0, "HomeKit Demo");

    // Define HomeKit accessories
    hkSetCode("111-22-333");
    hkAdd("Temperature", HK_TEMPERATURE); hkVar(temperature);
    hkAdd("Humidity",    HK_HUMIDITY);    hkVar(humidity);
    hkAdd("Switch",      HK_SWITCH);      hkVar(sw_state);
    hkStart();

    return 0;
}