Beispiel: Zeitverzögertes Schalten


In diesem Beispiel wird gezeigt, wie mehrere Lichter zeitverzögert ein- und ausgeschaltet werden können.

 1// This script implements a logic to automate staircase lights.
 2// If motion is detected, multiple lights are successively
 3// turned on with a 1 second delay. After 1 minute, the lights
 4// are turned off again. If motion is detected, while the 
 5// lights are on, the 1 minute timer is restarted.
 6hkknx, time = import("hkknx"), import("time")
 7
 8// sendValue writes val to a list of addresses and
 9// sleeps between the successive writes.
10sendValue = func(value, sleep) {
11    // Iterate over the addresses
12    for addr in []string{"0/5/1", "0/5/2", "0/5/3"} {
13        // Send the value to an address.
14        err = hkknx.GroupWrite(value, addr)
15        if err != nil {
16            // Log the error.
17            printf("%s: %s\n", addr, err)
18        }
19        // Sleep for a while.
20        <-time.After(sleep)
21    }
22}
23
24// Use a channel to get notified when a
25// value is written to 0/0/1.
26ch = hkknx.GroupWriteBoolNotify("0/0/1")
27
28for {
29    // Wait until a value is received.
30    motion = <-ch
31    if motion == true { // is motion detected?
32        // Send "true" with a one second delay.
33        sendValue(true, 1 * time.Second)
34		
35        // oneMinute fires in 1 minute from now.
36        oneMinute = time.After(1 * time.Minute)
37        
38        // Wait until 
39        // - oneMinute is over
40        // - or a motion value is received
41        for {
42            select {
43            case motion = <-ch:
44                if motion == true { // is motion detected?
45                    // Reset the oneMinute time.
46                    oneMinute = time.After(1 * time.Minute)
47                }
48            case <-oneMinute: // time is over
49                // Send "false" with a one second delay.
50                sendValue(false, 1 * time.Second)
51                break // break out of the second loop
52            }
53        }
54    }
55}

Auf dieser Seite
Ähnliche Beiträge
© Matthias Hochgatterer – MastodonGithubRésumé