def main(self): """Called after on_startup. Use this method for your main loop (we don't need one here). Set self.LOOP_TIMER for your regular tick """ while True: start = monotonic() # loop code in here stop = monotonic() if self.wait_for_shutdown(max(0, self.LOOP_TIMER - (stop - start))): break
def __run_random_number(self): if monotonic() - self.__number_start >= RANDOM_NUMBER_SLEEP_SECS: feed = self.__thing.create_feed(RANDOM_NUMBER) feed.create_value("value", Datatypes.INTEGER, "en", "random number", data=random.randint(0, 10)) feed.share(time=datetime.utcnow()) self.__number_start = monotonic()
def __run_alphabet_upper(self): if monotonic() - self.__upper_start >= ALPHA_UPPER_SLEEP_SECS: feed = self.__thing.create_feed(ALPHA_UPPER) feed.create_value("value", Datatypes.STRING, "en", "value of letter", data=self.__upper_list[self.__upper_idx]) feed.share(time=datetime.utcnow()) self.__upper_idx += 1 if self.__upper_idx >= len(self.__upper_list): self.__upper_idx = 0 self.__upper_start = monotonic()
def __run_alphabet_random(self): if monotonic() - self.__alpha_start >= ALPHA_LOWER_SLEEP_SECS: feed = self.__thing.create_feed(RANDOM_ALPHA) feed.create_value("value", Datatypes.STRING, "en", "random letter", data=random.choice(self.__alpha_list)) feed.share(time=datetime.utcnow()) self.__alpha_idx += 1 if self.__alpha_idx >= len(self.__alpha_list): self.__alpha_idx = 0 self.__alpha_start = monotonic()
def __run_hourly_sine(self): if monotonic() - self.__sine_start >= HOURLY_SINE_SLEEP_SECS: radians = self.__sine_degrees * (math.pi / 180) feed = self.__thing.create_feed(HOURLY_SINE) feed.create_value("value", Datatypes.DECIMAL, "en", "value of sine function", data=math.sin(radians)) feed.share(time=datetime.utcnow()) self.__sine_degrees += 1 if self.__sine_degrees >= 360: self.__sine_degrees = 0 self.__sine_start = monotonic()
def run(self): lasttime = 0 while not self._stop.is_set(): nowtime = monotonic() if nowtime - lasttime > self.__refresh_time: lasttime = nowtime self.get_schools_from_API() self._stop.wait(timeout=5)
def main(self): """Called after on_startup. Use this method for your main loop (we need one here) Set self.LOOP_TIMER for your regular tick """ # use the template metadata for safe creation of control request templ_control = self.__remote_control.get_template() while True: start = monotonic() # loop code in here templ_control.values.temp = randint(50, 100) # ask doesn't care whether the control request worked or not. self.__remote_control.ask(templ_control) stop = monotonic() if self.wait_for_shutdown(max(0, self.LOOP_TIMER - (stop - start))): break
def main(self): """Called after on_startup. Use this method for your main loop (we need one here). Set self.LOOP_TIMER for your regular tick """ # feed template is the safe way to set up your share. It will reflect the value(s) created in on_startup templ_feed = self.__feed.get_template() while True: start = monotonic() # loop code in here templ_feed.values.count = randint(50, 100) self.__feed.share(templ_feed) stop = monotonic() if self.wait_for_shutdown(max(0, self.LOOP_TIMER - (stop - start))): break
def main(self): """Called after on_startup. Use this method for your main loop (we need one here). Set self.LOOP_TIMER for your regular tick """ # use the template metadata for safe creation of control request templ_control = self.__remote_control.get_template() while True: start = monotonic() # loop code in here templ_control.values.temp = randint(50, 100) # tell() requires the far end to confirm that they've done the action. # tell_result will be True for success or contain a string reason for failure, e.g. timeout tell_result = self.__remote_control.tell(templ_control) if tell_result is not True: logger.warning("Tell failed - reason: %s", tell_result) stop = monotonic() if self.wait_for_shutdown(max(0, self.LOOP_TIMER - (stop - start))): break
def get_recent(self, count): """ Get the last instance(s) of feeddata from the feed. Useful if the remote Thing doesn't publish very often. Returns: An iterable of dicts (in chronologically ascending order) containing :: 'data' # (decoded or raw bytes) 'mime' # (None, unless payload was not decoded and has a mime type) 'time' # (datetime representing UTC timestamp of share) Args: count (integer): How many recent instances to retrieve. High values might be floored to a maximum as defined by the container. Note: Feed data is iterable as soon as it arrives, rather than when the request completes. """ queue = Queue() evt = self.get_recent_async(count, queue.put) timeout_time = monotonic() + self._client.sync_timeout while True: try: yield queue.get(True, .1) except Empty: if evt.is_set() or monotonic() >= timeout_time: break # Forward any remaining samples which arrived e.g. during this thread being inactive try: while True: yield queue.get_nowait() except Empty: pass self._client._except_if_failed(evt)
def __run_saw_tooth(self): if monotonic() - self.__saw_start >= SAW_TOOTH_SLEEP_SECS: feed = self.__thing.create_feed(SAW_TOOTH) feed.create_value("value", Datatypes.DECIMAL, "en", "value of sawtooth", data=self.__saw_value) feed.share(time=datetime.utcnow()) if self.__saw_count_up: self.__saw_value += 1 else: self.__saw_value -= 1 if self.__saw_value > 10: self.__saw_value = 9 self.__saw_count_up = False elif self.__saw_value < 0: self.__saw_value = 1 self.__saw_count_up = True self.__saw_start = monotonic()
def main(self): """Called after on_startup. Use this method for your main loop (we need one here). Set self.LOOP_TIMER for your regular tick """ # feed template is the safe way to set up your share. It will reflect the value(s) created in on_startup templ_feed = self.__feed.get_template() count = 0 while True: start = monotonic() # loop code in here templ_feed.values.count = randint(50, 100) self.__feed.share(templ_feed) # deliberately raise an exception so we can see on_exception working count += 1 if count % 4 == 0: raise DemoException("Deliberate error") stop = monotonic() if self.wait_for_shutdown(max(0, self.LOOP_TIMER - (stop - start))): break
def run(self): # get the list of hvacs self.__hvac_list = self.__get_hvac_list_from_API() if len(self.__hvac_list) > 0: lasttime = 0 while not self._stop.is_set(): nowtime = monotonic() if nowtime - lasttime > self.__refresh_time: lasttime = nowtime # hit the api for the readings for each hvac in list for hvac in self.__hvac_list: self.__get_hvac_reading_from_API(hvac[KEY_ID]) self._stop.wait(timeout=5) else: logger.critical("no HVACs found - is the REST API running?")
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()