关于物联网:用户手册与-deviceShifu-交互的应用

2次阅读

共计 2167 个字符,预计需要花费 6 分钟才能阅读完成。

Shifu会对每一个连贯的设施创立一个 deviceShifudeviceShifu 是物理设施的数字孪生并负责管制,收集设施指标。

这个教程会创立一个简略的温度检测程序,通过和一个温度计的 deviceShifu 交互来演示如何应用利用来和 deviceShifu 交互。

前提

本示例须要装置 Go, Docker, kind, kubectl 和 kubebuilder。

1. 运行 Shifu 并连贯一个简略的温度计

shifu/examples/deviceshifu/demo_device 门路中曾经有一个演示温度计的 deployment 配置。该温度计会上报一个整数代表以后温度,它领有一个 read_value API 来汇报这个数值。

shifu 根目录下,运行上面两条命令来运行 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 交互,每两秒检测 read_value 节点来获取温度计 deviceShifu 的读数。

利用示例如下:

high-temperature-detector.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. 加载利用镜像并启动利用 Pod

首先将利用镜像加载到 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. 查看利用输入

温度检测利用会每两秒钟通过温度计的 deviceShifu 获取以后数值。

所有准备就绪,通过 log 来查看程序输入:

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
正文完
 0