Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
cloud4rpi/cloud4rpi/__init__.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
61 lines (48 sloc)
1.63 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import time | |
import logging | |
from logging import StreamHandler, Formatter | |
from logging.handlers import RotatingFileHandler | |
from cloud4rpi.version import __version__ | |
from cloud4rpi.config import mqqtBrokerHost | |
from cloud4rpi.config import mqttBrokerPort, mqttsBrokerPort | |
from cloud4rpi.config import loggerName | |
from cloud4rpi.device import Device | |
from cloud4rpi.mqtt_api import MqttApi | |
from cloud4rpi.errors import get_error_message | |
log = logging.getLogger(loggerName) | |
log.setLevel(logging.INFO) | |
log.addHandler(StreamHandler()) | |
def connect(device_token, | |
host=mqqtBrokerHost, | |
port=None, | |
tls_config=None): | |
if port is None: | |
port = mqttsBrokerPort if isinstance(tls_config, dict) \ | |
else mqttBrokerPort | |
api = MqttApi(device_token, host, port, tls_config) | |
__attempt_to_connect_with_retries(api) | |
return Device(api) | |
def __attempt_to_connect_with_retries(api, attempts=10): | |
retry_interval = 5 | |
for attempt in range(attempts): | |
try: | |
api.connect() | |
except Exception as e: | |
log.debug('MQTT connection error %s. Attempt %s', e, attempt) | |
time.sleep(retry_interval) | |
continue | |
else: | |
break | |
else: | |
raise Exception('Impossible to connect to MQTT broker. Quiting.') | |
def set_logging_to_file(log_file_path): | |
log_file = RotatingFileHandler( | |
log_file_path, | |
maxBytes=1024 * 1024, | |
backupCount=10 | |
) | |
log_file.setFormatter(Formatter('%(asctime)s: %(message)s')) | |
log.addHandler(log_file) | |
def set_logging_level(level=logging.INFO): | |
log.setLevel(level) |