Shifu は、接続されたデバイスごとにdeviceShifuを作成します。deviceShifuは物理デバイスのデジタル ツインであり、デバイス メトリクスの制御と収集を担当します。
このチュートリアルでは、単純な温度検出プログラムを作成し、アプリケーションを使用して温度計のdeviceShifuと対話することによってdeviceShifuと対話する方法を示します。
前提
この例では、Go、Docker、kind、kubectl 、およびkubebuilderがインストールされている必要があります。
1. Shifuを実行し、簡易温度計を接続します
shifu/examples/deviceshifu/demo_device
パスにはデモ用温度計のデプロイメント構成がすでに存在します。温度計は現在の温度を表す整数を報告し、read_value API
この値を報告するための整数を備えています。
shifu
ルート ディレクトリから次の 2 つのコマンドを実行して、デモ温度計のShifuとdeviceShifuを実行します。
./test/scripts/deviceshifu-setup.sh apply # setup and start shifu services for this demo
kubectl apply -f examples/deviceshifu/demo_device/edgedevice-thermometer # connect mock thermometer to shifu
2. 温度検知プログラム
このアプリケーションは、 HTTP リクエストを通じてdeviceShifuと対話し、2 秒ごとにノードを検出して温度計deviceShifuread_value
の測定値を取得します。
適用例は次のとおりです。
高温検出器.go
package main
import (
"log"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
targetUrl := "http://edgedevice-thermometer/read_value"
req, _ := http.NewRequest("GET", targetUrl, nil)
for {
res, _ := http.DefaultClient.Do(req)
body, _ := ioutil.ReadAll(res.Body)
temperature, _ := strconv.Atoi(string(body))
if temperature > 20 {
log.Println("High temperature:", temperature)
} else if temperature > 15 {
log.Println("Normal temperature:", temperature)
} else {
log.Println("Low temperature:", temperature)
}
res.Body.Close()
time.Sleep(2 * time.Second)
}
}
生成しますgo.mod
:
go mod init high-temperature-detector
3. コンテナ化されたアプリケーション
以下の場合には申請が必要ですDockerfile
。
Dockerfile
# syntax=docker/dockerfile:1
FROM golang:1.17-alpine
WORKDIR /app
COPY go.mod ./
RUN go mod download
COPY *.go ./
RUN go build -o /high-temperature-detector
EXPOSE 11111
CMD [ "/high-temperature-detector" ]
その後、アプリケーションを作成します。
docker build --tag high-temperature-detector:v0.0.1 .
これで、温度検出アプリケーションのイメージが構築されました。
4. アプリケーションイメージをロードし、アプリケーションポッドを起動します。
まず、アプリケーション イメージを以下にロードしますkind
。
kind load docker-image high-temperature-detector:v0.0.1
次に、コンテナを実行しますPod
。
kubectl run high-temperature-detector --image=high-temperature-detector:v0.0.1 -n deviceshifu
5. アプリケーションの出力を確認する
温度検出アプリケーションは、2 秒ごとに温度計からdeviceShifu
現在の値を取得します。
すべての準備が完了しました。ログを通じてプログラム出力を確認してください。
kubectl logs -n default high-temperature-detector -f
出力例:
kubectl logs -n default high-temperature-detector -f
2021/10/18 10:35:35 High temperature: 24
2021/10/18 10:35:37 High temperature: 23
2021/10/18 10:35:39 Low temperature: 15
2021/10/18 10:35:41 Low temperature: 11
2021/10/18 10:35:43 Low temperature: 12
2021/10/18 10:35:45 High temperature: 28
2021/10/18 10:35:47 Low temperature: 15
2021/10/18 10:35:49 High temperature: 30
2021/10/18 10:35:51 High temperature: 30
2021/10/18 10:35:53 Low temperature: 15
この記事は Boundless Authorization によって公開されています