Make MqttClient a singleton

master
esensar 2018-05-04 08:35:26 +02:00
parent 4dbba2b44c
commit 50d67fd521
2 changed files with 25 additions and 6 deletions

View File

@ -3,11 +3,12 @@ from flask import Blueprint
from .mqtt_client import MqttClient from .mqtt_client import MqttClient
devices = Blueprint('devices', __name__) devices = Blueprint('devices', __name__)
mqtt_client = MqttClient() mqtt_client = None
# When app dies, stop mqtt connection # When app dies, stop mqtt connection
def on_stop(): def on_stop():
if mqtt_client:
mqtt_client.tear_down() mqtt_client.tear_down()
@ -22,4 +23,8 @@ def hello():
@devices.record @devices.record
def on_blueprint_setup(setup_state): def on_blueprint_setup(setup_state):
print('Blueprint setup')
mqtt_client = MqttClient()
if mqtt_client:
mqtt_client.setup(setup_state.app) mqtt_client.setup(setup_state.app)

View File

@ -5,11 +5,25 @@ from .models import Recording
from app import db, app from app import db, app
class MqttClient: class MqttClient:
class __MqttClient:
def __init__(self): def __init__(self):
self.mqtt = Mqtt() self.mqtt = Mqtt()
self.initialized = False self.initialized = False
def __str__(self):
return repr(self)
instance = None
def __init__(self):
if not MqttClient.instance:
MqttClient.instance = MqttClient.__MqttClient()
def __getattr__(self, name):
return getattr(self.instance, name)
# Mqtt setup # Mqtt setup
def setup(self, app): def setup(self, app):
if not self.initialized: if not self.initialized: