Node-RED使用指南:16:根据输出结果进行分支逻辑操作

在这里插入图片描述
在流的控制中,依据分支执行的结果可以分支结果的输出,这篇文章继续介绍Node-RED中的使用特性。

事前准备

以容器方式启动Node-RED服务,启动命令如下所示:

启动命令:docker run -it -p 1880:1880 -v $PWD/data:/data -e TZ=Asia/Shanghai --name nodered -d nodered/node-red:1.0.4

方式1: flow.state + switch节点

flow生成和设定

生成下图所示的flow
Node-RED使用指南:16:根据输出结果进行分支逻辑操作_第1张图片

  • Inject节点:flow.state传递结果
    在Node-RED中flow.state为此节点的执行结果,可根据此节点的执行结果进行后续的逻辑判断。
    Node-RED使用指南:16:根据输出结果进行分支逻辑操作_第2张图片
  • switch节点:根据flow.state传递结果进行多路分支处理
    此处用了三个分支,分别对应flow.state返回0、1和2的情况
    Node-RED使用指南:16:根据输出结果进行分支逻辑操作_第3张图片
  • Debug节点:显示msg.payload信息

部署并执行

点击Deploy进行部署,并通过点击Inject节点执行按钮手动触发,会发现执行结果总是显示flow.state == 0的分支,因为此处Inject的节点只是传个时间戳,并不会出错的原因。
Node-RED使用指南:16:根据输出结果进行分支逻辑操作_第4张图片

方式2: flow.state + change节点

flow生成和设定

生成下图所示的flow
Node-RED使用指南:16:根据输出结果进行分支逻辑操作_第5张图片

  • Inject节点:用作示例的传递输入
    分别使用三个Inject节点传入flow.state为0、1和2,比如flow.state=0的值的设定如下所示:
    Node-RED使用指南:16:根据输出结果进行分支逻辑操作_第6张图片

  • change节点:将三个节点的state属性转化为payload
    Node-RED使用指南:16:根据输出结果进行分支逻辑操作_第7张图片

  • Debug节点:显示msg.payload信息

部署并执行

点击Deploy进行部署,并通过点击三个Inject节点执行按钮手动触发,结果显示如下
Node-RED使用指南:16:根据输出结果进行分支逻辑操作_第8张图片

JSON格式的flow

[{"id":"8073b1db.7152","type":"inject","z":"73554227.4474dc","name":"多路输入:0","topic":"","payload":"0","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":190,"y":340,"wires":[["bca30b83.bb3328"]]},{"id":"223570a4.2ca28","type":"inject","z":"73554227.4474dc","name":"多路输入:0","topic":"","payload":"0","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":190,"y":380,"wires":[[]]},{"id":"fd948673.ecaf18","type":"inject","z":"73554227.4474dc","name":"多路输入:1","topic":"","payload":"1","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":190,"y":380,"wires":[["bca30b83.bb3328"]]},{"id":"532a5292.81ae0c","type":"inject","z":"73554227.4474dc","name":"多路输入:2","topic":"","payload":"2","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":190,"y":420,"wires":[["bca30b83.bb3328"]]},{"id":"bca30b83.bb3328","type":"change","z":"73554227.4474dc","name":"输入合并器","rules":[{"t":"set","p":"state","pt":"msg","to":"payload","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":390,"y":380,"wires":[["ced9de0c.8573f"]]},{"id":"ced9de0c.8573f","type":"debug","z":"73554227.4474dc","name":"结果输出显示","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":590,"y":380,"wires":[]}]

你可能感兴趣的:(#,Node-Red)