import webiopi webiopi.setDebug() GPIO = webiopi.GPIO ICMP_DEVICE = "icmp0" GAS_PORT = 0 SLEEP = 1 class State(object): def __init__(self, name, checks, expr, func): self.name = name self.checks = checks self.cur = 0 self.expr = expr self.func = func def set(self, duration): if not self.expr(duration): self.cur = 0 return if (self.cur >= self.checks): return self.cur += 1 if (self.cur == self.checks): webiopi.debug("ICMP script - State(%s) triggered" % (self.name)) self.func() def __str__(self): return "State(%s) %d/%d" % (self.name, self.cur, self.checks) online = State('Online', 2, lambda x: x > 0 and x < 300, lambda: GPIO.digitalWrite(GAS_PORT, GPIO.LOW)) offline = State('Offline', 30, lambda x: not online.expr(x), lambda: GPIO.digitalWrite(GAS_PORT, GPIO.HIGH)) STATES = [ online, offline ] def setup(): webiopi.debug("ICMP script - setup") GPIO.setFunction(GAS_PORT, GPIO.OUT) GPIO.digitalWrite(GAS_PORT, GPIO.HIGH) def loop(): icmp0 = webiopi.deviceInstance(ICMP_DEVICE) if icmp0 is None: webiopi.sleep(SLEEP) return duration = icmp0.getMilliseconds() webiopi.debug("ICMP script - %s: %dms" % (ICMP_DEVICE, duration)) for s in STATES: s.set(duration) webiopi.debug("ICMP script - %s" % (s)) webiopi.sleep(SLEEP) def destroy(): webiopi.debug("ICMP script - destroy") GPIO.setFunction(GAS_PORT, GPIO.OUT) GPIO.digitalWrite(GAS_PORT, GPIO.HIGH)