How to detect changes in firebase child with pytho

2020-02-10 10:51发布

I have some troubles with this application. What I need is that If I detect a change in the database (FIREBASE) particularly in 'sala' and 'ventilacion' nodes the function do what it have to do. If there isn't any change in the database it would not do nothing. I am using python and pyrebase library. Here is the code. Thank you very much for you help.

            import pyrebase
            import serial
            import time
            config = {
                        #firebase configurations
                 }


            firebase = pyrebase.initialize_app(config)


            db = firebase.database()
            def ReconfiguracionFabrica():
                    ser.write('AT')
                    time.sleep(0.2)
                    ser.write('AT+RENEW')
                    time.sleep(0.3)

            def ConfiguracionMaster():
                    time.sleep(0.5)
                    ser.write('AT+IMME1')
                    time.sleep(0.350)
                    ser.write('AT+ROLE1')
                    time.sleep(0.2)     

            ser=serial.Serial(port="/dev/ttyAMA0", baudrate=9600, timeout=1)
            ReconfiguracionFabrica()
            time.sleep(0.1)
            ConfiguracionMaster()
            time.sleep(0.1)

            print "**********   INICIO  *************"

            ser.flushInput()
            contador=0
            prender= ''
            ventilacion1= ''
            checkeo= ''

            while True:
                #if db.child("sala").: # It is the line where would be the conditional that allows me to detect any change only in the sala's node.
                            salidaLed1 = db.child("sala").get()
                            ser.write('AT')
                            time.sleep(0.1)
                            ser.write('AT+CON508CB16A7014')
                            time.sleep(0.1)
                            if salidaLed1.val()== True:
                                    prender=";"
                            if salidaLed1.val()== False:
                                    prender=","

                            ser.write('luz: %s \n' %(prender))
                            print ('luz: %s \n' %(prender))
                            time.sleep(1)
                            ser.read(checkeo)
                            if checkeo== 'j':
                                    ReconfiguracionFabrica()
                                    time.sleep(0.1)
                                    ConfiguracionMaster()

2条回答
爷的心禁止访问
2楼-- · 2020-02-10 11:05

Question: How to detect changes in firebase child


Note: All Examples use Public Access

  1. Setup Example Data and verify it's readable.
    This hase to be done once!

    enter image description here

    temperature_c = 30
    data = {'date':time.strftime('%Y-%m-%d'), 
            'time':time.strftime('%H:%M:%S'), 
            'temperature':temperature_c}
    db.child('public').child('Device_1').set(data)
    
    response = db.child('public').child('Device_1').get()
    print(response.val())
    
  2. Create First Script doing Updates:

    for t in [25, 26, 27, 28, 29, 30, 31, 32, 33, 35]:
        temperature_c = t
        data = {'date':time.strftime('%Y-%m-%d'), 
                'time':time.strftime('%H:%M:%S'), 
                'temperature':temperature_c}
        db.child('public').child('Device_1').update(data)
        time.sleep(60)
    
  3. Create Second Script with Stream Handler

    def stream_handler(message):
        print('event={m[event]}; path={m[path]}; data={m[data]}'
            .format(m=message))
    
    my_stream =db.child('public').child('Device_1').stream(stream_handler)
    
    # Run Stream Handler forever
    while True:
        data = input("[{}] Type exit to disconnect: ".format('?'))
        if data.strip().lower() == 'exit':
            print('Stop Stream Handler')
            if my_stream: my_stream.close()
            break
    
  4. Run Stream Handler Script:

    Response Output from def stream_handler after startup (Initial Data):

    event="put"; path=/;  data={'Device_1': {'temperature': 30, 'time': '13:34:24', 'date': '2017-07-20'}}
    
  5. Run Updater Script:

  6. Watch Output from Stream Handler Script

    Response Output from def stream_handler after First Update Data:

    event=patch; path=/Device_1;  data={'temperature': 25, 'time': '13:49:12'}
    

Tested with Python: 3.4.2


Pyrebase
streaming

You can listen to live changes to your data with the stream() method.

def stream_handler(message):
    print(message["event"]) # put
    print(message["path"]) # /-K7yGTTEp7O549EzTYtI
    print(message["data"]) # {'title': 'Pyrebase', "body": "etc..."}

my_stream = db.child("posts").stream(stream_handler)

You should at least handle put and patch events. Refer to "Streaming from the REST API" for details.

查看更多
劳资没心,怎么记你
3楼-- · 2020-02-10 11:12

I know this post is 2 years old but hope this helps. Try using firebase_admin module.

Use this command - pip install firebase-admin

I too had a requirement where I needed to check for changes made to the Firebase database. I referred here

Following is a sample code based on your question which you can refer from and try it out.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db


cred = credentials.Certificate("path/to/serviceAccountKey.json")
firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://example.firebaseio.com',
    'databaseAuthVariableOverride': None
})


def ignore_first_call(fn):
    called = False

    def wrapper(*args, **kwargs):
        nonlocal called
        if called:
            return fn(*args, **kwargs)
        else:
            called = True
            return None

    return wrapper


@ignore_first_call
def listener(event):
    print(event.event_type)  # can be 'put' or 'patch'
    print(event.path)  # relative to the reference, it seems
    print(event.data)  # new data at /reference/event.path. None if deleted

    node = str(event.path).split('/')[-2] #you can slice the path according to your requirement
    property = str(event.path).split('/')[-1] 
    value = event.data
    if (node=='sala'):
        #do something
    elif (node=='ventilacion'):
        #do something
    else:
        #do something else


db.reference('/').listen(listener)
查看更多
登录 后发表回答