繁体   English   中英

Kivy Python-具有部分回调功能

[英]Kivy Python - Callback Function with partial

我想从我的Arduino的Raspberry中“拉”一些值,这是通过无线NRF24模块连接的。 我正在将此库与python包装器一起使用

在纯Python中,代码运行良好,现在我想将其集成到Kivy中。

为此,我在zimmerwetter.py做了两个函数:

一种用于设置无线电设备并返回无线电对象的程序(应用程序启动后应运行):

def radiosetup():
    radio = RF24(RPI_BPLUS_GPIO_J8_22, RPI_BPLUS_GPIO_J8_24, BCM2835_SPI_SPEED_8MHZ)

    # doing setup stuff...

    return radio

另一个功能向Arduino发送请求,该请求提供了一些环境日期(温度,湿度等)。

def getenviroment(self,radio):

    millis = lambda: int(round(time.time() * 1000))
    # send command
    send_payload = 'getdata'
    # First, stop listening so we can talk.

    radio.stopListening()

    # Take the time, and send it.  This will block until complete
    print 'Now sending length ', len(send_payload), ' ... ',
    radio.write(send_payload[:len(send_payload)])

    a = datetime.datetime.now()

    # Now, continue listening
    radio.startListening()

    # Wait here until we get a response, or timeout
    started_waiting_at = millis()
    timeout = False
    while (not radio.available()) and (not timeout):
        if (millis() - started_waiting_at) > 1000:
            timeout = True

    # Describe the results
    if timeout:
        b = datetime.datetime.now()
        #      print(b - a)
        print 'failed, response timed out.'
    else:
        # Grab the response, compare, and send to debugging spew
        length = radio.getDynamicPayloadSize()
        receive_payload = []
        receive_payload = radio.read(length)

        print 'got response size=', length
        print struct.unpack("bbbbhbbbb", ''.join(chr(c) for c in receive_payload))
        b = datetime.datetime.now()
        print(b - a)
        return receive_payload

以后每隔x秒应从kivy应用程序调用一次getenviroment函数,该部分函数按照kivy clock模块中的建议使用

from zimmerwetter import *

class PyowmApp(App):
    def build(self):
        radio = radiosetup()
        Clock.schedule_interval(partial(getenviroment,radio), 10)

错误是:

   File "/home/pi/pyscripts/pyowm/zimmerwetter.py", line 83, in getenviroment
     radio.stopListening()
 AttributeError: 'float' object has no attribute 'stopListening'

我想知道为什么返回一个浮点对象,当我使用help(radio)打印单选对象时,它返回class RF24(Boost.Python.instance)且函数class RF24(Boost.Python.instance) ()存在。

Clock.schedule_interval调用的函数在通过partial传递的函数之后将接收dt作为参数。 函数的签名是getenviroment(self,radio) ,因此radio将分配给selfdt将分配给radio

而是使用lambda

Clock.schedule_once(lambda dt: self.getenviroment(radio), 10)

我自己找到了,将schedule语句更改为

Clock.schedule_interval(partial(getenviroment,radio=radio), 10)

做到了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM