Exemplo n.º 1
0
 def validateDeviceConfigUi(self, valuesDict, typeId, devId):
     self.debugLog(u"validating device Prefs called")
     if typeId == u"UniPiBoard":
         self.debugLog(u"validating IP Address")
         ipAdr = valuesDict[u'address']
         if ipAdr.count('.') != 3:
             errorMsgDict = indigo.Dict()
             errorMsgDict[
                 u'address'] = u"This needs to be a valid IP address."
             return (False, valuesDict, errorMsgDict)
         if self.validateAddress(ipAdr) == False:
             errorMsgDict = indigo.Dict()
             errorMsgDict[
                 u'address'] = u"This needs to be a valid IP address."
             return (False, valuesDict, errorMsgDict)
         self.debugLog(u"validating TCP Port")
         tcpPort = valuesDict[u'port']
         try:
             iPort = int(tcpPort)
             if iPort <= 0:
                 errorMsgDict = indigo.Dict()
                 errorMsgDict[
                     u'port'] = u"This needs to be a valid TCP port."
                 return (False, valuesDict, errorMsgDict)
         except Exception, e:
             errorMsgDict = indigo.Dict()
             errorMsgDict[u'port'] = u"This needs to be a valid TCP port."
             return (False, valuesDict, errorMsgDict)
    def validateActionConfigUi(self, valuesDict, typeId, deviceId):
        self.debugLog(valuesDict)
        # Validate Intensity
        if 'effectintensity' in valuesDict:
            try:
                effectintensity = int(valuesDict['effectintensity'])
            except:
                self.errorLog(
                    "Invalid entry for Effect Intensity - must be a whole number between 0 and 255"
                )
                errorsDict = indigo.Dict()
                errorsDict[
                    'effectintensity'] = "Invalid entry for Effect Intensity - must be a whole number between 0 and 255"
                return (False, valuesDict, errorsDict)
            self.debugLog(int(valuesDict['effectintensity']))
            if not (int(valuesDict['effectintensity']) in xrange(0, 256)):

                #if 0 <= int(valuesDict['effectintensity']) >= 256:
                self.errorLog(
                    "Invalid entry for Effect Intensity - must be a whole number between 0 and 255"
                )
                errorsDict = indigo.Dict()
                errorsDict[
                    'effectintensity'] = "Invalid entry for Effect Intensity - must be a whole number between 0 and 255"
                return (False, valuesDict, errorsDict)

        #Otherwise we are all good
        return (True, valuesDict)
Exemplo n.º 3
0
    def validateActionConfigUi(self, valuesDict, typeId, actionId):
        self.DebugMsg(u"validating config for %s:%s" % (actionId, typeId))
        if typeId == 'fanLightBrightness':
            try:
                i = int(valuesDict['lightLevel'])
                if i < 0 or i > 16:
                    errorDict = indigo.Dict()
                    errorDict[
                        "lightLevel"] = "Brightness must be an integer between 0 and 16"
                    return (False, valuesDict, errorDict)
                else:
                    return True
            except:
                errorDict = indigo.Dict()
                errorDict[
                    "lightLevel"] = "Brightness must be an integer between 0 and 16"
                return (False, valuesDict, errorDict)
        elif typeId == 'fanSpeed':
            try:
                i = int(valuesDict['speed'])
                if i < 0 or i > 6:
                    errorDict = indigo.Dict()
                    errorDict[
                        "speed"] = "Speed must be an integer between 0 and 6"
                    return (False, valuesDict, errorDict)
                else:
                    return True
            except:
                errorDict = indigo.Dict()
                errorDict["speed"] = "Speed must be an integer between 0 and 6"
                return (False, valuesDict, errorDict)

        return True
Exemplo n.º 4
0
    def getDeviceFactoryUiValues(self, dev_ids):
        """ Called by the IndigoUI to initialize values for the Device
        Factory dialog. If the device group has already been created,
        dev_ids will contain a list of devices. If so, grab the pluginProps
        from one of them and get the connection parameters, and try
        to connect.
        """
        log.debug("Initializing Device Factory UI")
        values = indigo.Dict()
        if dev_ids:
            props = indigo.devices[dev_ids[0]].pluginProps
            ip, port = self.split_url(props["url"])
            values["ipAddress"] = ip
            values["portNumber"] = str(port)
            values["prefix"] = props["prefix"]
            enc1, enc2 = self.keychain.get_keys(ip, port)
            values["encryptionKey1"] = enc1
            values["encryptionKey2"] = enc2
        else:
            values["encryptionKey1"] = ""
            values["encryptionKey2"] = ""

        if values["encryptionKey1"]:
            values["hiddenencryptionKey1"] = self.hidden
            values["hiddenencryptionKey2"] = self.hidden

        errors = self.checkConnectionParameters(values)
        if not errors:
            self.make_connection(self.make_url(values),
                                 values["encryptionKey1"],
                                 values["encryptionKey2"])
            if self.did_connection_succeed(values):
                values["isConnected"] = True
        return values, indigo.Dict()
Exemplo n.º 5
0
    def validateDeviceConfigUi(self, valuesDict, typeId, devId):

        self.debugLog(u"validateDeviceConfigUi() method called.")

        if valuesDict[u'sourcePort'] == '':
            errorMsgDict = indigo.Dict()
            errorMsgDict[
                u'sourcePort'] = u'Port Cannot be blank and must be number 1024-65535.'
            return (False, valuesDict, errorMsgDict)

        try:
            port = int(valuesDict[u'sourcePort'])

            if (port <= 1024 or port > 65535):
                errorMsgDict = indigo.Dict()
                errorMsgDict[
                    u'sourcePort'] = u"Port number needs to be a valid MacOS UDP port (1024-65535)."
                return (False, valuesDict, errorMsgDict)
        except ValueError:
            errorMsgDict = indigo.Dict()
            errorMsgDict[
                u'sourcePort'] = u"Port number needs to be a valid MacOS UDP port Number! (1024-65535)."
            return (False, valuesDict, errorMsgDict)
        # self.errorLog(u"Plugin configuration error: ")
        sipserver = valuesDict[u'sipServer']
        if sipserver.find('.') < 0:
            errorMsgDict = indigo.Dict()
            errorMsgDict[
                u'sipServer'] = u'Sip Server Details Need to be entered.'
            return (False, valuesDict, errorMsgDict)
        return True, valuesDict
Exemplo n.º 6
0
 def validateActionConfigUi(self, valuesDict, typeId, devId):
     fail = False
     descString = u"airfoil: "
     if typeId == "connectToSpeaker":
         descString += u"connect to speaker " + self.pluginPrefs[
             "speakers"]["ID-" + valuesDict['speaker']][0]
     elif typeId == "disconnectFromSpeaker":
         descString += u"disconnect from speaker " + self.pluginPrefs[
             "speakers"]["ID-" + valuesDict['speaker']][0]
     elif typeId == "toggleSpeaker":
         descString += u"toggle speaker " + self.pluginPrefs["speakers"][
             "ID-" + valuesDict['speaker']][0]
     elif typeId == "changeAudioSource":
         errorMsgDict = indigo.Dict()
         if valuesDict["sourceType"] == "system":
             descString += u"change audio source to System Audio"
         elif valuesDict["sourceType"] == "device":
             if valuesDict.get("devSource", "") == "":
                 errorMsgDict[
                     'devSource'] = u"You must select a valid source name."
                 return (False, valuesDict, errorMsgDict)
             descString += u"change audio source to " + valuesDict[
                 'devSource']
         else:
             if valuesDict.get("appSource", "") == "":
                 errorMsgDict[
                     'appSource'] = u"You must select a valid source name."
                 return (False, valuesDict, errorMsgDict)
             descString += u"change audio source to " + valuesDict[
                 'appSource']
     elif (typeId == "setVolume") or (typeId == "increaseVolume") or (
             typeId == "decreaseVolume"):
         errorMsgDict = indigo.Dict()
         if len(valuesDict.get("speakerIds", None)) < 1:
             errorMsgDict[
                 "speakerIds"] = u"You must select at least one speaker"
             fail = True
         try:
             theNumber = int(valuesDict.get("volume", "-1"))
         except ValueError:
             theNumber = -1
         if (theNumber < 0) or (theNumber > 100):
             errorMsgDict[
                 "volume"] = u"The number must be an integer between 0 and 100"
             valuesDict["volume"] = "0"
             fail = True
         if typeId == "setVolume":
             descString += u"set volume to " + unicode(theNumber)
         elif typeId == "increaseVolume":
             descString += u"increase volume by " + unicode(theNumber)
         else:
             descString += u"decrease volume by " + unicode(theNumber)
         valuesDict["volume"] = theNumber
     if fail:
         return (False, valuesDict, errorMsgDict)
     self.debugLog(u"description string: " + descString)
     valuesDict['description'] = descString
     return (True, valuesDict)
Exemplo n.º 7
0
    def getMenuActionConfigUiValues(self, menuId):
        #indigo.server.log(u'Called getMenuActionConfigUiValues(self, menuId):')
        #indigo.server.log(u'     (' + unicode(menuId) + u')')

        valuesDict = indigo.Dict()
        valuesDict["selectEvent"] = "0"
        valuesDict["eventType"] = "0"
        valuesDict["enableDisable"] = "0"
        errorMsgDict = indigo.Dict()
        return (valuesDict, errorMsgDict)
Exemplo n.º 8
0
 def getDeviceFactoryUiValues(self, devIdList):
     self.debugLog("getDeviceFactoryUiValues: %s" % str(devIdList))
     isInitialDefine = (len(devIdList) == 0)
     valuesDict = indigo.Dict()
     if not isInitialDefine and devIdList[0] in indigo.devices:
         dev = indigo.devices[devIdList[0]]
         nodeId = dev.address
         if nodeId != "":
             valuesDict['veraDeviceId'] = nodeId
     errorsDict = indigo.Dict()
     return (valuesDict, errorsDict)
Exemplo n.º 9
0
 def validatePrefsConfigUi(self, valuesDict):
     self.debugLog(u"validating Prefs called")
     tcpPort = valuesDict[u'listenPort']
     try:
         iPort = int(tcpPort)
         if iPort <= 0:
             errorMsgDict = indigo.Dict()
             errorMsgDict[u'port'] = u"This needs to be a valid TCP port."
             return (False, valuesDict, errorMsgDict)
     except Exception, e:
         errorMsgDict = indigo.Dict()
         errorMsgDict[u'port'] = u"This needs to be a valid TCP port."
         return (False, valuesDict, errorMsgDict)
Exemplo n.º 10
0
 def getDeviceFactoryUiValues(self, dev_id_list):
     """ Called when the device factory config UI is first opened.
     Used to populate the dialog with values from device 0. """
     values = indigo.Dict()
     errors = indigo.Dict()
     # Retrieve parameters stored in device 0"s props.
     if dev_id_list:
         dev = indigo.devices[dev_id_list[0]]
         values["address" ] = dev.pluginProps.get("hostname", u"192.168.1.166")
         values["port"    ] = dev.pluginProps.get("port",     80)
         values["username"] = dev.pluginProps.get("username", "admin")
         values["pwd"     ] = dev.pluginProps.get("pwd",      "12345678")
     return (values, errors)
Exemplo n.º 11
0
	def getDetailsByPluginId (self, pluginId, deviceTypeId = ""):
		try:
			# In case this isn't a plugin, assume the Indigo information
			plugInfo = indigo.Dict()
			plugInfo["id"] = "Indigo"
			plugInfo["name"] = "Indigo"
			plugInfo["path"] = ""
			
			# If it's a plugin then get the basic plugin info, otherwise claim it as Indigo
			if pluginId != "":
				if pluginId in self.pluginCache: plugInfo = self.pluginCache[pluginId]
			
			try:
				pluginXML = indigo.Dict()
				
				# If we are caching our own information then also cache the Indigo built-in actions since it's in our plugin folders.  This will
				# actually cache rather than simply return details
				if plugInfo["id"] == self.factory.plugin.pluginId:
					plugInfoEx = indigo.Dict()
					plugInfoEx["id"] = "Indigo"
					plugInfoEx["name"] = "Indigo"
					plugInfoEx["path"] = ""
				
					if os.path.isfile(plugInfo["path"] + "/Contents/Server Plugin/lib/actionslib.xml"):
						pluginXML["actions"] = self._parseActionsXML(plugInfo["path"] + "/Contents/Server Plugin/lib/actionslib.xml")
					
					pluginXML["devices"] = indigo.Dict() # Placeholder
					
					plugInfoEx["xml"] = pluginXML	
					self.pluginCache["Indigo"] = plugInfoEx
					#indigo.server.log(unicode(plugInfoEx))	
					
				if os.path.isfile(plugInfo["path"] + "/Contents/Server Plugin/Devices.xml"):
					pluginXML["devices"] = self._parseDevicesXML(plugInfo["path"] + "/Contents/Server Plugin/Devices.xml")
										
				if os.path.isfile(plugInfo["path"] + "/Contents/Server Plugin/Actions.xml"):
					pluginXML["actions"] = self._parseActionsXML(plugInfo["path"] + "/Contents/Server Plugin/Actions.xml")
				
				plugInfo["xml"] = pluginXML
				
			except Exception as e:
				self.logger.error ("Exception encountered with " + unicode(plugInfo["path"]) + " (this error is NOT critical)")
				self.logger.error (ext.getException(e))
			
			#indigo.server.log (unicode(plugInfo))
			return plugInfo
			
		except Exception as e:
			#raise
			self.logger.error (ext.getException(e))	
Exemplo n.º 12
0
 def validateDeviceConfigUi(self, valuesDict, typeId, device):
     if typeId == "daily_Consumption":
         return (True, valuesDict)
     self.debugLog(valuesDict)
     if valuesDict['brokerID'] == "":
         self.errorLog("MQTT Broker Device cannot be empty")
         errorsDict = indigo.Dict()
         errorsDict['brokerID'] = "Broker Device Cannot Be Empty"
         return (False, valuesDict, errorsDict)
     if valuesDict['octopus_enable'] and valuesDict['octopusID'] == "":
         self.errorLog("Octopus Tariff Device cannot be empty")
         errorsDict = indigo.Dict()
         errorsDict['octopusID'] = "Octopus Tariff Device Cannot Be Empty"
         return (False, valuesDict, errorsDict)
     return (True, valuesDict)
Exemplo n.º 13
0
    def validateDeviceConfigUi(self, valuesDict, typeId, devId, runtime=False):
        self.logger.debug("validateDeviceConfigUi: " + typeId)
        errorsDict = indigo.Dict()

        if typeId == 'confirmedLock':
            if not zint(valuesDict.get('lockDevice', 0)):
                errorsDict['lockDevice'] = "Required"
            if valuesDict.get('doorSensorBool', False):
                if not zint(valuesDict.get('doorSensorDevice', 0)):
                    errorsDict['doorSensorDevice'] = "Required"
                if not valuesDict.get('doorSensorState', ''):
                    errorsDict['doorSensorState'] = "Required"
            if valuesDict.get('deadboltSensorBool', False):
                if not zint(valuesDict.get('deadboltSensorDevice', 0)):
                    errorsDict['deadboltSensorDevice'] = "Required"
                if not valuesDict.get('deadboltSensorState', ''):
                    errorsDict['ddeadboltSensorState'] = "Required"
            if valuesDict.get('actionBool', False):
                if not zint(valuesDict.get('actionGroup', 0)):
                    errorsDict['actionGroup'] = "Required"
                if zint(valuesDict.get('pesterCycles', '')):
                    if not zint(valuesDict.get('pesterDelay', 0)):
                        errorsDict['pesterDelay'] = "Required positive integer"
            if valuesDict.get('messageBool', False):
                if not zint(valuesDict.get('messageVariable', 0)):
                    errorsDict['messageVariable'] = "Required"
                if not valuesDict.get('messageText', ''):
                    errorsDict['messageText'] = "Required"

            valuesDict['address'] = zint(valuesDict.get('lockDevice', 0))

        if len(errorsDict) > 0:
            return (False, valuesDict, errorsDict)
        return (True, valuesDict)
Exemplo n.º 14
0
    def validatePrefsConfigUi(self, values):
        """ called by the Indigo UI to validate the values dictionary for
        the Plugin Preferences user interface dialog
        """
        errors = indigo.Dict()
        log.debug("Preferences Validation called")
        debug = values.get("showDebugInfo", False)
        if self.debug:
            if not debug:
                log.debug("Turning off debug logging")
        self.debug = debug
        log.debug("Debug logging is on")  # won't print if not self.debug

        self.debug_engine = values.get("showEngineDebugInfo", False)
        self.set_chatbot_logging()

        scripts_directory = values.get("scriptsPath", "")
        if not scripts_directory:
            errors["scriptsPath"] = "Directory of script files is required."
        elif scripts_directory != self.pluginPrefs.get("scriptsPath", ""):
            self.load_scripts(scripts_directory, errors, "scriptsPath")
        if errors:
            return (False, values, errors)
        else:
            return (True, values)
Exemplo n.º 15
0
    def checkFields(self, valuesDict):
        try:
            errorDict = indigo.Dict()
            success = True

            if "hbbIntegrated" not in valuesDict:
                errorDict[
                    "showAlertText"] = "Homebridge Buddy integration failure.  Device is missing the hbbIntegrated field, integration is not possible."
                return (False, valuesDict, errorDict)

            if "hbbServer" not in valuesDict:
                errorDict[
                    "showAlertText"] = "Homebridge Buddy integration failure.  Device is missing the hbbServer field, integration is not possible."
                return (False, valuesDict, errorDict)

            if "hbbTreatAs" not in valuesDict:
                errorDict[
                    "showAlertText"] = "Homebridge Buddy integration failure.  Device is missing the hbbTreatAs field, integration is not possible."
                return (False, valuesDict, errorDict)

        except Exception as e:
            success = False
            errorDict["showAlertText"] = unicode(e)
            self.logger.error(self.getException(e))

        return (success, valuesDict, errorDict)
Exemplo n.º 16
0
    def validatePrefsConfigUi(self, valuesDict):

        error_msg_dict = indigo.Dict()
        update_email = valuesDict['updaterEmail']
        update_wanted = valuesDict['updaterEmailsEnabled']

        # Test plugin update notification settings.
        try:
            if update_wanted and not update_email:
                error_msg_dict[
                    'updaterEmail'] = u"If you want to be notified of updates, you must supply an email address."
                error_msg_dict[
                    'showAlertText'] = u"Updater Email Error:\n\nThe plugin requires a valid email address in order to notify of plugin updates."
                return False, valuesDict, error_msg_dict

            elif update_wanted and "@" not in update_email:
                error_msg_dict[
                    'updaterEmail'] = u"Valid email addresses have at least one @ symbol in them ([email protected])."
                error_msg_dict['showAlertText'] = u"Updater Email Error:\n\nThe plugin requires a valid email address in order to notify of plugin updates (email address must " \
                                                  u"contain an '@' sign."

                return False, valuesDict, error_msg_dict

        except Exception as sub_error:
            self.logger.warning(
                u"Plugin configuration error: {0}".format(sub_error))

        return True, valuesDict
Exemplo n.º 17
0
    def validateDeviceConfigUi(self,
                               valuesDict,
                               deviceTypeId,
                               devId,
                               runtime=False):
        self.logger.debug("validateDeviceConfigUi: " + deviceTypeId)
        errorsDict = indigo.Dict()

        if not valuesDict.get('volumeName', ''):
            errorsDict['volumeName'] = "Required"
        else:
            valuesDict['mountPoint'] = "/Volumes/" + valuesDict['volumeName']

        if deviceTypeId == 'networkDisk':
            if not valuesDict.get('volumeURL', ''):
                errorsDict['volumeURL'] = "Required"
            elif not is_valid_url(valuesDict['volumeURL']):
                errorsDict['volumeURL'] = "Not valid URL"
            else:
                try:
                    parsed = urlparse.urlsplit(valuesDict['volumeURL'])
                    valuesDict['urlScheme'] = k_urlSchemes[parsed.scheme]
                except:
                    errorsDict['volumeURL'] = "Not supported filesystem type"

        if len(errorsDict) > 0:
            self.logger.debug('validate device config error: \n{0}'.format(
                str(errorsDict)))
            return (False, valuesDict, errorsDict)
        else:
            return (True, valuesDict)
Exemplo n.º 18
0
    def validateEventConfigUi(self, valuesDict, typeId, triggerId):
        errorsDict = indigo.Dict()

        if not valuesDict.get('calendarID', ''):
            errorsDict['calendarID'] = 'Required'
        try:
            float(valuesDict.get('timeCount', '0'))
        except:
            errorsDict['timeCount'] = 'Must be a number'

        if len(errorsDict) > 0:
            return (False, valuesDict, errorsDict)
        else:
            valuesDict['searchWords'] = valuesDict['searchWords'].lower()
            if float(valuesDict.get('timeCount', '0')) == 0.0:
                time_desc = u'at {}'.format(valuesDict['timeField'])
            else:
                time_logic = 'before' if float(
                    valuesDict['timeCount']) >= 0.0 else 'after'
                time_desc = u'{}min {} {}'.format(
                    abs(float(valuesDict['timeCount'])), time_logic,
                    valuesDict['timeField'])
            if valuesDict['searchWords']:
                event_desc = u'events with "{}" in {}'.format(
                    valuesDict['searchWords'], valuesDict['searchField'])
            else:
                event_desc = u'all events'
            calendar_name = indigo.devices[int(valuesDict['calendarID'])].name
            valuesDict['description'] = u'{} of {} from device "{}"'.format(
                time_desc, event_desc, calendar_name)
            return (True, valuesDict)
Exemplo n.º 19
0
    def validateDeviceConfigUi(self, values_dict, type_id, dev_id):

        error_msg_dict = indigo.Dict()

        # try:
        # Announcements device
        if type_id == 'announcementsDevice':
            return True, values_dict

        # Salutations device
        try:
            if type_id == 'salutationsDevice':
                morning = int(values_dict['morningStart'])
                afternoon = int(values_dict['afternoonStart'])
                evening = int(values_dict['eveningStart'])
                night = int(values_dict['nightStart'])

                if not (morning < afternoon < evening < night):
                    for key in ('morningStart', 'afternoonStart',
                                'eveningStart', 'nightStart'):
                        error_msg_dict[
                            key] = u"Each start time must be greater than the prior one."

        except ValueError:
            for key in ('morningStart', 'afternoonStart', 'eveningStart',
                        'nightStart'):
                error_msg_dict[
                    key] = u"You must set *all* the time controls to proceed. Otherwise, select cancel."

        if len(error_msg_dict) > 0:
            return False, values_dict, error_msg_dict

        self.announcement_update_states()
        return True, values_dict
Exemplo n.º 20
0
def refresh_token(self):
    url = "https://api.glowmarkt.com/api/v0-1/auth"

    payload = "{\n\"username\": \"" + self.pluginPrefs['bright_account'] + "\",\n\"password\": \"" + \
        self.pluginPrefs['bright_password'] + "\"\n}"
    headers = {
        'Content-Type': 'application/json',
        'applicationId': "b0f1b774-a586-4f72-9edd-27ead8aa7a8d",
    }
    try:
        response = requests.request("POST", url, headers=headers, data=payload)
        response.raise_for_status()
    except requests.exceptions.HTTPError as err:
        self.debugLog("HTTP Error when refreshing token")
    except Exception as err:
        self.debugLog("Other error when refreshing token")

    response_json = response.json()
    if response.status_code != 200:
        self.errorLog(
            "Failed to Authenticate with Glow Servers, Check Password and Account Name"
        )
        errorsDict = indigo.Dict()
        errorsDict[
            'bright_password'] = "******"
        return False
    else:
        self.pluginPrefs['token'] = response_json['token']
        self.pluginPrefs['token_expires'] = response_json['exp']
        self.debugLog("Token is " + self.pluginPrefs['token'])
        self.debugLog("Expiry is " + str(self.pluginPrefs['token_expires']))
        return True
Exemplo n.º 21
0
	def validatePrefsConfigUi(self, valuesDict):
		self.log.debug("validatePrefsConfigUi: %s" % valuesDict)
		self.update_logging(bool(valuesDict['debuggingEnabled'] and "y" == valuesDict['debuggingEnabled']))

		errorDict = indigo.Dict()

		if not valuesDict["updateDelayMinutesWhenCharging"] > 0:
			errorDict["updateDelayMinutesWhenCharging"] = "This value must be a whole number >= 1"
		if not valuesDict["updateDelayMinutesWhenNotCharging"] > 0:
			errorDict["updateDelayMinutesWhenNotCharging"] = "This value must be a whole number >= 1"
		if not valuesDict["updateDelayMinutesOnError"] > 0:
			errorDict["updateDelayMinutesOnError"] = "This value must be a whole number >= 1"

		if len(errorDict) > 0:
			return (False, valuesDict, errorDict)


		IndigoLeaf.use_distance_scale(valuesDict["distanceUnit"])

		if self.leaves:
			for l in self.leaves:
				l.set_update_frequencies(charging_freq_min=self.pluginPrefs['updateDelayMinutesWhenCharging'],
										 not_charging_freq_min=self.pluginPrefs['updateDelayMinutesWhenNotCharging'],
										 error_freq_min=self.pluginPrefs['updateDelayMinutesOnError'])


		if (self.pluginPrefs['region'] != valuesDict['region']) or (self.pluginPrefs['username'] != valuesDict['username']) or (self.pluginPrefs['password'] != valuesDict['password']):
			IndigoLeaf.setup(valuesDict['username'], valuesDict['password'], valuesDict['region'])
			# no need to log in here; that will happen automatically next time we use the service



		return True
Exemplo n.º 22
0
    def validateDeviceConfigUi(self, valuesDict, typeId, devId, runtime=False):
        self.logger.debug("validateDeviceConfigUi: " + typeId)
        errorsDict = indigo.Dict()

        if typeId == 'cbpi-server':
            address = valuesDict.get('cbpi_address','')
            port = valuesDict.get('cbpi_port','')
            url = u'http://{}:{}'.format(address,port)
            if not any([is_valid_hostname(address),is_valid_ipv4_address(address),is_valid_ipv6_address(address)]):
                errorsDict['cbpi_address'] = "Not valid IP or host name"
            if not validateTextFieldNumber(port, numberType=int, zeroAllowed=False, negativeAllowed=False, maximumAllowed=65535):
                errorsDict['cdpi_port'] = "Invalid port number"
            if is_valid_url(url):
                valuesDict['address'] = url
        else:
            server_id = int(valuesDict.get('server_id',0))
            cbpi_id = int(valuesDict.get('cbpi_id',0))
            if not server_id:
                errorsDict['server_id'] = 'Required'
            elif not cbpi_id:
                errorsDict['cbpi_id'] = 'Required'
            else:
                server_device = self.serverDict.get(server_id)
                address = server_device.device.pluginProps.get('address')
                valuesDict['address'] = address

        if len(errorsDict) > 0:
            return (False, valuesDict, errorsDict)
        return (True, valuesDict)
Exemplo n.º 23
0
    def validateDeviceConfigUi(self, valuesDict, typeId, devId):
        try:
            errorDict = indigo.Dict()

            if "voiceIntegrated" in valuesDict:
                if valuesDict["voiceIntegrated"]:
                    if valuesDict["voiceHKBAvailable"]:
                        if valuesDict["voiceHKBServer"] == "":
                            errorDict[
                                "voiceHKBServer"] = "Select a HomeKit Bridge server"
                            errorDict[
                                "showAlertText"] = "If you opt to integrate with HomeKit Bridge then you must select which server to attach this device to."
                            return (valuesDict, errorDict)

                        if valuesDict["voiceHKBDeviceType"] == "":
                            errorDict[
                                "voiceHKBDeviceType"] = "Select a HomeKit Bridge device type"
                            errorDict[
                                "showAlertText"] = "If you opt to integrate with HomeKit Bridge then you must select how you want this device treated."
                            return (valuesDict, errorDict)

        except Exception as e:
            self.logger.error(self.getException(e))

        return (valuesDict, errorDict)
Exemplo n.º 24
0
    def validatePluginConfigUi(self, valuesDict, typeId, triggerId):
        errorsDict = indigo.Dict()

        if len(errorsDict) > 0:
            return (False, valuesDict, errorsDict)
        else:
            return (True, valuesDict)
Exemplo n.º 25
0
    def validatePrefsConfigUi(self, valuesDict):
        self.logger.debug("validatePrefsConfigUi")
        errorsDict = indigo.Dict()

        if len(errorsDict) > 0:
            return (False, valuesDict, errorsDict)
        return (True, valuesDict)
Exemplo n.º 26
0
    def validateActionConfigUi(self, valuesDict, typeId, devId):
        errorsDict = indigo.Dict()

        positiveIntegerFields = ['duration', 'trackNumber']
        otherRequiredFields = [
            'variable', 'playlist', 'trackName', 'device', 'status',
            'specifier', 'applescriptText'
        ]

        for key, value in valuesDict.items():
            if key == 'volume':
                if not validateTextFieldNumber(value,
                                               numberType=int,
                                               zeroAllowed=True,
                                               negativeAllowed=False,
                                               maximumAllowed=100):
                    errorsDict[key] = "Must be an integer between 0 and 100"
            elif key in positiveIntegerFields:
                if not validateTextFieldNumber(value,
                                               numberType=int,
                                               zeroAllowed=False,
                                               negativeAllowed=False):
                    errorsDict[key] = "Must be a positive integer"
            elif key in otherRequiredFields:
                if value == "":
                    errorsDict[key] = "Required"

        if len(errorsDict) > 0:
            self.logger.debug(u'\n{}'.format(valuesDict))
            return (False, valuesDict, errorsDict)
        else:
            return (True, valuesDict)
Exemplo n.º 27
0
    def validateDeviceConfigUi(self, valuesDict, typeId, devId, runtime=False):
        self.logger.debug("validateDeviceConfigUi: " + typeId)
        errorsDict = indigo.Dict()

        if not valuesDict.get('fans', ''):
            errorsDict['fans'] = "Select at least one fan"

        if typeId == 'thermAssist':
            for key in ['onThreshold', 'offThreshold']:
                if valuesDict.get(key, "") == "":
                    errorsDict[key] = "Required"
                else:
                    try:
                        t = float(valuesDict[key])
                        if t <= 0.0:
                            raise
                    except:
                        errorsDict[key] = "Must be positive real number"
            if not errorsDict:
                if float(valuesDict['offThreshold']) > float(
                        valuesDict['offThreshold']):
                    errorsDict[
                        'offThreshold'] = "Must be less than or equal to ON Threshold"

        if len(errorsDict) > 0:
            return (False, valuesDict, errorsDict)
        else:
            return (True, valuesDict)
Exemplo n.º 28
0
    def validatePrefsConfigUi(self, valuesDict):
        self.debugLog(u"validatePrefsConfigUi() method called")
        errorsDict = indigo.Dict()
        errorsFound = False

        if len(valuesDict[u'urltoken']) == 0:
            errorsDict[
                u'urltoken'] = u'The plugin requires a Slack webhook token.'
            errorsFound = True
        if " " in (valuesDict[u'urltoken']):
            errorsDict[
                u'urltoken'] = u'The Slack webhook token can not contain spaces.'
            errorsFound = True

        if len(valuesDict[u'slacktoken']) == 0:
            errorsDict[u'slacktoken'] = u'The plugin requires a Slack token.'
            errorsFound = True
        if " " in (valuesDict[u'slacktoken']):
            errorsDict[
                u'slacktoken'] = u'The Slack token can not contain spaces.'
            errorsFound = True

        if len(valuesDict[u'userid']) == 0:
            errorsDict[u'userid'] = u'The plugin requires a Slack user ID.'
            errorsFound = True
        if " " in (valuesDict[u'userid']):
            errorsDict[
                u'userid'] = u'The Slack user ID can not contain spaces.'
            errorsFound = True

        if errorsFound:
            return (False, valuesDict, errorsDict)
        else:
            return (True, valuesDict)
Exemplo n.º 29
0
	def addDevice (self, dev):
		try:
			if self.items.isInCache (dev.id):
				self.logger.debug ("Not adding {0} to cache because it's already there".format(dev.name))
				return
			else:
				self.logger.debug ("Adding {0} to cache".format(dev.name))
		
			cDev = cacheDev(dev)
			self.items.add(cDev)
			
			if cDev.pluginId == self.factory.plugin.pluginId: 
				self._autoCacheFields (dev)
				
				if cDev.id in self.pluginDevices:
					pass
				else:
					self.pluginDevices.append(cDev.id) 
				
				pluginItem = indigo.Dict()
				if cDev.deviceTypeId in self.pluginItems:
					pluginItem = self.pluginItems[cDev.deviceTypeId]
				
				else:
					pluginItem = indigo.List()

				if cDev.id in pluginItem:
					pass
				else:
					pluginItem.append(cDev.id)
					
				self.pluginItems[cDev.deviceTypeId] = pluginItem	
				
		except Exception as e:
			self.logger.error (ext.getException(e))	
Exemplo n.º 30
0
    def validateActionConfigUi(self, values, type_id, action_id):
        """ called by the Indigo UI to validate the values dictionary
        for the Action user interface dialog
        """
        log.debug("Action Validation called for %s" % type_id)
        errors = indigo.Dict()
        if (StrictVersion(values.get("actionVersion", "0.0")) <
                StrictVersion(_VERSION)):
            values["actionVersion"] = _VERSION

        if type_id != "checkSecurityCode":
            return (not errors, values, errors)

        code = values["code"]
        if "%%" in code:
            self.validate_substitution(values, errors, "code")
        elif not self.is_valid_code(code):
            errors["code"] = "Security codes must be four digits: 0001 to 9999"

        area = values["area"]
        if "%%" in area:
            self.validate_substitution(values, errors, "area")
        elif not self.is_valid_area(area):
            errors["area"] = ("Please enter the area number in which to check "
                              "the security code")

        return (not errors, values, errors)