80 lines
2.9 KiB
Python
80 lines
2.9 KiB
Python
# mqtt_motor_control.py
|
|
import paho.mqtt.client as mqtt
|
|
import time
|
|
|
|
# Настройки MQTT
|
|
MQTT_BROKER = "192.168.31.225" # Адрес MQTT брокера
|
|
MQTT_PORT = 1883 # Порт MQTT
|
|
MQTT_USER = "test" # Имя пользователя
|
|
MQTT_PASSWORD = "1234" # Пароль
|
|
MQTT_TOPIC = "motor/control" # Топик для управления двигателем
|
|
|
|
def on_connect(client, userdata, flags, rc):
|
|
if rc == 0:
|
|
print("Connected to MQTT broker")
|
|
else:
|
|
print(f"Failed to connect, return code {rc}")
|
|
|
|
def send_command(command):
|
|
"""Отправка команды в MQTT топик"""
|
|
client.publish(MQTT_TOPIC, command)
|
|
print(f"Sent command: {command}")
|
|
|
|
def main():
|
|
# Создание клиента MQTT
|
|
global client
|
|
client = mqtt.Client()
|
|
|
|
# Установка учетных данных
|
|
client.username_pw_set(MQTT_USER, MQTT_PASSWORD)
|
|
|
|
# Установка функции обратного вызова при подключении
|
|
client.on_connect = on_connect
|
|
|
|
# Подключение к брокеру
|
|
try:
|
|
client.connect(MQTT_BROKER, MQTT_PORT, 60)
|
|
client.loop_start() # Запуск цикла обработки в отдельном потоке
|
|
|
|
print("MQTT Motor Controller")
|
|
print("Commands:")
|
|
print(" start - запустить двигатель")
|
|
print(" stop - остановить двигатель")
|
|
print(" turnon - включить управление двигателем")
|
|
print(" turnoff - выключить управление двигателем")
|
|
print(" speed <value> - установить скорость (например: speed 2000)")
|
|
print(" exit - выход")
|
|
|
|
while True:
|
|
command = input("\nEnter command: ").strip()
|
|
|
|
if command == "exit":
|
|
break
|
|
elif command == "start":
|
|
send_command("start")
|
|
elif command == "stop":
|
|
send_command("stop")
|
|
elif command == "turnon":
|
|
send_command("turnon")
|
|
elif command == "turnoff":
|
|
send_command("turnoff")
|
|
elif command.startswith("speed "):
|
|
try:
|
|
speed = int(command.split()[1])
|
|
send_command(f"speed:{speed}")
|
|
except ValueError:
|
|
print("Invalid speed value. Please enter a number.")
|
|
else:
|
|
print("Unknown command. Use 'start', 'stop', 'speed <value>', or 'exit'")
|
|
|
|
except KeyboardInterrupt:
|
|
print("\nShutting down...")
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
finally:
|
|
client.loop_stop()
|
|
client.disconnect()
|
|
print("Disconnected")
|
|
|
|
if __name__ == "__main__":
|
|
main() |