Esempio n. 1
0
def run(voc, config):

    # FIXME: Allow MQTT credentials in voc.conf

    client_id = 'voc_{hostname}_{time}'.format(hostname=hostname(),
                                               time=time())

    mqtt_config = read_mqtt_config()

    mqtt = paho.Client(client_id=client_id, clean_session=False)
    mqtt.username_pw_set(username=mqtt_config['username'],
                         password=mqtt_config['password'])
    mqtt.tls_set(certs.where())

    mqtt.on_connect = on_connect
    mqtt.on_disconnect = on_disconnect
    mqtt.on_publish = on_publish
    mqtt.on_message = on_message
    mqtt.on_subscribe = on_subscribe

    mqtt.event_connected = Event()

    mqtt.connect(host=mqtt_config['host'], port=int(mqtt_config['port']))
    mqtt.loop_start()

    interval = int(config['interval'])
    _LOGGER.info(f'Polling every {interval} seconds')

    entities = {}

    while True:

        if not mqtt.event_connected.is_set():
            _LOGGER.debug('Waiting for MQTT connection')
            mqtt.event_connected.wait()
            _LOGGER.debug('Connected')

        available = True
        for vehicle in voc.vehicles:
            if vehicle not in entities:
                _LOGGER.debug('creating vehicle %s', vehicle)

                dashboard = Dashboard(vehicle)
                dashboard.configurate(**config)

                entities[vehicle] = [
                    Entity(mqtt, instrument, config)
                    for instrument in dashboard.instruments
                ]

            for entity in entities[vehicle]:
                _LOGGER.debug('%s: %s', entity.instrument.full_name,
                              entity.state)
                entity.publish_discovery()
                entity.publish_availability(available)
                if available:
                    entity.publish_state()

        sleep(interval)
        available = voc.update()
Esempio n. 2
0
    def reinit(self, inputarchive, outputarchive):
        """
        @param tempdir: a path to store temporary files
        @param inputarchive: tarchive with input files
        @param outputarchive: tarchive where results are written to
        """

        logger.info('Working on %s.', inputarchive)

        try:
            shutil.rmtree(self.tmp)
            del self._md
        except AttributeError:
            pass

        os.makedirs(self.tmp)
        os.chdir(self.tmp)
        self._executable()

        if self.alpha is not None:
            import analysis
            fname = os.path.basename(inputarchive)
            name = fname.split('_')

            if len(name) == 2:
                mutant = name[0]
                replik = int(name[1].split('.')[0])
            else:
                mutant = name[0]
                replik = 0
                logger.warning('No replik-info found. Setting to 0')

            mset = analysis.MapSettings(mutant, replik, self.alpha, self.hij,
                                        self.force_remap)

            self._md = self._tar2md(inputarchive, mset)
        else:
            self._md = self._tar2md(inputarchive, None)

        if outputarchive is None:
            logger.warning("NO OUTPUTARCHIVE. Appending data to inputarchive.")
            self.archive = inputarchive
        else:
            self.archive = outputarchive

        self.saved_files = {}

        # initizalize self.saved_files, so we do not add files to archive 2x
        if inputarchive == outputarchive:
            for obj in self._check_files_to_store():
                fname, mtim, md5, size = obj
                self.saved_files[MTIME][fname] = mtim
                self.saved_files[SIZE][fname] = size
                self.saved_files[MD5][fname] = md5

        self.lastbackup = time.time()

        logger.debug('Initialized on %s, in %s', hostname(), os.getcwd())
Esempio n. 3
0
    def run(self, exe):
        """ run simulation with executable exe """
        if os.path.isfile(self.logfile[0]):
            self.status = self.checklogfile()
            if self.status == 0:
                return 0

        ifname = self.inputfile[0]
        ofname = self.logfile[0]

        if len(ifname) == 1 or len(ofname) == 1:
            raise (Exception, 'WTF')

        self._deploy()

        # run q
        start = time.time()
        cmd = exe + " " + ifname
        logger.info("%s", ifname)
        logger.debug("%s %s", hostname(), cmd)
        try:
            subprocess.check_call([exe, ifname], stdout=open(ofname, 'w'))
            self.q_exitcode = 0
        except subprocess.CalledProcessError as exitstatus:
            logger.warning('Detected a non-zero exit status!', exitstatus)
            self.q_exitcode = exitstatus.returncode

        # check logfile
        self.checklogfile()

        self.time = time.time() - start

        if self.status == 0 and self.q_exitcode == 0:
            return 0
        else:
            logger.warning('Detected status %s %s %s', self.status,
                           'and an exitcode', self.q_exitcode)
            return self.status + self.q_exitcode
Esempio n. 4
0

if __name__ == "__main__":

    try:
        Watcher()

        config_filename = "config.local.json"
        config_file = Path(config_filename)
        if not config_file.is_file():
            config_filename = "config.json"

        log("Loading config from '%s'" % config_filename)
        MQTTCFG = json.load(open(config_filename))

        CLIENT = "evmqtt_{hostname}_{time}".format(hostname=hostname(),
                                                   time=time())

        MQ = MQTTClient(CLIENT, MQTTCFG)
        MQ.start()

        topic = MQTTCFG["topic"]
        devices = MQTTCFG["devices"]

        available_devices = [
            evdev.InputDevice(path) for path in evdev.list_devices()
        ]
        log("Found %s available devices:" % len(available_devices))
        for device in available_devices:
            log("Path:'%s', Name: '%s'" % (device.path, device.name))
Esempio n. 5
0
async def run(voc, config):

    logging.getLogger("hbmqtt.client.plugins.packet_logger_plugin").setLevel(
        logging.WARNING)

    client_id = "voc_{hostname}_{time}".format(hostname=hostname(),
                                               time=time())

    mqtt = MQTTClient(client_id=client_id)
    url = config.get("mqtt_url")

    if url:
        _LOGGER.debug("Using MQTT url from voc.conf")
    else:
        _LOGGER.debug("Using MQTT url from mosquitto_pub")
        mqtt_config = read_mqtt_config()
        try:
            username = mqtt_config["username"]
            password = mqtt_config["password"]
            host = mqtt_config["host"]
            port = mqtt_config["port"]
            url = "mqtts://{username}:{password}@{host}:{port}".format(
                username=username, password=password, host=host, port=port)
        except Exception as e:
            exit(e)

    entities = {}

    async def mqtt_task():
        try:
            await mqtt.connect(url, cleansession=False, cafile=certifi.where())
            _LOGGER.info("Connected to MQTT server")
        except ConnectException as e:
            exit("Could not connect to MQTT server: %s" % e)
        while True:
            _LOGGER.debug("Waiting for messages")
            try:
                message = await mqtt.deliver_message()
                packet = message.publish_packet
                topic = packet.variable_header.topic_name
                payload = packet.payload.data.decode("ascii")
                _LOGGER.debug("got message on %s: %s", topic, payload)
                Entity.route_message(topic, payload)
            except ClientException as e:
                _LOGGER.error("MQTT Client exception: %s", e)

    asyncio.create_task(mqtt_task())  # pylint:disable=no-member

    interval = int(config["interval"])
    _LOGGER.info("Polling VOC every %d seconds", interval)
    while True:
        available = await voc.update(journal=True)
        wait_list = []
        for vehicle in voc.vehicles:
            if vehicle not in entities:
                _LOGGER.debug("creating vehicle %s", vehicle)

                dashboard = vehicle.dashboard(**config)

                entities[vehicle] = [
                    Entity(mqtt, instrument, config)
                    for instrument in dashboard.instruments
                ]
            for entity in entities[vehicle]:
                _LOGGER.debug("%s: %s", entity.instrument.full_name,
                              entity.state)
                wait_list.append(entity.publish_discovery())
                wait_list.append(entity.publish_availability(available))
                if available:
                    wait_list.append(entity.publish_state())

        await asyncio.gather(*wait_list)
        _LOGGER.debug("Waiting for new VOC update in %d seconds", interval)
        await asyncio.sleep(interval)
Esempio n. 6
0
# -*- coding: utf-8 -*-

import subprocess
import sys
from asyncio import sleep
from json import loads, dumps
from os import system as cmd, getenv as env, listdir as ls, execl, devnull
from pengaelicutils import newops, getops, remove_duplicates, list2str, jsoncheck
from platform import node as hostname
from random import choice, randint
print("Imported modules")

if hostname() != "localhost":
    devnull = open(devnull, "w")
    requirements = ["fortune-mod", "fortunes",
                "fortunes-min", "neofetch", "toilet", "toilet-fonts"]
    need2install = False
    for package in requirements:
        if subprocess.call(["dpkg", "-s", package], stdout=devnull, stderr=subprocess.STDOUT):
            print(f"Package {package} not installed.")
            need2install = True
    devnull.close()
    if need2install:
        print("Install these with APT.")
        exit()
    print("Passed package test")
else:
    print("Ignored package test")

requirements = ["discord.py", "num2words",
                "python-dotenv", "speedtest-cli", "tinydb"]
Esempio n. 7
0
    def _create_adaptive_streams(self, info, streams):
        if not MuxedStream.is_usable(self.session):
            log.info("Cannot use FFMPEG")
            return streams

        adaptive_streams = {}
        best_audio_itag = None
        adp_video = self.adp_video_h264.copy()
        vp9 = "vp9" if hostname() in self.stb_vp9_1 or hostname(
        ) in self.stb_vp9_2 else ""
        if not vp9:
            log.debug("STB w/o vp9 4K support detected")
            if self.get_option("yes-vp9-codecs"):
                vp9 = "vp9"
        elif self.get_option("no-vp9-codecs"):
            vp9 = ""
            log.info("VP9 Codecs are skipped")
        if vp9:
            adp_video.update(self.adp_video_vp9)
            if self.get_option(
                    "yes-vp9-hdr-codecs") or hostname() in self.stb_vp9_2:
                adp_video.update(self.adp_video_vp9_hdr)

        # Extract streams from the DASH format list
        for stream_info in info.get("formats", []):
            itag = int(stream_info["format_id"])
            if itag not in self.adp_audio and itag not in adp_video:
                log.debug(
                    "Skipped format:{}, Codec:{}",
                    stream_info["format"],
                    stream_info["acodec"] if stream_info["acodec"] != "none"
                    else stream_info["vcodec"],
                )
                continue

            # extract any high quality streams only available in adaptive formats and not skipped
            adaptive_streams[itag] = stream_info["url"]
            stream_format = stream_info["ext"]
            if itag in self.adp_audio:
                if self.get_option(
                        "no-opus-codec") and stream_info["acodec"] == "opus":
                    log.debug("Skipped format:{}, Codec:{}",
                              stream_info["format"], stream_info["acodec"])
                    continue

                stream = HTTPStream(self.session, stream_info["url"])
                name = "audio_{0}".format(stream_format)
                streams[name] = stream

                # find the best quality audio stream m4a, opus or vorbis
                if best_audio_itag is None or self.adp_audio[
                        itag] > self.adp_audio[best_audio_itag]:
                    best_audio_itag = itag

        if best_audio_itag and adaptive_streams and MuxedStream.is_usable(
                self.session):
            aurl = adaptive_streams[best_audio_itag]
            for itag, name in adp_video.items():
                if itag in adaptive_streams:
                    vurl = adaptive_streams[itag]
                    log.debug(
                        "MuxedStream: v {video} a {audio} = {name}".format(
                            audio=best_audio_itag,
                            name=name,
                            video=itag,
                        ))
                    streams[name] = MuxedStream(self.session,
                                                HTTPStream(self.session, vurl),
                                                HTTPStream(self.session, aurl))

        return streams
Esempio n. 8
0
async def run(discover, config):
    _LOGGER.debug("Found %d devices in config", len(config))

    logging.getLogger("hbmqtt.client.plugins.packet_logger_plugin").setLevel(
        logging.WARNING
    )

    client_id = "tellsticknet_{hostname}_{time}".format(
        hostname=hostname(), time=time()
    )

    _LOGGER.debug("Client id is %s", client_id)

    mqtt = MQTTClient(client_id=client_id)

    mqtt_url = get_mqtt_url()

    devices_setup = asyncio.Event()

    async def mqtt_task():
        try:
            _LOGGER.info("Connecting")
            await mqtt.connect(uri=mqtt_url, cleansession=False)
            _LOGGER.info("Connected to MQTT server")
        except ConnectException as e:
            exit("Could not connect to MQTT server: %s" % e)

        await devices_setup.wait()
        while True:
            _LOGGER.debug("Waiting for MQTT messages")
            try:
                message = await mqtt.deliver_message()
                packet = message.publish_packet
                topic = packet.variable_header.topic_name
                payload = packet.payload.data.decode("ascii")
                _LOGGER.debug("got message on %s: %s", topic, payload)
                await Device.route_message(topic, payload)
            except ClientException as e:
                _LOGGER.error("MQTT Client exception: %s", e)

    loop = asyncio.get_event_loop()
    loop.create_task(mqtt_task())
    controller = await discover()

    if not controller:
        await mqtt._connected_state.wait()
        await mqtt.disconnect()
        exit("No tellstick device found")

    _LOGGER.info("Controller found")
    await mqtt._connected_state.wait()
    _LOGGER.info("Connected to MQTT server")

    # FIXME: Make it possible to have more components with same component
    # type but different device_class_etc

    _LOGGER.debug("Setting up devices")
    devices = [
        Device(e, mqtt, controller)
        for e in config
        if e.get("controller", controller.mac_address).lower()
        in (controller.ip_address, controller.mac_address)
    ]
    _LOGGER.debug("Configured %d devices", len(devices))
    devices_setup.set()

    # Commands are visible directly,
    # sensors only when data becomes available
    await asyncio.gather(
        *[
            device.publish_discovery()
            for device in devices
            if device.is_command
        ]
    )

    _LOGGER.info("Waiting for packets")
    async for packet in controller.events():
        if not packet:  # timeout
            continue
        received = [await d.receive_local(packet) for d in devices]
        if not any(received):
            _LOGGER.warning("Skipped packet %s", packet)
Esempio n. 9
0
                        self.mqttclient.publish(self.topic, msg)
                        # log what we publish
                        log("Published message %s" % (msg))


if __name__ == "__main__":

    try:
        Watcher()

        MQTTCFG = json.load(
            open("config.json")
        )

        CLIENT = "evmqtt_{hostname}_{time}".format(
            hostname=hostname(), time=time()
        )

        MQ = MQTTClient(CLIENT, MQTTCFG)
        MQ.start()

        # your event key device, IR, whatever goes here
        IM0 = InputMonitor(
            MQ.mqttclient,
            "/dev/input/event4",
            "homeassistant/sensor/loungeremote/state"
        )
        IM0.start()

        # add more instances
        # IM1 = InputMonitor(