예제 #1
0
    def __init__(self,
                 credential_path,
                 database_url="https://ledypie.firebaseio.com/",
                 debug=False,
                 tracker=None,
                 thread_name="FireBaseConnectorThread"):
        """
        :param credential_path: str, path to the firebase credential json file
        :param database_url: str, URL of the firebase
        :param debug: bool, set to true to allow debug output
        :param tracker: func, function to be called when the database has been updated with new values
        """

        # init thread class
        super().__init__(name=thread_name)

        # define local attributes
        self.tracker = tracker if tracker is not None else lambda: None
        self.stop = False
        self.rgba = None
        self.random_colors = False
        self.local_db = None

        if debug:
            fire_logger.setLevel(logging.DEBUG)

        # connect to firebase
        cred = credentials.Certificate(credential_path)

        try:
            firebase_admin.initialize_app(
                credential=cred,
                options={'databaseURL': database_url},
            )
        except ValueError:
            firebase_admin.initialize_app(
                credential=cred,
                options={'databaseURL': database_url},
                name=socket.gethostname())

        # update db and get references
        self.root = db.reference('/')

        self.init_db()
        self.db_refs = dict(pattern_attributes={
            pt: db.reference(f"/pattern_attributes/{pt}")
            for pt in Patterns.keys()
        },
                            cur_pattern=db.reference('/cur_pattern'),
                            rate=db.reference('/rate'),
                            RGBA=db.reference('/RGBA'))

        # add listener and sleep to wait for the first call where self.local_db is initialized
        self.listener = self.root.listen(self.listener_method)
        time.sleep(1)
        fire_logger.debug("FireBaseConnector initialized")