from time import sleep
from umqttsimple import MQTTClient
import ubinascii
from machine import Pin, unique_id, reset, PWM
import songs
#Definição dos LED's
blue = PWM(Pin(25, Pin.OUT))
green = PWM(Pin(26, Pin.OUT))
red = PWM(Pin(32, Pin.OUT))
#definição dos Botões
up = Pin(18, Pin.IN)
down = Pin(22, Pin.IN)
left = Pin(23, Pin.IN)
right = Pin(5, Pin.IN)
center = Pin(19, Pin.IN)
#Definição do Buzzer
buzzer = PWM(Pin(21, Pin.OUT))
buzzer.deinit()
#Frequência do PWM
blue.freq(50)
green.freq(50)
red.freq(50)
#Definir frequência PWM
f = 50
blue.freq(f)
green.freq(f)
red.freq(f)
#Definir LED's desligados
leds = [red, green, blue]
dutys = [0, 0, 1023]
red.duty(dutys[0])
green.duty(dutys[1])
blue.duty(dutys[2])
#Rede do Broker
mqtt_server = 'broker.hivemq.com'
client_id = ubinascii.hexlify(unique_id())
topic_base = 'fprojectedm'
#Formatação permitida para tópico RGB
def topic_RGB_format(message):
if message.count(" ") == 2 and len(message.split()) == 3:
for i in message.split():
if not i.isdigit() or int(i) > 255 or int(i) < 0:
return False
else:
return True
else:
return False
#Tópicos
def sub_cb(topic, message):
print("Received MQTT message: topic '{0}', value '{1}'" \
.format(topic.decode("utf-8"), message.decode("utf-8")))
#Tópico RGB - Mudar a cor
if topic == b'' + topic_base + '/RGB':
if message.decode("utf-8") != "Escreva o código RGB da cor neste formato:000 000 000" and message.decode("utf-8") != "O formato não está correto":
if topic_RGB_format(message.decode("utf-8")):
red.duty(int(- float(message.decode("utf-8").split()[0]) * 1023 / 255 + 1023))
green.duty(int(- float(message.decode("utf-8").split()[1]) * 1023 / 255 + 1023))
blue.duty(int(- float(message.decode("utf-8").split()[2]) * 1023 / 255 + 1023))
else:
client.publish(b'' + topic_base + '/RGB', b"O formato não está correto")
#Tópico Músicas
if topic == b'' + topic_base + '/songs':
if message.decode("utf-8") != "Escreva o nome da música pretendida. Opções: Jingle Bells; Fly Me to the Moon; Toy Story" and message.decode("utf-8") != "A música que escolheu não está disponível":
if message.decode("utf-8") == "Jingle Bells":
songs.Jingle_Bells(red, green, blue, buzzer)
elif message.decode("utf-8") == "Fly Me to the Moon":
songs.To_the_Moon(red, green, blue, buzzer)
elif message.decode("utf-8") == "Toy Story":
songs.Toy_Story(red, green, blue, buzzer)
else:
client.publish(b'' + topic_base + '/songs', b"A música que escolheu não está disponível")
#Conectar ao Broker
def connect_and_subscribe():
mqtt_client = MQTTClient(client_id, mqtt_server)
mqtt_client.set_callback(sub_cb)
mqtt_client.connect()
mqtt_client.subscribe(topic_base + '/RGB')
mqtt_client.subscribe(topic_base + '/songs')
print('Connected to {0} MQTT broker'.format(mqtt_server))
red.duty(1023)
for i in range(3):
green.duty(0)
sleep(0.5)
green.duty(1023)
sleep(0.5)
return mqtt_client
#Reconectar ao Broker (Erros)
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
green.duty(1023)
for i in range(3):
red.duty(0)
sleep(0.5)
red.duty(1023)
sleep(0.5)
sleep(10)
reset()
try:
client = connect_and_subscribe()
client.publish(b'' + topic_base + '/RGB', b"Escreva o código RGB da cor neste formato:000 000 000")
client.publish(b'' + topic_base + '/songs', b"Escreva o nome da música pretendida. Opções: Jingle Bells; Fly Me to the Moon; Toy Story")
except OSError as e:
restart_and_reconnect()
#Verificar mensagens do MQTT
def loop():
try:
client.check_msg()
except OSError as e:
restart_and_reconnect()
#Correr Programa
i = 0
cor, dut = leds[i], dutys[i]
try:
while True:
loop()
#Botão Central - Trocar a Cor
if not center.value():
i += 1
if i > 2:
i = 0
cor, dut = leds[i], dutys[i] #mudança do LED selecionado
#LED pisca para mostrar qual está selecionado
for j in leds:
j.duty(int(1023))
cor.duty(int(0))
sleep(0.2)
cor.duty(int(1023))
sleep(0.2)
for j in range(len(dutys)):
leds[j].duty(int(dutys[j]))
sleep(0.2)
#Botão Superir - Aumento Grosso
if not up.value():
dut -= 100
if dut <= 0:
dut = 0
cor.duty(int(dut))
dutys[i] = dut
sleep(0.1)
#Diminuição Grossa
if not down.value():
dut += 100
if dut >= 1023:
dut = 1023
cor.duty(int(dut))
dutys[i] = dut
sleep(0.1)
#Aumento Fino
if not right.value():
dut -= 10
if dut <= 0:
dut = 0
cor.duty(int(dut))
dutys[i] = dut
sleep(0.1)
#Diminuição Fina
if not left.value():
dut += 10
if dut >= 1023:
dut = 1023
cor.duty(int(dut))
dutys[i] = dut
sleep(0.1)
except KeyboardInterrupt:
pass