虚拟设备脚本字段总结
*注意:
一定要把crds里面的老版本删除掉,用新版本!
1.$hw/events/device/dht11-sensor-1/twin/update {
"event_id": "","timestamp": 0,"twin": {
"temperature": {
"actual":{
"value": "%s"}, "metadata": {
"type": "Updated" }}, "humidity": {
"actual" : {
"value": "%s" },"metadata": {
"type": "Updated" }} } } 2.$hw/events/device/led-light-instance-01/twin/update {
"event_id": "","timestamp": 0,"twin": {
"power-status": {
"actual":{
"value": "ON"}, "metadata": {
"type": "Updated" }} } } 3.$hw/events/device/counter/twin/update {
"event_id": "","timestamp": 0,"twin": {
"status": {
"actual":{
"value": ON"}, "metadata": {"type": "Updated" }}, {"actual" : { "value": "%s" },"metadata": {"type": "Updated" }} } } 4.$hw/events/device//traffic-light-instance-01/twin/update { "event_id": "","timestamp": 0,"twin": { "red": {"actual":{ "value": "OFF"}, "metadata": {"type": "Updated" }}, "yellow": {"actual" : { "value": "OFF" },"metadata": {"type": "Updated" }} "green": {"actual" : { "value": "OFF" },"metadata": {"type": "Updated" }} } } 5.$hw/events/device//switch/twin/update {
\"event_id\": \"\",\"timestamp\": 0,\"twin\": {
\"state\": {
\"actual\":{
\"value\": \"%s\"}, \"metadata\": {
\"type\": \"Updated\" }}, } }
讯享网
创建一个路径:/data/gopath/src/github.com/kubeedge/examples/temperature将下列文件放在次路径下
go脚本文件
讯享网package main import ( "context" "encoding/json" "fmt" "math/rand" "os" "strconv" "syscall" "time" "github.com/d2r2/go-dht" "github.com/d2r2/go-shell" "github.com/yosssi/gmq/mqtt" "github.com/yosssi/gmq/mqtt/client" logger "github.com/d2r2/go-logger" ) var lg = logger.NewPackageLogger("main", logger.DebugLevel, // logger.InfoLevel, ) //DeviceStateUpdate is the structure used in updating the device state type DeviceStateUpdate struct {
State string `json:"state,omitempty"` } //BaseMessage the base struct of event message type BaseMessage struct {
EventID string `json:"event_id"` Timestamp int64 `json:"timestamp"` } //TwinValue the struct of twin value type TwinValue struct {
Value *string `json:"value, omitempty"` Metadata *ValueMetadata `json:"metadata,omitempty"` } //ValueMetadata the meta of value type ValueMetadata struct {
Timestamp int64 `json:"timestamp, omitempty"` } //TypeMetadata the meta of value type type TypeMetadata struct {
Type string `json:"type,omitempty"` } //TwinVersion twin version type TwinVersion struct {
CloudVersion int64 `json:"cloud"` EdgeVersion int64 `json:"edge"` } //MsgTwin the struct of device twin type MsgTwin struct {
Expected *TwinValue `json:"expected,omitempty"` Actual *TwinValue `json:"actual,omitempty"` Optional *bool `json:"optional,omitempty"` Metadata *TypeMetadata `json:"metadata,omitempty"` ExpectedVersion *TwinVersion `json:"expected_version,omitempty"` ActualVersion *TwinVersion `json:"actual_version,omitempty"` } //DeviceTwinUpdate the struct of device twin update type DeviceTwinUpdate struct {
BaseMessage Twin map[string]*MsgTwin `json:"twin"` } func main() {
defer logger.FinalizeLogger() lg.Notify("*") lg.Notify("* You can change verbosity of output, to modify logging level of module \"dht\"") lg.Notify("* Uncomment/comment corresponding lines with call to ChangePackageLogLevel(...)") lg.Notify("*") lg.Notify("* Massive stress test of sensor reading, printing in the end summary statistical results") lg.Notify("*") // Uncomment/comment next line to suppress/increase verbosity of output logger.ChangePackageLogLevel("dht", logger.InfoLevel) // create context with cancellation possibility ctx, cancel := context.WithCancel(context.Background()) // use done channel as a trigger to exit from signal waiting goroutine done := make(chan struct{
}) defer close(done) // build actual signal list to control signals := []os.Signal{
os.Kill, os.Interrupt} if shell.IsLinuxMacOSFreeBSD() {
signals = append(signals, syscall.SIGTERM) } // run goroutine waiting for OS termination events, including keyboard Ctrl+C shell.CloseContextOnSignals(cancel, done, signals...) sensorType := dht.DHT11 // sensorType := dht.AM2302 //sensorType := dht.DHT12 //pin := 11 totalRetried := 0 totalMeasured := 0 totalFailed := 0 term := false // connect to Mqtt broker cli := connectToMqtt() for {
// Read DHT11 sensor data from specific pin, retrying 10 times in case of failure. //temperature, humidity, retried, err := //dht.ReadDHTxxWithContextAndRetry(ctx, sensorType, pin, false, 10) temperature := float32(rand.Intn(100)) humidity := 0 retried := 1 var err error = nil totalMeasured++ totalRetried += retried if err != nil && ctx.Err() == nil {
totalFailed++ lg.Error(err) continue } // print temperature and humidity if ctx.Err() == nil {
lg.Infof("Sensor = %v: Temperature = %v*C, Humidity = %v%% (retried %d times)", sensorType, temperature, humidity, retried) } // publish temperature status to mqtt broker publishToMqtt(cli, temperature) select {
// Check for termination request. case <-ctx.Done(): lg.Errorf("Termination pending: %s", ctx.Err()) term = true // sleep 1.5-2 sec before next round // (recommended by specification as "collecting period") case <-time.After(2000 * time.Millisecond): } if term {
break } } lg.Info("exited") } func connectToMqtt() *client.Client {
cli := client.New(&client.Options{
// Define the processing of the error handler. ErrorHandler: func(err error) {
fmt.Println(err) }, }) defer cli.Terminate() // Connect to the MQTT Server. err := cli.Connect(&client.ConnectOptions{
Network: "tcp", Address: "192.168.1.100:1883", //边缘节点ip地址 ClientID: []byte("receive-client"), }) if err != nil {
panic(err) } return cli } func publishToMqtt(cli *client.Client, temperature float32) {
deviceTwinUpdate := "$hw/events/device/" + "dht11设备名称" + "/twin/update" updateMessage := createActualUpdateMessage(strconv.Itoa(int(temperature)) + "C") twinUpdateBody, _ := json.Marshal(updateMessage) cli.Publish(&client.PublishOptions{
TopicName: []byte(deviceTwinUpdate), QoS: mqtt.QoS0, Message: twinUpdateBody, }) } //createActualUpdateMessage function is used to create the device twin update message func createActualUpdateMessage(actualValue string) DeviceTwinUpdate {
var deviceTwinUpdateMessage DeviceTwinUpdate actualMap := map[string]*MsgTwin{
"temperature-status": {
Actual: &TwinValue{
Value: &actualValue}, Metadata: &TypeMetadata{
Type: "Updated"}}} deviceTwinUpdateMessage.Twin = actualMap return deviceTwinUpdateMessage }
依赖
go.mod
module github.com/kubeedge/examples/temperature-demo go 1.14 require ( github.com/d2r2/go-dht v0.0.0-753-b6103ae97a4b github.com/d2r2/go-logger v0.0.0-742-9998ae github.com/d2r2/go-shell v0.0.0-817-7664ea33645f github.com/davecgh/go-spew v1.1.1 // indirect github.com/yosssi/gmq v0.0.1 )
go.sum
讯享网github.com/d2r2/go-dht v0.0.0-753-b6103ae97a4b h1:leyHWzcQM15PG2OTEZ+ZzUJ8jVeOX1ELngYheX3Dl6M= github.com/d2r2/go-dht v0.0.0-753-b6103ae97a4b/go.mod h1:AzSqP4S4/6pINOKg3VC79WC7YY3zskQcrXMFzphCry0= github.com/d2r2/go-logger v0.0.0-742-9998ae h1:ZG3JBA6rPRl0xxQ+nNSfO7tor8w+CNCTs05DNJQYbLM= github.com/d2r2/go-logger v0.0.0-742-9998ae/go.mod h1:oA+9PUt8F1aKJ6o4YU1T120i7sgo1T6/1LWEEBy0BSs= github.com/d2r2/go-shell v0.0.0-817-7664ea33645f h1:VrZEIdW45kHrPChbu4fvZnolG9l9Wu70znnLQUY/yFg= github.com/d2r2/go-shell v0.0.0-817-7664ea33645f/go.mod h1:FdrNob+jQ3UkEpNVeZFVn8mW86Aa2wa6U5z0vGQOEXQ= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/yosssi/gmq v0.0.1 h1:GhlDVaAQoi3Mvjul/qJXXGfL4JBeE0GQwbWp3eIsja8= github.com/yosssi/gmq v0.0.1/go.mod h1:mReykazh0U1JabvuWh1PEbzzJftqOQWsjr0Lwg5jL1Y=
devicemodel.yaml
apiVersion: devices.kubeedge.io/v1alpha2 kind: DeviceModel metadata: name: dht11-model namespace: default spec: properties: - name: temperature-status description: Temperature collected from the edge device type: string: accessMode: ReadOnly defaultValue: ''
deviceinstance.yaml
讯享网apiVersion: devices.kubeedge.io/v1alpha2 kind: Device metadata: name: dht11 labels: description: 'temperature' spec: deviceModelRef: name: dht11-model nodeSelector: nodeSelectorTerms: - matchExpressions: - key: '' operator: In values: - raspberrypi status: twins: - propertyName: temperature-status desired: metadata: type: string value: ''

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/11912.html