Software_and_hardware/Сервер1.py

83 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from flask import Flask, jsonify
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
import threading
app = Flask(__name__)
# Настройка Modbus
client = ModbusClient( port='COM4', baudrate=9600, timeout=1)
client.close()
client.connect()
# Хранилище данных состояния пина
pin_status = {"state": 0}
# Функция для обновления состояния пина с помощью Modbus
def read_modbus():
global pin_status
while True:
result = client.read_holding_registers(0, 1, unit=1) # Чтение первого регистра
if result.isError():
print("Ошибка чтения данных Modbus")
else:
pin_status["state"] = result.registers[0] # 0 - это состояние пина (0 или 1)
print(f"Регистр успешно считан: {result.registers}")
# Запуск потока для чтения данных
modbus_thread = threading.Thread(target=read_modbus)
modbus_thread.daemon = True
modbus_thread.start()
# Эндпоинт для отдачи состояния пина
@app.route('/state', methods=['GET'])
def get_pin_state():
return jsonify(pin_status)
# Главная страница для отображения круга
@app.route('/')
def index():
return '''
<html>
<head>
<style>
.circle {
width: 100px;
height: 100px;
border-radius: 50%;
margin: 50px;
transition: background-color 0.5s ease;
}
.green {
background-color: green;
}
.red {
background-color: red;
}
</style>
</head>
<body>
<div id="circle" class="circle"></div>
<script>
function updateCircleColor() {
fetch('/state')
.then(response => response.json())
.then(data => {
const circle = document.getElementById('circle');
if (data.state === 0) {
circle.className = 'circle green'; // Зеленый цвет
} else {
circle.className = 'circle red'; // Красный цвет
}
});
}
setInterval(updateCircleColor, 1000); // Обновляем состояние каждую секунду
updateCircleColor(); // Первоначальный вызов
</script>
</body>
</html>
'''
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)