如何检测python的firebase孩子的变化? [英] How to detect changes in firebase child with python?

查看:477
本文介绍了如何检测python的firebase孩子的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个应用程序的一些麻烦。我需要的是,如果我检测到数据库(FIREBASE)的变化,特别是在'sala'和'ventilacion'节点中,函数做它必须做的事情。如果数据库中没有任何改变,它不会无所事事。我正在使用python和pyrebase库。这是代码。非常感谢你的帮助。

  import pyrebase 
import serial
import time
config = {
# firebase配置


$ b firebase = pyrebase.initialize_app(config)

$ b db = firebase.database()
def ReconfiguracionFabrica():
ser.write('AT')
time.sleep(0.2)
ser.write('AT + RENEW')
time.sleep(0.3 )
$ b $ 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 = ''

,而真:
#if db.child(sala):#这是条件允许我检测任何变化只有在萨拉节点。
salidaLed1 = db.child(sala)。get()
ser.write('AT')
time.sleep(0.1)
ser.write('AT + CON508CB16A7014')
time.sleep(0.1)
如果salidaLed1.val()==真:
prender =;
如果salidaLed1.val()==假:
prender =,

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


$


b
$ b $ hr
$ b


注意:所有示例均使用公开访问 / p>




  1. 设置示例数据并验证它是adable。

    这样做一次一次



      temperature_c = 30 
    data = {'date':time.strftime('%Y-%m-% d'),
    'time':time.strftime('%H:%M:%S'),
    'temperature':temperature_c}
    db.child('public') ('Device_1').set(data)

    response = db.child('public')。child('Device_1')。get()
    print(response.val ())


  2. 创建执行更新的第一个脚本:
    $对于[25,26,27,28,29,30,31,32,33,35]中的t,b $ b

     
    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. 使用流处理程序的脚本

      def stream_handler(消息):
    print('event = {m [event]};路径= {M [路径]};数据= {m [data]}'
    .format(m = message))

    my_stream = db.child('public')。child('Device_1')。stream(stream_handler )

    #永远运行流处理程序
    而真:
    data = input([{}]键入exit断开:.format('?'))
    if data.strip()。lower()=='exit':
    print('Stop Stream Handler')
    如果my_stream:my_stream.close()
    break


  4. 运行流处理程序脚本:
    $ b 响应输出来自 def stream_handler 启动后(初始数据):

      event = 放;路径= /; data = {'Device_1':{'temperature':30,'time':'13:34:24','date':'2017-07-20'}} 
  5. / p>
    $ b

    def stream_handler 第一个更新数据之后的输出:

      event = patch;路径= / DEVICE_1; data = {'temperature':25,'time':'13:49:12'} 


使用Python测试:3.4.2
$ b





Pyrebase



您可以使用stream()方法监听数据的实时更改。

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

my_stream = db.child(posts)。 (stream_handler)

您至少应该处理put和patch事件。有关详细信息,请参阅从REST API进行流式处理。



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()

解决方案

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!

    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.

这篇关于如何检测python的firebase孩子的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆