예제 #1
0
 def onStart(self):
     if errmsg == "":
         try:
             Domoticz.Heartbeat(10)
             self.debugging = Parameters["Mode6"]
             if self.debugging == "Verbose":
                 Domoticz.Debugging(2+4+8+16+64)
             if self.debugging == "Debug":
                 Domoticz.Debugging(2)
             
             global pluginDebug
             pluginDebug = False
             setTasmotaDebug(True)
             setMqttDebug(False)
             
             Debug("Plugin::onStart: Parameters: {}".format(repr(Parameters)))
             self.mqttserveraddress = Parameters["Address"].strip()
             self.mqttserverport = Parameters["Port"].strip()
             self.mqttClient = MqttClient(self.mqttserveraddress, self.mqttserverport, "",
                                          self.onMQTTConnected, self.onMQTTDisconnected, self.onMQTTPublish, self.onMQTTSubscribed)
             self.mqttClient.debug(False)
             self.tasmotaHandler = Handler(Parameters["Mode4"].strip().split('|'), Parameters["Mode1"].strip(
                 ), Parameters["Mode2"].strip(), Parameters["Mode3"].strip(), self.mqttClient, Devices)
             self.tasmotaHandler.debug(True)
         except Exception as e:
             Domoticz.Error("Plugin::onStart: {}".format(str(e)))
             self.mqttClient = None
     else:
         Domoticz.Error(
             "Plugin::onStart: Domoticz Python env error {}".format(errmsg))
         self.mqttClient = None
예제 #2
0
    def onStart(self):
        self.debugging = Parameters["Mode6"]

        if self.debugging == "Verbose":
            Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2)

        Domoticz.Debug("onStart called")

        self.base_topic = Parameters["Mode1"].strip()
        self.domoticz_port = int(Parameters["Port"].strip())
        self.delete_removed_devices = Parameters["Mode5"].strip()
        if Parameters["Address"].find('mqtt.gbridge.io') >= 0:
            self.domoticz_mqtt_used = False
        else:
            self.domoticz_mqtt_used = True

        self.mqttClient = MqttClient(Parameters["Address"].strip().split(":")[0],
                                     Parameters["Address"].strip().split(":")[1],
                                     self.onMQTTConnected,
                                     self.onMQTTDisconnected,
                                     self.onMQTTPublish,
                                     self.onMQTTSubscribed)
        self.gBridgeClient = gBridgeClient(Parameters["Mode2"].strip(),
                                           Parameters["Mode3"].strip(),
                                           Parameters["Mode4"].strip())
        self.domoticz_client = DomoticzClient(self.domoticz_port)

        self.syncDevices()

        Domoticz.Debug("Done")
예제 #3
0
class Server(object):
    app = Flask(__name__)
    MQTTC = MqttClient()

    @app.route("/")
    def getRequest():
        return "Hello World!"

    """webhook api"""
    @app.route("/webhook", methods=['GET'])
    def verify():
        return request.args.get('hub.challenge')

    @app.route("/webhook", methods=['POST'])
    def fb_feeds_webhook():
        """webhook api"""
        logging.debug('Handling webhook request!!')
        content = request.get_json()
        if content['entry'][0]['changes'][0]['value']['item'] == 'like':
            Server.MQTTC.publish(
                Config.MQTT_FB_WEBHOOK_TOPIC_NAME, Msg(
                    int(content['entry'][0]['time']),'LIKE',
                    content['entry'][0]['changes'][0]['value']['user_id']))

        logging.info('Handled webhook request ' + str(content))
        return ''

    if __name__ == '__main__':
        app.debug = True
        app.run(host = '0.0.0.0', port = int(os.environ.get("PORT", 5000)))
예제 #4
0
    def onStart(self):

        # Debugging On/Off
        self.debug = _DEBUG_ON if Parameters["Mode6"] == "Debug" else _DEBUG_OFF
        Domoticz.Debugging(self.debug)

        # Create images if necessary
        if _IMAGE_ROOMBA not in Images:
            Domoticz.Image("Roomba.zip").Create()

        # Create devices (USED BY DEFAULT)
        CreateDevicesUsed()
        TimeoutDevice(All=True)

        # Create devices (NOT USED BY DEFAULT)
        CreateDevicesNotUsed()

        # Global settings
        DumpConfigToLog()

        # Start MQTT
        try:
            self.mqttClient = MqttClient('localhost', '1883',
                                         self.onMQTTConnected,
                                         self.onMQTTDisconnected,
                                         self.onMQTTPublish,
                                         self.onMQTTSubscribed)
        except Exception as e:
            Domoticz.Error("MQTT client start error: " + str(e))
            self.mqttClient = None
예제 #5
0
class Server(object):
    app = Flask(__name__)
    MQTTC = MqttClient()

    @app.route("/", methods=['GET', 'POST'])
    def Welcome():
        return "Welcome to my page :)"

    """webhook api"""

    @app.route("/webhook", methods=['GET'])
    def verify():
        return request.args.get('hub.challenge')

    @app.route("/webhook", methods=['POST'])
    def fb_feeds_webhook():
        """webhook api"""
        print('Handling webhook request!!')
        content = request.get_json()
        if content['entry'][0]['changes'][0]['value']['item'] == 'like':
            msg = {
                "time": int(content['entry'][0]['time']),
                "topic": "LIKE",
                "user_id":
                content['entry'][0]['changes'][0]['value']['user_id']
            }
            Server.MQTTC.publish('Facebook', msg)

        print('Handled webhook request' + str(content))
        return ''
예제 #6
0
 def onStart(self):
     global errmsg
     self.devnames = []
     self.devtimes = []
     if errmsg == "":
         try:
             Domoticz.Heartbeat(10)
             self.debugging = Parameters["Mode6"]
             if self.debugging == "Verbose":
                 Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
             if self.debugging == "Debug":
                 Domoticz.Debugging(2)
             self.base_topic = Parameters["Mode1"]
             self.learnmode = Parameters["Mode2"]
             self.mqttserveraddress = Parameters["Address"].strip()
             self.mqttserverport = Parameters["Port"].strip()
             self.mqttClient = MqttClient(self.mqttserveraddress,
                                          self.mqttserverport, "",
                                          self.onMQTTConnected,
                                          self.onMQTTDisconnected,
                                          self.onMQTTPublish,
                                          self.onMQTTSubscribed)
         except Exception as e:
             Domoticz.Error("MQTT client start error: " + str(e))
             self.mqttClient = None
     else:
         Domoticz.Error(
             "Your Domoticz Python environment is not functional! " +
             errmsg)
         self.mqttClient = None
예제 #7
0
    def onStart(self):
        self.debugging = Parameters["Mode6"]
        if self.debugging == "Verbose":
            Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2)
        DumpConfigToLog()
        Domoticz.Log("Chirpstack2Domoticz Plugin started")
        #App ID Base TOPIC
        if (Parameters["Mode1"].strip() != ""):
            self.base_topic = "application/" + Parameters["Mode1"].strip()
        else:
            Domoticz.Log(
                "Warning : No Application ID submitted. It will subscribe to all application topics"
            )
            self.base_topic = "application"
        self.subscribed_for_devices = False
        self.create_new_devices = Parameters["Mode2"].strip()
        mqtt_server_address = Parameters["Address"].strip()
        mqtt_server_port = Parameters["Port"].strip()
        mqtt_client_id = Parameters["Mode3"].strip()

        self.mqttClient = MqttClient(mqtt_server_address, mqtt_server_port,
                                     mqtt_client_id, self.onMQTTConnected,
                                     self.onMQTTDisconnected,
                                     self.onMQTTPublish, self.onMQTTSubscribed)
        self.api = API(Devices, self.publishToMqtt)
예제 #8
0
    def onStart(self):
        self.debugging = Parameters["Mode6"]
        
        if self.debugging == "Verbose+":
            Domoticz.Debugging(2+4+8+16+64)
        if self.debugging == "Verbose":
            Domoticz.Debugging(2+4+8+16+64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2+4+8)

        self.devices_manager = DevicesManager()
        self.devices_manager.set_devices(Devices)
        device_topic = Parameters["Mode1"].strip()

        if (Parameters["Mode2"] == "Dimmer"):
            self.controller = Dimmer(self.devices_manager, device_topic)
        elif (Parameters["Mode2"] == "PwmDimmer"):
            self.controller = PwmDimmer(self.devices_manager, device_topic)
        elif (Parameters["Mode2"] == "RGB"):
            self.controller = ColorDimmer(self.devices_manager, device_topic, 3)
        elif (Parameters["Mode2"] == "RGBW"):
            self.controller = ColorDimmer(self.devices_manager, device_topic, 4)
        elif (Parameters["Mode2"] == "RGBWW"):
            self.controller = ColorDimmer(self.devices_manager, device_topic, 5)

        self.controller.checkDevices()

        self.topics = list(["stat/" + device_topic + "/RESULT", "tele/" + device_topic + "/STATE"])
        
        mqtt_server_address = Parameters["Address"].strip()
        mqtt_server_port = Parameters["Port"].strip()
        mqtt_client_id = Parameters["Mode3"].strip()
        self.mqttClient = MqttClient(mqtt_server_address, mqtt_server_port, mqtt_client_id, self.onMQTTConnected, self.onMQTTDisconnected, self.onMQTTPublish, self.onMQTTSubscribed)
예제 #9
0
    def onStart(self):
        if Parameters["Mode6"] == "Debug":
            Domoticz.Debugging(1)
        DumpConfigToLog()
        self.devices = {}

        Parameters["Username"] = "******"
        Parameters["Port"] = "8884"
        Parameters["Protocol"] = "MQTTS"

        mqtt_server_address = Parameters["Address"].strip()
        mqtt_server_port = Parameters["Port"].strip()
        self.mqttClient = MqttClient(mqtt_server_address, mqtt_server_port,
                                     "NHCDomoticz", self.onMQTTConnected,
                                     self.onMQTTDisconnected,
                                     self.onMQTTPublish, self.onMQTTSubscribed)
예제 #10
0
    def onStart(self):
        self.debugging = Parameters["Mode6"]

        if self.debugging == "Verbose":
            Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2)

        self.base_topic = "shellies"  # hardwired

        self.mqttserveraddress = Parameters["Address"].strip()
        self.mqttserverport = Parameters["Port"].strip()
        self.mqttClient = MqttClient(self.mqttserveraddress,
                                     self.mqttserverport, self.onMQTTConnected,
                                     self.onMQTTDisconnected,
                                     self.onMQTTPublish, self.onMQTTSubscribed)
    def onStart(self):
        self.debugging = Parameters["Mode6"]
        
        if self.debugging == "Verbose":
            Domoticz.Debugging(2+4+8+16+64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2)

        Domoticz.Debug("onStart called")
        self.base_topic = Parameters["Mode1"].strip()
        self.pairing_enabled = True if Parameters["Mode2"] == 'true' else False
        self.subscribed_for_devices = False

        mqtt_server_address = Parameters["Address"].strip()
        mqtt_server_port = Parameters["Port"].strip()
        mqtt_client_id = Parameters["Mode3"].strip()
        self.mqttClient = MqttClient(mqtt_server_address, mqtt_server_port, mqtt_client_id, self.onMQTTConnected, self.onMQTTDisconnected, self.onMQTTPublish, self.onMQTTSubscribed)

        self.available_devices = DeviceStorage.getInstance()
예제 #12
0
    def onStart(self):
        self.debugging = Parameters["Mode6"]
        
        if self.debugging == "Verbose":
            Domoticz.Debugging(2+4+8+16+64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2)

        Domoticz.Debug("onStart called")
        self.install()
        self.base_topic = Parameters["Mode1"].strip()

        mqtt_server_address = Parameters["Address"].strip()
        mqtt_server_port = Parameters["Port"].strip()
        mqtt_client_id = Parameters["Mode3"].strip()
        self.mqttClient = MqttClient(mqtt_server_address, mqtt_server_port, mqtt_client_id, self.onMQTTConnected, self.onMQTTDisconnected, self.onMQTTPublish, self.onMQTTSubscribed)

        self.api = API(Devices, self.onApiCommand)
        self.devices_manager = DevicesManager()
        self.groups_manager = GroupsManager()
예제 #13
0
    def onStart(self):
        self.debugging = Parameters["Mode6"]

        if self.debugging == "Verbose":
            Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2)

        self.devices = {}
        self.base_topic = Parameters["Mode1"].strip()

        mqttserver_address = Parameters["Address"].strip()
        mqttserver_port = Parameters["Port"].strip()
        mqtt_client_id = Parameters["Mode3"].strip()

        self.mqttClient = MqttClient(mqttserver_address, mqttserver_port,
                                     mqtt_client_id, self.onMQTTConnected,
                                     self.onMQTTDisconnected,
                                     self.onMQTTPublish, self.onMQTTSubscribed)

        Domoticz.Debug("onStart called")
예제 #14
0
파일: plugin.py 프로젝트: Neonox31/boiler
    def onStart(self):
        self.debugging = Parameters["Mode6"]

        if self.debugging == "Verbose+":
            Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
        if self.debugging == "Verbose":
            Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2 + 4 + 8)

        self.controller = Thermostat()

        self.controller.checkDevices()

        self.topics = list([
            "ems-esp/thermostat_data1", "ems-esp/boiler_data", "ems-esp/STATE"
        ])
        self.mqttserveraddress = Parameters["Address"].replace(" ", "")
        self.mqttserverport = Parameters["Port"].replace(" ", "")
        self.mqttClient = MqttClient(self.mqttserveraddress,
                                     self.mqttserverport, self.onMQTTConnected,
                                     self.onMQTTDisconnected,
                                     self.onMQTTPublish, self.onMQTTSubscribed)
예제 #15
0
class Server(object):
    """Server class"""
    app = Flask(__name__)
    MQTTC = MqttClient()

    @app.route("/")
    def hello(self):
        """default"""
        return "Hello World!"

    @app.route("/webhook", methods=['GET'])
    def verify(self):
        """webhook api"""
        return request.args.get('hub.challenge')

    @app.route("/webhook", methods=['POST'])
    def fb_feeds_webhook(self):
        """webhook api"""
        content = request.get_json()
        if content['entry'][0]['changes'][0]['value']['item'] == 'like':
            Server.MQTTC.publish(
                Credentials.MQTT_FB_WEBHOOK_TOPIC_NAME,
                Msg(int(content['entry'][0]['time']), 'LIKE',
                    content['entry'][0]['changes'][0]['value']['user_id']))
예제 #16
0
    def onStart(self):
        self.debugging = Parameters["Mode6"]

        if self.debugging == "Verbose":
            Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2)

        Domoticz.Debug("onStart called")
        self.install()
        self.base_topic = "zigbee2mqtt"
        self.subscribed_for_devices = False

        mqtt_server_address = "127.0.0.1"
        mqtt_server_port = "1883"
        mqtt_client_id = ""
        self.mqttClient = MqttClient(mqtt_server_address, mqtt_server_port,
                                     mqtt_client_id, self.onMQTTConnected,
                                     self.onMQTTDisconnected,
                                     self.onMQTTPublish, self.onMQTTSubscribed)

        self.api = API(Devices, self.onApiCommand)
        self.devices_manager = DevicesManager()
        self.groups_manager = GroupsManager()
예제 #17
0
    def onStart(self):
        Domoticz.Debug("onStart called")
        #read out parameters for local connection
        self.ip_address = Parameters["Address"].strip()
        self.port_number = Parameters["Port"].strip()
        self.otp_code = Parameters['Mode1']
        self.runCounter = int(Parameters['Mode2'])
        self.log_level = Parameters['Mode4']
        self.account_password = Parameters['Mode3']
        self.account_email = Parameters['Mode5']
        self.machine_name = Parameters['Mode6']

        if self.log_level == 'Debug':
            Domoticz.Debugging(2)
            DumpConfigToLog()
        if self.log_level == 'Verbose':
            Domoticz.Debugging(1 + 2 + 4 + 8 + 16 + 64)
            DumpConfigToLog()
        if self.log_level == 'Reset':
            Domoticz.Log(
                "Plugin config will be erased to retreive new cloud account data"
            )
            Config = {}
            Config = Domoticz.Configuration(Config)

        #PureLink needs polling, get from config
        Domoticz.Heartbeat(10)

        self.checkVersion(self.version)

        mqtt_client_id = ""

        #create a Dyson account
        deviceList = self.get_device_names()

        if deviceList != None and len(deviceList) > 0:
            Domoticz.Debug(
                "Number of devices found in plugin configuration: '" +
                str(len(deviceList)) + "'")
        else:
            Domoticz.Log(
                "No devices found in plugin configuration, request from Dyson cloud account"
            )

            #new authentication
            Domoticz.Debug(
                "=== start making connection to Dyson account, new method as of 2021 ==="
            )
            dysonAccount2 = DysonAccount()
            challenge_id = getConfigItem(Key="challenge_id", Default="")
            setConfigItem(Key="challenge_id", Value="")  #clear after use
            if challenge_id == "":
                #request otp code via email when no code entered
                challenge_id = dysonAccount2.login_email_otp(
                    self.account_email, "NL")
                setConfigItem(Key="challenge_id", Value=challenge_id)
                Domoticz.Log(
                    '==== An OTP verification code had been requested, please check email and paste code into plugin====='
                )
                return
            else:
                #verify the received code
                if len(self.otp_code) < 6:
                    Domoticz.Error("invalid verification code supplied")
                    return
                dysonAccount2.verify(self.otp_code, self.account_email,
                                     self.account_password, challenge_id)
                setConfigItem(
                    Key="challenge_id",
                    Value="")  #reset challenge id as it is no longer valid
                Parameters['Mode1'] = "0"  #reset the stored otp code
                #get list of devices info's
                deviceList = dysonAccount2.devices()
                deviceNames = list(deviceList.keys())
                Domoticz.Log("Received new devices: " + str(deviceNames) +
                             ", they will be stored in plugin configuration")
                i = 0
                for device in deviceList:
                    setConfigItem(
                        Key="{0}.name".format(i),
                        Value=deviceNames[i])  #store the name of the machine
                    Domoticz.Debug('Key="{0}.name", Value = {1}'.format(
                        i, deviceNames[i]))  #store the name of the machine
                    setConfigItem(
                        Key="{0}.credential".format(
                            deviceList[deviceNames[i]].name),
                        Value=deviceList[
                            deviceNames[i]].credential)  #store the credential
                    Domoticz.Debug('Key="{0}.credential", Value = {1}'.format(
                        deviceList[deviceNames[i]].name, deviceList[
                            deviceNames[i]].credential))  #store the credential
                    setConfigItem(
                        Key="{0}.serial".format(
                            deviceList[deviceNames[i]].name),
                        Value=deviceList[
                            deviceNames[i]].serial)  #store the serial
                    Domoticz.Debug('Key="{0}.serial", Value =  {1}'.format(
                        deviceList[deviceNames[i]].name,
                        deviceList[deviceNames[i]].serial))  #store the serial
                    setConfigItem(Key="{0}.product_type".format(
                        deviceList[deviceNames[i]].name),
                                  Value=deviceList[deviceNames[i]].product_type
                                  )  #store the product_type
                    Domoticz.Debug(
                        'Key="{0}.product_type" , Value = {1}'.format(
                            deviceList[deviceNames[i]].name,
                            deviceList[deviceNames[i]].product_type)
                    )  #store the product_type
                    i = i + 1

        if deviceList == None or len(deviceList) < 1:
            Domoticz.Error(
                "No devices found in plugin configuration or Dyson cloud account"
            )
            return
        else:
            Domoticz.Debug("Number of devices in plugin: '" +
                           str(len(deviceList)) + "'")

        if deviceList != None and len(deviceList) > 0:
            if len(self.machine_name) > 0:
                if self.machine_name in deviceList:
                    password, serialNumber, deviceType = self.get_device_config(
                        self.machine_name)
                    Domoticz.Debug(
                        "password: {0}, serialNumber: {1}, deviceType: {2}".
                        format(password, serialNumber, deviceType))
                    self.myDevice = DysonPureLinkDevice(
                        password, serialNumber, deviceType, self.machine_name)
                else:
                    Domoticz.Error(
                        "The configured device name '" + self.machine_name +
                        "' was not found in the cloud account. Available options: "
                        + str(list(deviceList)))
                    return
            elif len(deviceList) == 1:
                self.myDevice = deviceList[list(deviceList)[0]]
                Domoticz.Log(
                    "1 device found in plugin, none configured, assuming we need this one: '"
                    + self.myDevice.name + "'")
            else:
                #more than 1 device returned in cloud and no name configured, which the the plugin can't handle
                Domoticz.Error(
                    "More than 1 device found in cloud account but no device name given to select. Select and filter one from available options: "
                    + str(list(deviceList)))
                return
            #the Domoticz connection object takes username and pwd from the Parameters so write them back
            Parameters[
                'Username'] = self.myDevice.serial  #take username from account
            Parameters[
                'Password'] = self.myDevice.password  #override the default password with the one returned from the cloud
        else:
            Domoticz.Error("No usable credentials found")
            return

        #check, per device, if it is created. If not,create it
        Options = {
            "LevelActions": "|||",
            "LevelNames": "|OFF|ON|AUTO",
            "LevelOffHidden": "true",
            "SelectorStyle": "1"
        }
        if self.fanModeUnit not in Devices:
            Domoticz.Device(Name='Fan mode',
                            Unit=self.fanModeUnit,
                            TypeName="Selector Switch",
                            Image=7,
                            Options=Options).Create()
        if self.fanStateUnit not in Devices:
            Domoticz.Device(Name='Fan state',
                            Unit=self.fanStateUnit,
                            Type=244,
                            Subtype=62,
                            Image=7,
                            Switchtype=0).Create()
        if self.heatStateUnit not in Devices:
            Domoticz.Device(Name='Heating state',
                            Unit=self.heatStateUnit,
                            Type=244,
                            Subtype=62,
                            Image=7,
                            Switchtype=0).Create()
        if self.nightModeUnit not in Devices:
            Domoticz.Device(Name='Night mode',
                            Unit=self.nightModeUnit,
                            Type=244,
                            Subtype=62,
                            Switchtype=0,
                            Image=9).Create()

        Options = {
            "LevelActions": "|||||||||||",
            "LevelNames": "OFF|1|2|3|4|5|6|7|8|9|10|AUTO",
            "LevelOffHidden": "false",
            "SelectorStyle": "1"
        }
        if self.fanSpeedUnit not in Devices:
            Domoticz.Device(Name='Fan speed',
                            Unit=self.fanSpeedUnit,
                            TypeName="Selector Switch",
                            Image=7,
                            Options=Options).Create()

        if self.fanOscillationUnit not in Devices:
            Domoticz.Device(Name='Oscilation mode',
                            Unit=self.fanOscillationUnit,
                            Type=244,
                            Subtype=62,
                            Image=7,
                            Switchtype=0).Create()
        if self.standbyMonitoringUnit not in Devices:
            Domoticz.Device(Name='Standby monitor',
                            Unit=self.standbyMonitoringUnit,
                            Type=244,
                            Subtype=62,
                            Image=7,
                            Switchtype=0).Create()
        if self.filterLifeUnit not in Devices:
            Options: {'Custom': '1;hrs'}
            Domoticz.Device(Name='Remaining filter life',
                            Unit=self.filterLifeUnit,
                            TypeName="Custom",
                            Options=Options).Create()
        if self.resetFilterLifeUnit not in Devices:
            Domoticz.Device(Name='Reset filter: 0 hrs',
                            Unit=self.resetFilterLifeUnit,
                            TypeName="Switch",
                            Image=9).Create()
        if self.tempHumUnit not in Devices:
            Domoticz.Device(Name='Temperature and Humidity',
                            Unit=self.tempHumUnit,
                            TypeName="Temp+Hum").Create()
        if self.volatileUnit not in Devices:
            Domoticz.Device(Name='Volatile organic',
                            Unit=self.volatileUnit,
                            TypeName="Air Quality").Create()
        if self.sleepTimeUnit not in Devices:
            Domoticz.Device(Name='Sleep timer',
                            Unit=self.sleepTimeUnit,
                            TypeName="Custom").Create()

        if self.particlesUnit not in Devices:
            Domoticz.Device(Name='Dust',
                            Unit=self.particlesUnit,
                            TypeName="Air Quality").Create()
        if self.qualityTargetUnit not in Devices:
            Options = {
                "LevelActions": "|||",
                "LevelNames":
                "|Normal|Sensitive (Medium)|Very Sensitive (High)|Off",
                "LevelOffHidden": "true",
                "SelectorStyle": "1"
            }
            Domoticz.Device(Name='Air quality setpoint',
                            Unit=self.qualityTargetUnit,
                            TypeName="Selector Switch",
                            Image=7,
                            Options=Options).Create()

        if self.particles2_5Unit not in Devices:
            Domoticz.Device(Name='Dust (PM 2,5)',
                            Unit=self.particles2_5Unit,
                            TypeName="Air Quality").Create()
        if self.particles10Unit not in Devices:
            Domoticz.Device(Name='Dust (PM 10)',
                            Unit=self.particles10Unit,
                            TypeName="Air Quality").Create()
        if self.particlesMatter25Unit not in Devices:
            Domoticz.Device(Name='Particles (PM 25)',
                            Unit=self.particlesMatter25Unit,
                            TypeName="Air Quality").Create()
        if self.particlesMatter10Unit not in Devices:
            Domoticz.Device(Name='Particles (PM 10)',
                            Unit=self.particlesMatter10Unit,
                            TypeName="Air Quality").Create()
        if self.fanModeAutoUnit not in Devices:
            Domoticz.Device(Name='Fan mode auto',
                            Unit=self.fanModeAutoUnit,
                            Type=244,
                            Subtype=62,
                            Image=7,
                            Switchtype=0).Create()
        if self.fanFocusUnit not in Devices:
            Domoticz.Device(Name='Fan focus mode',
                            Unit=self.fanFocusUnit,
                            Type=244,
                            Subtype=62,
                            Image=7,
                            Switchtype=0).Create()
        if self.nitrogenDioxideDensityUnit not in Devices:
            Domoticz.Device(Name='Nitrogen Dioxide Density (NOx)',
                            Unit=self.nitrogenDioxideDensityUnit,
                            TypeName="Air Quality").Create()
        if self.heatModeUnit not in Devices:
            Options = {
                "LevelActions": "||",
                "LevelNames": "|Off|Heating",
                "LevelOffHidden": "true",
                "SelectorStyle": "1"
            }
            Domoticz.Device(Name='Heat mode',
                            Unit=self.heatModeUnit,
                            TypeName="Selector Switch",
                            Image=7,
                            Options=Options).Create()
        if self.heatTargetUnit not in Devices:
            Domoticz.Device(Name='Heat target',
                            Unit=self.heatTargetUnit,
                            Type=242,
                            Subtype=1).Create()
        if self.deviceStatusUnit not in Devices:
            Domoticz.Device(Name='Machine status',
                            Unit=self.deviceStatusUnit,
                            TypeName="Text",
                            Image=7).Create()

        Domoticz.Log("Device instance created: " + str(self.myDevice))
        self.base_topic = self.myDevice.device_base_topic
        Domoticz.Debug("base topic defined: '" + self.base_topic + "'")

        #create the connection
        if self.myDevice != None:
            self.mqttClient = MqttClient(self.ip_address, self.port_number,
                                         mqtt_client_id, self.onMQTTConnected,
                                         self.onMQTTDisconnected,
                                         self.onMQTTPublish,
                                         self.onMQTTSubscribed)
예제 #18
0
from mqtt import MqttClient

mqtt = MqttClient()
mqtt.client.loop_start()
예제 #19
0
파일: main.py 프로젝트: azadyasar/PiCAN
    if key == keyboard.Key.esc:
        # Stop listener
        return False


def start():
    with keyboard.Listener(on_press=on_press,
                           on_release=on_release) as listener:
        listener.join()


if __name__ == "__main__":
    logger.info("########## OBD Tracker ##########")

    logger.info("MqttClient is connecting to the broker")
    mqtt_client = MqttClient()
    mqtt_client.connect()

    obd_tracker = OBDTracker(mqtt_client=mqtt_client)
    obd_tracker.connect()
    obd_tracker.test_query()

    start()

    logger.info("Shutting down the OBDTracker...")
    obd_tracker.shut_down(reason="Shut down requested")
    logger.info("Shutting down the MqttClient...")
    mqtt_client.shut_down()

    # import asyncio
    # loop = asyncio.get_event_loop()
예제 #20
0
파일: lam.py 프로젝트: macbury/lam.py
from mqtt import MqttClient
from actions import EmitPresence, EmitStatus, ButtonHandler, EmitFood, EmitCoffee

from ruamel.yaml import YAML

LOGGER = logging.getLogger('lamp')
logging.basicConfig(level=logging.INFO,
                    format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s")

CONFIG_PATH = os.path.join('./', 'config.yaml')
LOGGER.info("Loading config: " + CONFIG_PATH)
CONFIG = YAML(typ='safe').load(open(CONFIG_PATH))

jenkins = JenkinsClient(CONFIG['jenkins'])
hipchat = Hipchat(CONFIG['hipchat'])
mqtt = MqttClient(CONFIG['mqtt'])

EMITTERS = [
    EmitStatus(mqtt, jenkins, CONFIG['jenkins']['topic']),
    EmitPresence(mqtt, hipchat, CONFIG['hipchat']['topic']),
    EmitFood(mqtt, CONFIG['lunching']),
    EmitCoffee(mqtt, CONFIG['coffee'])
]

ButtonHandler(mqtt, hipchat, CONFIG['button'])

# import code; code.interact(local=dict(globals(), **locals()))

try:
    while True:
        for emitter in EMITTERS:
예제 #21
0
_LOGGER = logger.get()
if parsed.quiet:
    _LOGGER.setLevel(logging.WARNING)
elif parsed.debug:
    _LOGGER.setLevel(logging.DEBUG)
    logger.enable_debug_formatter()
else:
    _LOGGER.setLevel(logging.INFO)
logger.suppress_update_failures(parsed.suppress)

_LOGGER.info("Starting")

global_topic_prefix = settings["mqtt"].get("topic_prefix")

mqtt = MqttClient(settings["mqtt"])
manager = WorkersManager(settings["manager"])
manager.register_workers(global_topic_prefix)
manager.start(mqtt)

running = True

while running:
    try:
        mqtt.publish(_WORKERS_QUEUE.get(timeout=10).execute())
    except queue.Empty:  # Allow for SIGINT processing
        pass
    except (WorkerTimeoutError, DeviceTimeoutError) as e:
        logger.log_exception(
            _LOGGER,
            str(e) if str(e) else "Timeout while executing worker command",
예제 #22
0
                    help='Suppress any errors regarding failed device updates')
parsed = parser.parse_args()

_LOGGER = logger.get()
if parsed.quiet:
    _LOGGER.setLevel(logging.WARNING)
elif parsed.debug:
    _LOGGER.setLevel(logging.DEBUG)
    logger.enable_debug_formatter()
else:
    _LOGGER.setLevel(logging.INFO)
logger.suppress_update_failures(parsed.suppress)

_LOGGER.info('Starting')

mqtt = MqttClient(mqtt_settings['mqtt'])
manager = WorkersManager(settings['manager'])
manager.register_workers().start(mqtt)

running = True

while running:
    try:
        mqtt.publish(_WORKERS_QUEUE.get(timeout=10).execute())
    except queue.Empty:  # Allow for SIGINT processing
        pass
    except TimeoutError as e:
        logger.log_exception(
            _LOGGER,
            str(e) if str(e) else 'Timeout while executing worker command',
            suppress=True)
예제 #23
0
from workers_manager import WorkersManager

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-d', '--debug', action='store_true', default=False)
group.add_argument('-q', '--quiet', action='store_true', default=False)
parsed = parser.parse_args()

if parsed.debug:
    _LOGGER.setLevel(logging.DEBUG)
else:
    _LOGGER.setLevel(logging.INFO)

_LOGGER.debug('Starting')

mqtt = MqttClient(settings['mqtt'])
manager = WorkersManager()
manager.register_workers(settings['manager']).start(mqtt)

running = True

try:
    while running:
        try:
            mqtt.publish(_WORKERS_QUEUE.get(block=True).execute())
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception as e:
            if not parsed.quiet:
                _LOGGER.exception(e)
except KeyboardInterrupt:
예제 #24
0
    def onStart(self):
        Domoticz.Log("onStart called")
        if Parameters['Mode4'] == 'Debug':
            Domoticz.Debugging(2)
            DumpConfigToLog()
        if Parameters['Mode4'] == 'Verbose':
            Domoticz.Debugging(1 + 2 + 4 + 8 + 16 + 64)
            DumpConfigToLog()

        #PureLink needs polling, get from config
        Domoticz.Heartbeat(10)

        #check, per device, if it is created. If not,create it
        Options = {
            "LevelActions": "|||",
            "LevelNames": "|OFF|ON|AUTO",
            "LevelOffHidden": "true",
            "SelectorStyle": "1"
        }
        if self.fanModeUnit not in Devices:
            Domoticz.Device(Name='Fan mode',
                            Unit=self.fanModeUnit,
                            TypeName="Selector Switch",
                            Image=7,
                            Options=Options).Create()
        Options = {
            "LevelActions": "||",
            "LevelNames": "|OFF|ON",
            "LevelOffHidden": "true",
            "SelectorStyle": "1"
        }
        if self.fanStateUnit not in Devices:
            Domoticz.Device(Name='Fan state',
                            Unit=self.fanStateUnit,
                            TypeName="Selector Switch",
                            Image=7,
                            Options=Options).Create()
        if self.nightModeUnit not in Devices:
            Domoticz.Device(Name='Night mode',
                            Unit=self.nightModeUnit,
                            Type=244,
                            Subtype=62,
                            Switchtype=0,
                            Image=9).Create()

        Options = {
            "LevelActions": "|||||||||||",
            "LevelNames": "|1|2|3|4|5|6|7|8|9|10|Auto",
            "LevelOffHidden": "false",
            "SelectorStyle": "1"
        }
        if self.fanSpeedUnit not in Devices:
            Domoticz.Device(Name='Fan speed',
                            Unit=self.fanSpeedUnit,
                            TypeName="Selector Switch",
                            Image=7,
                            Options=Options).Create()

        if self.fanOscillationUnit not in Devices:
            Domoticz.Device(Name='Oscilation mode',
                            Unit=self.fanOscillationUnit,
                            Type=244,
                            Subtype=62,
                            Image=7,
                            Switchtype=0).Create()
        if self.standbyMonitoringUnit not in Devices:
            Domoticz.Device(Name='Standby monitor',
                            Unit=self.standbyMonitoringUnit,
                            Type=244,
                            Subtype=62,
                            Image=7,
                            Switchtype=0).Create()
        if self.filterLifeUnit not in Devices:
            Domoticz.Device(Name='Remaining filter life',
                            Unit=self.filterLifeUnit,
                            TypeName="Custom").Create()
        if self.tempHumUnit not in Devices:
            Domoticz.Device(Name='Temperature and Humidity',
                            Unit=self.tempHumUnit,
                            TypeName="Temp+Hum").Create()
        if self.volatileUnit not in Devices:
            Domoticz.Device(Name='Volatile organic',
                            Unit=self.volatileUnit,
                            TypeName="Air Quality").Create()
        if self.sleepTimeUnit not in Devices:
            Domoticz.Device(Name='Sleep timer',
                            Unit=self.sleepTimeUnit,
                            TypeName="Custom").Create()

        if self.particlesUnit not in Devices:
            Domoticz.Device(Name='Dust',
                            Unit=self.particlesUnit,
                            TypeName="Air Quality").Create()
        if self.qualityTargetUnit not in Devices:
            Options = {
                "LevelActions": "||",
                "LevelNames":
                "|Normal|Sensitive (Medium)|Very Sensitive (High)",
                "LevelOffHidden": "true",
                "SelectorStyle": "1"
            }
            Domoticz.Device(Name='Air quality setpoint',
                            Unit=self.qualityTargetUnit,
                            TypeName="Selector Switch",
                            Image=7,
                            Options=Options).Create()

        if self.particles2_5Unit not in Devices:
            Domoticz.Device(Name='Dust (PM 2,5)',
                            Unit=self.particles2_5Unit,
                            TypeName="Air Quality").Create()
        if self.particles10Unit not in Devices:
            Domoticz.Device(Name='Dust (PM 10)',
                            Unit=self.particles10Unit,
                            TypeName="Air Quality").Create()
        Options = {
            "LevelActions": "|||",
            "LevelNames": "|OFF|ON",
            "LevelOffHidden": "true",
            "SelectorStyle": "1"
        }
        if self.fanModeAutoUnit not in Devices:
            Domoticz.Device(Name='Fan mode auto',
                            Unit=self.fanModeAutoUnit,
                            TypeName="Selector Switch",
                            Image=7,
                            Options=Options).Create()
        Options = {
            "LevelActions": "|||",
            "LevelNames": "|OFF|ON",
            "LevelOffHidden": "true",
            "SelectorStyle": "1"
        }
        if self.fanFocusUnit not in Devices:
            Domoticz.Device(Name='Fan focus mode',
                            Unit=self.fanFocusUnit,
                            Type=244,
                            Subtype=62,
                            Image=7,
                            Switchtype=0).Create()
        if self.nitrogenDioxideDensityUnit not in Devices:
            Domoticz.Device(Name='Nitrogen Dioxide Density (NOx)',
                            Unit=self.nitrogenDioxideDensityUnit,
                            TypeName="Air Quality").Create()

        #read out parameters for local connection
        self.ip_address = Parameters["Address"].strip()
        self.port_number = Parameters["Port"].strip()
        self.password = self._hashed_password(Parameters['Password'])
        mqtt_client_id = ""
        self.runCounter = int(Parameters['Mode2'])

        #create a Dyson account
        Domoticz.Debug("=== start making connection to Dyson account ===")
        dysonAccount = DysonAccount(Parameters['Mode5'], Parameters['Mode3'],
                                    "NL")
        dysonAccount.login()
        #deviceList = ()
        deviceList = []
        deviceList = dysonAccount.devices()

        if deviceList == None or len(deviceList) < 1:
            Domoticz.Log("No devices found in Dyson cloud account")
        else:
            Domoticz.Debug("Number of devices from cloud: '" +
                           str(len(deviceList)) + "'")

        if deviceList != None and len(deviceList) > 0:
            if len(Parameters['Mode6']) > 0:
                if Parameters['Mode6'] in deviceList:
                    self.myDevice = deviceList[Parameters['Mode6']]
                else:
                    Domoticz.Error(
                        "The configured device name '" + Parameters['Mode6'] +
                        "' was not found in the cloud account. Available options: "
                        + str(list(deviceList)))
                    return
            elif len(deviceList) == 1:
                self.myDevice = deviceList[list(deviceList)[0]]
                Domoticz.Log(
                    "1 device found in cloud, none configured, assuming we need this one: '"
                    + self.myDevice.name + "'")
            else:
                Domoticz.Error(
                    "More than 1 device found in cloud account but no device name given to select"
                )
                return
            Domoticz.Debug("local device pwd:      '" + self.password + "'")
            Domoticz.Debug("cloud device pwd:      '" +
                           self.myDevice.password + "'")
            Parameters[
                'Username'] = self.myDevice.serial  #take username from account
            Parameters[
                'Password'] = self.myDevice.password  #override the default password with the one returned from the cloud
        elif len(Parameters['Username']) > 0:
            Domoticz.Log(
                "No cloud devices found, the local credentials will be used")
            #create a Dyson device object using plugin parameters
            Domoticz.Debug("local device pwd:      '" + self.password + "'")
            Domoticz.Debug("local device usn:      '" +
                           Parameters['Username'] + "'")
            Parameters['Password'] = self.password
            self.myDevice = DysonPureLinkDevice(Parameters['Password'],
                                                Parameters['Username'],
                                                Parameters['Mode1'])
        else:
            Domoticz.Error("No usable credentials found")

        Domoticz.Log("Device instance created: " + str(self.myDevice))
        self.base_topic = self.myDevice.device_base_topic
        Domoticz.Debug("base topic defined: '" + self.base_topic + "'")

        #create the connection
        if self.myDevice != None:
            self.mqttClient = MqttClient(self.ip_address, self.port_number,
                                         mqtt_client_id, self.onMQTTConnected,
                                         self.onMQTTDisconnected,
                                         self.onMQTTPublish,
                                         self.onMQTTSubscribed)