Advertisement
Guest User

clipspy example

a guest
Nov 14th, 2017
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. import time
  2. from queue import Queue, Empty
  3.  
  4. from clips import Environment, LoggingRouter
  5.  
  6.  
  7. class FactsQueue:
  8.     """Facts are coming from this queue."""
  9.     def __init__(self):
  10.         self.queue = Queue()  # this simulates your input
  11.  
  12.     def get_next_fact(self, timeout):
  13.         """This function receives a fact already as CLIPS string.
  14.  
  15.        It blocks for maximum timeout seconds and returns None
  16.        if no new fact is in the queue.
  17.  
  18.        """
  19.         try:
  20.             self.queue.get(timeout=timeout)
  21.         except Empty:
  22.             return None
  23.  
  24.  
  25. def run(facts_queue, clips_file):
  26.     tick_fact = None
  27.     env = Environment()
  28.  
  29.     # The logging router will deal with CLIPS output messages itself
  30.     router = LoggingRouter()
  31.     router.add_to_environment(env)
  32.  
  33.     env.batch_star(clips_file)
  34.  
  35.     # Consume the next fact, wait max 3 seconds if not facts are available
  36.     for fact in facts_queue.get_next_fact(3.0):
  37.         # deal with time
  38.         if tick_fact is not None:
  39.             tick_fact.retract()
  40.         tick_fact = env.assert_string("(current-time {})".format(time.time()))
  41.  
  42.         # deal with command messages
  43.         if fact == 'ENABLE_FIRING_TRACING':
  44.             enable_firings_tracing(env)
  45.         elif fact == 'DISABLE_FIRING_TRACING':
  46.             disable_firings_tracing(env)
  47.         elif fact == 'STOP_ENGINE':  
  48.             break
  49.         # assert the fact as a string in CLIPS
  50.         elif fact is not None:
  51.             env.assert_string(fact)
  52.  
  53.         # finally, fire the activations in the CLIPS agenda
  54.         env.run()
  55.  
  56.     # print the currently asserted facts if the engine was stopped
  57.     for fact in env.facts():
  58.         print(fact)
  59.  
  60.  
  61. def enable_firings_tracing(env):
  62.     for rule in env.rules():
  63.         rule.watch_firings = True
  64.  
  65.  
  66. def disable_firings_tracing(env):
  67.     for rule in env.rules():
  68.         rule.watch_firings = False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement