[英]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
將分配給self
而dt
將分配給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.