Files
pyButtons/pyButtons.py
2020-11-30 15:17:19 +01:00

100 lines
2.5 KiB
Python

from gpiozero import Button
from paho.mqtt import client as mqtt
import time
import sys
#numero pin GPIO secondo lo schema BCM
SU = "GPIO5"
GIU = "GPIO6"
SX = "GPIO13"
DX = "GPIO19"
OK = "GPIO12"
CAN = "GPIO16"
# code mqtt
MQTT_SEND = "buttons/send"
MQTT_RECEIVE = "buttons/receive"
#variabili globali
isRunning = True
client = None
debounce = 0.25
def on_message(client, userdata, msg):
print(f"{msg.topic} -> {str(msg.payload)}")
if "STOP" in str(msg.payload):
isRunning = False
pass
def send_SU():
client.publish(MQTT_SEND,payload="SU",qos=1)
pass
def send_GIU():
client.publish(MQTT_SEND,payload="GIU",qos=1)
pass
def send_SX():
client.publish(MQTT_SEND,payload="SX",qos=1)
pass
def send_DX():
client.publish(MQTT_SEND,payload="DX",qos=1)
pass
def send_OK():
client.publish(MQTT_SEND,payload="OK",qos=1)
pass
def send_CAN():
client.publish(MQTT_SEND,payload="CAN",qos=1)
pass
def main():
global client
global isRunning
btn_su = Button(SU, bounce_time=debounce, hold_repeat=True)
btn_giu = Button(GIU, bounce_time=debounce, hold_repeat=True)
btn_sx = Button(SX, bounce_time=debounce, hold_repeat=True)
btn_dx = Button(DX, bounce_time=debounce, hold_repeat=True)
btn_ok = Button(OK, bounce_time=debounce, hold_repeat=True)
btn_can = Button(CAN, bounce_time=debounce, hold_repeat=True)
while isRunning:
try:
if client is None:
client = mqtt.Client()
client.connect('localhost',1883)
client.subscribe(MQTT_RECEIVE)
client.on_message = on_message
#evento premuto
btn_su.when_pressed = send_SU
btn_giu.when_pressed = send_GIU
btn_sx.when_pressed = send_SX
btn_dx.when_pressed = send_DX
btn_ok.when_pressed = send_OK
btn_can.when_pressed = send_CAN
#evento tenuto
btn_su.when_held = send_SU
btn_giu.when_held = send_GIU
btn_sx.when_held = send_SX
btn_dx.when_held = send_DX
btn_ok.when_held = send_OK
btn_can.when_held = send_CAN
while isRunning:
client.loop(timeout=1)
time.sleep(1)
except Exception as e:
print(f"Exception: {e}")
client.disconnect()
client=None
pass
pass
if __name__=="__main__":
sys.exit(main())