def main(): #configuring Twitter API configurator = Configurator() api = configurator.returnAPI() analyzer = Analyzer(api) analyzer.filterByTerm("created_at", "tweets.json")
def GetConfiguration(self): # Message width self.logger_message_width = Configurator.GetOption( self.globalConfig, [LOGGER_CONFIG_KEY, LOGGER_MESSAGE_WIDTH_KEY], LOGGER_MESSAGE_WIDTH_DEFAULT) # File level self.file_log_level = Configurator.GetOption( self.globalConfig, [LOGGER_CONFIG_KEY, LOGGER_FILE_LEVEL_KEY], LOGGER_DEFAULT_LEVEL) # Console level self.console_log_level = Configurator.GetOption( self.globalConfig, [LOGGER_CONFIG_KEY, LOGGER_CONSOLE_LEVEL_KEY], LOGGER_DEFAULT_LEVEL)
def rancilio_ready_handler(): configs = Configurator.instance() ready = configs.RancilioHeatedUp if ready: blynk.virtual_write(4, 255) else: blynk.virtual_write(4, 0)
def setpoint_handler(value): logger = logging.getLogger('__main__.' + __name__) configs: Configurator = Configurator.instance() value = float(value) configs.pid_configs[configs.RancilioPowerMode]['setpoint'] = value configs.update()
def setConfig(self,config,rnargs=None): self.config = Configurator(config) self.config.parseConfig() if not rnargs: self.running=None self.srtd=[] self.awakelog = AwakeLog.alloc().initWithInfo_( {'filename':__name__}) self.two = None
def FrequencyFormatter(value, options): # Get value in hertz result = value # Add unit if cf.GetOption(options, VALUEFORMATTER_OPTIONS_UNIT_OF_MEASUREMENT_KEY, VALUEFORMATTER_OPTIONS_UNIT_OF_MEASUREMENT_DEFAULT): result = str(value) + 'hz' return result
def TimeFormatter(value, options): # Get value in milliseconds result = value # Add unit if cf.GetOption(options, VALUEFORMATTER_OPTIONS_UNIT_OF_MEASUREMENT_KEY, VALUEFORMATTER_OPTIONS_UNIT_OF_MEASUREMENT_DEFAULT): result = str(value) + 'ms' return result
def __init__(self): self.output = 0 self.cycleStartTime = time.time() self.cycleMilliseconds = 1000 self.onTime = 0 self.configs = Configurator.instance() self.pinHandler = PinHandler.instance()
def rancilio_main_switch_handler(value): logger = logging.getLogger('__main__.' + __name__) configs = Configurator.instance() powerOn = int(value) configs.RancilioPoweredOn = bool(powerOn) configs.update() status = 'on' if bool(powerOn) else 'off' logger.info('Rancilio is powered {}'.format(status))
def __init__(self, sensorAddress: str = None): self.logger = logging.getLogger(__name__) self.configs = Configurator.instance() self.oneWireStatus = oneWire.setupOneWire( self.configs.tempSensorPin) self.lastTemperature = None self.sensorAddress = sensorAddress self.sensor = None
def main(argv): parser = OptionParser() parser.add_option("-a", "--article", dest="url", help="Url of the article to be processed") parser.add_option("-o", "--ofile", dest="outputfile", help="Define the output file where the result will be stored - if not set will be defined automatically") parser.add_option("-c", "--config", dest="config", help="config file location") parser.add_option("-v", "--verbose", dest="verbose",action="store_true", default=False, help="Print HTML parser output to stdout") (options, args) = parser.parse_args(argv) if (len(argv) < 2): progName = parser.get_prog_name() if ".py" in progName: print 'Please see help : python', progName, '-h' else: print 'Please see help :', progName, '-h' sys.exit() print 'Url to process "', options.url, '"' if not uri_validator(options.url): print 'Url is not valid. Exit.' sys.exit(1) configurator = Configurator(options.config) config = configurator.getConfig() textArray = TextFromHtmlExtractor.getTextArrayFromUrl(options.url, config, options.verbose) fileGenerator = FilePathGenerator.FilePathGenerator(options.url) if (options.outputfile is not None): file = fileGenerator.generateProvided(options.outputfile) else: file = fileGenerator.generateByUrl('./out') print 'Output file is "', file.name, '"' with TextPrettyWriter(file, config) as prettyWriter: prettyWriter.write(textArray) print 'Work completed.'
def ByteFormatter(value, options): # Get value in bytes asked_size = cf.GetOption(options, VALUEFORMATTER_OPTIONS_SIZE_KEY) decimals = cf.GetOption(options, VALUEFORMATTER_OPTIONS_DECIMALS_KEY) if asked_size and asked_size in BYTE_SIZES: powOf1024 = BYTE_SIZES.index(asked_size) else: powOf1024 = math.floor(math.log(value, 1024)) result = str(round(value / (math.pow(1024, powOf1024)), decimals)) # Add unit if cf.GetOption(options, VALUEFORMATTER_OPTIONS_UNIT_OF_MEASUREMENT_KEY, VALUEFORMATTER_OPTIONS_UNIT_OF_MEASUREMENT_DEFAULT): result = result + BYTE_SIZES[powOf1024] return result
def __init__(self): self.configs = Configurator.instance() self.configs.functionList.append(self.update_configs) self.heatingElement = self.configs.heaterElementPin os.system('fast-gpio set-output {}'.format( self.heatingElement )) self.last_value = 0 self.logger = logging.getLogger('__main__.' + __name__)
def LoadRequirements(self): # Here I load sensors and commands # I have a dict with {'sensors':[SENSORS],'commands':[COMMANDS]} # SENSORS and COMMANDS have the same format as the configutaration.yaml so I # tell to LoadSensor and LoadCommands what to load with the usual method for requirements in self.requirements: sensors = cf.GetOption(requirements, SETTINGS_REQUIREMENTS_SENSOR_KEY) commands = cf.GetOption(requirements, SETTINGS_REQUIREMENTS_COMMAND_KEY) if sensors: self.LoadEntities(sensors, SENSOR_NAME_SUFFIX, loadingRequirements=True) if commands: self.LoadEntities(commands, COMMAND_NAME_SUFFIX, loadingRequirements=True) self.requirements.remove(requirements)
class CertChecker( object ): def __init__( self ): self.ssh = SSHConnector( ) self.conf = Configurator( '/etc//cfg/cert-checker.cfg', 'cert-checker' ) mailto = self.conf.getValue('MAILTO').split(',') self.mail = Mailer( self.conf.getValue('MAILFROM'), mailto, self.conf.getValue('SMTPRELAY') ) def __processDays( self ): files = self.conf.getValue('REMOTE_FILES') files = files.split(',') server = self.conf.getValue('SERVER') server = server.split(',') server = Server( server[0], server[1], server[2], server[3], server[4] ) tmp = self.conf.getValue('TMP') contents = list() for file in files: self.ssh.getFile( server, file, "%s/" % tmp ) cont_tmp = open("%s" % file, 'r' ) expiring = list() for line in cont_tmp: line = line.strip() line = line.split( '|' ) if int( line[1] ) < int( self.conf.getValue('DAYS') ): expiring.append( {'name':line[0], 'days':line[1]} ) contents.append( { '%s' % (file): expiring } ) return contents def startCheck( self ): expiring = self.__processDays() subject = "Certificates expiration report" body = "This is an automatic report of certificates that are about to expire\n\n" for exp in expiring: if len( exp[ exp.keys()[0] ] ) > 0: title = exp.keys()[0].split('-')[3].split('.')[0] body += "%s\n" % title for cert in exp[ exp.keys()[0] ]: if int( cert['days'] ) < 0: body += " !! CERTIFICATE EXPIRED %s\n\n" % cert['name'] else: body += " W CERTIFICATE %s EXPIRES IN %s DAYS\n\n" % ( cert['name'], cert['days'] ) body += "\n\n\n\nThis email will be sent every Monday at morning\n\n" body += "Recipients: %s\n" % self.conf.getValue('MAILTO') self.mail.sendMail( subject, body )
def __init__(self, stopEvent: Event = None): self.input_value = 0 self.configs = Configurator.instance() self.configs.functionList.append(self.update_configs) self.heater = Heater() self.pid = PID.instance() self.update_configs() self.isPoweredOn = False self.powerMode = self.configs.energy_mode.eco self.dataLogger = self.configs.dataLogger self._stopEvent = stopEvent self.logger = logging.getLogger('__main__.' + __name__)
def GetValueFormatterOptionForTopic( self, valueTopic): # Return the ValueFormat options for the passed topic VFoptions = self.GetOption(self.consts.VALUE_FORMAT_OPTION_KEY) # if the options are not in a list: specified options are for every topic if type(VFoptions) is not list: return VFoptions else: # I have the same structure (topic with wildcard and configs) that I have for the topic settings in discovery for topicOptions in VFoptions: optionTopic = cf.GetOption(topicOptions, "topic") if optionTopic == "*" or optionTopic == valueTopic: return topicOptions return None return None
def rancilio_temperature_status_handler(): configs: Configurator = Configurator.instance() dataLogger = configs.dataLogger pid = PID.instance() logger = logging.getLogger('__main__.' + __name__) temperature = dataLogger.boilerTemp if temperature is None: logger.warning('Temperature is None: {}'.format(temperature)) return blynk.virtual_write(3, temperature) blynk.virtual_write(6, pid.proportional_term) blynk.virtual_write(7, pid.integral_term) blynk.virtual_write(8, pid.derivative_term)
def __init__(self, stopEvent: Event, error_in_method_event: Event): self.boilerTemp = 21 self.steamTemp = 21 self._boilerTempSensors = [] self._boilerTempSensorsIter = None self._steamTempSensors = [] self.configs = Configurator.instance() self.configs.functionList.append(self.update_configs) self._smoothingFactor = self.configs.smoothingFactor self._stopEvent = stopEvent self._error_in_method_event = error_in_method_event self.lastValue = 23 self.logger = logging.getLogger('__main__.' + __name__)
def PrepareDiscoveryPayloads(self): discovery_data = [] # Check if Discovery is enabled if self.GetOption([ self.consts.CONFIG_DISCOVERY_KEY, self.consts.DISCOVERY_ENABLE_KEY ], False) is not False: # Okay need auto discovery # Not for don't send sensors if self.GetOption('dont_send') is True: return # Don't send if disabled in config prefix = self.GetOption([ self.consts.CONFIG_DISCOVERY_KEY, self.consts.DISCOVERY_DISCOVER_PREFIX_KEY ], self.consts.DISCOVERY_DISCOVER_PREFIX_DEFAULT) preset = self.GetOption([ self.consts.CONFIG_DISCOVERY_KEY, self.consts.DISCOVERY_PRESET_KEY ]) entity_preset_data = None if preset: # Check here if I have an entry in the discovery file for this topic and use that data (PLACE IN 'sensor_data') entity_preset_data = cf.GetOption( self.settings, [self.consts.SETTINGS_DISCOVERY_KEY, preset]) # THIS for topic in self.outTopics: # discoveryData: {name, config_topic, payload} # print(topic) data = self.PrepareTopicDiscoveryData( topic['topic'], self.consts.TYPE_TOPIC_OUT, prefix, preset, entity_preset_data) if data: discovery_data.append(data) for topic in self.inTopics: # discoveryData: {name, config_topic, payload} data = self.PrepareTopicDiscoveryData( topic, self.consts.TYPE_TOPIC_IN, prefix, preset, entity_preset_data) if data: discovery_data.append(data) return discovery_data
def LoadEntities(self, entitiesToAdd, name_suffix, loadingRequirements=False): # From configs I read sensors list and I give the names to the sensors manager which will initialize them # and will keep trace of who is the mqtt_client and the logger of the sensor # self.entityManager.PostInitializeEntities() if entitiesToAdd: for entity in entitiesToAdd: # I load the sensor and if I need some requirements, I save them to the list # Additional check to not load double if I am loading requirements if not (loadingRequirements and entity in self.loadedEntities): settings = self.entityManager.LoadEntity( name_suffix, entity, self.monitor_id, self.config, self.mqttClient, self.config['send_interval'], self.logger) requirements = cf.GetOption(settings, SETTINGS_REQUIREMENTS_KEY) if requirements: self.requirements.append(requirements) self.loadedEntities.append(entity)
def GetFormattedValue(value, valueType, options=None): if options == None: options = ValueFormatter.Options() # Default will be used if valueType == ValueFormatter.TYPE_NONE: # No edit needed return value elif valueType == ValueFormatter.TYPE_BYTE: return ValueFormatter.ByteFormatter(value, options) elif valueType == ValueFormatter.TYPE_TIME: return ValueFormatter.TimeFormatter(value, options) elif valueType == ValueFormatter.TYPE_FREQUENCY: return ValueFormatter.FrequencyFormatter(value, options) elif valueType == ValueFormatter.TYPE_PERCENTAGE: if cf.GetOption( options, VALUEFORMATTER_OPTIONS_UNIT_OF_MEASUREMENT_KEY, VALUEFORMATTER_OPTIONS_UNIT_OF_MEASUREMENT_DEFAULT): return str(value) + '%' else: return value else: return value
def rancilio_power_mode_handler(value): configs = Configurator.instance() logger = logging.getLogger('__main__.' + __name__) value = int(value) if value == 1: configs.RancilioPowerMode = configs.energy_mode.off elif value == 2: configs.RancilioPowerMode = configs.energy_mode.eco elif value == 3: configs.RancilioPowerMode = configs.energy_mode.on elif value == 4: configs.RancilioPowerMode = configs.energy_mode.steam else: configs.RancilioPowerMode = configs.energy_mode.off logger.error('Power Mode Handler: undefined value: {}'.format(value)) return configs.update() status = configs.energy_mode._fields[configs.RancilioPowerMode] logger.info('Rancilio is powered in {} mode'.format(status)) # set Gauge to new range setpoint = configs.pid_configs[configs.RancilioPowerMode]['setpoint'] blynk.setProperty(3, 'min', setpoint * 0.8) blynk.setProperty(3, 'max', setpoint * 1.2) # set Slider settings blynk.virtual_write(9, setpoint) if configs.RancilioPowerMode == configs.energy_mode.off: blynk.setProperty(9, 'min', 18) blynk.setProperty(9, 'max', 25) elif configs.RancilioPowerMode == configs.energy_mode.eco: blynk.setProperty(9, 'min', 40) blynk.setProperty(9, 'max', 60) elif configs.RancilioPowerMode == configs.energy_mode.on: blynk.setProperty(9, 'min', 92) blynk.setProperty(9, 'max', 110) elif configs.RancilioPowerMode == configs.energy_mode.steam: blynk.setProperty(9, 'min', 105) blynk.setProperty(9, 'max', 125)
def GetOption(self, path, defaultReturnValue=None): return cf.GetOption(self.options, path, defaultReturnValue)
def __init__(self): self.configurator = Configurator() self.dbmanager = DBManager(self.configurator.config['DBPATH']) self.dbmanager.recreate_tables()
def rancilio_heater_status_handler(): configs = Configurator.instance() dutyCycle = configs.heater_output blynk.virtual_write(5, dutyCycle)
sys.exit(2) if not os.path.isdir(args.output): print("[!] Missing output directory : " + args.output) sys.exit(1) if not os.access(args.output, os.W_OK | os.X_OK): print("[!] Can't write to the templates directory : " + args.output) sys.exit(2) if not os.path.exists(args.variables): print("[!] Missing variables file : " + args.variables) sys.exit(1) if not os.access(args.variables, os.R_OK): print("[!] Can't read variables file : " + args.variables) sys.exit(2) # Compute the final config configurator = Configurator() configurator.load_settings(args.settings) variables = utils.load_variables(args.variables) configurator.load_variables(variables) config = configurator.get_config() # Remove old files files = glob.glob(args.output + "/*") for file in files: if (file.endswith(".conf") or file.endswith(".env") ) and os.path.isfile(file) and not os.path.islink(file): os.remove(file) elif os.path.isdir(file) and not os.path.islink(file): shutil.rmtree(file, ignore_errors=False) # Generate the files from templates and config
def __init__(self): self.c = Configurator('/etc/core/cfg/lororeceiver.cfg', 'lororeceiver') self.l = Logger(self.c.getValue('FILELOG'), self.c.getValue('SYSTEM'), self.c.getValue('DEBUG'))
class LoroReceiver( object ): def __init__(self): self.c = Configurator('/etc/core/cfg/lororeceiver.cfg', 'lororeceiver') self.l = Logger(self.c.getValue('FILELOG'), self.c.getValue('SYSTEM'), self.c.getValue('DEBUG')) def __searchKeyword(self, standardinput): self.l.addInfoLine("El cuerpo del email es el correcto?") process = standardinput.split(' ') for line in process: if re.search('Good_Auto_Response', line): return True return False def __isFromGranted(self, standardinput): self.l.addInfoLine('Es de un sender permitido?') process = standardinput.split('|') FROM = None for line in process: if re.search('From ', line): FROM = line.split('From ')[1] FROM = FROM.split(' ')[0] break accepted_from = self.c.getValue('ACCEPTEDFROM').split('|') for user_from in accepted_from: if FROM == user_from: self.l.addInfoLine('Si lo es') return True self.l.addInfoLine('No lo es') return False def __storeValue(self, value): file_pointer = open(self.c.getValue('STATEFILE'),'w') self.l.addInfoLine('Valor storeado: %s' % value) file_pointer.write(value) file_pointer.close() def main(self): self.l.addInfoLine('--------------') self.__storeValue("0") EMAIL_buffer = sys.stdin.read() self.l.addInfoLine('Email Received') self.addInfoLine(EMAIL_buffer) if self.__isFromGranted(EMAIL_buffer): self.l.addInfoLine("Sender accepted") if self.__searchKeyword(EMAIL_buffer): self.l.addInfoLine("El cuerpo es correcto") self.__storeValue("1") else: self.l.addWarningLine("El cuerpo incorrecto") self.__storeValue("0") self.l.addInfoLine('--------------')
def __init__( self ): self.ssh = SSHConnector( ) self.conf = Configurator( '/etc//cfg/cert-checker.cfg', 'cert-checker' ) mailto = self.conf.getValue('MAILTO').split(',') self.mail = Mailer( self.conf.getValue('MAILFROM'), mailto, self.conf.getValue('SMTPRELAY') )
def smoothing_factor_handler(value): value = float(value) configs: Configurator = Configurator.instance() configs.smoothingFactor = value configs.update()
class Administration(NSObject): def setConfig(self,config,rnargs=None): self.config = Configurator(config) self.config.parseConfig() if not rnargs: self.running=None self.srtd=[] self.awakelog = AwakeLog.alloc().initWithInfo_( {'filename':__name__}) self.two = None def play_string(self, stri): resstring = "" try: import StringIO outlog = StringIO.StringIO() AwakeLog.toanotherhandle = outlog x= self.config.parseConfig(stri) if not x==None: resstring = "%s\n%s" % (x, outlog.getValue()) outlog.close() else: self.srtd = [] self.schedule() finally: AwakeLog.toanotherhandle = None resstring = outlog.getValue() outlog.close() return resstring ## return a success string def stopCurrentRunning(self,info=None): if self.running: self.running.stop(info) self.running = None def getEnv(self): return self.config.getEnv() def cancelRequests(self): for i in self.srtd: if i: i.cancel() try: if self.two: self.two.cancel() except: pass # no reason for exception, but i'm too lazy to verify, such bad coding, sigh if self.running: self.running.cancel() NSObject.cancelPreviousPerformRequestsWithTarget_(self) def snooze(self): if self.running: self.running.stop({'snooze':True}) if self.getEnv().get(HOOKS['ONSNOOZE'],None): self.getEnv()[HOOKS['ONSNOOZE']](self.running) snooze_time = self.getEnv().get(HOOKS['SNOOZETIME'],15) self.performSelector_withObject_afterDelay_("snoozeOff",self.running,snooze_time) def snoozeOff(self,p): self.stopCurrentRunning() self.running = p self.running.fadein['dur']=float(15) self.running.start() def runPlayer(self, p): self.awakelog.info("Will play %s" % p.title) self.stopCurrentRunning() self.running = p self.running.start() def scheduleWakeup(self,plyr): import datetime current_time = datetime.datetime.today() timedelta = (plyr.wake_time - current_time).seconds self.performSelector_withObject_afterDelay_("runPlayer",plyr,timedelta) def scheduleOne(self,one): self.two = self.config.singleWakeUp(one) self.scheduleWakeup(self.two) self.awakelog.info(str(self.two)) return str(self.two) def schedule(self): self.srtd = self.config.getWakeups() self.srtd.sort(key=lambda x: x.wake_time) for i in self.srtd: self.scheduleWakeup(i)
def __init__(self): self.c = Configurator('/etc//cfg/ack.conf', 'ack') self.l = Logger(self.c.getValue('FILE_LOG'), self.c.getValue('NAME'), self.c.getValue('DEBUG')) self.z = ZabbixDB(self.l, self.c.getValue('DB_HOST'), self.c.getValue('DB_USER'), self.c.getValue('DB_PASS'), self.c.getValue('DB_NAME'))
def IsDiscoveryEnabled(self): return cf.GetOption(self.brokerConfigs, [ self.consts.CONFIG_DISCOVERY_KEY, self.consts.DISCOVERY_ENABLE_KEY ], False)
class ACK( object ): def __init__(self): self.c = Configurator('/etc//cfg/ack.conf', 'ack') self.l = Logger(self.c.getValue('FILE_LOG'), self.c.getValue('NAME'), self.c.getValue('DEBUG')) self.z = ZabbixDB(self.l, self.c.getValue('DB_HOST'), self.c.getValue('DB_USER'), self.c.getValue('DB_PASS'), self.c.getValue('DB_NAME')) def __checkUserPIN(self, pin, ffrom): users_raw = self.c.getValue('USERS') users_lines = users_raw.split(',') for user in users_lines: self.l.addInfoLine("%s :: %s" % ( user.split('|')[0], user.split('|')[1] )) if user.split('|')[0] == ffrom and user.split('|')[1] == pin: return True return False def __clearSubject(self, subject, pipes): if pipes: self.l.addInfoLine(subject) try: filtered = subject.split('|') self.l.addInfoLine(filtered[0]) return filtered[1] except: self.l.addWarningLine('El subject esta mal formado') return "Mal formed subject" else: return subject def __sendEmail(self, user, subject, type): self.m = Mailer('[email protected]', self.c.getValue('MAIL_TO'), self.c.getValue('RELAY')) self.m.sendMail("ACK: %s" % self.__clearSubject(subject, type), "ACK Message: %s" % self.__clearSubject(subject, type)) self.l.addInfoLine('Email Sended to itnetworking') self.m = Mailer('[email protected]', user, self.c.getValue('RELAY')) self.m.sendMail("ACK: %s" % self.__clearSubject(subject, type), "ACK Message: %s" % self.__clearSubject(subject, type)) self.l.addInfoLine('Email Sended to %s' % user) def __isException(self, e_from): filtered = e_from.split('|') for email in filtered: if email == e_from: return True return False def main(self): stdin_raw = sys.stdin.read() stdin_lines = stdin_raw.split('\n') KEY = None PIN = "" FROM = "" ACK = False self.l.addInfoLine('---------------------------------') for line in stdin_lines: if re.search('From ', line): FROM = line.split('From ')[1] FROM = FROM.split(' ')[0] self.l.addInfoLine("From: %s" % FROM) if re.search('Subject: ', line): SUBJECT = line.split('Subject: ')[1] self.l.addInfoLine("Subject: %s" % SUBJECT) ack_key = SUBJECT.split(' ')[0] if ack_key == 'ACK': PIN = SUBJECT.split(' ')[1] self.l.addInfoLine("ACK PIN: %s" % PIN) ACK = True if re.search('KEY: ', line): if KEY is None: KEY = line.split('KEY: ')[1] self.l.addInfoLine('KEY: %s' % KEY) if ACK: if not self.__checkUserPIN(PIN, FROM): self.l.addWarningLine('Invalid PIN/USER combination') self.l.addWarningLine('User %s has given an incorrect PIN %s' % (FROM, PIN)) self.__sendEmail(FROM, "USER %s has given an incorrect PIN %s" % (FROM, PIN), False) else: self.l.addInfoLine('PIN/USER ACCEPTED') if self.z.ACK( KEY ): self.l.addInfoLine('ACK OK') self.__sendEmail(FROM, "ACK! %s" % SUBJECT, True) else: self.l.addErrorLine('ACK ERROR') else: if not self.__isException(FROM): self.__sendEmail(FROM, "WARNING USER %s MALFORMED EMAIL" % FROM, False) self.l.addInfoLine('---------------------------------')
def PrepareTopicDiscoveryData(self, topic, entity_model, prefix, preset, entity_preset_data): payload = {} topicSettings = None # Warning ! Discovery configuration for a single topic could be in: entity settings; user configuration # DISCOVERY DATA FROM ENTITY SETTINGS # Look for custom discovery settings for this sensor, topic and preset: if entity_preset_data: for discoveryTopic in entity_preset_data: dtTopic = cf.GetOption(discoveryTopic, "topic") if (dtTopic == topic or dtTopic == "*") and cf.GetOption( discoveryTopic, self.consts.SETTINGS_DISCOVERY_PRESET_PAYLOAD_KEY): # Found dict for this topic in this sensor for this preset: Place in the payload topicSettings = discoveryTopic payload = cf.GetOption( discoveryTopic, self.consts. SETTINGS_DISCOVERY_PRESET_PAYLOAD_KEY).copy() # Check for Advanced information topic if I don't send advanced infomration: PS THIS IS USELESS CAUSE THIS TOPIC WON'T BE IN OUTTOPIC IN THAT CASE BUT IT'S BETTER TO CHECK # If I don't send advanced_information and the topic settings says the topic is advanced, I return None because this entity won't send any message on this topic if self.GetOption( self.consts.ADVANCED_INFO_OPTION_KEY, False) == False and cf.GetOption(topicSettings, [ self.consts.SETTINGS_DISCOVERY_KEY, self.consts.SETTINGS_DISCOVERY_ADVANCED_TOPIC_KEY ], False) == True: return None # DISCOVERY DATA FROM USER CONFIGURATION in entityConfig -> discovery -> settings # Take user_discovery_config not from options( thaht includes also monitors discovery config but oly from entity configs user_discovery_config = cf.ReturnAsList( cf.GetOption(self.entityConfigs, [ self.consts.ENTITY_DISCOVERY_KEY, self.consts.ENTITY_DISCOVERY_PAYLOAD_KEY ]), None) if user_discovery_config: for user_topic_config in user_discovery_config: dtTopic = cf.GetOption(user_topic_config, "topic") if not dtTopic or dtTopic == topic or dtTopic == "*": # Copy all the configuration I have in the payload for key, value in user_topic_config.items(): if key != "topic": # Avoid topic because is a non-payload information but only to recognise settings payload[key] = value # If I have to disable, return None if cf.GetOption(topicSettings, self.consts.SETTINGS_DISCOVERY_PRESET_DISABLE_KEY, False): return None # Do I have the name in the preset settings or do I set it using the default topic ? if not 'name' in payload: payload['name'] = topic.replace("/", "_") # Check and add this only if has option true if self.GetOption([ self.consts.CONFIG_DISCOVERY_KEY, self.consts.DISCOVERY_NAME_PREFIX_KEY ], self.consts.DISCOVERY_NAME_PREFIX_DEFAULT): payload['name'] = self.brokerConfigs['name'] + \ " - " + payload['name'] # Prepare the part of the config topic after the prefix and the sensortype topic_component = self.TopicRemoveBadCharacters( self.SelectTopic(topic)) payload['device'] = self.GetDiscoveryDeviceData() # Unique hashed payload['unique_id'] = hashlib.md5( (self.SelectTopic(topic)).encode('utf-8')).hexdigest() if (entity_model == self.consts.TYPE_TOPIC_OUT): # Do I have the type in the sensor preset settings or do I set it to 'sensor' ? entity_type = cf.GetOption( topicSettings, self.consts.SETTINGS_DISCOVERY_PRESET_TYPE_KEY, "sensor") # Send the topic where the Sensor will send his state payload['expire_after'] = self.GetOption([ self.consts.CONFIG_DISCOVERY_KEY, self.consts.DISCOVERY_EXPIRE_AFTER_KEY ], self.consts.DISCOVERY_EXPIRE_AFTER_DEFAULT) payload['state_topic'] = self.SelectTopic(topic) else: # Do I have the type in the sensor preset settings or do I set it to 'sensor' ? entity_type = cf.GetOption( topicSettings, self.consts.SETTINGS_DISCOVERY_PRESET_TYPE_KEY, "switch") # Send the topic where the Switch will receive the message payload['command_topic'] = self.SelectTopic(topic) # Compose the topic that will be used to send the disoovery configuration config_send_topic = self.consts.AUTODISCOVERY_TOPIC_CONFIG_FORMAT.format( prefix, entity_type, topic_component) return { "name": topic, "config_topic": config_send_topic, "payload": dict(payload) }
if not os.path.isdir(path): log("GENERATOR", "❌", "Missing directory : " + path) sys.exit(1) if not os.access(path, os.R_OK | os.X_OK): log("GENERATOR", "❌", "Missing RX rights on directory : " + path) sys.exit(1) for path in paths_rwx: if not os.access(path, os.W_OK): log("GENERATOR", "❌", "Missing W rights on directory : " + path) sys.exit(1) # Compute the config log("GENERATOR", "ℹ️", "Computing config ...") configurator = Configurator(args.settings, args.core, args.plugins, args.variables) config = configurator.get_config() # Remove old files log("GENERATOR", "ℹ️", "Removing old files ...") files = glob.glob(args.output + "/*") for file in files: if os.path.islink(file): os.unlink(file) elif os.path.isfile(file): os.remove(file) elif os.path.isdir(file): shutil.rmtree(file, ignore_errors=False) # Render the templates log("GENERATOR", "ℹ️", "Rendering templates ...")
def __init__(self, _stopEvent: Event): self.stopEvent = _stopEvent def run(self): while not self.stopEvent.is_set(): rancilio_temperature_status_handler() Rancilio.update() rancilio_heater_status_handler() rancilio_ready_handler() time.sleep(1) # stop event is set Rancilio.setHeaterOutput(0) configs = Configurator.instance() # Threading stuff stopEvent = Event() error_in_method_event = Event() dataLogger = DataLogger(stopEvent, error_in_method_event) dataLogger.addTemperatureSensor('boiler', configs.boilerTempSensor1) dataLogger.addTemperatureSensor('boiler', configs.boilerTempSensor2) configs.dataLogger = dataLogger temperatureAcquisitionProcess = Thread(target=dataLogger.acquireData) temperatureAcquisitionProcess.start() Rancilio = RancilioSilvia() configs.Rancilio = Rancilio rancilioError = RancilioError.instance()