예제 #1
0
 def __init__(self,
              usuarios_por_pagina: int = 10,
              total_de_usuarios: int = 0):
     Singleton.__init__(self)
     self.usuarios_por_pagina = usuarios_por_pagina
     self.total_de_usuarios = 0
     self.paginas = Paginas()
예제 #2
0
 def log(level, message, source):
     date = str(datetime.datetime.now())
     singleton = Singleton()
     aLog = date + " " + "[" + threading.current_thread(
     ).name + "] " + level + " " + source + " " + message
     if (level == "DBG"):
         if singleton.debug:
             Functions.logdebug()
             print(aLog, flush=True)
     elif (level == "ERR" or level == "WNG" or level == "DEAD"):
         Functions.logred()
         print(aLog, end='', flush=True)
         Functions.lognormal()
     elif (level == "ASK"):
         Functions.logyellow()
         print(aLog, flush=True)
     else:
         Functions.lognormal()
         print(aLog, flush=True)
     if (level == "DEAD"):
         sys.exit(1)
     singleton.logs.append(aLog)
     f = open("/tmp/pimpMySuperWatt.log", "a+")
     f.write(aLog + "\r\n")
     sys.stdout.flush()
예제 #3
0
def startWeb():
    singleton = Singleton()
    # Ok now check if we webserver is asked
    if singleton.parameters["webserver"]:
        Functions.log("DBG", "Webserver is asked, starting it", "CORE")
        importlib.import_module('web')
        Functions.log(
            "DBG",
            "Trying instanciation of " + str(singleton.parameters["webClass"]),
            "CORE")
        mod = importlib.import_module('.' + singleton.parameters["webClass"],
                                      package="web")
        aSiteClass = getattr(mod, singleton.parameters["webClass"])
        singleton.instanceWebApp = aSiteClass()
    else:
        Functions.log("DBG", "Webserver not asked", "CORE")
예제 #4
0
def pimpMySuperWatt():
    Functions.log("INF", "Instanciate Singleton", "CORE")
    singleton = Singleton()
    Functions.log("INF",
                  "Starting PimpMySuperWatts on " + socket.gethostname(),
                  "CORE")
    Functions.log("INF", "Analysing arguments", "CORE")
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "configFile",
        help="The absolute path to the configuration file (pimpMySuperWatt.py)"
    )
    parser.add_argument("--debug",
                        help="Debug mode, more verbosity",
                        action="store_true")
    args = parser.parse_args()

    checkParameter(args)

    # Web starting
    waitServer = threading.Thread(target=startWeb)
    waitServer.start()

    # Connector communication starting
    waitConnector = threading.Thread(target=startConnector)
    waitConnector.start()

    waitThread = threading.Thread(target=waitEnd)
    waitThread.start()

    startDaemons()
    startPlugins()
    waitServer.join()
예제 #5
0
def pluginRequest():
    Functions.log("DBG", "Start plugin request", "CORE")
    singleton = Singleton()
    for plugin in singleton.plugins:
        plugin.runPlugin()
        influxData = plugin.influxData()
        sendToInflux(influxData)
        sendToMqtt(influxData)
예제 #6
0
 def inverterParameters():
     singleton = Singleton()
     return {
         "qpi": singleton.QPI,
         "qid": singleton.QID,
         "qfw": singleton.QVFW,
         "qfw2": singleton.QVFW2,
     }
예제 #7
0
def startConnector():
    singleton = Singleton()
    Functions.log("DBG", "Start connector now", "CORE")
    # Ok let's start with connector checking
    importlib.import_module('communication')
    Functions.log(
        "DBG", "Trying instanciation of " +
        str(singleton.parameters["communicationClass"]), "CORE")
    if not singleton.parameters["communicationClass"] == "":
        try:
            Functions.log(
                "DBG", "Importing module communicationClass " +
                str(singleton.parameters["communicationClass"]), "CORE")
            modCom = importlib.import_module(
                '.' + singleton.parameters["communicationClass"],
                package="communication")
            Functions.log(
                "DBG", "Retrieving class object " +
                str(singleton.parameters["communicationClass"]), "CORE")
            aConnectorClass = getattr(
                modCom, singleton.parameters["communicationClass"])
            singleton.connector = aConnectorClass()
            Functions.log("DBG", "Launching QPI command", "CORE")
            singleton.QPI = Functions.command("QPI", "")
            Functions.log("DBG", "Launching QID command", "CORE")
            singleton.QID = Functions.command("QID", "")
            Functions.log("DBG", "Launching QVFW command", "CORE")
            singleton.QVFW = Functions.command("QVFW", "")
            Functions.log("DBG", "Launching QVFW2 command", "CORE")
            singleton.QVFW2 = Functions.command("QVFW2", "")
        except Exception as err:
            Functions.log("ERR", "Connector exception " + str(err), "CORE")
    else:
        Functions.log("DBG", "No serial connector defined.", "CORE")
예제 #8
0
 def __init__(self):
     self.starttime = datetime.datetime.now()
     self.endtime = ""
     self.singleton = Singleton()
     Functions.log(
         "DBG", "Instanciation of a Connector Class on " +
         self.singleton.hostName + " start=" + str(self.starttime), "CORE")
     self.populateDevices()
     self.connect()
예제 #9
0
def startPlugins():
    Functions.log("DBG", "Start plugins now", "CORE")
    singleton = Singleton()
    try:
        singleton.internalScheduler.add_job(
            pluginRequest,
            'interval',
            seconds=singleton.parameters["queryPluginInterval"])
    except Exception as err:
        Functions.log("ERR", "Error with scheduler " + str(err), "CORE")
예제 #10
0
def checkParameter(args):
    singleton = Singleton()
    # If debug
    if args.debug:
        Functions.log("INF", "Debug activated", "CORE")
        singleton.debug = True

    # Populate version
    singleton.version = Functions.kommandShell("git log | head -6")

    # Read configuration file json
    configFile = os.path.abspath(args.configFile)
    if not os.path.isfile(configFile):
        Functions.log("DEAD", "File " + str(configFile) + " doesn't exist",
                      "CORE")
    Functions.log("INF", "Config file exist " + configFile, "CORE")
    singleton.configFile = configFile

    # Setting current hostname & ip
    singleton.hostName = socket.gethostname()
    for ifaceName in interfaces():
        addrs = ifaddresses(ifaceName)
        try:
            for subAdress in addrs[netifaces.AF_INET]:
                if subAdress["addr"] != "127.0.0.1":
                    Functions.log(
                        "INF", "Local ip detected " + str(subAdress["addr"]),
                        "CORE")
                    singleton.ip = str(subAdress["addr"])
        except Exception as err:
            Functions.log("WNG",
                          "Error while trying to detect local ip " + str(err),
                          "CORE")
            pass

    # Parsing the configFile
    Functions.log("DBG", "Parsing configFile " + configFile, "CORE")
    try:
        jsonLine = Functions.loadFileInALine(configFile)
        singleton.parameters = json.loads(jsonLine)
        Functions.log(
            "DBG", "Json config file successfully loaded " +
            json.dumps(singleton.parameters, indent=4), "CORE")
    except Exception as err:
        Functions.log(
            "DEAD", "Can't parse file " + configFile +
            " is it a json file ? details " + str(err), "CORE")

    # Instanciate plugin
    intanciatePlugins()
예제 #11
0
def sendToMqtt(json_body):
    singleton = Singleton()
    if not singleton.parameters["mqttServers"] == "":
        Functions.log("DBG", "Sending now to mqtts", "CORE")
        for mqtt in singleton.parameters["mqttServers"]:
            Functions.log(
                "DBG", "Sending now to " + mqtt["mqttServer"] + ":" +
                str(mqtt["mqttServerPort"]) + " server now", "CORE")
            publish.single(topic=mqtt["mqttTopic"],
                           payload=json.dumps(json_body),
                           hostname=mqtt["mqttServer"],
                           port=mqtt["mqttServerPort"])
    else:
        Functions.log("DBG", "No mqtt target specified", "CORE")
예제 #12
0
def startDaemons():
    Functions.log("DBG", "Start daemons now", "CORE")
    singleton = Singleton()
    try:
        Functions.log(
            "DBG", "Add poolingRequest job to scheduler with " +
            str(singleton.parameters["queryPoolingInterval"]) +
            " sec(s) interval", "CORE")
        singleton.internalScheduler.add_job(
            poolingRequest,
            'interval',
            seconds=singleton.parameters["queryPoolingInterval"])
    except Exception as err:
        Functions.log("ERR", "Error with scheduler " + str(err), "CORE")
예제 #13
0
def intanciatePlugins():
    singleton = Singleton()
    singleton.plugins = []
    for file in sorted(glob.glob('plugins/*/*.py')):
        moduleName = os.path.basename(file.replace(".py", ""))
        try:
            Functions.log("DBG",
                          "Loading plugins/" + moduleName + "/" + moduleName,
                          "CORE")
            mod = importlib.import_module("plugins." + moduleName + "." +
                                          moduleName)
            Functions.log(
                "DBG", "End loading plugins/" + moduleName + "/" + moduleName,
                "CORE")
            Functions.log("DBG", "Trying dynamic instantiation " + moduleName,
                          "CORE")
            aClass = getattr(mod, moduleName)
            instancePlugin = aClass()

            if isinstance(instancePlugin, abstractPlugin):
                Functions.log(
                    "DBG", "Plugin " +
                    str(instancePlugin.__class__.__name__.upper()) +
                    " is an instance of AbstractPlugin, populating array",
                    "CORE")
                singleton.plugins.append(instancePlugin)
            else:
                Functions.log(
                    "ERR", "Plugin " + moduleName +
                    " isn't an instance of AbstractPlugin did u extend abstractPlugin ?",
                    "CORE")
        except Exception as err:
            Functions.log(
                "ERR",
                "Couldn't instantiate " + moduleName + " error " + str(err),
                "CORE")
예제 #14
0
def sendToInflux(json_body):
    singleton = Singleton()
    if not singleton.parameters["influxDbUrls"] == "":
        Functions.log("DBG", "Sending now to influxdbs", "CORE")
        for db in singleton.parameters["influxDbUrls"]:
            Functions.log("DBG",
                          "Sending now to " + db["dbHost"] + " database now",
                          "CORE")
            dbUser = db["username"]
            dbPassword = db["password"]
            dbHost = db["dbHost"]
            dbPort = db["dbPort"]
            dbName = db["dbName"]
            Functions.log(
                "DBG", "Sending data to " + dbHost + ":" + dbPort + " user: "******" password: "******" database: " + dbName,
                "CORE")
            client = InfluxDBClient(dbHost, dbPort, dbUser, dbPassword, dbName)
            client.create_database(dbName)
            client.write_points(json_body)
    else:
        Functions.log("DBG", "No influxdb target specified", "CORE")
예제 #15
0
 def __init__(self):
     self.singleton = Singleton()
     Functions.log("DBG", "Site instance created starting site...", "site")
     self.create_app()
예제 #16
0
 def __init__(self):
     self.error = 0
     self.accept = -1
     self.singleton = Singleton()
예제 #17
0
 def get_instance(self):
     rw = Singleton()
     rw.conn = self.connection_database
     return rw.conn
예제 #18
0
def poolingRequest():
    Functions.log("DBG", "Start pooling request", "CORE")
    singleton = Singleton()
    singleton.QPIGS = Functions.command("QPIGS", "")
    json_body = [{
        "measurement": "pimpMySuperWatt",
        "tags": {
            "hostname":
            singleton.hostName,
            "version":
            singleton.version,
            "qpi":
            singleton.QPI,
            "qid":
            singleton.QID,
            "qfw":
            singleton.QVFW,
            "qfw2":
            singleton.QVFW2,
            "url":
            "http://" + singleton.ip + ":" +
            str(singleton.parameters["httpPort"]),
            "instance":
            singleton.parameters["instance"]
        },
        "fields": singleton.QPIGS
    }]
    json_body_parameters = [{
        "measurement": "pimpMySuperWatt_Parameters",
        "tags": {
            "hostname": singleton.hostName,
            "version": singleton.version,
        },
        "fields": {
            "qpi":
            singleton.QPI,
            "qid":
            singleton.QID,
            "qfw":
            singleton.QVFW,
            "qfw2":
            singleton.QVFW2,
            "url":
            "http://" + singleton.ip + ":" +
            str(singleton.parameters["httpPort"]),
            "instance":
            singleton.parameters["instance"],
            "debug":
            singleton.parameters["debug"],
            "communicationClass":
            singleton.parameters["communicationClass"],
            "portPath":
            singleton.parameters["portPath"],
            "webserver":
            singleton.parameters["webserver"],
            "webserverDebug":
            singleton.parameters["webserverDebug"],
            "webClass":
            singleton.parameters["webClass"],
            "httpBind":
            singleton.parameters["httpBind"],
            "queryPoolingInterval":
            singleton.parameters["queryPoolingInterval"]
        }
    }]
    sendToInflux(json_body)
    sendToInflux(json_body_parameters)

    sendToMqtt(json_body)
    sendToMqtt(json_body_parameters)
예제 #19
0
        if path is not None and cfg is None:
            self.__path = os.path.abspath(os.path.join(os.curdir, path))
            with open(os.path.join(self.__path, "default.yaml"), "rb") as default_config:
                self.__data.update(load_yaml(default_config))
            for cfg in sorted(os.listdir(self.__path)):
                if cfg != "default.yaml" and cfg[-4:] in ["yaml", "yml"]:
                    with open(os.path.join(self.__path, cfg), "rb") as config_file:
                        self.__data = update_config(self.__data, load_yaml(config_file))

    def set_(self, key, value):
        self.__data[key] = value

    def values_(self):
        return self.__data

    def save_(self, file):
        file = os.path.abspath(os.path.join(os.curdir, file))
        with open(file, 'w') as f:
            yaml.dump(self.__data, f)

    def __getattr__(self, item):
        if type(self.__data[item]) == dict:
            return Config(cfg=self.__data[item])
        return self.__data[item]

    def __getitem__(self, item):
        return self.__data[item]


config = Singleton(Config)
예제 #20
0
 def inverterQuery():
     singleton = Singleton()
     return singleton.QPIGS
예제 #21
0
            with open(self.file, "a+") as f:
                f.write(self._to_string(self.messages[-1]) + "\n")

    def error(self, message):
        self.log(message, "error")

    def warning(self, message):
        self.log(message, "warning")

    def _to_string(self, msg):
        message = ""
        if msg['type'] != '':
            message += f"*{msg['type']}* "
        message += f"[{msg['time']}] {msg['stack']} - {msg['message']}"
        return message

    def _get_fulltext(self):
        message = ""
        for msg in self.messages:
            message += self._to_string(msg) + "\n"
        return message

    def dump(self, file=None):
        file = self.file if file is None else file
        file = abspath(file)
        with open(file, "w") as f:
            f.write(self._get_fulltext())


logger = Singleton(Logger)
예제 #22
0
 def __init__(self):
     Singleton.__init__(self)
예제 #23
0
 def __init__(self):
         self.error=0
         self.singleton=Singleton()
예제 #24
0
import sys

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox

from global_data.system import get_system_running
from gui.qds_gui import Ui_qds_gui
from utils.singleton import Singleton

instance = Singleton()


class QdsWindow(QtWidgets.QMainWindow, Ui_qds_gui):
    def __init__(self):
        super(QdsWindow, self).__init__()
        ret = instance.detect_instance()
        if not ret:
            QMessageBox.information(self, '提示', '同一目录,只允许一个实例运行')
            sys.exit(-1)

        self.setupUi(self)

    def closeEvent(self, event):  # 函数名固定不可变
        if get_system_running():
            QMessageBox.information(self, '提示', '请先停止软件运行,再关闭')
            event.ignore()
        else:
            instance.delete_lok_file()

    """
    def closeEvent(self, event):#函数名固定不可变