from machine import Pin, reset, I2C, Timer
from neopixel import NeoPixel
from ujson import load, loads, dump, dumps
from funcs import wifi_connect, mqtt_connect, make_json, oled_show
from utime import ticks_ms, sleep_ms
from ssd1306 import SSD1306_I2C
### Funções ########################################
def mqtt_callback(topic, msg):
global startGame, win, check, request, begin
msg = loads(msg.decode())
print(msg)
if not startGame and check:
if msg.get("tipo") == "começar":
client.publish(responseTopic, make_json("começar").encode())
startGame = True
begin = True
if not startGame and not check:
if msg.get("tipo") == "começar":
request = True
oled_show(display, "pedido de", "jogo recebido", "aperte OK", "para iniciar")
if startGame:
if msg["tipo"] == "feedback":
feedback = list(msg["senha"])
print('\n', feedback)
for i, item in enumerate(feedback):
npReturn[i] = returnedColors[int(item)]
npReturn.write()
if len(set(msg["senha"])) == 1 and msg["senha"][0] == '1':
win = True
### Botões, Neopixels e Display########################################
buttons = (
(
Pin(12, Pin.IN, Pin.PULL_DOWN),
Pin(14, Pin.IN, Pin.PULL_DOWN),
Pin(27, Pin.IN, Pin.PULL_DOWN),
Pin(26, Pin.IN, Pin.PULL_DOWN)
),
(
Pin(5, Pin.IN, Pin.PULL_DOWN),
Pin(22, Pin.IN, Pin.PULL_DOWN)
)
)
colorButtonHist = [0]*4
actionButtonHist = [0]*2
colorSelection = [0]*4
colors = {
0: (255, 0, 0), # vermelho
1: (0, 255, 0), # verde
2: (0, 0 ,255), # azul
3: (255, 255, 0), #amarelo
4: (255, 192, 203), # rosa
5: (255, 165, 0), # laranja
}
returnedColors = {
0: (0, 0, 0), # off
1: (95, 159, 159), # azul claro
2: (165, 96, 102), # rosa claro
}
np = NeoPixel(Pin(4), 4)
npReturn = NeoPixel(Pin(2), 4)
display = SSD1306_I2C(128, 64, I2C(0))
### Wi-Fi e MQTT ########################################
with open('web_config.json', 'r') as file:
jsonFile = load(file)
operator = jsonFile['operator']
ssid = jsonFile['wifi']['ssid']
wifiPassword = jsonFile['wifi']['password']
mqttBroker = jsonFile['mqtt']['broker']
responseTopic = jsonFile['mqtt']['topics']['rsp'].encode()
commandTopic = jsonFile['mqtt']['topics']['cmd'].encode()
mqttUser = jsonFile['mqtt']['user']
mqttPassword = jsonFile['mqtt']['password']
mqttClient = operator
subscription = commandTopic # trocar para o tópico de inscrição
try:
wifi_connect(ssid, wifiPassword)
client = mqtt_connect(mqttClient, mqttBroker, mqttUser, mqttPassword, subscription, mqtt_callback)
except:
reset()
### Timer callback ###################################################
def timer_callback(t):
client.publish(responseTopic, make_json("keepAlive").encode())
keepAlive = Timer(0)
### Código principal ########################################
startGame, check, win, request, begin = [False]*5
tax = 4
attempts = 8
taxDelay = ticks_ms()
startDelay = ticks_ms()
once = True
cmd = "init"
while True:
client.check_msg()
if not startGame:
if once:
keepAlive.deinit()
tax = 4
attempts = 8
oled_show(display, "Aperte OK", "para iniciar", "o jogo")
for i in range(4):
np[i] = (0, 0, 0)
np.write()
once = check = begin = request = False
if not check and not request:
status = buttons[1][0].value()
if status != actionButtonHist[0]:
if status == 1:
oled_show(display, "Enviando", "pedido de jogo")
check = True
actionButtonHist[0] = status
if check and not request:
if ticks_ms() >= startDelay:
client.publish(responseTopic, make_json("começar").encode())
print(".", end="")
startDelay = ticks_ms() + 1000
if request:
status = buttons[1][0].value()
if status != actionButtonHist[0]:
if status == 1:
client.publish(responseTopic, make_json("começar").encode())
startGame, begin = [True]*2
actionButtonHist[0] = status
status = buttons[1][1].value()
if status != actionButtonHist[1]:
if status == 1:
display.fill(0)
oled_show(display, "Jogo rejeitado.")
startGame = False
actionButtonHist[1] = status
elif begin:
print(" conexão efetuada")
oled_show(display, f"Tentativas: {attempts}")
for i in range(4):
np[i] = colors[0]
np.write()
keepAlive = Timer(0)
keepAlive.init(mode=Timer.PERIODIC, period=1000, callback=timer_callback)
begin = False
else:
if win:
blink = True
oled_show(display, "Voce ganhou!")
for i in range(8):
for j in range(4):
if blink:
np[j] = colors[colorSelection[j]]
npReturn[j] = returnedColors[1]
np.write()
npReturn.write()
else:
np[j] = (0, 0, 0)
npReturn[j] = (0, 0, 0)
np.write()
npReturn.write()
blink = not blink
sleep_ms(500)
startGame, once = False, True
# loop dos botões das cores
for i, button in enumerate(buttons[0]):
status = button.value()
if status != colorButtonHist[i]:
if status == 0:
colorSelection[i] = (colorSelection[i] + 1) % 6
np[i] = colors[colorSelection[i]]
colorButtonHist[i] = status
np.write()
# loop dos botões de ação
status = buttons[1][0].value()
if status != actionButtonHist[0]:
if status == 1:
attempts -= 1
oled_show(display, f"Tentativas: {attempts}")
payload = ''
for key in colorSelection:
payload += str(key)
print(f'\nenviando senha: {payload}')
client.publish(responseTopic, make_json("tentativa", pw = payload).encode())
actionButtonHist[0] = status
status = buttons[1][1].value()
if status == 1:
if ticks_ms() >= taxDelay:
tax -= 1
oled_show(display, f"Cancelando: {tax}")
taxDelay = ticks_ms() + 500
if not tax:
print("\njogo cancelado.\n")
oled_show(display, "Hasta la", "vista, baby!")
startGame, once = False, True
for i in range(len(np)):
np[i] = (0, 0, 0)
sleep_ms(2000)
elif status != actionButtonHist[1]:
tax = 4
print('\nprocesso não executado.')
oled_show(display, f"Tentativas: {attempts}")
actionButtonHist[1] = status
if attempts <= 0:
oled_show(display, "Voce perdeu.")
sleep_ms(2000)
startGame, once = False, True
Loading
ssd1306
ssd1306