80 lines
2.5 KiB
Python
80 lines
2.5 KiB
Python
from flask import Flask, jsonify
|
|
from pymodbus.client.serial import ModbusSerialClient
|
|
|
|
app = Flask(__name__)
|
|
|
|
# Настройка Modbus клиента
|
|
port_Arduino = 'COM3' # Убедитесь, что это правильный порт для вашего компьютера
|
|
baudrate = 115200
|
|
|
|
client = ModbusSerialClient(port=port_Arduino, baudrate=115200, timeout=1, stopbits=1, bytesize=8, parity='N')
|
|
|
|
# Попытка подключения к Modbus клиенту
|
|
try:
|
|
if client.connect():
|
|
print("Подключение успешно!")
|
|
else:
|
|
print("Не удалось подключиться к порту.")
|
|
except PermissionError as e:
|
|
print(f'Ошибка доступа к порту: {e}')
|
|
except Exception as e:
|
|
print(f'Ошибка подключения: {e}')
|
|
|
|
STATUS_REGISTER = 0 # Адрес регистра, где хранится статус
|
|
|
|
@app.route('/modbus-status', methods=['GET'])
|
|
def modbus_status():
|
|
try:
|
|
result = client.read_holding_registers(STATUS_REGISTER, 1)
|
|
if result.isError():
|
|
return jsonify({'error': 'Не удалось прочитать данные с Arduino'}), 500
|
|
else:
|
|
connected = bool(result.registers[0])
|
|
return jsonify({'connected': connected})
|
|
except Exception as e:
|
|
return jsonify({'error': str(e)}), 500
|
|
|
|
@app.route('/')
|
|
def index():
|
|
return '''
|
|
<!DOCTYPE html>
|
|
<html lang="ru">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Статус пина</title>
|
|
<style>
|
|
#status-circle {
|
|
width: 100px;
|
|
height: 100px;
|
|
border-radius: 50%;
|
|
background-color: red;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div id="status-circle"></div>
|
|
|
|
<script>
|
|
function updateStatus() {
|
|
fetch('/modbus-status')
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
const circle = document.getElementById('status-circle');
|
|
if (data.connected) {
|
|
circle.style.backgroundColor = 'green';
|
|
} else {
|
|
circle.style.backgroundColor = 'red';
|
|
}
|
|
});
|
|
}
|
|
|
|
setInterval(updateStatus, 1000); // Проверка статуса каждую секунду
|
|
</script>
|
|
</body>
|
|
</html>
|
|
'''
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True, host='0.0.0.0')
|