在使用Autobahn和WAMP之前,我一直在使用子类化方法,但在装饰器/函数方法上遇到了挫折,与子类化相比,我真的更喜欢它。
然而。我有一个从外部硬件(通过回调)调用的函数,该函数在被调用时需要发布到Crossbar.io路由器。
这就是我如何做到这一点的,在on_join -> async def joined(session, details)被调用后立即保留对Session的引用。
from autobahn.asyncio.component import Component
from autobahn.asyncio.component import run
global_session = None
comp = Component(
transports=u"ws://localhost:8080/ws",
realm=u"realm1",
)
def callback_from_hardware(msg):
if global_session is None:
return
global_session.publish(u'com.someapp.somechannel', msg)
@comp.on_join
async def joined(session, details):
global global_session
global_session = session
print("session ready")
if __name__ == "__main__":
run([comp])然而,这种在组件连接连接后保留引用的方法感觉有点“奇怪”。有没有不同的方法呢?有没有其他方法可以做到这点。
如果不是这样,在子类化和让所有应用程序依赖于该子类中的代码方面感觉更“正确”一些(但将我的应用程序的所有内容都放在一个子类中感觉也很奇怪)。
发布于 2018-02-27 19:05:54
我建议使用异步队列而不是共享会话:
import asyncio
from autobahn.asyncio.component import Component
from autobahn.asyncio.component import run
queue = asyncio.queues.Queue()
comp = Component(
transports=u"ws://localhost:8080/ws",
realm=u"realm1",
)
def callback_from_hardware(msg):
queue.put_nowait((u'com.someapp.somechannel', msg,))
@comp.on_join
async def joined(session, details):
print("session ready")
while True:
topic, message, = await queue.get()
print("Publishing: topic: `%s`, message: `%s`" % (topic, message))
session.publish(topic, message)
if __name__ == "__main__":
callback_from_hardware("dassdasdasd")
run([comp])发布于 2018-03-29 05:02:56
您可以在这里采用多种方法,尽管最简单的IMO方法是使用Crossbar的http桥。因此,每当从您的硬件收到事件回调时,您只需向Crossbar发出http POST请求,您的消息就会被传递。
有关http桥https://crossbar.io/docs/HTTP-Bridge-Publisher/的更多详细信息
https://stackoverflow.com/questions/48162436
复制相似问题