remote_control/remote_control.py

61 lines
2.4 KiB
Python
Raw Normal View History

2022-09-04 12:58:52 +01:00
import config
import json
import lirc
import logging
import paho.mqtt.client as mqtt
import report
import socket
import time
try:
from config import APP_NAME as ROOT_LOGGER_NAME
except ImportError:
ROOT_LOGGER_NAME = 'root'
logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('main')
class remote_control(object):
def __init__(self):
self.__lirc_client__ = lirc.Client()
self.__client__ = mqtt.Client(config.APP_NAME) # create client object
self.__client__.on_message = self.__receive__ # attach function to callback
self.__client__.username_pw_set(config.MQTT_USER, config.MQTT_PASS) # login with credentials
try:
self.__client__.connect(config.MQTT_SERVER, 1883) # establish connection
self.__client__.loop_start() # start the loop
for remote in config.SUPPORTED_REMOTES:
for command in config.SUPPORTED_REMOTES[remote]:
topic = config.MQTT_TOPIC + "/" + remote + "/" + command
logger.debug("Subscribing \"%s\"", topic)
self.__client__.subscribe(topic) # subscibe a topic
except (socket.timeout, OSError) as e:
logger.warning("Erro while setting up mqtt instance and listener")
def __receive__(self, client, userdata, message):
try:
payload = json.loads(message.payload)
except json.decoder.JSONDecodeError:
payload = None
if payload is None:
remote = message.topic.split("/")[-2]
command = message.topic.split("/")[-1]
try:
self.__lirc_client__.send_once(remote, command)
except TimeoutError:
logger.exception("Timeout-Error while sending IR-Command.")
logger.info("Sending once: %s to %s.", command, remote)
elif payload is True:
logger.warning("Start of remote command NYI!")
elif payload is False:
logger.warning("Stop of remote command NYI!")
if __name__ == '__main__':
report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
#
rc = remote_control()
#
while (True):
time.sleep(30)