ti-powerbar/app/__init__.py

64 lines
2.1 KiB
Python
Raw Normal View History

2023-11-20 10:33:19 +00:00
from flask import Flask
2023-11-19 00:07:25 +00:00
from app.views import routes
2023-11-19 00:48:18 +00:00
from flask import jsonify
2023-11-20 10:33:19 +00:00
from app.settings import powerbars
2024-02-01 10:58:27 +00:00
from app.utils import get_baytech_status_outlet_telnet
2023-12-02 17:17:42 +00:00
from flask_socketio import SocketIO, emit
2023-12-02 17:28:24 +00:00
from gevent import monkey
2024-02-09 11:39:28 +00:00
from app.jobs import scheduler, generate_batch_jobs
2023-12-02 17:17:42 +00:00
2023-12-02 17:28:24 +00:00
socketio = SocketIO(async_mode="gevent", logger=True, engineio_logger=True, cors_allowed_origins="*")
2023-12-02 17:17:42 +00:00
@socketio.on('connect', namespace='/powerupdates')
def connect_handler():
print('connected')
emit('response', {'meta': 'WS connected'})
2023-11-18 23:23:17 +00:00
2024-02-07 17:18:33 +00:00
def powerbar_status():
2023-11-20 10:33:19 +00:00
for powerbar_name, powerbar_info in powerbars.items():
print(f"Checking powerbar state {powerbar_name}")
if powerbar_info['type'] == 'baytech':
try:
print("Is a baytech powerbar, getting outlet status")
2024-02-07 17:18:33 +00:00
if powerbar_info['method'] in ["telnet", "batch_telnet"]:
2024-02-01 22:48:19 +00:00
outlets = get_baytech_status_outlet_telnet(powerbar_name)
2024-02-01 10:58:27 +00:00
2023-11-20 10:33:19 +00:00
try:
for outlet_id, outlet_info in powerbar_info['outlets'].items():
powerbar_info['outlets'][outlet_id]['state'] = outlets[outlet_id].lower()
print(f" Powerbar: {powerbar_name} Outlet: {outlet_id}, State: {outlets[outlet_id].lower()}")
except:
print(f"Failed to get outlet status from powerbar {powerbar_name} outlet: {outlet_id}")
continue
except:
print(f"Failed to get outlet status from powerbar {powerbar_name}")
continue
2024-02-07 17:18:33 +00:00
return
def create_app():
# create and configure the app
app = Flask(__name__)
app.config.from_pyfile('settings.py')
app.register_blueprint(routes)
powerbar_status()
scheduler.init_app(app)
2024-02-09 11:39:28 +00:00
generate_batch_jobs()
2023-12-02 17:17:42 +00:00
socketio.init_app(app)
2023-11-19 00:07:25 +00:00
return app
2023-11-19 00:48:18 +00:00
2023-11-19 00:48:57 +00:00
app = create_app()
2024-02-07 17:18:33 +00:00
scheduler.start()
2023-11-19 00:48:18 +00:00
@app.errorhandler(403)
def not_authorised(e):
return jsonify(error="Not authorized"), 403
@app.errorhandler(500)
def internal_server_error(e):
return jsonify(error="Internal server error"), 500
2023-11-19 00:48:57 +00:00
2023-12-02 17:28:24 +00:00
if not app.config["DEBUG"]:
monkey.patch_all()
2024-02-07 17:18:33 +00:00