虚拟设备执行go脚本

5 篇文章 0 订阅
5 篇文章 1 订阅

虚拟设备脚本字段总结

***注意:

一定要把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-20190501193753-b6103ae97a4b
	github.com/d2r2/go-logger v0.0.0-20181221090742-9998a510495e
	github.com/d2r2/go-shell v0.0.0-20191113051817-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-20190501193753-b6103ae97a4b h1:leyHWzcQM15PG2OTEZ+ZzUJ8jVeOX1ELngYheX3Dl6M=
github.com/d2r2/go-dht v0.0.0-20190501193753-b6103ae97a4b/go.mod h1:AzSqP4S4/6pINOKg3VC79WC7YY3zskQcrXMFzphCry0=
github.com/d2r2/go-logger v0.0.0-20181221090742-9998a510495e h1:ZG3JBA6rPRl0xxQ+nNSfO7tor8w+CNCTs05DNJQYbLM=
github.com/d2r2/go-logger v0.0.0-20181221090742-9998a510495e/go.mod h1:oA+9PUt8F1aKJ6o4YU1T120i7sgo1T6/1LWEEBy0BSs=
github.com/d2r2/go-shell v0.0.0-20191113051817-7664ea33645f h1:VrZEIdW45kHrPChbu4fvZnolG9l9Wu70znnLQUY/yFg=
github.com/d2r2/go-shell v0.0.0-20191113051817-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: ''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值