100 lines
2.5 KiB
Python
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):
|
|
global isRunning
|
|
print(f"{msg.topic} -> {str(msg.payload.decode('ascii'))}")
|
|
if "STOP" in msg.payload.decode('ascii'):
|
|
isRunning = False
|
|
pass
|
|
|
|
def send_SU():
|
|
client.publish(MQTT_SEND,payload="SU")
|
|
pass
|
|
|
|
def send_GIU():
|
|
client.publish(MQTT_SEND,payload="GIU")
|
|
pass
|
|
|
|
def send_SX():
|
|
client.publish(MQTT_SEND,payload="SX")
|
|
pass
|
|
|
|
def send_DX():
|
|
client.publish(MQTT_SEND,payload="DX")
|
|
pass
|
|
|
|
def send_OK():
|
|
client.publish(MQTT_SEND,payload="OK")
|
|
pass
|
|
|
|
def send_CAN():
|
|
client.publish(MQTT_SEND,payload="CAN")
|
|
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())
|
|
|