import network
import time
from machine import Pin, I2C
from umqtt.simple import MQTTClient
from i2c_lcd import I2cLcd
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-button-tic-tac-toe-player-1"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = "sea-chess/move"
AddressOfLcd = 0x27
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000) # connect scl to GPIO 22, sda to GPIO 21
lcd = I2cLcd(i2c, AddressOfLcd, 4, 20)
board = [0] * 9
current_player = 1
def testLcd(num):
lcd.move_to(3, 0)
lcd.putstr('Micropython')
lcd.move_to(0, 1)
lcd.putstr("hello " + str(num))
def connect_to_wifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
def connect_to_mqtt_broker():
# Connect to HiveMQ MQTT broker
connect_to_wifi()
print("Connecting to MQTT server... ", end="")
client.connect()
print("Connected!")
client.subscribe(MQTT_TOPIC)
print("Subscribed to {}".format(MQTT_TOPIC))
def show_board():
lcd.move_to(0, 0)
for i in range(3):
for j in range(3):
lcd.putchar(str(board[i * 3 + j]))
def process_move(topic, message):
global current_player
topic = topic.decode("utf-8")
message = message.decode("utf-8")
print("Received from MQTT topic: {} - message: {}".format(topic, message))
player, move = message.split()
player = int(player)
move = eval(move)
if player == current_player and board[move[0] * 3 + move[1]] == 0:
board[move[0] * 3 + move[1]] = current_player
show_board()
current_player = 3 - current_player
client.publish(MQTT_TOPIC, str(current_player))
else:
response_topic = f"{MQTT_TOPIC}/response"
response_message = f"Invalid move or not your turn, current player: {current_player}"
client.publish(response_topic, response_message)
def game_change(topic, message):
global current_player
topic = topic.decode("utf-8")
message = message.decode("utf-8")
move = message.split(",")
print("Received from MQTT topic: {} - mes: {}".format(topic, move))
board[int(move[2]) * 3 + int(move[1])] = current_player
show_board()
current_player = 3 - current_player
# set up MQTT client
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(process_move)
connect_to_mqtt_broker()
testLcd(5)
try:
while 1:
client.wait_msg()
finally:
client.disconnect()