refactor v2
This commit is contained in:
37
app.py
37
app.py
@@ -17,7 +17,7 @@ app = Flask(__name__)
|
||||
app.config['SECRET_KEY'] = config.FLASK_CONFIG['secret_key']
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = config.FLASK_CONFIG.get('static_cache_timeout', 60)
|
||||
# Bez Eventlet (deprecated) – prosty tryb wątkowy.
|
||||
socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading", logger=False)
|
||||
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading', logger=False)
|
||||
|
||||
def get_file_hash(filename):
|
||||
full_path = os.path.join(app.static_folder, filename)
|
||||
@@ -291,11 +291,32 @@ def api_outages(phase_id):
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
clients = 0
|
||||
task = None
|
||||
|
||||
@socketio.on('connect')
|
||||
def handle_connect():
|
||||
global clients, task
|
||||
clients += 1
|
||||
if task is None:
|
||||
task = socketio.start_background_task(background_voltage_update)
|
||||
|
||||
@socketio.on('disconnect')
|
||||
def handle_disconnect():
|
||||
global clients
|
||||
clients = max(0, clients - 1)
|
||||
|
||||
def background_voltage_update():
|
||||
global clients
|
||||
last_refresh = 0
|
||||
refresh_every_s = config.CHART_CONFIG.get("refresh_interval_seconds", 15)
|
||||
interval_s = config.CHART_CONFIG['update_interval'] / 1000.0
|
||||
|
||||
while True:
|
||||
if clients == 0:
|
||||
socketio.sleep(1)
|
||||
continue
|
||||
|
||||
try:
|
||||
voltages = {'timestamp': None}
|
||||
|
||||
@@ -305,29 +326,21 @@ def background_voltage_update():
|
||||
if res['timestamp']:
|
||||
voltages['timestamp'] = res['timestamp']
|
||||
|
||||
# aktualizacja gauge
|
||||
socketio.emit('voltage_update', voltages)
|
||||
|
||||
# cykliczny refresh wykresu + eventów
|
||||
now = time.time()
|
||||
if now - last_refresh >= refresh_every_s:
|
||||
socketio.emit('refresh_timeseries', {'ts': int(now)})
|
||||
last_refresh = now
|
||||
|
||||
except Exception as e:
|
||||
print(f"Worker Error: {e}")
|
||||
app.logger.error(f"Worker Error: {e}")
|
||||
|
||||
#time.sleep(config.CHART_CONFIG['update_interval'] / 1000.0)
|
||||
socketio.sleep(interval_s)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("\n" + "="*50)
|
||||
print(f"Voltage Monitor API / Port: {config.FLASK_CONFIG['port']}")
|
||||
print("="*50 + "\n")
|
||||
|
||||
socketio.start_background_task(background_voltage_update)
|
||||
socketio.run(
|
||||
app,
|
||||
host="0.0.0.0",
|
||||
port=config.FLASK_CONFIG["port"],
|
||||
allow_unsafe_werkzeug=True
|
||||
)
|
||||
socketio.run(app, host='0.0.0.0', port=config.FLASK_CONFIG['port'], allow_unsafe_werkzeug=True)
|
||||
Reference in New Issue
Block a user