You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Piface Digital回调函数传递自定义参数?

How to Pass Custom Arguments to Piface Digital Input Event Callbacks

Great question! The pifacedigitalio library doesn't explicitly cover passing custom arguments to input event callbacks in its official docs, but there are two simple, reliable ways to make this work—especially since your callback is an async function. Let's walk through them:

1. Use a Lambda Expression to Capture External Variables

Lambda functions are perfect for wrapping your async callback and passing in the extra websocket and path parameters. Since pifacedigitalio expects a synchronous callback, we also need to schedule the async function with asyncio.create_task to ensure it runs properly.

Here's how to adjust your code:

import asyncio
import pifacedigitalio

# Initialize Piface
pifacedigitalio.init()
listener = pifacedigitalio.InputEventListener()

# Assume websocket and path are already available in your scope
listener.register(
    1,
    pifacedigitalio.IODIR_ON,
    lambda event: asyncio.create_task(self.sendEventPushed(websocket, path))
)

# Run the listener in a separate thread to avoid blocking your async event loop
import threading
threading.Thread(target=listener.activate, daemon=True).start()

2. Use functools.partial to Bind Arguments

If you prefer a more explicit approach, functools.partial lets you pre-bind your custom arguments to the callback function. Just like with the lambda method, you'll need to wrap the partial function in a lambda to trigger the async task:

import asyncio
import functools
import pifacedigitalio

pifacedigitalio.init()
listener = pifacedigitalio.InputEventListener()

# Bind websocket and path to your async callback
bound_callback = functools.partial(self.sendEventPushed, websocket, path)

# Register the wrapped callback
listener.register(
    1,
    pifacedigitalio.IODIR_ON,
    lambda event: asyncio.create_task(bound_callback())
)

# Start the listener in a daemon thread
import threading
threading.Thread(target=listener.activate, daemon=True).start()

Key Notes to Keep in Mind

  • Async Compatibility: pifacedigitalio's event system runs synchronously, so you must use asyncio.create_task (or asyncio.run_coroutine_threadsafe if your listener is in a different thread) to execute your async callback without blocking.
  • Object Lifetime: Make sure websocket and path are still valid when the button is pressed—avoid situations where these objects are garbage-collected before the event triggers.
  • Thread Safety: Running the listener in a daemon thread prevents it from blocking your main async event loop, which is crucial for WebSocket applications.

内容的提问来源于stack exchange,提问作者Juliosor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:20:04