% Config params, overwrite any previous settings from the commandline config ap_ssid MQTTbroker config ap_password stupidPassword config ntp_server 1.de.pool.ntp.org config broker_user Martin config broker_password secret config mqtt_host martinshome.fritz.box config speed 160 % Now the initialization, this is done once after booting on init do % Device number ("* 1" to make even "" a number) setvar $device_number = @1 * 1 % @ vars are stored in flash and are persistent even after reboot setvar $run = @2 + 1 setvar @2 = $run println "This is reboot no "|$run % Status of the relay setvar $relay_status=0 gpio_out 12 $relay_status gpio_out 13 not ($relay_status) % Blink flag setvar $blink=0 % Command topic setvar $command_topic="/martinshome/switch/" | $device_number | "/command" % Status topic setvar $status_topic="/martinshome/switch/" | $device_number | "/status" publish local $status_topic $relay_status retained % local subscriptions once in 'init' subscribe local $command_topic % Now the MQTT client init, this is done each time the client connects on mqttconnect do % remote subscriptions for each connection in 'mqttconnect' subscribe remote $command_topic publish remote $status_topic $relay_status retained % Now the events, checked whenever something happens % Is there a remote command? on topic remote $command_topic do println "Received remote command: " | $this_data % republish this locally - this does the action publish local $command_topic $this_data % Is there a local command? on topic local $command_topic do println "Received local command: " | $this_data if $this_data = "on" then setvar $relay_status = 1 setvar $blink = 0 gpio_out 12 $relay_status gpio_out 13 not ($relay_status) else if $this_data = "off" then setvar $relay_status = 0 setvar $blink = 0 gpio_out 12 $relay_status gpio_out 13 not ($relay_status) endif endif if $this_data = "toggle" then setvar $relay_status = not ($relay_status) gpio_out 12 $relay_status gpio_out 13 not ($relay_status) endif if $this_data = "blink" then setvar $blink = 1 settimer 1 500 endif publish local $status_topic $relay_status retained publish remote $status_topic $relay_status retained % The local pushbutton on gpio_interrupt 0 pullup do println "New state GPIO 0: " | $this_gpio if $this_gpio = 0 then setvar $blink = 0 publish local $command_topic "toggle" endif % Blinking on timer 1 do if $blink = 1 then publish local $command_topic "toggle" settimer 1 500 endif