def get_measure_conditions(self): d = Database() c = Config() self.measure_conditions = [] self.meursing_code = False measure_sid_string = self.get_measure_sid_string() c.sql["measure_conditions"] = c.sql["measure_conditions"].replace( "<params>", measure_sid_string) rows = d.run_query(c.sql["measure_conditions"]) for row in rows: mc = MeasureCondition() mc.measure_sid = row[0] mc.condition_code = row[1] mc.condition_code_description = row[2] mc.certificate_type_code = row[3] mc.certificate_code = row[4] mc.document_code = row[5] mc.action_code = row[6] mc.action = row[7] mc.certificate_type_description = row[8] mc.component_sequence_number = row[9] mc.certificate_description = row[10] mc.get_requirement() self.measure_conditions.append(mc) if mc.condition_code == "V": self.meursing_code = True
def do_GET(self): code = dict(parse.parse_qsl(parse.urlsplit(self.path).query)).get( 'code', None) if code: response = requests.post( 'https://hh.ru/oauth/token', { 'grant_type': 'authorization_code', 'client_id': os.getenv('APP_ID'), 'client_secret': os.getenv('APP_SECRET'), 'code': code, 'redirect_uri': redirect_uri }) result = json.loads(response.text) if 'access_token' in result: c = Config() c.setAccessToken(AccessTokenEntity(result)) print(c.getAccessToken().getAccessToken()) exit() self.send_response(200) self.end_headers() return
def main(): """ Main function. It loads the settings and starts the telegram bot. """ print_splashscreen() # Find the config file path and creates a config manager. config_path = config_loader() manager = Config(config_path) if not DOWNLOADED_DEFAULT_CONFIG_FILE: # Load settings settings = manager.get_settings() print("[!] Settings loaded correctly:") print_settings(settings) # Start the bot using the settings start_bot(settings) else: print("") print("") print("!!!!!!!!!!!! PLEASE READ CAREFULLY !!!!!!!!!!!!") print("! You've just downloaded a new config file !") print("! Now you have to edit that config file to !") print("! use the bot correctly !") print("! ########################################### !") print("! If you have question write me a message !") print("! Telegram: @lucadibello !") print("! Instagram: @lucaa_dibello !") print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
class AuthApp: config = None def __init__(self): self.config = Config() def handle(self) -> Union[bool, str]: try: response = requests.post(self.config.getOauthTokenEndpoint(), { 'grant_type': 'client_credentials', 'client_id': self.config.getAppId(), 'client_secret': self.config.getAppSecret(), } ) except Exception as e: logger.error(e) return False responseDict = json.loads(response.text) if 'error' in responseDict: logger.error(responseDict.get('error')) return False if 'access_token' in responseDict: self.config.setAccessToken(AccessTokenEntity(responseDict)) return True
def test_get_translated_config(self): config = Config(self.config_file) self.assertEqual(5432, int(config.data['mapi']['port'])) print(config.get_translated_config()['mapi_port']) self.assertEqual(5432, int(config.get_translated_config()['mapi_port'])) self.assertEqual('template', config.get_translated_config()['tmpl_db'])
def test_step_3(self): vo_mock = Mock() vo_mock.side_effect = [ fill_step_mock(self.brain_name, np.full((10, 10, 1), 0.17)), fill_step_mock(self.brain_name, np.full((10, 10, 1), 0.23)), fill_step_mock(self.brain_name, np.full((10, 10, 1), 0.02)), fill_step_mock(self.brain_name, np.full((10, 10, 1), 0.11)), fill_step_mock(self.brain_name, np.full((10, 10, 1), 0.90)), fill_step_mock(self.brain_name, np.full((10, 10, 1), 0.14)), fill_step_mock(self.brain_name, np.full((10, 10, 1), 0.10)), fill_step_mock(self.brain_name, np.full((10, 10, 1), 0.19)) ] self.env_mock.step = vo_mock self.env_provider_mock.provide.return_value = self.env_mock cfg = Config('tests/config.json') cfg.set_config_value('OBS_SIZE', 10) cfg.set_config_value('FRAMES_SKIP', 0) cfg.set_config_value('FRAMES_LOOKBACK', 5) cfg.set_config_value('USE_DIFF', True) env = Environment(self.env_provider_mock, cfg) res = env.step(1) self.assertTrue( frames_helper( res["stacked_observation"], [0, 0, 0, 0, 0], True)) res = env.step(1) self.assertTrue( frames_helper( res["stacked_observation"], [0, 0, 0, 0, 0.06], True)) res = env.step(1) self.assertTrue( frames_helper( res["stacked_observation"], [0, 0, 0, 6, -21], True)) res = env.step(1) self.assertTrue( frames_helper( res["stacked_observation"], [0, 0, 6, -21, 9], True)) res = env.step(1) self.assertTrue( frames_helper( res["stacked_observation"], [0, 6, -21, 9, -2], True)) res = env.step(1) self.assertTrue( frames_helper( res["stacked_observation"], [6, -21, 9, -2, 5], True)) res = env.step(1) self.assertTrue( frames_helper( res["stacked_observation"], [-21, 9, -2, 5, -4], True)) res = env.step(1) self.assertTrue( frames_helper( res["stacked_observation"], [9, -2, 5, -4, 9], True))
def process_command(self, data): config = Config('darkscience_new') command = data[data.find('PRIVMSG '):].split(':') if command[1][1:1] == config.get_item('bot.command_char')[0]: print command[1], command[1:1] len = data.find(' ') if len != -1: for plugin in self._plugins: print plugin
def get_measures(self): c = Config() d = Database() self.measures = [] if self.is_meursing: params = [ self.meursing_additional_code_id, self.meursing_additional_code_id, self.meursing_geographical_area_id, '2021-01-01', '2021-01-01', self.meursing_geographical_area_id ] rows = d.run_query(c.sql["meursing_measures"], params) else: comm_code_string = self.get_comm_code_string() c.sql["measures"] = c.sql["measures"].replace("<params>", comm_code_string) c.sql["measures"] = c.sql["measures"].replace("<date>", self.date) rows = d.run_query(c.sql["measures"]) self.measure_sids = [] for row in rows: m = Measure() m.measure_sid = row[0] m.goods_nomenclature_item_id = row[1] m.geographical_area_id = row[2] m.measure_type_id = row[3] m.measure_type_description = row[4] m.trade_movement_code = row[5] m.measure_type_series_id = row[6] m.measure_generating_regulation_id = row[7] m.ordernumber = row[8] m.additional_code_type_id = row[9] m.additional_code_id = row[10] m.additional_code = row[11] m.geographical_area_sid = row[12] m.goods_nomenclature_sid = row[13] m.additional_code_sid = row[14] m.effective_start_date = row[15] m.effective_end_date = row[16] m.regulation_officialjournal_number = row[17] m.regulation_officialjournal_page = row[18] m.regulation_published_date = row[19] m.regulation_validity_start_date = row[20] m.regulation_validity_end_date = row[21] m.geographical_area_description = row[22] m.reduction_indicator = row[23] self.measure_sids.append(m.measure_sid) if m.effective_start_date is not None: m.effective_start_date += "T00:00:00.000Z" m.interpret() self.measures.append(m)
def test_step_1(self): self.env_mock.step.return_value = fill_step_mock( self.brain_name, np.random.rand(10, 10, 1)) self.env_provider_mock.provide.return_value = self.env_mock cfg = Config('tests/config.json') cfg.set_config_value('OBS_SIZE', 10) cfg.set_config_value('FRAMES_SKIP', 4) cfg.set_config_value('FRAMES_LOOKBACK', 5) cfg.set_config_value('USE_DIFF', False) env = Environment(self.env_provider_mock, cfg) res = env.step(1) self.assertEqual(res["stacked_observation"].shape, (1, 10, 10, 5))
def get_commodity_footnotes(self): d = Database() c = Config() self.commodity_footnotes = [] comm_code_string = self.get_comm_code_string() c.sql["commodity_footnotes"] = c.sql["commodity_footnotes"].replace( "<params>", comm_code_string) rows = d.run_query(c.sql["commodity_footnotes"]) for row in rows: f = Footnote(row[0], row[1], row[2]) self.commodity_footnotes.append(f.as_dict())
def get_measure_exclusions(self): d = Database() c = Config() self.measure_exclusions = [] measure_sid_string = self.get_measure_sid_string() c.sql["exclusions"] = c.sql["exclusions"].replace( "<params>", measure_sid_string) rows = d.run_query(c.sql["exclusions"]) for row in rows: ga = GeographicalArea(row[0], row[1]) ga.measure_sid = row[2] self.measure_exclusions.append(ga)
def get_measure_footnotes(self): d = Database() c = Config() self.measure_footnotes = [] measure_sid_string = self.get_measure_sid_string() c.sql["measure_footnotes"] = c.sql["measure_footnotes"].replace( "<params>", measure_sid_string) rows = d.run_query(c.sql["measure_footnotes"]) for row in rows: f = Footnote(row[0], row[1], row[2], row[3]) self.measure_footnotes.append(f)
def get_eu_url(self): c = Config() if self.officialjournal_number is not None: year = self.published_date.year self.officialjournal_page = c.mstr(self.officialjournal_page) page = f'{self.officialjournal_page:0>4}' template = "http://eur-lex.europa.eu/search.html?whOJ=NO_OJ%3D<journal>,YEAR_OJ%3D<year>,PAGE_FIRST%3D<page>&DB_COLL_OJ=oj-l&type=advanced&lang=en" s = template.replace("<page>", page) s = s.replace("<year>", str(year)) s = s.replace("<journal>", ''.join( filter(str.isdigit, self.officialjournal_number))) self.regulation_url = s else: self.regulation_url = None
class TestConfig(unittest.TestCase): def setUp(self): self.cfg = Config('tests/config.json') def test_get_config_value(self): actual = self.cfg.get('GAMMA') expected = 0.90 self.assertEqual(actual, expected) def test_set_config_value(self): self.cfg.set_config_value('GAMMA', 0.999) expected = 0.999 actual = self.cfg.get('GAMMA') self.assertEqual(actual, expected)
def __init__(self, Log): self.logger = Log # Instance maps self.telemetry_server_instance = None self.telemetry_server_instance_stop = None self.telemetry_server_instance_init = None # Namespaces self.id_namespace_twins = None self.id_namespace_gateways = None self.id_namespace_devices = None # Load configuration config = Config(self.logger) self.config = config.data # Logging Mappers data = [x for x in self.config["ClassLoggingMaps"] if x["Name"] == "TelemetryServer"] self.class_name_map = data[0]["LoggingId"] # Telemetry Mapping self.map_telemetry = [] self.map_telemetry_interfaces = [] self.map_telemetry_interfaces_variables = [] # meta self.telemetry_interface = {} self.telemetry_payload = {}
def __init__(self, config: Config, key: str = 'sshtunnels'): self.__autostart = False self.__base_config = config.get_config() #self.__config = self.__base_config[key] self.set_config(self.__base_config[key]) self.__tunnels = dict() self.set_tunnels()
def __init__(self): config = Config(); mqttClient = MqttClient(config); onewireClient = OnewireClient(config, mqttClient); mqttClient.subscribe(onewireClient.writeDevice); onewireClient.start();
def load_config(self): # Load all the configuration config = Config(self.logger) self.config = config.data self.nodes = self.config["Nodes"] return
def _get_resolucao(self): resolucao = Config.get('resolucao') if len(resolucao) == '': self._largura_tela = 800 self._altura_tela = 600 posicao_x = resolucao.find('x') self._largura_tela = resolucao[0:posicao_x] self._altura_tela = resolucao[posicao_x + 1:len(resolucao)]
def get_geo_memberships(self): d = Database() c = Config() geo_memberships = [] params = [ self.date, self.date ] rows = d.run_query(c.sql["geo_memberships"], params) row_count = len(rows) if row_count < 1: return for row in rows: gam = GeoMembership(row[0], row[1], row[2]) geo_memberships.append(gam) c.set_geo_memberships(geo_memberships)
def __init__(self): config = Config(); mqttClient = MqttClient(config); zwayClient = ZwayClient(config, mqttClient); mqttClient.subscribe(zwayClient.writeDevice); zwayClient.start();
def get_children_geographical_areas(self): c = Config() self.geographical_area.children_geographical_areas = [] for item in c.geo_memberships: if item.geographical_area_group_sid == self.geographical_area_sid: self.geographical_area.children_geographical_areas.append( item.as_dict()) pass
async def main(argv): # execution state from args provisioning_scope = None gateway_type = None short_options = "hvp:g:" long_options = ["help", "verbose", "provisioningscope=", "gatewaytype="] full_cmd_arguments = sys.argv argument_list = full_cmd_arguments[1:] try: arguments, values = getopt.getopt(argument_list, short_options, long_options) except getopt.error as err: print (str(err)) for current_argument, current_value in arguments: if current_argument in ("-h", "--help"): print("HELP for provisiondevices.py") print("------------------------------------------------------------------------------------------------------------------") print("-h or --help - Print out this Help Information") print("-v or --verbose - Debug Mode with lots of Data will be Output to Assist with Debugging") print("-p or --provisioningscope - Provisioning Scope give you fine grained control over the devices you want to provision.") print(" ALL - Re-Provision Every device listed in the DevicesCache.json file") print(" NEW - Only Provision Devices DevicesCache.json file that have 'LastProvisioned=Null'") print(" device name - Provision a Specifc Device in DevicesCache.json file") print("-g or --gatewaytype - Indicate the Type of Gateway Relationship") print(" OPAQUE - Devices will look like Stand-Alone Devices in IoT Central") print(" TRANSPARENT - Devices will look like Stand-Alone Devices in IoT Central") print(" PROTOCOL - IoT Central will show a Single Gateway and all Data is Associated with the Gateway") print(" PROTOCOLWITHIDENTITY - IoT Central will show a Single Gateway and Leaf Devices") print("------------------------------------------------------------------------------------------------------------------") sys.exit() if current_argument in ("-v", "--verbose"): Log.basicConfig(format="%(levelname)s: %(message)s", level=Log.DEBUG) Log.info("Verbose mode...") else: Log.basicConfig(format="%(levelname)s: %(message)s") if current_argument in ("-p", "--provisioningscope"): Log.info("Provisioning Scope Override...%s" % current_value) provisioning_scope = current_value if current_argument in ("-g", "--gatewaytype"): Log.info("Gateway Type Override...%s" % current_value) gateway_type = current_value # Load Configuration File config = Config(Log) config_data = config.data if provisioning_scope == None: provisioning_scope = config_data["ProvisioningScope"] if gateway_type == None: gateway_type = config_data["GatewayType"] await provision_devices(ProvisioningScope=provisioning_scope, GatewayType=gateway_type)
def __init__(self, **kwargs): super().__init__(description=kwargs.pop("description"), command_prefix=self.__get_prefix, activity=kwargs.pop("activity")) self.config = Config.fromJSON("config.json") self.motorClient = motor_asyncio.AsyncIOMotorClient( self.config.mongo['URI'], serverSelectionTimeoutMS=self.config.mongo['timeout']) self.mongoIO = mongoIO(self)
async def main(argv): # execution state from args is_resethci = False scan_seconds = 0 bluetooth_interface = -1 short_options = "hvrb:s:" long_options = ["help", "verbose", "resethci", "btiface=", "scanseconds="] full_cmd_arguments = sys.argv argument_list = full_cmd_arguments[1:] try: arguments, values = getopt.getopt(argument_list, short_options, long_options) except getopt.error as err: print (str(err)) for current_argument, current_value in arguments: if current_argument in ("-h", "--help"): print("HELP for scandevices.py") print("------------------------------------------------------------------------------------------------------------------") print("-h or --help - Print out this Help Information") print("-v or --verbose - Debug Mode with lots of Data will be Output to Assist with Debugging") print("-b or --btiface - Bluetooth Interface? '0' = Built in or '1' if you added a BT Device and Antenna, etc. (default=0)") print("-r or --resethci - OS command to Reset the Bluetooth Interface (default=false)") print("-s or --scanseconds - Number of Seconds the BLE Scan should Scan for Devices (default=10)") print("------------------------------------------------------------------------------------------------------------------") sys.exit() if current_argument in ("-v", "--verbose"): Log.basicConfig(format="%(levelname)s: %(message)s", level=Log.DEBUG) Log.info("Verbose mode...") else: Log.basicConfig(format="%(levelname)s: %(message)s") if current_argument in ("-r", "--resethci"): Log.info("Bluetooth Reset Interface mode...") is_resethci = True if current_argument in ("-b", "--btiface"): Log.info("Bluetooth Interface Override...%s" % current_value) btiface = current_value if current_argument in ("-s", "--scanseconds"): Log.info("Scan Seconds Override...%s" % current_value) scan_seconds = current_value # Load Configuration File config = Config(Log) config_data = config.data if scan_seconds == 0: scan_seconds = config_data["ScanSeconds"] if bluetooth_interface == -1: bluetooth_interface = config_data["BluetoothInterface"] await scan_for_devices(BluetoothInterface=bluetooth_interface, ResetHCI=is_resethci, ScanSeconds=scan_seconds)
def get_descendants(self): # Get descendants of the selected commodity code or heading d = Database() c = Config() self.descendants = [] params = [ self.date, self.date, self.date, self.heading_id, self.goods_nomenclature_item_id + self.productline_suffix ] rows = d.run_query(c.sql["descendants"], params) row_count = len(rows) if row_count < 1: return False # Data in the first row is the current commodity self.goods_nomenclature_sid = rows[0][0] self.description = rows[0][3] self.get_formatted_descriptions() self.number_indents = rows[0][4] self.commcode_plus_suffix = rows[0][5] start_indent = self.number_indents for row in rows: goods_nomenclature_sid = row[0] goods_nomenclature_item_id = row[1] productline_suffix = row[2] description = row[3] number_indents = row[4] commcode_plus_suffix = row[5] if (number_indents > start_indent): gn = GoodsNomenclature(goods_nomenclature_item_id) gn.goods_nomenclature_sid = goods_nomenclature_sid gn.productline_suffix = productline_suffix gn.description = description gn.number_indents = number_indents gn.commcode_plus_suffix = commcode_plus_suffix gn.context = "descendant" gn.get_formatted_descriptions() if commcode_plus_suffix != self.commcode_plus_suffix: self.descendants.append(gn.as_dict()) if commcode_plus_suffix > self.commcode_plus_suffix: if number_indents <= start_indent: break self.leaf = True if len(self.descendants) == 0 else False self.declarable = True if ( len(self.descendants) == 0 and self.productline_suffix == '80') else False self.get_descendant_parentage(self.goods_nomenclature_sid) return True
def assign_measures_to_import_export(self): c = Config() self.import_measures = [] self.export_measures = [] for m in self.measures: if m.measure_type_id not in c.excluded_measure_types: if m.is_import: self.import_measures.append(m.as_dict()) if m.is_export: self.export_measures.append(m.as_dict())
def __init__(self): print "starting smarthome..." self.setPid() self.threads = [] self.dispatcher = Dispatcher() self.config = Config(self.dispatcher) self.values = Values() self.hue = Hue(self.config.getHueIP(), self.dispatcher) self.hue.start() self.threads.append(self.hue) self.switch = Switch(self.dispatcher, self.config.getSwitchConfig()) self.pilight = PilightClient(self.dispatcher) self.pilight.registerCallback(self.switch.callback, 'protocol', ['arctech_screen']) self.pilight.registerCallback(self.climateCallback, 'protocol', ['alecto_ws1700']) self.pilight.start() self.threads.append(self.pilight) if self.config.hasLCD(): self.lcd = Lcd(self.values) self.lcd.start() self.threads.append(self.lcd) self.fhem = Fhem(self.config.getFhemIp(), self.config.getFhemPort(), self.dispatcher) self.fhem.registerCallback(self.fhemCallback) self.config.initDevices(self.fhem, self.values) self.fhem.start() self.threads.append(self.fhem) self.api = Api(self.values, self.dispatcher) self.events = Events(self.values, self.dispatcher) self.config.initEvents(self.events) self.events.start() self.threads.append(self.events) self.logger = Logger(self.values) self.logger.start() self.threads.append(self.logger) self.highcharts = Highcharts(self.logger, self.dispatcher) self.webserver = Webserver(self.values, self.dispatcher, self.config.getWebserverPort()) self.webserver.start() self.dispatcher.start() self.threads.append(self.dispatcher) self.serve() self.clearPid()
def get_ancestors(self): # Get core data like the description d = Database() c = Config() self.ancestors = [] self.codes = [] params = [ self.date, self.date, self.date, self.chapter_id, self.goods_nomenclature_item_id ] rows = d.run_query(c.sql["ancestors"], params) row_count = len(rows) if row_count < 1: return # Data in the first row is the current commodity self.description = rows[0][3] self.number_indents = rows[0][4] self.commcode_plus_suffix = rows[0][5] current_indent = 99 for row in rows: goods_nomenclature_sid = row[0] goods_nomenclature_item_id = row[1] productline_suffix = row[2] description = row[3] number_indents = row[4] commcode_plus_suffix = row[5] if (number_indents < current_indent) or (goods_nomenclature_item_id[-8:] == "00000000"): gn = GoodsNomenclature(goods_nomenclature_item_id) gn.goods_nomenclature_sid = goods_nomenclature_sid gn.productline_suffix = productline_suffix gn.description = description gn.number_indents = number_indents gn.commcode_plus_suffix = commcode_plus_suffix gn.get_formatted_descriptions() gn.context = "ancestor" if commcode_plus_suffix != self.commcode_plus_suffix: self.ancestors.append(gn) if productline_suffix == '80': self.codes.append(goods_nomenclature_item_id) if number_indents < current_indent: current_indent = number_indents return row_count
def get_section(self): d = Database() c = Config() # Get core data like the description params = [ self.chapter.goods_nomenclature_sid ] rows = d.run_query(c.sql["section"], params) row = rows[0] section_position = row[0] section_title = row[1] s = Section(section_position, section_title) self.section = s.as_dict()
async def main(argv): # execution state from args is_provisiondevices = False is_scandevices = False is_resethci = False short_options = "hvpsr" long_options = [ "help", "verbose", "provisiondevices", "scandevices", "resethci" ] full_cmd_arguments = sys.argv argument_list = full_cmd_arguments[1:] try: arguments, values = getopt.getopt(argument_list, short_options, long_options) except getopt.error as err: print(str(err)) #sys.exit(2) for current_argument, current_value in arguments: if current_argument in ("-v", "--verbose"): Log.basicConfig(format="%(levelname)s: %(message)s", level=Log.DEBUG) Log.info("Verbose mode...") else: Log.basicConfig(format="%(levelname)s: %(message)s") if current_argument in ("-p", "--provisiondevices"): Log.info("Provision Devices mode...") is_provisiondevices = True if current_argument in ("-s", "--scandevices"): Log.info("Scan Devices mode...") is_scandevices = True if current_argument in ("-r", "--resethci"): Log.info("Bluetooth Reset Interface mode...") is_resethci = True # Load Configuration File config = Config(Log) config_data = config.data if (is_scandevices): await scan_devices(is_resethci, config_data["BluetoothInterface"], config_data["ScanSeconds"]) elif (is_provisiondevices): await provision_devices(is_resethci, config_data["BluetoothInterface"], config_data["ScanSeconds"])
class App: pidfile = "/tmp/smarthome.pid" def __init__(self): print "starting smarthome..." self.setPid() self.threads = [] self.dispatcher = Dispatcher() self.config = Config(self.dispatcher) self.values = Values() self.hue = Hue(self.config.getHueIP(), self.dispatcher) self.hue.start() self.threads.append(self.hue) self.switch = Switch(self.dispatcher, self.config.getSwitchConfig()) self.pilight = PilightClient(self.dispatcher) self.pilight.registerCallback(self.switch.callback, 'protocol', ['arctech_screen']) self.pilight.registerCallback(self.climateCallback, 'protocol', ['alecto_ws1700']) self.pilight.start() self.threads.append(self.pilight) if self.config.hasLCD(): self.lcd = Lcd(self.values) self.lcd.start() self.threads.append(self.lcd) self.fhem = Fhem(self.config.getFhemIp(), self.config.getFhemPort(), self.dispatcher) self.fhem.registerCallback(self.fhemCallback) self.config.initDevices(self.fhem, self.values) self.fhem.start() self.threads.append(self.fhem) self.api = Api(self.values, self.dispatcher) self.events = Events(self.values, self.dispatcher) self.config.initEvents(self.events) self.events.start() self.threads.append(self.events) self.logger = Logger(self.values) self.logger.start() self.threads.append(self.logger) self.highcharts = Highcharts(self.logger, self.dispatcher) self.webserver = Webserver(self.values, self.dispatcher, self.config.getWebserverPort()) self.webserver.start() self.dispatcher.start() self.threads.append(self.dispatcher) self.serve() self.clearPid() def setPid(self): pid = str(os.getpid()) if os.path.isfile(self.pidfile): try: os.kill(int(file(self.pidfile,'r').readlines()[0]), 9) except: pass else: time.sleep(2) file(self.pidfile, 'w').write(pid) def clearPid(self): os.unlink(self.pidfile) def serve(self): print "started!\n" while True: try: run = False for thread in self.threads: self.sendChanges() thread.join(1) if thread.isAlive(): run = True if not run: self.webserver.stop() for thread in self.threads: if thread.isAlive(): thread.stop() return except KeyboardInterrupt: for thread in self.threads: thread.stop() def sendChanges(self): if self.values.changed: data = { 'params': ['path', 'values'], 'path': 'outputToJs', 'values': { 'type': 'values', 'data': self.values.getValues() } } self.values.changed = False self.dispatcher.send(data) def fhemCallback(self, data): uid = data.get('id') for attr in data.get('values').get('attr'): value = data.get(attr) if value: if attr == 'state' and data.get('values').get('type') == 'climate': if value.find('set_desired-temp') != -1: desired = value.replace('set_desired-temp','').strip() self.values.addValue(uid, 'desired-temp', desired) self.values.addValue(uid, 'info', 'Set to %s°C (Current: %s°C)' %(desired, data.get('desired-temp'))) else: self.values.addValue(uid, 'info', '') else: self.values.addValue(uid, attr, value) self.values.addValue(uid, 'device', uid) def climateCallback(self, data): code = data.get('message') if not code: return temperature = code.get('temperature') humidity = code.get('humidity') if temperature: self.values.addValue(code.get('id'), 'temperature', temperature) if humidity: self.values.addValue(code.get('id'), 'humidity', humidity)
from flask import Flask, abort from flask.ext import restful from classes.config import Config from classes.exceptions import ApiException from classes.scrape import Scrape from classes.report import Report cfg = Config() cfg.load() app = Flask(__name__) api = restful.Api(app) class HelloWorld(restful.Resource): def get(self): return {'hello': 'world'} api.add_resource(HelloWorld, '/') api.add_resource(Scrape, '/scrape/<string:keyword>', '/scrape/<string:keyword>/<string:source>') api.add_resource(Report, '/report', '/report/<string:keyword>') if __name__ == '__main__': app.run(debug=True)