【问题标题】:SSE with Leshan LWM2M Demo ServerSSE 与乐山 LWM2M 演示服务器
【发布时间】:2020-06-12 12:04:43
【问题描述】:

我正在尝试做一个与乐山演示服务器交互的http api。 我试图在 LWM2M 中处理 OBSERVE,但我需要使用 http 处理通知。 我发现乐山通知使用 SSE。所以我尝试使用 requests 和 sseclient 在 python 中实现 sse 客户端。

这是我的代码:

    response= requests.post(url_request , "format=TLV" , stream= True)    
    client = sseclient.SSEClient(response)
    for event in client.events():
        print(json.loads(event.data))

我尝试运行我的脚本,但似乎流没有打开并且它立即关闭而无需等待服务器的响应,即使请求默认为 HTTP 下的 TCP 连接实现 keep_alive 并且流为 True。

有人知道为什么吗?

【问题讨论】:

    标签: http python-requests iot server-sent-events lwm2m


    【解决方案1】:

    阅读sseclient 文档,正确使用 SSEClient 的方法似乎是:

    from sseclient import SSEClient
    messages = SSEClient('http://example.com/sse_stream/')
    for msg in messages:
        do_something_useful(msg)
    

    阅读乐山Github上的answer,乐山服务器Demo的流URL好像是http://your.leshan.server.org/event?ep=your_device_endpoint_name

    所以我尝试了:

    from sseclient import SSEClient
    messages = SSEClient('http://localhost:8080/event?ep=my_device')
    for msg in messages:
        print (msg.event, msg.data)
    

    它对我有用?!当我观察乐山客户端Demo的温度实例时得到这样的结果:

    (u'NOTIFICATION', u'{"ep":"my_device","res":"/3303/0","val":{"id":0,"resources":[{"id":5601,"value":-18.9},{"id":5602,"value":31.2},{"id":5700,"value":-18.4},{"id":5701,"value":"cel"}]}}')
    (u'COAPLOG', u'{"timestamp":1592296453808,"incoming":true,"type":"CON","code":"POST","mId":29886,"token":"889372029F81C124","options":"Uri-Path: \\"rd\\", \\"reWfKIgPYD\\"","ep":"my_device"}')
    (u'COAPLOG', u'{"timestamp":1592296453809,"incoming":false,"type":"ACK","code":"2.04","mId":29886,"token":"889372029F81C124","ep":"my_device"}')
    (u'UPDATED', u'{"registration":{"endpoint":"my_device","registrationId":"reWfKIgPYD","registrationDate":"2020-06-16T10:02:25+02:00","lastUpdate":"2020-06-16T10:34:13+02:00","address":"127.0.0.1:44400","lwM2mVersion":"1.0","lifetime":300,"bindingMode":"U","rootPath":"/","objectLinks":[{"url":"/","attributes":{"rt":"\\"oma.lwm2m\\""}},{"url":"/1/0","attributes":{}},{"url":"/3/0","attributes":{}},{"url":"/6/0","attributes":{}},{"url":"/3303/0","attributes":{}}],"secure":false,"additionalRegistrationAttributes":{}},"update":{"registrationId":"reWfKIgPYD","identity":{"peerAddress":{}},"additionalAttributes":{}}}')
    (u'COAPLOG', u'{"timestamp":1592296455150,"incoming":true,"type":"NON","code":"2.05","mId":29887,"token":"3998C5DE2588F835","options":"Content-Format: \\"application/vnd.oma.lwm2m+tlv\\" - Observe: 2979","payload":"Hex:e3164563656ce8164408c03199999999999ae815e108c032e66666666666e815e208403f333333333333","ep":"my_device"}')
    

    如果您只对通知感兴趣,只需添加一个if msg.event == 'NOTIFICATION': 块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      相关资源
      最近更新 更多