---
# System prepended metadata

title: Using RPC capabilities
tags: [ThingsBoard]

---

---
title: Using RPC capabilities
tags: ThingsBoard
image:
disque: hackmd
---

# Using RPC capabilities
:::info
TB平台，允許經由RPC (Remote Procedure Calls)方式，可以從伺服器端應用程式發送命令到設備端，反之亦然。

基本上，此功能可以讓我們向設備端發送命令並接收命令執行的結果。
同樣，我們也可以執行來自設備的請求，在後端應用一些計算或其他伺服器端邏輯，將回應發送回設備端。
:::

## RPC call types

* **Client-side RPC**
:::success
實作上利用TB平台現有的Device RPC API 
:::
![](https://i.imgur.com/ZOoV3Tk.png)

* **Server-side RPC有單向和雙向**
:::success
TB平台提供系統RPC服務，讓我們可以從伺服器端應用程式向設備發送RPC命令。
**為了發送RPC請求，實作上是對以下 URL執行HTTP POST請求。**
:::
```
http(s)://host:port/api/plugins/rpc/{callType}/{deviceId}

https://demo.thingsboard.io/api/plugins/rpc/oneway/{deviceId}
https://demo.thingsboard.io/api/plugins/rpc/twoway/{deviceId}
```
>swagger-ui.html
![](https://i.imgur.com/7WlT6eq.png)

* ++One-way Server-side RPC++
![](https://i.imgur.com/hEUIsN5.png)
* ++Two-way Server-side RPC++
![](https://i.imgur.com/0PuldZz.png)


### on demand read


Device RPC API
---
:::info
從設備端角度，TB根據不同協定(MQTT, CoAP, HTTP)提供相對應的設備API，讓我們可以從設備上運行的韌體或程式發送和接收 RPC 命令。確認要實作後，細節再詳閱Resource(s)相關連結。
:::
* MQTT
    * client-side
        * publish: v1/devices/me/rpc/request/$request_id
        * subscribe: v1/devices/me/rpc/response/$request_id 
    * server-side
        * subscribe: v1/devices/me/rpc/request/+
        * publish: v1/devices/me/rpc/response/$request_id
* CoAP
    * client-side
        * POST: coap://host/api/v1/$ACCESS_TOKEN/rpc
    * server-side
        * GET: coap://host/api/v1/$ACCESS_TOKEN/rpc
        * POST: coap://host/api/v1/$ACCESS_TOKEN/rpc/{$id}
* HTTP
    * client-side
        * POST: http(s)://host:port/api/v1/$ACCESS_TOKEN/rpc
    * server-side
        * GET: http(s)://host:port/api/v1/$ACCESS_TOKEN/rpc
        * POST: http(s)://host:port/api/v1/$ACCESS_TOKEN/rpc/{$id}

```bash=
star@tb-postgresql:~/workspace/device$ python3 emulator.py
Traceback (most recent call last):
  File "emulator.py", line 15, in <module>
    import paho.mqtt.client as mqtt
ModuleNotFoundError: No module named 'paho'
```
```bash=
sudo apt install python3-pip
pip3 install paho-mqtt
```

```python=

```

## RPC Rule Nodes - Action
* rpc call request
* rpc call reply


## RPC widgets (to be updated)
---

Resource(s)
---
* [Facebook ThingsBoard Taiwan Group](https://facebook.com/groups/thingsboard)
* https://thingsboard.io/docs/user-guide/rpc/
* https://thingsboard.io/docs/reference/mqtt-api/#rpc-api
* https://thingsboard.io/docs/reference/coap-api/#rpc-api
* https://thingsboard.io/docs/reference/http-api/#rpc-api

* https://shiyaztech.wordpress.com/
    * 