1

我在自己的主机上安装了 freeboard,但无法将其连接到 PubNub。我曾尝试使用 mqtt 插件通过 MQTT 连接到 pubnub,但没有成功。如何将 PubNub 连接到 freeboard?我自己的 freeboard 实例不是 freeboard.io 托管的仪表板

4

1 回答 1

3

我可以给你一些指点。虽然PubNub 支持 MQTT,但没有必要使用该协议。根据您使用的 IoT 设备,您可以将标准 PubNub 连接与您的设备支持的任何 SDK 一起使用。

如果你确实想使用 MQTT,你可以使用 Python 和 Paho:

import paho.mqtt.client as mqtt

publish_key = "<your publish key>"
subscribe_key = "<your subscribe key>"
client_id = "<your unique client identifier>"


client = mqtt.Client(client_id=publish_key + "/" + subscribe_key + "/" + client_id)
client.connect("mqtt.pndsn.com", 1883, 60)
client.publish("<topic to publish>", json.dumps({ "hi": 10 }))

此代码的作用是将 JSON 数据发布到 MQTT 主题(PubNub 术语中的通道)。

您可以发布适合您的仪表板的数据,而不是“hi = 10”。我坚持要包含一个 Unix 时间戳,以便您知道数据何时提交。

您还可以使用Python或任何其他有 SDK 的语言(有 70 多个 SDK )使用PubNub 标准发布

import time
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()
pnconfig.publish_key = '<your publish key>'
pubnub = PubNub(pnconfig)

## makes a timetoken that is easily converted to 
## a JavaScript date object in a web browser
javascript_timetoken = int(time.time() * 1000) 

pubnub.publish().channel("my_channel").message({
    'tt': javascript_timetoken,
    'foo': 'bar'
}).sync()

现在,此消息已发布,可以在 Web 浏览器中打开的仪表板中实时接收。如果在发布消息时仪表板未打开,则可以稍后使用PubNub 存储和回放来检索它。

在此处输入图像描述

您可以在密钥信息选项卡下的PubNub 管理仪表板中启用消息保留。

酒吧历史

这就是用于订阅的JavaScript 代码在带有仪表板的网页中的样子。

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.20.2.js"></script>
<script>
var pubnub = new PubNub({
    subscribeKey: "mySubscribeKey",
    ssl: true
});

var time;

pubnub.addListener({
    message: function(message) {
        time = new Date(message.tt);
        // do more stuff
        // write data to the dashboard
    },
});

pubnub.subscribe({
    channels: ['my_channel'] 
});

// Get messages from the channel history in case there were 
// updates that happened while the browser was not yet opened
pubnub.history(
    {
        channel: 'my_channel',
        reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
        count: 100, // how many items to fetch
        stringifiedTimeToken: true, // false is the default
        start: '123123123123', // start time token to fetch
        end: '123123123133' // end timetoken to fetch
    },
    function (status, response) {
        response.messages.forEach(function (message) {
            time = new Date(message.tt);
            // do more stuff
            // write data to the dashboard
        });
    }
);

于 2018-04-02T18:01:32.260 回答