def main(): print("Starting energy monitor example") energenie.init() # Replace the names here with those in your own registry.kvs d_plug = energenie.registry.get("plug893") d_open = energenie.registry.get("open2664") d_motion = energenie.registry.get("motion4162") devices = (d_plug, d_open, d_motion) with IOT.Client(config="energenie_pi_staging.ini") as client: # create energenie "Thing" t_energenie = create_energenie_thing(client) # create a feed for each room and add its instance to the rooms dict f_monitor = create_monitor_feed(t_energenie) f_open = create_open_feed(t_energenie) f_motion = create_motion_feed(t_energenie) feeds = (f_monitor, f_open, f_motion) t_energenie.set_public(True) # provide a default incoming message handler, useful for logging every message def incoming(address, message): print("\nIncoming from %s" % str(address)) Logger.logMessage(message) energenie.fsk_router.when_incoming(incoming) print("Logging to file:%s" % Logger.LOG_FILENAME) try: while True: sensor_monitor_loop(feeds, devices) finally: energenie.finished()
def main(): # Get command args parser = argparse.ArgumentParser() parser.add_argument("cfg", nargs="?") args = parser.parse_args() cfg = args.cfg if cfg is not None and not exists(cfg): print("Config file not found: %s" % cfg) return 1 elif exists(join(getcwd(), "mqtt.ini")): cfg = join(getcwd(), "mqtt.ini") if cfg is None: print("Usage: mqtt.py config.ini (else ./mqtt.ini will be used)") return 1 # Load config from file host = DEFAULT_HOST port = DEFAULT_PORT config = IOT.Config.Config(fn=cfg) if config.get('mqtt', 'host') is not None: host = config.get('mqtt', 'host') if config.get('mqtt', 'port') is not None: try: port = int(config.get('mqtt', 'port')) except: logger.error("Unable to parse config [mqtt] port, using default.") # Connect agent and mqtt and loop forever try: client = IOT.Client(config=cfg) mqttclient = mqtt.Client() mqttclient.on_connect = on_connect mqttclient.on_message = partial(on_message, client) client.register_catchall_feeddata( partial(catchall_feeddata, mqttclient)) client.register_catchall_controlreq( partial(catchall_controlreq, mqttclient)) client.register_callback_subscription( partial(catchall_subscription, mqttclient)) with client: logger.info("Agent connected: %s", client.agent_id) try: mqttclient.connect(host, port) logger.info("MQTT connected. Press ctrl+c to quit.") mqttclient.loop_forever() except ConnectionRefusedError: logger.error("MQTT Connection Refused. Give up.") except KeyboardInterrupt: pass except: logger.exception("todo: unhandled mqtt exception?") except LinkException: print("Failed to connect") return 1 except KeyboardInterrupt: return 1 return 0
def main(): with IOT.Client(config='My First Agent.ini') as client: # ADD OWN CONFIG .ini HERE create_thing(client) while True: try: print("Main running, press ctrl+c to quit.") time.sleep(10) except KeyboardInterrupt: break
def main(): with IOT.Client('My First Agent.ini') as client: my_thing = create_thing(client) create_feed(my_thing) while True: try: print("Main running, press ctrl+c to quit.") time.sleep(10) except KeyboardInterrupt: break
def main(): with IOT.Client('Control_Offer.ini') as client: my_thing = create_thing(client) create_control(my_thing) while True: try: print("Main running, press ctrl+c to quit.") time.sleep(10) except KeyboardInterrupt: break
def main(): with IOT.Client( config='My First Agent.ini') as client: # ADD OWN CONFIG .ini HERE my_thing = connect_thing(client) show_metadata(my_thing) show_subscriptions(my_thing) while True: try: print("Main running, press ctrl+c to quit.") time.sleep(10) except KeyboardInterrupt: break
def main(): with IOT.Client('Control_Offer.ini') as client: my_thing = create_thing(client) my_control = create_control(my_thing) set_private(my_thing) add_thing_metadata(my_thing) add_thing_tags(my_thing) add_control_metadata(my_control) while True: try: print("Main running, press ctrl+c to quit.") time.sleep(10) except KeyboardInterrupt: break
def main(): with IOT.Client('My First Agent.ini') as client: my_thing = create_thing(client) my_feed = create_feed(my_thing) set_public(my_thing) add_thing_metadata(my_thing) add_thing_tags(my_thing) add_feed_metadata(my_feed) while True: try: print("Main running, press ctrl+c to quit.") time.sleep(10) except KeyboardInterrupt: break
def main(): # Get the main arguments ( Agent and Thing ) agent_file = sys.argv[1] thing_local_name = sys.argv[2] print("Connecting to your agent", sep=' ', end=' ... ') sys.stdout.flush() with IOT.Client(config=agent_file) as client: my_thing = setup_thing(client, thing_local_name) my_feed = setup_thing_feed(my_thing) my_feed_skeleton = my_feed.get_template() connect_subscriptions(client, my_thing, follow_feed_callback) # Create a new function which recieves a iotic-client manage_new_subsciptions = partial(incoming_subscription_callback, client=client) client.register_callback_subscription(manage_new_subsciptions) print("///////////////////////////////") print("// Welcome to the Iotic Chat //") print("///////////////////////////////") print("Write /quit to exit") user = input('Type your nickname: ') my_feed_skeleton.values.user = user while True: try: text = input() my_feed_skeleton.values.message = text print() if text != '/quit': share_data(my_feed, my_feed_skeleton) else: share_goodbye_data(my_feed, my_feed_skeleton) break except KeyboardInterrupt: share_goodbye_data(my_feed, my_feed_skeleton) break
def __init__(self, name, config, stop, datapath): """ """ self.__name = name self.__config = config self.__stop = stop self.__datapath = datapath # self.__module = None self.__agentfile = None self.__workers = 1 # self.__validate_config() # self.__agent = IOT.Client(config=self.__agentfile) fname = path.join(datapath, name + '.json') self.__stash = Stash(fname, self.__agent, self.__workers) self.__modinst = self.__module(self.__stash, self.__config, self.__stop) self.__thread = None
def main(): with IOT.Client() as client: data_point = iot_setup(client) last_time = 0 while True: try: print("Running, press ctrl+c to quit.") # new_data = egcsv_read(last_time) for row in new_data: if row['timestamp'] > last_time: last_time = row['timestamp'] # data_point.share_async(row) time.sleep(0.11) # todo: ensure never exceed 10 msg/s print("Shared: ", row) # time.sleep(EG_POLL) except KeyboardInterrupt: break
# INFO----------------------------------------------------------------------------------------------------------------- # 01_its_alive.py 12/02/2016 Iotic Labs. # This little wonder connects your script to Iotic Space. # Be aware - this script does not create a Thing. # Be aware - no callback or loop in this script (minimal code example). # PYTHON2 COMPATIBILITY ----------------------------------------------------------------------------------------------- from __future__ import unicode_literals, print_function # pylint: disable=unused-import # LOGGING ------------------------------------------------------------------------------------------------------------- # Logging set to only CRITICAL messages by default. To see more, use logging.INFO, or to see loads, logging.DEBUG import logging logging.basicConfig( format= '%(asctime)s,%(msecs)03d %(levelname)s [%(name)s] {%(threadName)s} %(message)s', level=logging.CRITICAL) # IOTIC AGENT IMPORTS ------------------------------------------------------------------------------------------------- from IoticAgent import IOT # --------------------------------------------------------------------------------------------------------------------- with IOT.Client(config="ram.ini") as client: # ADD OWN CONFIG .ini HERE # do something print("Connected? ...", client.is_connected())
def extmon(config, stop): stash = {FEEDS: {}, CHANGED: True, LASTCHANGE: 0} stashlock = Lock() templatedir = split(config.get(EXTMON2, 'template'))[0] templatefile = split(config.get(EXTMON2, 'template'))[1] wwwfile = join(config.get(EXTMON2, 'wwwpath'), 'index.html') feeds_list = config.get(EXTMON2, 'feeds') for feed in feeds_list: guid = config.get(feed, 'guid') stash[FEEDS][guid] = config.get(feed) stash[FEEDS][guid][SEEN] = False stash[FEEDS][guid][LAST_SEEN] = datetime.utcnow() max_age = stash[FEEDS][guid][MAX_AGE] = int( stash[FEEDS][guid][MAX_AGE]) if WARN_AGE not in stash[FEEDS][guid]: stash[FEEDS][guid][WARN_AGE] = max_age * 2 else: stash[FEEDS][guid][WARN_AGE] = int(stash[FEEDS][guid][WARN_AGE]) if ERROR_AGE not in stash[FEEDS][guid]: stash[FEEDS][guid][ERROR_AGE] = max_age * 3 else: stash[FEEDS][guid][ERROR_AGE] = int(stash[FEEDS][guid][ERROR_AGE]) client = IOT.Client(config=config.get(EXTMON2, 'agent')) client.register_catchall_feeddata( partial(__feeddata, client, stash, stashlock)) while not stop.is_set(): with client: try: thing = client.create_thing("extmon2") except: logger.error("Failed to create_thing(extmon2). Giving up.") stop.set() return with stashlock: for guid in stash[FEEDS]: try: thing.follow(guid) except: logger.error("Failed to follow('%s'). Giving up.", guid) stop.set() return if NAME not in stash[FEEDS][guid]: desc = client.describe(guid) if desc is None: stash[FEEDS][guid][ NAME] = 'No Public Meta GUID: ' + guid else: stash[FEEDS][guid][NAME] = desc['meta']['label'] while not stop.is_set(): with stashlock: if stash[CHANGED] or monotonic( ) - stash[LASTCHANGE] >= MINCHANGE: logger.debug("Stash changed, updating HTML") nowtime = datetime.utcnow() stash[LASTCHANGE] = monotonic() for guid in stash[FEEDS]: delta = nowtime - stash[FEEDS][guid][LAST_SEEN] delta_secs = delta.total_seconds() stash[FEEDS][guid][LASTSEEN] = naturaltime( delta_secs) if delta_secs < stash[FEEDS][guid][ MAX_AGE] and stash[FEEDS][guid][SEEN]: stash[FEEDS][guid][CLASS] = 'green' elif delta_secs < stash[FEEDS][guid][WARN_AGE]: stash[FEEDS][guid][CLASS] = 'yellow' else: stash[FEEDS][guid][CLASS] = 'red' if stash[FEEDS][guid][SEEN] is False: stash[FEEDS][guid][ LASTSEEN] = "Not seen since restart: " + stash[ FEEDS][guid][LASTSEEN] j2env = Environment( loader=FileSystemLoader(templatedir), trim_blocks=True) with open(wwwfile, 'w') as f: f.write( j2env.get_template(templatefile).render( feeds=stash[FEEDS])) stash[CHANGED] = False stop.wait(timeout=1) # If this function ends prematurely ensure stop is set! stop.set()
# INFO----------------------------------------------------------------------------------------------------------------- # 01_its_alive.py 12/02/2016 Iotic Labs. # This little wonder connects your script to Iotic Space. # Be aware - this script does not create a Thing. # Be aware - no callback or loop in this script (minimal code example). # PYTHON2 COMPATIBILITY ----------------------------------------------------------------------------------------------- from __future__ import unicode_literals, print_function # pylint: disable=unused-import # LOGGING ------------------------------------------------------------------------------------------------------------- # Logging set to only CRITICAL messages by default. To see more, use logging.INFO, or to see loads, logging.DEBUG import logging logging.basicConfig( format= '%(asctime)s,%(msecs)03d %(levelname)s [%(name)s] {%(threadName)s} %(message)s', level=logging.CRITICAL) # IOTIC AGENT IMPORTS ------------------------------------------------------------------------------------------------- from IoticAgent import IOT # --------------------------------------------------------------------------------------------------------------------- with IOT.Client( config="My First Agent.ini") as client: # ADD OWN CONFIG .ini HERE # do something print("Connected? ...", client.is_connected())
sdb.close() if __name__ == '__main__': # stop = Event() queue = Queue() thread = Thread(target=sqlite_thread, args=( stop, queue, )) thread.start() # client = None try: client = IOT.Client() client.register_catchall_feeddata(partial(data_cb, queue)) client.register_catchall_controlreq(partial(data_cb, queue)) client.start() except Exception as exc: print("Failed to start. Give up.") print(exc) exit(1) while True: try: print("Main loop is running. Press ctrl+c to quit.") sleep(60) except KeyboardInterrupt: break print("Stopping...") client.stop()