将各节点用线连接起来,形成如下所示的流:
图 20 最终的工作流
在所有节点都修改之后,点击右上角的 Deploy 按钮来部署此工作流。当屏幕中间弹出成功部署(Successfully deployed)时,说明此流已经部署成功。
你也可以通过导入功能导入以上工作流。先找到菜单->导入->剪切板。
图 21 Node-RED 的导入功能
然后把以下代码粘贴到剪切板上,点击 Ok 按钮。当鼠标在画布上点击时,工作流即会落到画布上,然后部署即可。
[{"id":"1b156a6f.f4bd96","type":"ibmiot","z":"2282255c.190b3a","name":"my
api key"},{"id":"1007c76.d968b39","type":"ibmiot
in","z":"2282255c.190b3a","authentication":"boundService","apiKey":"1b156a6f.f4bd96","inputType":"evt","deviceId":"","applicationId":"","deviceType":"+","eventType":"+","commandType":"","format":"json","name":"IBM
IoT","service":"registered","allDevices":true,"allApplications":"","allDeviceTypes":true,"allEvents":true,"allCommands":"","allFormats":true,"x":212,"y":139,"wires":[["ba7c7e78.984a9"]]},{"id":"ba7c7e78.984a9","type":"json","z":"2282255c.190b3a","name":"","x":334,"y":139.5,"wires":[["13ed7f07.efa891"]]},{"id":"13ed7f07.efa891","type":"function","z":"2282255c.190b3a","name":"Message","func":"var
message = JSON.parse(msg.payload).d
;\nmsg.payload=message.content;\nreturn
msg;","outputs":"1","noerr":0,"x":466.5,"y":140,"wires":[["1b7a992d.274b47","27c244f9.52993c"]]},{"id":"1b7a992d.274b47","type":"cloudant
out","z":"2282255c.190b3a","name":"","cloudant":"","database":"demodb","service":"iot-push-cloudantNoSQLDB","payonly":true,"operation":"insert","x":613.5,"y":165.5,"wires":[]},{"id":"27c244f9.52993c","type":"ibmpush","z":"2282255c.190b3a","name":"","ApplicationID":"","identifiers":"","notification":"ios","mode":"PRODUCTION","x":612,"y":115,"wires":[]}]
第七步:发送 MQTT 消息
我们用 Java 实现一段程序,以发送 MQTT 消息给 IoT 平台。其中,我们引用了如下包:
com.ibm.iotf.client.2016.4.21.jar, gson-2.2.4.jar,httpclient-4.3.6.jar, httpcore-4.3.3.jar,
org.eclipse.paho.client.mqttv3-1.0.3-20150818.040635-202.jar
核心代码及解析如下:
public class DeviceMessage {
DeviceClient deviceClient = null;
public DeviceMessage() {
//设置连接属性,用我们已经创建好的设备的凭证,连接到我们的 IoT 服务。
Properties options = new Properties();
options.setProperty("org", "6bnaci");
options.setProperty("type", "Type1");
options.setProperty("id", "Device1");
options.setProperty("auth-method", "token");
options.setProperty("auth-token", "12345678");
try {
deviceClient = new DeviceClient(options);
} catch (Exception e) {
e.printStackTrace();
}
try {
//连接到 IoT 服务,参数设成 false,如果连接失败,不自动重新连接;如果设置成 true,那么程序会一直重试直到连接成功。
deviceClient.connect(false);
} catch (MqttException e) {
e.printStackTrace();
System.out.println("network connection error !");
}
}
public void sendMessage(String[] msg) {
//创建一个对象 event
JsonObject event = new JsonObject();
//如果此类被执行时有一个参数传入,我们即把它作为属性赋给 event,否则即赋值“This is alt="物联网" width="550" height="174" />