def runit(self, payload, file_pointer, check_results=True): test_data = json.load(file_pointer, object_hook=utils.byteify) config_dict = configobj.ConfigObj(test_data['config']) testruns = test_data['testruns'] cdict = config_dict['MQTTSubscribeService'] if not 'message_callback' in config_dict['MQTTSubscribeService']: config_dict['MQTTSubscribeService']['message_callback'] = {} config_dict['MQTTSubscribeService']['message_callback'][ 'type'] = payload unit_system_name = cdict['topics'].get('unit_system', 'US').strip().upper() if unit_system_name not in weewx.units.unit_constants: raise ValueError("MQTTSubscribe: Unknown unit system: %s" % unit_system_name) unit_system = weewx.units.unit_constants[unit_system_name] min_config_dict = { 'Station': { 'altitude': [0, 'foot'], 'latitude': 0, 'station_type': 'Simulator', 'longitude': 0 }, 'Simulator': { 'driver': 'weewx.drivers.simulator', }, 'Engine': { 'Services': {} } } engine = StdEngine(min_config_dict) service = MQTTSubscribeService(engine, config_dict) host = 'localhost' port = 1883 keepalive = 60 userdata = { 'topics': [], 'connected_flag': False, } client = mqtt.Client(userdata=userdata) client.on_connect = utils.on_connect client.connect(host, port, keepalive) client.loop_start() max_connect_wait = 1 # ToDo - configure i = 1 while not userdata['connected_flag']: if i > max_connect_wait: self.fail("Timed out waiting for connections.") time.sleep(1) i += 1 userdata2 = { 'topics': cdict['topics'].sections, 'connected_flag': False, 'msg': False, 'max_msg_wait': 1 #ToDo - configure } client2 = mqtt.Client(userdata=userdata2) client2.on_connect = utils.on_connect client2.on_message = utils.on_message client2.connect(host, port, keepalive) client2.loop_start() max_connect2_wait = 1 # ToDo - configure i = 1 while not userdata2['connected_flag']: if i > max_connect2_wait: self.fail("Timed out waiting for connection 2.") time.sleep(1) i += 1 max_waits = 10 for testrun in testruns: for topics in testrun['messages']: for topic in topics: topic_info = topics[topic] msg_count = utils.send_msg(utils.send_mqtt_msg, payload, client.publish, topic, topic_info, userdata2, self) utils.wait_on_queue(service, msg_count, max_waits, 1) record = {} interval = 300 current_time = int(time.time() + 0.5) end_period_ts = (int(current_time / interval) + 1) * interval record['dateTime'] = end_period_ts record['usUnits'] = unit_system new_loop_packet_event = weewx.Event(weewx.NEW_LOOP_PACKET, packet=record) service.new_loop_packet(new_loop_packet_event) records = [record] if check_results: results = testrun['results'] result = {} found = False for result in results: if 'service' in result['test']: if payload in result['payloads']: found = True break self.assertTrue(found, "No results for %s" % payload) utils.check(self, payload, records, result['records']) else: for record in records: print(record) service.shutDown() client.disconnect() client2.disconnect()
config_file = 'weewx.conf' # pylint: disable=invalid-name config_path = os.path.abspath(config_file) # pylint: disable=invalid-name config = configobj.ConfigObj(config_path, file_error=True) # pylint: disable=invalid-name service = FieldCache(std_engine, config) # pylint: disable=invalid-name data = { # pylint: disable=invalid-name 'usUnits': 1, 'dateTime': time.time(), 'field1': 'value1-a', 'field2': 'value2-a', 'field3': 'value3-a', 'field4': 'value4-a' } print(weeutil.weeutil.to_sorted_string(data)) new_archive_record_event = weewx.Event(weewx.NEW_ARCHIVE_RECORD, # pylint: disable=invalid-name record=data, origin='hardware') service.new_archive_record(new_archive_record_event) print(weeutil.weeutil.to_sorted_string(data)) del data['field1'] del data['field2'] del data['field3'] data['field4'] = 'value4-b' print(weeutil.weeutil.to_sorted_string(data)) service.new_archive_record(new_archive_record_event) print(weeutil.weeutil.to_sorted_string(data))
if len(args) < 1: sys.stderr.write("Missing argument(s).\n") sys.stderr.write(parser.parse_args(["--help"])) exit() config_path = args[0] weewx.debug = 1 try : config_dict = configobj.ConfigObj(config_path, file_error=True) except IOError: print ("Unable to open configuration file ", config_path) exit() if 'S3upload' not in config_dict: print >>sys.stderr, "No [S3upload] section in the configuration file %s" % config_path exit(1) engine = None S3upload = uploadFiles(engine, config_dict) rec = {'extraTemp1': 1.0, 'outTemp' : 38.2, 'dateTime' : int(time.time())} event = weewx.Event(weewx.NEW_ARCHIVE_RECORD, record=rec) S3upload.newArchiveRecord(event)
def test_service(hostname, port): from weewx.engine import StdEngine, DummyEngine from tempfile import NamedTemporaryFile INTERVAL = 60 NUM_INTERATIONS = 3 with NamedTemporaryFile() as temp_file: config = configobj.ConfigObj({ 'Station': { 'station_type': 'Simulator', 'altitude': [0, 'foot'], 'latitude': 0, 'longitude': 0}, 'Simulator': { 'driver': 'weewx.drivers.simulator', 'mode': 'simulator'}, 'PurpleAirMonitor': { 'binding': 'purpleair_binding', 'hostname': hostname, 'port': port, 'interval': INTERVAL}, 'DataBindings': { 'purpleair_binding': { 'database': 'purpleair_sqlite', 'manager': 'weewx.manager.DaySummaryManager', 'table_name': 'archive', 'schema': 'user.purpleair.schema'}}, 'Databases': { 'purpleair_sqlite': { 'root': '%(WEEWX_ROOT)s', 'database_name': temp_file.name, 'driver': 'weedb.sqlite'}}, 'Engine': { 'Services': { 'archive_services': 'user.purpleair.PurpleAirMonitor' } }}) weeutil.logger.setup("weewx_purpleair", { 'Logging': { 'root' : { 'handlers': ['console' ] } } }) print("NOTICE: please be patient this will take ~%d seconds to run" % (INTERVAL * (NUM_INTERATIONS - 0.5))) engine = DummyEngine(config) manager = engine.db_binder.get_manager(data_binding='purpleair_binding') last_time = time.time() try: # wait a moment for the 1st download time.sleep(INTERVAL / 2) for x in range(NUM_INTERATIONS): record = { 'dateTime': int(time.time()), } event = weewx.Event(weewx.NEW_ARCHIVE_RECORD, record=record) engine.dispatchEvent(event) # get and print all the current records now_time = time.time() for record in manager.genBatchRecords(last_time - 1, now_time + 1): print(record) # update the time window last_time = now_time # wait for the INTERVAL if this isn't the last cycle if x < NUM_INTERATIONS - 1: time.sleep(INTERVAL) except KeyboardInterrupt: pass finally: try: svc.shutDown() except: pass engine.shutDown()