Пример #1
0
 def runConfig(conf: Config.BasicConfig, logger: logging.Logger):
     c = Config.PluginConfig(conf, PluginLoader.getConfigKey())
     c["dev"] = ConsoleInputTools.get_input("Serial Device Pfad: ",
                                            require_val=True,
                                            std_val="/dev/ttyACM0")
     c["tp"] = [[0, 0], [50, 30], [60, 50], [75, 75], [80, 100]]
     c["provider"] = "rpiCPUtemp"
Пример #2
0
 def __init__(self, client: mclient.Client, opts: conf.BasicConfig,
              logger: logging.Logger, device_id: str):
     self._config = conf.PluginConfig(opts, "ShellSwitch")
     self.__client = client
     self.__logger = logger.getChild("ShellSwitch")
     self._registered_callback_topics = []
     self._name_topic_map = {}
     self._state_name_map = {}
Пример #3
0
 def __init__(self, client: mclient.Client, opts: conf.BasicConfig,
              logger: logging.Logger, device_id: str):
     self._config = conf.PluginConfig(opts, "rpiCPUtemp")
     self.__client = client
     self.__logger = logger.getChild("PiCpuTemp")
     self._prev_deg = 0
     if self._config.get("diff", None) is None:
         self._config["diff"] = 1.5
     self._callables = []
     self._open_file()
Пример #4
0
 def __init__(self, client: mclient.Client, opts: conf.BasicConfig,
              logger: logging.Logger, device_id: str):
     self._config = conf.PluginConfig(opts, PluginLoader.getConfigKey())
     self.__client = client
     self.__logger = logger.getChild(PluginLoader.getConfigKey())
     self._prev_deg = True
     self.__lastTemp = 0.0
     self.__ava_topic = device_id
     self._callables = []
     self.device = None
Пример #5
0
 def __init__(self, logger: logging.Logger, config: tc.BasicConfig):
     self.logger = logger.getChild("PluginManager")
     self.config = config
     self._client = None
     self._client_name = None
     self._wasConnected = False
     self.shed_thread = None
     self._discovery_topics = self.config.getIndependendFile(
         "discovery_topics", no_watchdog=True, do_load=True)[0]
     self.discovery_topics = tc.PluginConfig(self._discovery_topics,
                                             "Registry")
Пример #6
0
 def __init__(self, client: mclient.Client, opts: conf.BasicConfig,
              logger: logging.Logger, device_id: str):
     self._config = conf.PluginConfig(config=opts, plugin_name="soundmeter")
     self.__client = client
     self.__logger = logger.getChild("SoundMeter")
     self.__ava_topic = device_id
     self._topic = None
     self._wasTriggered = False
     self._lastRMS = -1000
     self._thread = None
     self._match_filter = self._config.get("filter/needs_positive_matches",
                                           0)
     self._neg_match_filter = self._config.get(
         "filter/needs_negativ_matches", 0)
     self._timeout_shed = None
Пример #7
0
    def __init__(self, client: mclient.Client, opts: conf.BasicConfig,
                 logger: logging.Logger, device_id: str):
        self._subdevice_ready = False
        self._config = conf.PluginConfig(opts, CONST.CONFIG_NAME)
        self.__client = client
        self.__logger = logger.getChild(CONST.CONFIG_NAME)
        self._prev_deg = None
        self.__lastTemp = 0.0
        self.__ava_topic = device_id
        self._veDevice = None

        self.__logger.debug("Erstelle verbindung...")
        self._veDirCon = Connection(self._config, self.__logger)
        self._veDirCon._device_ready_call = lambda: self._device_ready()
        self._veDirCon.start()
Пример #8
0
    def __init__(self, client: mclient.Client, opts: conf.BasicConfig,
                 logger: logging.Logger, device_id: str):
        self._config = conf.PluginConfig(opts, PluginLoader.getConfigKey())
        self.__client = client
        self.__logger = logger.getChild(PluginLoader.getConfigKey())
        self._prev_deg = True
        self.__lastTemp = 0.0
        self.__ava_topic = device_id
        self._callables = []
        self.device = None
        self._running_sensor = None

        if self._config.get("enabled/systray", True):
            self._systray = win32Systray(self._config, self.__logger)
        if self._config.get("enabled/powerevents", True):
            self._pwr_ev = WindowEventProcessor(self._config, self.__logger)
        if self._config.get("enabled/wmi_pnp", True):
            self._wmi_devices = WMI_PnP(self._config, self.__logger)
Пример #9
0
    def __init__(self, client: mclient.Client, opts: conf.BasicConfig, logger: logging.Logger, device_id: str):
        self._client = client
        self._logger = logger.getChild("BH1750")
        self._devID = device_id
        
        self._job_inst = []

        if opts.get("BHL1750", None) is not None:
            opts["BH1750"] = opts["BHL1750"]
            del opts["BHL1750"]

        self._conf = conf.PluginConfig(opts, "BH1750")

        try:
            self._bus = smbus.SMBus(self._conf["bus"])
        except:
            self._logger.exception("SMBus wurde nicht gefunden")
            self.__broken = True
Пример #10
0
    def __init__(self, client: mclient.Client, opts: conf.PluginConfig,
                 logger: logging.Logger, device_id: str):
        self._config = opts
        self.__client = client
        self.__logger = logger.getChild("kaifa")
        self._devices = []

        meters: list = self._config.get("meters", default=[])
        self.__logger.debug(f"Beginne mit verarbeiten von Meters: {meters = }")

        for dev in range(len(meters)):
            meter_key = f"meters/{dev}"
            self.__logger.debug(
                f"Baue Reader({self._config = }, {meter_key = }, {self.__logger = })"
            )
            self._devices.append(
                Reader(subConfig=conf.PluginConfig(self._config, meter_key),
                       logger=self.__logger.getChild(str(dev))))
        self.__logger.debug("Alle SmartMeter erstellt!")
Пример #11
0
    def __init__(self, client: mclient.Client, opts: conf.BasicConfig,
                 logger: logging.Logger, device_id: str):
        self._bus = None
        self._proxy = None
        self._login1 = None
        self._logger = logger
        self._mainloop = None
        self.thread_gml = GlibThread.getThread()

        self.sleeping = False
        self.shutdown = False

        self.inhibit_lock = -1
        self._switches: dict[str, Switch] = {}
        self.sessions = {}
        self._config = conf.PluginConfig(opts, "logind")

        self._poff_notiy = None
        self._sleep_notiy = None
        self._nsess_notiy = None
        self._rsess_notiy = None
        self._idle_monitor = None
Пример #12
0
 def __init__(self, client: mclient.Client, opts: Config.BasicConfig,
              logger: logging.Logger, device_id: str):
     self.__client = client
     self.__logger = logger.getChild("SerialFan")
     self._config = Config.PluginConfig(opts, "SerialFan")
     self._registered_callback_topics = []
     self._pm = None
     self.temperature = 0
     self._serial = serial.Serial(port=self._config["dev"],
                                  dsrdtr=True,
                                  rtscts=True)
     self._serial_thr = None
     self._shutdown = False
     self._rpm = 0
     self._pct = 0
     self._err = None
     self._last_rpm = 0
     self._last_pct = 0
     self._last_err = "BOOTED"
     self._speed_topics = None
     self._rpm_topics = None
     self._err_topics = None
Пример #13
0
    def __init__(self, client: mclient.Client, opts: conf.BasicConfig, logger: logging.Logger, device_id: str):
        from gpiozero.pins.native import NativeFactory
        from gpiozero import Device
        Device.pin_factory = NativeFactory()

        self._config = conf.PluginConfig(opts, PluginLoader.getConfigKey())
        self.__client = client
        self.__logger = logger.getChild("Fingerprint")
        self._finger = PyFingerprint(
            self._config["serial"],
            57600,
            0xFFFFFFFF,
            self._config.get("password", 0x00000000)
            )
        
        if not self._finger.verifyPassword():
            self.err_str = "PASSWD"
        
        if self._config.get("WAKEUP", 0) is not 0:
            self.wakupPin = Pin.Pin(pin=self._config.get("WAKEUP", 0), direction=Pin.PinDirection.IN_PULL_LOW)
            self.wakupPin.set_detect(self.wakeup, Pin.PinEventEdge.BOTH)
        else:
            self.wakeup(None, threadsleep=False)
Пример #14
0
 def __init__(self, conff: conf.BasicConfig):
     self.c = conf.PluginConfig(conff, PluginLoader.getConfigKey())
Пример #15
0
 def __init__(self, c: conf.BasicConfig):
     self.c = conf.PluginConfig(c, CONFIG_NAME)
Пример #16
0
 def __init__(self, opts: conf.BasicConfig):
     self.c = conf.PluginConfig(opts, "ShellSwitch")
     self.c.get("entrys", {})
Пример #17
0
from Tools import Config
import requests, time
import configparser

cf = configparser.ConfigParser()
cf.read("cache.ini", encoding="utf-8")  # 读取配置文件,如果写文件的绝对路径,就可以不用os模块
conf = Config()
save_conf = conf.get('save')


def baidu():
    # https://openapi.baidu.com/oauth/2.0/device/code?client_id=YOUR_CLIENT_ID&response_type=device_code& scope=basic,netdisk
    authorization_code = save_conf['baidu']['authorization_code']
    if len(authorization_code) <= 5:
        url = 'https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=%s&redirect_uri=oob&scope=basic,netdisk&display=tv&qrcode=1&force_login=1' % (
            save_conf['baidu']['client_id'])
        code = input('请在浏览器中访问此地址,并将授权码回填\n%s\n请输入授权码:' % url)
    else:
        code = authorization_code
    url = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s&redirect_uri=oob' % (
        code, save_conf['baidu']['client_id'], save_conf['baidu']['secret_key'],)
    res = requests.get(url)
    res = res.json()
    if 'error' in res:
        print('返回出错,错误代码:%s。错误信息:%s.具体请参阅%s' % (
            res['error'], res['error_description'], 'https://developer.baidu.com/newwiki/dev-wiki/fu-lu.html'))
    else:
        if not cf.has_section('baidu'):
            cf.add_section('baidu')
        cf.set("baidu", "expires_in", str(res['expires_in']))
        cf.set("baidu", "refresh_token", res['refresh_token'])
Пример #18
0
import smtplib, time, requests, os, hashlib, json
import log, traceback
from Tools import Config
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from datetime import datetime
import configparser
import lead
from requests.adapters import HTTPAdapter

cf = configparser.ConfigParser()
cf.read("/program/cache.ini", encoding="utf-8")  # 读取配置文件,如果写文件的绝对路径,就可以不用os模块

logTool = log.logs()
conf = Config()


class Mail:
    def __init__(self):
        mail_conf = conf.get('save')['mail']
        self.host = mail_conf['host']
        self.port = mail_conf['port']
        self.to = mail_conf['to']
        self.user = mail_conf['user']
        self.password = mail_conf['password']

    def save(self, path, name):

        dt = datetime.now()
        logTool.info('开始构建邮件')
Пример #19
0
 def __init__(self, con: conf.BasicConfig):
     self.__ids = []
     self.c = conf.PluginConfig(config=con, plugin_name="soundmeter")
Пример #20
0
    def launch(self):
        prog_args = sys.argv[1:]
        t_args = prog_args.copy()

        configPath = "~/.config/mqttra.config"
        auto_reload_config = True

        logPath = None

        door_hall_calib_mode = False
        conf_all_mods = False
        systemd = False
        debug = False

        while True:
            try:
                opts, args = getopt.gnu_getopt(t_args, "h?sdc:l:",
                                               ["help", "config=", "systemd", "no-reload", "door-hall-calibnoise", "configure-all-plugins", "log=", "debug"])
                break
            except getopt.error as e:
                opt = e.msg.replace("option ", "").replace(" not recognized", "")
                t_args.remove(opt)

        for opt, arg in opts:
            if opt == "-c" or opt == "--config":
                configPath = arg
            elif opt == "-s" or opt == "--systemd":
                systemd = True
                self._log.info("OK Systemflag gefunden. Bin ein Service.")
            elif opt == "--no-reload":
                auto_reload_config = False
            elif opt == "-?" or opt == "-h" or opt == "help":
                self._log.info("""
                                        ============ HILFE ============
                    -c --config             Konfigurations Datei angeben (Standartpfad ~/.config/mqttra.config)
                    -s --systemd            Verändert die logger Formatierung damit sie zu systemd passt, verhindert Fragen über installieren von pip Packeten
                    --no-reload             Neuladen des Server bei externen änderungen der Konfigurationsdatei ausschalten
                    -? -h --help            Diese Nachricht anzeigen
                    --door-hall-calibnoise  Noise Level von dem Halleffekt Sensor von Raspberry Tor ermitteln
                    --configure-all-plugins Alle Plugins Konfigureieren, wird eines Konfiguriert wird es
                                            beim nächsten Start automatisch geladen.
                    --log                   Log in Datei speichern und nicht in der Konsole ausgeben
                    --debug                 Zeit im log anzeigen, überschreibt systemd logger format
                """)
                return
            elif opt == "--door-hall-calibnoise":
                door_hall_calib_mode = True
            elif opt == "--configure-all-plugins":
                conf_all_mods = True
            elif opt == "--log":
                try:
                    if arg is not None:
                        p = Path(arg)
                        p.parent.mkdir(parents=True, exist_ok=True)
                        self._logFile = p.open(mode="wt", buffering=4096, encoding="utf-8")
                        self._log.info("Logger wird jetzt auf Logfile umgestellt...")
                        if self._ch.setStream(self._logFile) is None:
                            self._log.warning("Umstellen Fehlgeschlagen!")
                except Exception as e:
                    print("Kann logfile nicht erstellen! {}".format(e))
            elif opt == "-d" or opt == "--debug":
                debug = True
                pass

        self.config = tc.config_factory(configPath, logger=self._log, do_load=True, filesystem_listen=auto_reload_config)
        from Tools import _std_dev_info
        import Tools.Autodiscovery as ad
        devInfo = _std_dev_info.DevInfoFactory.build_std_device_info(self._log.getChild("std_dev"))
        ad.Topics.set_standard_deviceinfo(devInfo)

        try:
            import Tools.error as err
            err.set_system_mode(systemd)
        except:
            pass
        
        if door_hall_calib_mode:
            self._log.info("Ermittle noise für Halleffekt Sensor (Raspberry Tor)...")
            import Mods.DoorOpener.calibrate as calib
            calib.Calibrate.run_calibration(conf=self.config, logger=self._log)
            self._log.info("Noise ermittelt. Beende anwendung.")
            return

        elif conf_all_mods:
            pm = pman.PluginManager(self._log, self.config)
            pm.run_configurator()
            self.config.save()
            i = input("Beenden= [N/y]")
            if i == "y" or i == "Y":
                return

        

        configFolder = Path(configPath).parent
        failFile = configFolder.joinpath("fails")
        failFile.mkdir(exist_ok=True)
        failFile = failFile.joinpath(
            "{}.log".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        )
        self.faultFile = failFile.open('w')
        faulthandler.enable(file=self.faultFile, all_threads=True)

        formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
        if debug or not systemd:
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)8s - %(message)s')

        self._ch.setFormatter(formatter)

        self.relaunch(systemd)
Пример #21
0
 def __init__(self, conf: conf.BasicConfig):
     self.c = conf.PluginConfig(conf, "BH1750")
     self.c["device"] = False
     self.c["device_alt"] = False
     self.c["bus"] = -1