import time
import network
from machine import Pin, ADC, I2C
from umqtt.simple import MQTTClient
from ssd1306 import SSD1306_I2C
# MQTT
MQTT_ID_CLIENT = "micropython-linha-de-producao"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = "monitorando-linha-de-producao"
MQTT_USER = ""
MQTT_PASSWORD = ""
# Sensores
count_sensor = Pin(14, Pin.IN, Pin.PULL_UP)
fail_sensor = Pin(27, Pin.IN, Pin.PULL_UP)
speed_sensor = ADC(Pin(32))
# Display OLED
i2c = I2C(1, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
def show_data(garrafas, velocidade, falha, oee):
oled.fill(0)
oled.text(f"Garrafas: {garrafas}", 0, 0)
oled.text(f"Velocidade: {velocidade}%", 0, 16)
oled.text(f"Falha: {falha}", 0, 32)
oled.text(f"OEE: {oee:.1f}%", 0, 48)
oled.show()
# Variáveis
garrafas = 0
tempo_inicio = time.time()
# Eficiência OEE
def calc_oee(garrafas, falha, tempo_inicio):
tempo_total = time.time() - tempo_inicio
if tempo_total <= 0:
tempo_total = 1
disponibilidade = 100 if falha == 0 else 80
performance = min(100, garrafas / (tempo_total / 2))
qualidade = 98
oee = (disponibilidade * performance * qualidade) / 10000
return oee * 100, disponibilidade, performance, qualidade
# Interrupção do sensor de contagem
def contar(pin):
global garrafas
garrafas += 1
count_sensor.irq(trigger=Pin.IRQ_FALLING, handler=contar)
# Conexão Wi-Fi
print("Conectando ao 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("\nWiFi conectado!")
# Conexão MQTT
print("Conectando ao servidor MQTT...", end="")
client = MQTTClient(MQTT_ID_CLIENT, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Conectado!")
# Loop principal
while True:
velocidade = int(speed_sensor.read() / 40.95) # 0 - 100%
falha = fail_sensor.value() # 1 = OK, 0 = Falha
oee, disp, perf, qual = calc_oee(garrafas, falha, tempo_inicio)
# Publicação MQTT
client.publish("fabrica/linha1/garrafas", str(garrafas))
client.publish("fabrica/linha1/velocidade", str(velocidade))
client.publish("fabrica/linha1/falha", str(falha))
client.publish("fabrica/linha1/oee", str(oee))
# Mostrar no display
show_data(garrafas, velocidade, falha, oee)
time.sleep(2)