class RedisClient:

    conn = ""
    CHANNEL = "key-update"
    pubsub = ""

    def __init__(self, db_path):
        os.makedirs(os.path.dirname(db_path), exist_ok=True)

        try:
            if not self.conn:
                self.conn = Redis(db_path)
        except:
            raise Exception("Unable to create connection with Redis server")

    def get_key(self, key):
        return self.conn.get(key)

    def set_key(self, key, value, publish_update=False):
        if publish_update:
            self.publish_update(message=json.dumps({key: value}))

        return self.conn.set(key, value)

    def remove_key(self, key):
        return self.conn.delete(key)

    def publish_update(self, channel=CHANNEL, message=""):
        self.conn.pubsub()
        self.conn.publish(channel, message)

    def get_update(self, channel=CHANNEL):
        if not self.pubsub:
            self.pubsub = self.conn.pubsub()
            self.pubsub.subscribe(channel)

        return self.pubsub.get_message(channel)
Exemplo n.º 2
0
}
channels = list(handlers.keys())


# Main Listener Event Handler
def main_event_handler(self, event):
    print("Logic main event handler called")
    handlers[event['channel']](self.redis, event['data'])


if __name__ == '__main__':
    print("Channel logic started")
    redis_object = Redis(REDIS_DB_FILE)
    listener = RedisListener('Logic Listener', redis_object, channels,
                             main_event_handler)
    listener.start()
    time.sleep(10)
    print('Pushing to ui channel')
    redis_object.publish(UI_CHANNEL, 'Test message!')
    time.sleep(5)
    print('Pushing to TTS channel')
    redis_object.publish(TTS_CHANNEL, 'Test speech message')
    time.sleep(10)
    print('Pushing to ui channel again')
    redis_object.publish(UI_CHANNEL, 'Another test message!')

    # emotions & speech to text need pubsub objects
    # ui & text to speech & leds need to subscribe & publish
    # each subscription gets their own thread to be async
    # publish when we want to change the state