diff --git a/_template/README.md b/_template/README.md deleted file mode 100644 index fac611d7..00000000 --- a/_template/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# How to create your own mappers -Before you start, read the mapper design to familiar with the mapper structure and communications with other part in Kubeedge: [mapper design v2](https://github.com/kubeedge/kubeedge/blob/master/docs/proposals/mapper-design-v2.md). - -## 1. Design the device model and device instance CRDs - -## 2. Generate the code template -The mapper template is to generate a framework for the customized mapper. Run the command and input your mapper's name: -```shell -github.com/kubeedge/mappers-go$ make template -Please input the mapper name (like 'Bluetooth', 'BLE'): test -``` -A folder named as you input will be generated in the directory "mappers". The file tree is as below: -``` -mapper -├── cmd ----------------------------- Main process. -│   └── main.go --------------------- Almost need not change. -├── config -------------------------- Configuration parse. -│   ├── config.go ------------------- Almost need not change. -│   ├── config_test.go -│   └── config.yaml ----------------- Configuration file including Mqtt access information. -├── configmap ----------------------- Configmap parse and generate related structure. -│   ├── configmap_negtest.json -│   ├── configmap_test.json -│   ├── parse.go -------------------- Refine the parse process as your CRD. -│   ├── parse_test.go -│   └── type.go --------------------- Add the mapper-specific data structure here. -├── config.yaml -├── deployment.yaml -├── device -------------------------- Device management. Such as reading the device configuration and create the data structure accordingly, connecting the devices, and reading/writing device registers. -│   ├── device.go ------------------- Refine the initialization of driver client and customized visitor parsing. -│   ├── devstatus.go ---------------- Almost need not change. It's for device status process. -│   └── twindata.go ----------------- Almost need not change. It's for Twin or data message process. -├── Dockerfile -├── driver -------------------------- This is for reading/writing devices. -│   └── client.go ------------------- Fill in the functions like getting register/setting register. -├── globals -│   └── globals.go ------------------ Almost need not change. -├── hack -│   └── make-rules -│   └── mapper.sh -└── Makefile -``` diff --git a/_template/mapper-sdk/Dockerfile b/_template/mapper-sdk/Dockerfile deleted file mode 100644 index ccec035f..00000000 --- a/_template/mapper-sdk/Dockerfile +++ /dev/null @@ -1,6 +0,0 @@ -FROM alpine:3.14 -RUN mkdir -p kubeedge -COPY ./bin/Template kubeedge/bin/ -COPY ./res kubeedge/res/ -WORKDIR kubeedge/bin -ENTRYPOINT ["./Template"] \ No newline at end of file diff --git a/_template/mapper-sdk/Makefile b/_template/mapper-sdk/Makefile deleted file mode 100644 index a266fedd..00000000 --- a/_template/mapper-sdk/Makefile +++ /dev/null @@ -1,36 +0,0 @@ -SHELL := /bin/bash - -curr_dir := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST))))) -rest_args := $(wordlist 2, $(words $(MAKECMDGOALS)), $(MAKECMDGOALS)) -$(eval $(rest_args):;@:) - -help: - # - # Usage: - # make template : create a mapper based on a template. - # make mapper {mapper-name} : execute mapper building process. - # make all : execute building process to all mappers. - # - # Actions: - # - mod, m : download code dependencies. - # - lint, l : verify code via go fmt and `golangci-lint`. - # - build, b : compile code. - # - package, p : package docker image. - # - test, t : run unit tests. - # - clean, c : clean output binary. - # - # Parameters: - # ARM : true or undefined - # ARM64 : true or undefined - # - # Example: - # - make mapper modbus ARM64=true : execute `build` "modbus" mapper for ARM64. - # - make mapper modbus test : execute `test` "modbus" mapper. - @echo - -make_rules := $(shell ls $(curr_dir)/hack/make-rules | sed 's/.sh//g') -$(make_rules): - @$(curr_dir)/hack/make-rules/$@.sh $(rest_args) - -.DEFAULT_GOAL := help -.PHONY: $(make_rules) build test package diff --git a/_template/mapper-sdk/README.md b/_template/mapper-sdk/README.md deleted file mode 100644 index e368fa08..00000000 --- a/_template/mapper-sdk/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Tips -1. Place your certificate under [res](./res) -2. Complete TODO in the generated files -3. ```make mapper Template package``` -4. Modify the `deployment.yaml` according to your needs -5. Copy `deployment.yaml` to the CloudCore and ```kubectl apply -f deployment.yaml``` \ No newline at end of file diff --git a/_template/mapper-sdk/cmd/main.go b/_template/mapper-sdk/cmd/main.go deleted file mode 100644 index d18a7b64..00000000 --- a/_template/mapper-sdk/cmd/main.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "github.com/kubeedge/mappers-go/mapper-sdk-go/pkg/service" - "github.com/kubeedge/mappers-go/mappers/Template/driver" -) - -// main Template device program entry -func main() { - d := &driver.Template{} - // TODO: Modify your protocol name to be consistent with the CRDs definition - service.Bootstrap("Template", d) -} diff --git a/_template/mapper-sdk/deployment.yaml b/_template/mapper-sdk/deployment.yaml deleted file mode 100644 index afaacc14..00000000 --- a/_template/mapper-sdk/deployment.yaml +++ /dev/null @@ -1,31 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: Template-mapper -spec: - replicas: 1 - selector: - matchLabels: - app: Templatemapper - template: - metadata: - labels: - app: Templatemapper - spec: - hostNetwork: true - containers: - - name: Template-mapper-container - image: Templatemapper:v1.0 - imagePullPolicy: IfNotPresent - securityContext: - privileged: true - volumeMounts: - - name: config-volume - mountPath: /opt/kubeedge/ - nodeSelector: - Template: "true" - volumes: - - name: config-volume - configMap: - name: device-profile-config-test - restartPolicy: Always diff --git a/_template/mapper-sdk/driver/driver.go b/_template/mapper-sdk/driver/driver.go deleted file mode 100644 index 068b940d..00000000 --- a/_template/mapper-sdk/driver/driver.go +++ /dev/null @@ -1,124 +0,0 @@ -package driver - -import ( - "encoding/json" - "fmt" - "sync" -) - -type TemplateProtocolConfig struct { - ProtocolName string `json:"protocolName"` - ProtocolConfigData `json:"configData"` -} - -type ProtocolConfigData struct { - // TODO: add your config data according to configmap -} - -type TemplateProtocolCommonConfig struct { - CommonCustomizedValues `json:"customizedValues"` -} - -type CommonCustomizedValues struct { - // TODO: add your CommonCustomizedValues according to configmap -} -type TemplateVisitorConfig struct { - ProtocolName string `json:"protocolName"` - VisitorConfigData `json:"configData"` -} - -type VisitorConfigData struct { - // TODO: add your Visitor ConfigData according to configmap -} - -// Template Realize the structure -type Template struct { - // TODO: add some vars to help your implement the SDK interfaces - mutex sync.Mutex - protocolConfig TemplateProtocolConfig - protocolCommonConfig TemplateProtocolCommonConfig - visitorConfig TemplateVisitorConfig -} - -// InitDevice Sth that need to do in the first -// If you need mount a persistent connection, you should provide parameters in configmap's protocolCommon. -// and handle these parameters in the following function -func (d *Template) InitDevice(protocolCommon []byte) (err error) { - if protocolCommon != nil { - if err = json.Unmarshal(protocolCommon, &d.protocolCommonConfig); err != nil { - fmt.Printf("Unmarshal ProtocolCommonConfig error: %v\n", err) - return err - } - } - // TODO: add init operation - return nil -} - -// SetConfig Parse the configmap's raw json message -// In the case of high concurrency, d.mutex helps you get the correct value -func (d *Template) SetConfig(protocolCommon, visitor, protocol []byte) (err error) { - d.mutex.Lock() - defer d.mutex.Unlock() - if protocolCommon != nil { - if err = json.Unmarshal(protocolCommon, &d.protocolCommonConfig); err != nil { - fmt.Printf("Unmarshal protocolCommonConfig error: %v\n", err) - return err - } - } - if visitor != nil { - if err = json.Unmarshal(visitor, &d.visitorConfig); err != nil { - fmt.Printf("Unmarshal visitorConfig error: %v\n", err) - return err - } - - } - if protocol != nil { - if err = json.Unmarshal(protocol, &d.protocolConfig); err != nil { - fmt.Printf("Unmarshal protocolConfig error: %v\n", err) - return err - } - } - return -} - -// ReadDeviceData is an interface that reads data from a specific device, data's dataType is consistent with configmap -func (d *Template) ReadDeviceData(protocolCommon, visitor, protocol []byte) (data interface{}, err error) { - // Parse raw json message to get a Template instance - err = d.SetConfig(protocolCommon, visitor, protocol) - if err != nil { - return nil, err - } - // TODO: get device's data by protocolCommonConfig,visitorConfig,protocolConfig - return nil, err -} - -// WriteDeviceData is an interface that write data to a specific device, data's dataType is consistent with configmap -func (d *Template) WriteDeviceData(data interface{}, protocolCommon, visitor, protocol []byte) (err error) { - // Parse raw json message to get a Template instance - err = d.SetConfig(protocolCommon, visitor, protocol) - if err != nil { - return err - } - // TODO: set device's config to data interface{} by protocolCommonConfig,visitorConfig,protocolConfig - return nil -} - -// StopDevice is an interface to disconnect a specific device -// This function is called when mapper stops serving -func (d *Template) StopDevice() (err error) { - // TODO: If you need to exit safely, set the exit operation, otherwise it can be ignored - fmt.Println("----------Stop Template Successful----------") - return nil -} - - - -// GetDeviceStatus is an interface to get the device status true is OK , false is DISCONNECTED -func (d *Template) GetDeviceStatus(protocolCommon, visitor, protocol []byte) (status bool) { - err := d.SetConfig(protocolCommon, visitor, protocol) - if err != nil { - return false - } - // TODO: get device's status by protocolCommonConfig,visitorConfig,protocolConfig - return true -} diff --git a/_template/mapper-sdk/hack/make-rules/mapper.sh b/_template/mapper-sdk/hack/make-rules/mapper.sh deleted file mode 100644 index 74715aa0..00000000 --- a/_template/mapper-sdk/hack/make-rules/mapper.sh +++ /dev/null @@ -1,190 +0,0 @@ -#!/usr/bin/env bash - -set -o errexit -set -o nounset -set -o pipefail - -CURR_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" -ROOT_DIR="$(cd "${CURR_DIR}/../.." && pwd -P)" -source "${ROOT_DIR}/hack/lib/init.sh" - -mkdir -p "${CURR_DIR}/bin" -mkdir -p "${CURR_DIR}/dist" - -function mod() { - [[ "${2:-}" != "only" ]] - local mapper="${1}" - - # the mapper is sharing the vendor with root - pushd "${ROOT_DIR}" >/dev/null || exist 1 - echo "downloading dependencies for mapper ${mapper}..." - - if [[ "$(go env GO111MODULE)" == "off" ]]; then - echo "go mod has been disabled by GO111MODULE=off" - else - echo "tidying" - go mod tidy - echo "vending" - go mod vendor - fi - - echo "...done" - popd >/dev/null || return -} - -function lint() { - [[ "${2:-}" != "only" ]] && mod "$@" - local mapper="${1}" - - echo "fmt and linting mapper ${mapper}..." - - gofmt -s -w "${CURR_DIR}/" - golangci-lint run "${CURR_DIR}/..." - - echo "...done" -} - -function build() { - [[ "${2:-}" != "only" ]] && lint "$@" - local mapper="${1}" - - local flags=" -w -s " - local ext_flags=" -extldflags '-static' " - local os="${OS:-$(go env GOOS)}" - local arch="${ARCH:-$(go env GOARCH)}" - - local platform - if [[ "${ARM:-false}" == "true" ]]; then - echo "crossed packaging for linux/arm" - platform=("linux/arm") - elif [[ "${ARM64:-false}" == "true" ]]; then - echo "crossed packaging for linux/arm64" - platform=("linux/arm64") - else - local os="${OS:-$(go env GOOS)}" - local arch="${ARCH:-$(go env GOARCH)}" - platform=("${os}/${arch}") - fi - - echo "building ${platform}" - - local os_arch - IFS="/" read -r -a os_arch <<<"${platform}" - local os=${os_arch[0]} - local arch=${os_arch[1]} - GOOS=${os} GOARCH=${arch} CGO_ENABLED=0 go build \ - -ldflags "${flags} ${ext_flags}" \ - -o "${CURR_DIR}/bin/${mapper}_${os}_${arch}" \ - "${CURR_DIR}/cmd/main.go" - - cp ${CURR_DIR}/bin/${mapper}_${os}_${arch} ${CURR_DIR}/bin/${mapper} - echo "...done" -} - -function package() { - [[ "${2:-}" != "only" ]] && build "$@" - local mapper="${1}" - - echo "packaging mapper ${mapper}..." - - local image_name="${mapper}-mapper" - local tag=v1.0 - - local platform - if [[ "${ARM:-false}" == "true" ]]; then - echo "crossed packaging for linux/arm" - platform=("linux/arm") - elif [[ "${ARM64:-false}" == "true" ]]; then - echo "crossed packaging for linux/arm64" - platform=("linux/arm64") - else - local os="${OS:-$(go env GOOS)}" - local arch="${ARCH:-$(go env GOARCH)}" - platform=("${os}/${arch}") - fi - - pushd "${CURR_DIR}" >/dev/null 2>&1 - if [[ "${platform}" =~ darwin/* ]]; then - echo "package into Darwin OS image is unavailable, please use CROSS=true env to containerize multiple arch images or use OS=linux ARCH=amd64 env to containerize linux/amd64 image" - fi - - local image_tag="${image_name}:${tag}-${platform////-}" - echo "packaging ${image_tag}" - sudo docker build \ - --platform "${platform}" \ - -t "${image_tag}" . - popd >/dev/null 2>&1 - - echo "...done" -} - -function test() { - [[ "${2:-}" != "only" ]] && build "$@" - local mapper="${1}" - - echo "running unit tests for mapper ${mapper}..." - - local unit_test_targets=( - "${CURR_DIR}/config/..." - "${CURR_DIR}/configmap/..." - "${CURR_DIR}/device/..." - "${CURR_DIR}/driver/..." - ) - - local os="${OS:-$(go env GOOS)}" - local arch="${ARCH:-$(go env GOARCH)}" - if [[ "${arch}" == "arm" ]]; then - # NB(thxCode): race detector doesn't support `arm` arch, ref to: - # - https://golang.org/doc/articles/race_detector.html#Supported_Systems - GOOS=${os} GOARCH=${arch} CGO_ENABLED=1 go test \ - -cover -coverprofile "${CURR_DIR}/dist/coverage_${mapper}_${os}_${arch}.out" \ - "${unit_test_targets[@]}" - else - GOOS=${os} GOARCH=${arch} CGO_ENABLED=1 go test \ - -race \ - -cover -coverprofile "${CURR_DIR}/dist/coverage_${mapper}_${os}_${arch}.out" \ - "${unit_test_targets[@]}" - fi - - echo "...done" -} - -function clean() { - local mapper="${1}" - - echo "cleanup mapper ${mapper}..." - - rm -rf "${CURR_DIR}/bin/*" - - echo "...done" -} - -function entry() { - local mapper="${1:-}" - shift 1 - - local stages="${1:-build}" - shift $(($# > 0 ? 1 : 0)) - - IFS="," read -r -a stages <<<"${stages}" - local commands=$* - if [[ ${#stages[@]} -ne 1 ]]; then - commands="only" - fi - - for stage in "${stages[@]}"; do - echo "# make mapper ${mapper} ${stage} ${commands}" - case ${stage} in - m | mod) mod "${mapper}" "${commands}" ;; - l | lint) lint "${mapper}" "${commands}" ;; - b | build) build "${mapper}" "${commands}" ;; - p | pkg | package) package "${mapper}" "${commands}" ;; - t | test) test "${mapper}" "${commands}" ;; - c | clean) clean "${mapper}" "${commands}" ;; - *) echo "unknown action '${stage}', select from mod,lint,build,test,clean" ;; - esac - done -} - -echo $@ -entry "$@" diff --git a/_template/mapper-sdk/res/config.yaml b/_template/mapper-sdk/res/config.yaml deleted file mode 100644 index 3b5675f0..00000000 --- a/_template/mapper-sdk/res/config.yaml +++ /dev/null @@ -1,14 +0,0 @@ -mqtt: - server: mqtt://127.0.0.1:1883 # mqtt's ip:port - servername: 127.0.0.1 # server's ip - username: "" - password: "" - clientId: "" - certification: "" - privatekey: "" - caCert: "" -http: - certification: "" - privatekey: "" - caCert: "" -configmap: /opt/kubeedge/deviceProfile.json diff --git a/_template/mapper/Dockerfile b/_template/mapper/Dockerfile deleted file mode 100644 index 0e29f579..00000000 --- a/_template/mapper/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ - -FROM ubuntu:16.04 - -RUN mkdir -p kubeedge - -COPY ./bin/Template kubeedge/ -COPY ./config.yaml kubeedge/ - -WORKDIR kubeedge - -ENTRYPOINT ["/kubeedge/Template", "--v", "5"] diff --git a/_template/mapper/Makefile b/_template/mapper/Makefile deleted file mode 100644 index a266fedd..00000000 --- a/_template/mapper/Makefile +++ /dev/null @@ -1,36 +0,0 @@ -SHELL := /bin/bash - -curr_dir := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST))))) -rest_args := $(wordlist 2, $(words $(MAKECMDGOALS)), $(MAKECMDGOALS)) -$(eval $(rest_args):;@:) - -help: - # - # Usage: - # make template : create a mapper based on a template. - # make mapper {mapper-name} : execute mapper building process. - # make all : execute building process to all mappers. - # - # Actions: - # - mod, m : download code dependencies. - # - lint, l : verify code via go fmt and `golangci-lint`. - # - build, b : compile code. - # - package, p : package docker image. - # - test, t : run unit tests. - # - clean, c : clean output binary. - # - # Parameters: - # ARM : true or undefined - # ARM64 : true or undefined - # - # Example: - # - make mapper modbus ARM64=true : execute `build` "modbus" mapper for ARM64. - # - make mapper modbus test : execute `test` "modbus" mapper. - @echo - -make_rules := $(shell ls $(curr_dir)/hack/make-rules | sed 's/.sh//g') -$(make_rules): - @$(curr_dir)/hack/make-rules/$@.sh $(rest_args) - -.DEFAULT_GOAL := help -.PHONY: $(make_rules) build test package diff --git a/_template/mapper/cmd/main.go b/_template/mapper/cmd/main.go deleted file mode 100644 index 67501aca..00000000 --- a/_template/mapper/cmd/main.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright 2021 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package main - -import ( - "os" - - "k8s.io/klog/v2" - - "github.com/kubeedge/mappers-go/mappers/Template/config" - "github.com/kubeedge/mappers-go/mappers/Template/device" - "github.com/kubeedge/mappers-go/mappers/Template/globals" - "github.com/kubeedge/mappers-go/mappers/common" -) - -func main() { - var err error - var c config.Config - - klog.InitFlags(nil) - defer klog.Flush() - - if err = c.Parse(); err != nil { - klog.Fatal(err) - os.Exit(1) - } - klog.V(4).Info(c.Configmap) - - globals.MqttClient = common.MqttClient{IP: c.Mqtt.ServerAddress, - User: c.Mqtt.Username, - Passwd: c.Mqtt.Password, - Cert: c.Mqtt.Cert, - PrivateKey: c.Mqtt.PrivateKey} - if err = globals.MqttClient.Connect(); err != nil { - klog.Fatal(err) - os.Exit(1) - } - - if err = device.DevInit(c.Configmap); err != nil { - klog.Fatal(err) - os.Exit(1) - } - device.DevStart() -} diff --git a/_template/mapper/config.yaml b/_template/mapper/config.yaml deleted file mode 100644 index 1216a2c2..00000000 --- a/_template/mapper/config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -mqtt: - server: tcp://127.0.0.1:1883 - username: "" - password: "" - certification: "" - privatekey: "" -configmap: /opt/kubeedge/deviceProfile.json diff --git a/_template/mapper/config/config.go b/_template/mapper/config/config.go deleted file mode 100644 index b949ddf8..00000000 --- a/_template/mapper/config/config.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2021 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package config - -import ( - "errors" - "io/ioutil" - - "github.com/spf13/pflag" - "gopkg.in/yaml.v2" - "k8s.io/klog/v2" -) - -// Config is the Template mapper configuration. -type Config struct { - Mqtt Mqtt `yaml:"mqtt,omitempty"` - Configmap string `yaml:"configmap"` -} - -// Mqtt is the Mqtt configuration. -type Mqtt struct { - ServerAddress string `yaml:"server,omitempty"` - Username string `yaml:"username,omitempty"` - Password string `yaml:"password,omitempty"` - Cert string `yaml:"certification,omitempty"` - PrivateKey string `yaml:"privatekey,omitempty"` -} - -// ErrConfigCert error of certification configuration. -var ErrConfigCert = errors.New("Both certification and private key must be provided") - -var defaultConfigFile = "./config.yaml" - -// Parse parse the configuration file. If failed, return error. -func (c *Config) Parse() error { - var level klog.Level - var loglevel string - var configFile string - - pflag.StringVar(&loglevel, "v", "1", "log level") - pflag.StringVar(&configFile, "config-file", defaultConfigFile, "Config file name") - pflag.Parse() - cf, err := ioutil.ReadFile(configFile) - if err != nil { - return err - } - if err = yaml.Unmarshal(cf, c); err != nil { - return err - } - if err = level.Set(loglevel); err != nil { - return err - } - - return c.parseFlags() -} - -// parseFlags parse flags. Certification and Private key must be provided at the same time. -func (c *Config) parseFlags() error { - pflag.StringVar(&c.Mqtt.ServerAddress, "mqtt-address", c.Mqtt.ServerAddress, "MQTT broker address") - pflag.StringVar(&c.Mqtt.Username, "mqtt-username", c.Mqtt.Username, "username") - pflag.StringVar(&c.Mqtt.Password, "mqtt-password", c.Mqtt.Password, "password") - pflag.StringVar(&c.Mqtt.Cert, "mqtt-certification", c.Mqtt.Cert, "certification file path") - pflag.StringVar(&c.Mqtt.PrivateKey, "mqtt-priviatekey", c.Mqtt.PrivateKey, "private key file path") - pflag.Parse() - - if (c.Mqtt.Cert != "" && c.Mqtt.PrivateKey == "") || - (c.Mqtt.Cert == "" && c.Mqtt.PrivateKey != "") { - return ErrConfigCert - } - return nil -} diff --git a/_template/mapper/config/config.yaml b/_template/mapper/config/config.yaml deleted file mode 100644 index 1216a2c2..00000000 --- a/_template/mapper/config/config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -mqtt: - server: tcp://127.0.0.1:1883 - username: "" - password: "" - certification: "" - privatekey: "" -configmap: /opt/kubeedge/deviceProfile.json diff --git a/_template/mapper/config/config_test.go b/_template/mapper/config/config_test.go deleted file mode 100644 index 77336e68..00000000 --- a/_template/mapper/config/config_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package config - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestParse(t *testing.T) { - config := Config{} - if err := config.Parse(); err != nil { - t.Log(err) - t.FailNow() - } - - assert.Equal(t, "tcp://127.0.0.1:1883", config.Mqtt.ServerAddress) - assert.Equal(t, "/opt/kubeedge/deviceProfile.json", config.Configmap) -} diff --git a/_template/mapper/configmap/configmap_negtest.json b/_template/mapper/configmap/configmap_negtest.json deleted file mode 100644 index f7342b39..00000000 --- a/_template/mapper/configmap/configmap_negtest.json +++ /dev/null @@ -1,90 +0,0 @@ - - "deviceInstances": [{ - "id": "sensor-tag-instance-01", - "name": "sensor-tag-instance-01", - "protocol": "Template-sensor-tag-instance-01", - "model": "sensor-tag-model", - "twins": [{ - "propertyName": "temperature-enable", - "desired": { - "value": "OFF", - "metadata": { - "timestamp": "1550049403598", - "type": "string" - } - }, - "reported": { - "value": "OFF", - "metadata": { - "timestamp": "1550049403598", - "type": "string" - } - } - }], - "propertyVisitors": [{ - "name": "temperature", - "propertyName": "temperature", - "modelName": "sensor-tag-model", - "protocol": "Template", - "visitorConfig": { - "register": "CoilRegister", - "offset": 2, - "limit": 1, - "scale": 1, - "isSwap": true, - "isRegisterSwap": true - } - }, { - "name": "temperature-enable", - "propertyName": "temperature-enable", - "modelName": "sensor-tag-model", - "protocol": "Template", - "visitorConfig": { - "register": "DiscreteInputRegister", - "offset": 3, - "limit": 1, - "scale": 1, - "isSwap": true, - "isRegisterSwap": true - } - }] - }], - "deviceModels": [{ - "name": "sensor-tag-model", - "properties": [{ - "name": "temperature", - "dataType": "int", - "description": "temperature in degree celsius", - "accessMode": "ReadWrite", - "defaultValue": 0, - "minimum": 0, - "maximum": 100, - "unit": "degree celsius" - }, { - "name": "temperature-enable", - "dataType": "string", - "description": "enable data collection of temperature sensor", - "accessMode": "ReadWrite", - "defaultValue": "OFF" - }] - }], - "protocols": [{ - "name": "Template-sensor-tag-instance-01", - "protocol": "Template", - "protocolConfig": { - "slaveID": 1 - }, - "protocolCommonConfig": { - "com": { - "serialPort": "1", - "baudRate": 115200, - "dataBits": 8, - "parity": "even", - "stopBits": 1 - }, - "customizedValues": { - "serialType": "RS485" - } - } - }] -} diff --git a/_template/mapper/configmap/configmap_test.json b/_template/mapper/configmap/configmap_test.json deleted file mode 100644 index ed71be2a..00000000 --- a/_template/mapper/configmap/configmap_test.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "deviceInstances": [{ - "id": "sensor-tag-instance-01", - "name": "sensor-tag-instance-01", - "protocol": "Template-sensor-tag-instance-01", - "model": "sensor-tag-model", - "twins": [{ - "propertyName": "temperature-enable", - "desired": { - "value": "OFF", - "metadata": { - "timestamp": "1550049403598", - "type": "string" - } - }, - "reported": { - "value": "OFF", - "metadata": { - "timestamp": "1550049403598", - "type": "string" - } - } - }], - "propertyVisitors": [{ - "name": "temperature", - "propertyName": "temperature", - "modelName": "sensor-tag-model", - "protocol": "Template", - "visitorConfig": { - } - }, { - "name": "temperature-enable", - "propertyName": "temperature-enable", - "modelName": "sensor-tag-model", - "protocol": "Template", - "visitorConfig": { - } - }] - }], - "deviceModels": [{ - "name": "sensor-tag-model", - "properties": [{ - "name": "temperature", - "dataType": "int", - "description": "temperature in degree celsius", - "accessMode": "ReadWrite", - "defaultValue": 0, - "minimum": 0, - "maximum": 100, - "unit": "degree celsius" - }, { - "name": "temperature-enable", - "dataType": "string", - "description": "enable data collection of temperature sensor", - "accessMode": "ReadWrite", - "defaultValue": "OFF" - }] - }], - "protocols": [{ - "name": "Template-sensor-tag-instance-01", - "protocol": "Template", - "protocolConfig": { - "slaveID": 1 - }, - "protocolCommonConfig": { - } - }] -} diff --git a/_template/mapper/configmap/parse.go b/_template/mapper/configmap/parse.go deleted file mode 100644 index 41ef0801..00000000 --- a/_template/mapper/configmap/parse.go +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright 2021 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package configmap - -import ( - "encoding/json" - "errors" - "io/ioutil" - - "k8s.io/klog/v2" - - "github.com/kubeedge/mappers-go/mappers/Template/globals" - "github.com/kubeedge/mappers-go/mappers/common" -) - -// Parse parse the configmap. -func Parse(path string, - devices map[string]*globals.TemplateDev, - dms map[string]common.DeviceModel, - protocols map[string]common.Protocol) error { - var deviceProfile common.DeviceProfile - - jsonFile, err := ioutil.ReadFile(path) - if err != nil { - return err - } - - if err = json.Unmarshal(jsonFile, &deviceProfile); err != nil { - return err - } - - for i := 0; i < len(deviceProfile.DeviceInstances); i++ { - instance := deviceProfile.DeviceInstances[i] - j := 0 - for j = 0; j < len(deviceProfile.Protocols); j++ { - if instance.ProtocolName == deviceProfile.Protocols[j].Name { - instance.PProtocol = deviceProfile.Protocols[j] - break - } - } - if j == len(deviceProfile.Protocols) { - err = errors.New("Protocol not found") - return err - } - - if instance.PProtocol.Protocol != "customized-protocol" { - continue - } else { - cprotocol := struct { - ProtocolName string `json:"protocolName"` - ConfigData json.RawMessage - }{} - err = json.Unmarshal(instance.PProtocol.ProtocolConfigs, &cprotocol) - if err != nil { - klog.Error("customized-protocol unmarshal error:", err) - continue - } - if cprotocol.ProtocolName != "Template" { - continue - } - } - - for k := 0; k < len(instance.PropertyVisitors); k++ { - modelName := instance.PropertyVisitors[k].ModelName - propertyName := instance.PropertyVisitors[k].PropertyName - l := 0 - for l = 0; l < len(deviceProfile.DeviceModels); l++ { - if modelName == deviceProfile.DeviceModels[l].Name { - m := 0 - for m = 0; m < len(deviceProfile.DeviceModels[l].Properties); m++ { - if propertyName == deviceProfile.DeviceModels[l].Properties[m].Name { - instance.PropertyVisitors[k].PProperty = deviceProfile.DeviceModels[l].Properties[m] - break - } - } - - if m == len(deviceProfile.DeviceModels[l].Properties) { - err = errors.New("Property not found") - return err - } - break - } - } - if l == len(deviceProfile.DeviceModels) { - err = errors.New("Device model not found") - return err - } - } - - for k := 0; k < len(instance.Twins); k++ { - name := instance.Twins[k].PropertyName - l := 0 - for l = 0; l < len(instance.PropertyVisitors); l++ { - if name == instance.PropertyVisitors[l].PropertyName { - instance.Twins[k].PVisitor = &instance.PropertyVisitors[l] - break - } - } - if l == len(instance.PropertyVisitors) { - return errors.New("PropertyVisitor not found") - } - } - - for k := 0; k < len(instance.Datas.Properties); k++ { - name := instance.Datas.Properties[k].PropertyName - l := 0 - for l = 0; l < len(instance.PropertyVisitors); l++ { - if name == instance.PropertyVisitors[l].PropertyName { - instance.Datas.Properties[k].PVisitor = &instance.PropertyVisitors[l] - break - } - } - if l == len(instance.PropertyVisitors) { - return errors.New("PropertyVisitor not found") - } - } - - devices[instance.ID] = new(globals.TemplateDev) - devices[instance.ID].Instance = instance - klog.V(4).Info("Instance: ", instance.ID, instance) - } - - for i := 0; i < len(deviceProfile.DeviceModels); i++ { - dms[deviceProfile.DeviceModels[i].Name] = deviceProfile.DeviceModels[i] - } - - for i := 0; i < len(deviceProfile.Protocols); i++ { - protocols[deviceProfile.Protocols[i].Name] = deviceProfile.Protocols[i] - } - return nil -} diff --git a/_template/mapper/configmap/parse_test.go b/_template/mapper/configmap/parse_test.go deleted file mode 100644 index 39990cf1..00000000 --- a/_template/mapper/configmap/parse_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package configmap - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/kubeedge/mappers-go/mappers/Template/globals" - "github.com/kubeedge/mappers-go/mappers/common" -) - -func TestParse(t *testing.T) { - var devices map[string]*globals.TemplateDev - var models map[string]common.DeviceModel - var protocols map[string]common.Protocol - - devices = make(map[string]*globals.TemplateDev) - models = make(map[string]common.DeviceModel) - protocols = make(map[string]common.Protocol) - - assert.Nil(t, Parse("./configmap_test.json", devices, models, protocols)) -} - -func TestParseNeg(t *testing.T) { - var devices map[string]*globals.TemplateDev - var models map[string]common.DeviceModel - var protocols map[string]common.Protocol - - devices = make(map[string]*globals.TemplateDev) - models = make(map[string]common.DeviceModel) - protocols = make(map[string]common.Protocol) - - assert.NotNil(t, Parse("./configmap_negtest.json", devices, models, protocols)) -} diff --git a/_template/mapper/configmap/type.go b/_template/mapper/configmap/type.go deleted file mode 100644 index f485c54a..00000000 --- a/_template/mapper/configmap/type.go +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright 2021 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package configmap - -// TemplateVisitorConfig is the Template register configuration. -type TemplateVisitorConfig struct { -} - -// TemplateProtocolConfig is the protocol configuration. -type TemplateProtocolConfig struct { -} - -// TemplateProtocolCommonConfig is the Template protocol configuration. -type TemplateProtocolCommonConfig struct { -} - -// CustomizedValue is the customized part for Template protocol. -type CustomizedValue map[string]interface{} diff --git a/_template/mapper/deployment.yaml b/_template/mapper/deployment.yaml deleted file mode 100644 index afaacc14..00000000 --- a/_template/mapper/deployment.yaml +++ /dev/null @@ -1,31 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: Template-mapper -spec: - replicas: 1 - selector: - matchLabels: - app: Templatemapper - template: - metadata: - labels: - app: Templatemapper - spec: - hostNetwork: true - containers: - - name: Template-mapper-container - image: Templatemapper:v1.0 - imagePullPolicy: IfNotPresent - securityContext: - privileged: true - volumeMounts: - - name: config-volume - mountPath: /opt/kubeedge/ - nodeSelector: - Template: "true" - volumes: - - name: config-volume - configMap: - name: device-profile-config-test - restartPolicy: Always diff --git a/_template/mapper/device/device.go b/_template/mapper/device/device.go deleted file mode 100644 index d8c4091e..00000000 --- a/_template/mapper/device/device.go +++ /dev/null @@ -1,242 +0,0 @@ -/* -Copyright 2021 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/* -* TODO: This file is to control the devices. Please refine the configurations and -* reading/writing functions. - */ -package device - -import ( - "encoding/json" - "fmt" - "regexp" - "sync" - "time" - - mqtt "github.com/eclipse/paho.mqtt.golang" - "k8s.io/klog/v2" - - "github.com/kubeedge/mappers-go/mappers/Template/configmap" - "github.com/kubeedge/mappers-go/mappers/Template/driver" - "github.com/kubeedge/mappers-go/mappers/Template/globals" - "github.com/kubeedge/mappers-go/mappers/common" -) - -var devices map[string]*globals.TemplateDev -var models map[string]common.DeviceModel -var protocols map[string]common.Protocol -var wg sync.WaitGroup - -// setVisitor check if visitory property is readonly, if not then set it. -func setVisitor(visitorConfig *configmap.TemplateVisitorConfig, twin *common.Twin, client *driver.TemplateClient) { - if twin.PVisitor.PProperty.AccessMode == "ReadOnly" { - return - } - - // TODO - _, err := client.Set() - if err != nil { - klog.Errorf("Set error: %v, %v", err, visitorConfig) - return - } -} - -// getDeviceID extract the device ID from Mqtt topic. -func getDeviceID(topic string) (id string) { - re := regexp.MustCompile(`hw/events/device/(.+)/twin/update/delta`) - return re.FindStringSubmatch(topic)[1] -} - -// onMessage callback function of Mqtt subscribe message. -func onMessage(client mqtt.Client, message mqtt.Message) { - klog.V(2).Info("Receive message", message.Topic()) - // Get device ID and get device instance - id := getDeviceID(message.Topic()) - if id == "" { - klog.Error("Wrong topic") - return - } - klog.V(2).Info("Device id: ", id) - - var dev *globals.TemplateDev - var ok bool - if dev, ok = devices[id]; !ok { - klog.Error("Device not exist") - return - } - - // Get twin map key as the propertyName - var delta common.DeviceTwinDelta - if err := json.Unmarshal(message.Payload(), &delta); err != nil { - klog.Errorf("Unmarshal message failed: %v", err) - return - } - for twinName, twinValue := range delta.Delta { - i := 0 - for i = 0; i < len(dev.Instance.Twins); i++ { - if twinName == dev.Instance.Twins[i].PropertyName { - break - } - } - if i == len(dev.Instance.Twins) { - klog.Error("Twin not found: ", twinName) - continue - } - // Desired value is not changed. - if dev.Instance.Twins[i].Desired.Value == twinValue { - continue - } - dev.Instance.Twins[i].Desired.Value = twinValue - var visitorConfig configmap.TemplateVisitorConfig - if err := json.Unmarshal([]byte(dev.Instance.Twins[i].PVisitor.VisitorConfig), &visitorConfig); err != nil { - klog.Errorf("Unmarshal VisitorConfig error: %v", err) - } - setVisitor(&visitorConfig, &dev.Instance.Twins[i], dev.TemplateClient) - } -} - -// initTemplate initialize Template client. -func initTemplate(protocolConfig configmap.TemplateProtocolCommonConfig) (client *driver.TemplateClient, err error) { - // TODO: pass the configuration to the client. - config := driver.TemplateConfig{} - client, _ = driver.NewClient(config) - return client, nil -} - -// initTwin initialize the timer to get twin value. -func initTwin(dev *globals.TemplateDev) { - for i := 0; i < len(dev.Instance.Twins); i++ { - var visitorConfig configmap.TemplateVisitorConfig - if err := json.Unmarshal([]byte(dev.Instance.Twins[i].PVisitor.VisitorConfig), &visitorConfig); err != nil { - klog.Errorf("Unmarshal VisitorConfig error: %v", err) - continue - } - setVisitor(&visitorConfig, &dev.Instance.Twins[i], dev.TemplateClient) - - // TODO: pass the twin values to the timer. - twinData := TwinData{Client: dev.TemplateClient, - Name: dev.Instance.Twins[i].PropertyName, - Type: dev.Instance.Twins[i].Desired.Metadatas.Type, - Topic: fmt.Sprintf(common.TopicTwinUpdate, dev.Instance.ID)} - collectCycle := time.Duration(dev.Instance.Twins[i].PVisitor.CollectCycle) - // If the collect cycle is not set, set it to 1 second. - if collectCycle == 0 { - collectCycle = 1 * time.Second - } - timer := common.Timer{Function: twinData.Run, Duration: collectCycle, Times: 0} - wg.Add(1) - go func() { - defer wg.Done() - timer.Start() - }() - } -} - -// initData initialize the timer to get data. -func initData(dev *globals.TemplateDev) { - for i := 0; i < len(dev.Instance.Datas.Properties); i++ { - var visitorConfig configmap.TemplateVisitorConfig - if err := json.Unmarshal([]byte(dev.Instance.Datas.Properties[i].PVisitor.VisitorConfig), &visitorConfig); err != nil { - klog.Errorf("Unmarshal VisitorConfig error: %v", err) - } - - // TODO: pass the data values to the timer. - twinData := TwinData{Client: dev.TemplateClient, - Name: dev.Instance.Datas.Properties[i].PropertyName, - Type: dev.Instance.Datas.Properties[i].Metadatas.Type, - Topic: fmt.Sprintf(common.TopicDataUpdate, dev.Instance.ID)} - collectCycle := time.Duration(dev.Instance.Datas.Properties[i].PVisitor.CollectCycle) - // If the collect cycle is not set, set it to 1 second. - if collectCycle == 0 { - collectCycle = 1 * time.Second - } - timer := common.Timer{Function: twinData.Run, Duration: collectCycle, Times: 0} - wg.Add(1) - go func() { - defer wg.Done() - timer.Start() - }() - } -} - -// initSubscribeMqtt subscribe Mqtt topics. -func initSubscribeMqtt(instanceID string) error { - topic := fmt.Sprintf(common.TopicTwinUpdateDelta, instanceID) - klog.V(1).Info("Subscribe topic: ", topic) - return globals.MqttClient.Subscribe(topic, onMessage) -} - -// initGetStatus start timer to get device status and send to eventbus. -func initGetStatus(dev *globals.TemplateDev) { - getStatus := GetStatus{Client: dev.TemplateClient, - topic: fmt.Sprintf(common.TopicStateUpdate, dev.Instance.ID)} - timer := common.Timer{Function: getStatus.Run, Duration: 1 * time.Second, Times: 0} - wg.Add(1) - go func() { - defer wg.Done() - timer.Start() - }() -} - -// start start the device. -func start(dev *globals.TemplateDev) { - var protocolCommConfig configmap.TemplateProtocolCommonConfig - if err := json.Unmarshal([]byte(dev.Instance.PProtocol.ProtocolCommonConfig), &protocolCommConfig); err != nil { - klog.Errorf("Unmarshal ProtocolCommonConfig error: %v", err) - return - } - - var protocolConfig configmap.TemplateProtocolConfig - if err := json.Unmarshal([]byte(dev.Instance.PProtocol.ProtocolConfigs), &protocolConfig); err != nil { - klog.Errorf("Unmarshal ProtocolConfig error: %v", err) - return - } - - client, err := initTemplate(protocolCommConfig) - if err != nil { - klog.Errorf("Init error: %v", err) - return - } - dev.TemplateClient = client - - initTwin(dev) - initData(dev) - - if err := initSubscribeMqtt(dev.Instance.ID); err != nil { - klog.Errorf("Init subscribe mqtt error: %v", err) - return - } - - initGetStatus(dev) -} - -// DevInit initialize the device datas. -func DevInit(configmapPath string) error { - devices = make(map[string]*globals.TemplateDev) - models = make(map[string]common.DeviceModel) - protocols = make(map[string]common.Protocol) - return configmap.Parse(configmapPath, devices, models, protocols) -} - -// DevStart start all devices. -func DevStart() { - for id, dev := range devices { - klog.V(4).Info("Dev: ", id, dev) - start(dev) - } - wg.Wait() -} diff --git a/_template/mapper/device/devstatus.go b/_template/mapper/device/devstatus.go deleted file mode 100644 index ded9886a..00000000 --- a/_template/mapper/device/devstatus.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright 2021 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package device - -import ( - "k8s.io/klog/v2" - - "github.com/kubeedge/mappers-go/mappers/Template/driver" - "github.com/kubeedge/mappers-go/mappers/Template/globals" - "github.com/kubeedge/mappers-go/mappers/common" -) - -// GetStatus is the timer structure for getting device status. -type GetStatus struct { - Client *driver.TemplateClient - Status string - topic string -} - -// Run timer function. -func (gs *GetStatus) Run() { - gs.Status = gs.Client.GetStatus() - - var payload []byte - var err error - if payload, err = common.CreateMessageState(gs.Status); err != nil { - klog.Errorf("Create message state failed: %v", err) - return - } - if err = globals.MqttClient.Publish(gs.topic, payload); err != nil { - klog.Errorf("Publish failed: %v", err) - return - } -} diff --git a/_template/mapper/device/twindata.go b/_template/mapper/device/twindata.go deleted file mode 100644 index 5c6254a7..00000000 --- a/_template/mapper/device/twindata.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright 2021 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package device - -import ( - "strings" - - "k8s.io/klog/v2" - - "github.com/kubeedge/mappers-go/mappers/Template/driver" - "github.com/kubeedge/mappers-go/mappers/Template/globals" - "github.com/kubeedge/mappers-go/mappers/common" -) - -// TwinData is the timer structure for getting twin/data. -type TwinData struct { - Client *driver.TemplateClient - Name string - Type string - // TODO: add visiting parameters like register address, visiting count. - Results []byte - Topic string -} - -// Run timer function. -func (td *TwinData) Run() { - var err error - td.Results, err = td.Client.Get() - if err != nil { - klog.Errorf("Get register failed: %v", err) - return - } - // construct payload - var payload []byte - if strings.Contains(td.Topic, "$hw") { - // TODO: send the data as required. - if payload, err = common.CreateMessageTwinUpdate(td.Name, td.Type, string(td.Results)); err != nil { - klog.Errorf("Create message twin update failed: %v", err) - return - } - } else { - if payload, err = common.CreateMessageData(td.Name, td.Type, string(td.Results)); err != nil { - klog.Errorf("Create message data failed: %v", err) - return - } - } - if err = globals.MqttClient.Publish(td.Topic, payload); err != nil { - klog.Errorf("Publish topic %v failed, err: %v", td.Topic, err) - } - - klog.V(2).Infof("Update value: %s, topic: %s", string(td.Results), td.Topic) -} diff --git a/_template/mapper/driver/client.go b/_template/mapper/driver/client.go deleted file mode 100644 index 32661efa..00000000 --- a/_template/mapper/driver/client.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright 2021 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/* -* TODO: This file is for device visit like read, write and get status. -* Please refine those functions. - */ - -package driver - -import ( - "k8s.io/klog/v2" - - "github.com/kubeedge/mappers-go/mappers/common" -) - -// TemplateConfig is the structure for client configuration. -type TemplateConfig struct { -} - -// TemplateClient is the structure for Template client. -type TemplateClient struct { - Client interface{} - Config TemplateConfig -} - -var clients map[string]*TemplateClient - -// NewClient allocate and return a Template client. -func NewClient(config interface{}) (*TemplateClient, error) { - return nil, nil -} - -// GetStatus get device status. -func (c *TemplateClient) GetStatus() string { - return common.DEVSTOK -} - -// Get get register. -func (c *TemplateClient) Get() (results []byte, err error) { - klog.V(2).Info("Get result: ", results) - return results, err -} - -// Set set register. -func (c *TemplateClient) Set() (results []byte, err error) { - klog.V(1).Info("Set result:", err, results) - return results, err -} diff --git a/_template/mapper/globals/globals.go b/_template/mapper/globals/globals.go deleted file mode 100644 index 25338021..00000000 --- a/_template/mapper/globals/globals.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2021 The KubeEdge Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package globals - -import ( - "github.com/kubeedge/mappers-go/mappers/Template/driver" - "github.com/kubeedge/mappers-go/mappers/common" -) - -// TemplateDev is the Template device configuration and client information. -type TemplateDev struct { - Instance common.DeviceInstance - TemplateClient *driver.TemplateClient -} - -var MqttClient common.MqttClient diff --git a/_template/mapper/hack/make-rules/mapper.sh b/_template/mapper/hack/make-rules/mapper.sh deleted file mode 100755 index 74715aa0..00000000 --- a/_template/mapper/hack/make-rules/mapper.sh +++ /dev/null @@ -1,190 +0,0 @@ -#!/usr/bin/env bash - -set -o errexit -set -o nounset -set -o pipefail - -CURR_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" -ROOT_DIR="$(cd "${CURR_DIR}/../.." && pwd -P)" -source "${ROOT_DIR}/hack/lib/init.sh" - -mkdir -p "${CURR_DIR}/bin" -mkdir -p "${CURR_DIR}/dist" - -function mod() { - [[ "${2:-}" != "only" ]] - local mapper="${1}" - - # the mapper is sharing the vendor with root - pushd "${ROOT_DIR}" >/dev/null || exist 1 - echo "downloading dependencies for mapper ${mapper}..." - - if [[ "$(go env GO111MODULE)" == "off" ]]; then - echo "go mod has been disabled by GO111MODULE=off" - else - echo "tidying" - go mod tidy - echo "vending" - go mod vendor - fi - - echo "...done" - popd >/dev/null || return -} - -function lint() { - [[ "${2:-}" != "only" ]] && mod "$@" - local mapper="${1}" - - echo "fmt and linting mapper ${mapper}..." - - gofmt -s -w "${CURR_DIR}/" - golangci-lint run "${CURR_DIR}/..." - - echo "...done" -} - -function build() { - [[ "${2:-}" != "only" ]] && lint "$@" - local mapper="${1}" - - local flags=" -w -s " - local ext_flags=" -extldflags '-static' " - local os="${OS:-$(go env GOOS)}" - local arch="${ARCH:-$(go env GOARCH)}" - - local platform - if [[ "${ARM:-false}" == "true" ]]; then - echo "crossed packaging for linux/arm" - platform=("linux/arm") - elif [[ "${ARM64:-false}" == "true" ]]; then - echo "crossed packaging for linux/arm64" - platform=("linux/arm64") - else - local os="${OS:-$(go env GOOS)}" - local arch="${ARCH:-$(go env GOARCH)}" - platform=("${os}/${arch}") - fi - - echo "building ${platform}" - - local os_arch - IFS="/" read -r -a os_arch <<<"${platform}" - local os=${os_arch[0]} - local arch=${os_arch[1]} - GOOS=${os} GOARCH=${arch} CGO_ENABLED=0 go build \ - -ldflags "${flags} ${ext_flags}" \ - -o "${CURR_DIR}/bin/${mapper}_${os}_${arch}" \ - "${CURR_DIR}/cmd/main.go" - - cp ${CURR_DIR}/bin/${mapper}_${os}_${arch} ${CURR_DIR}/bin/${mapper} - echo "...done" -} - -function package() { - [[ "${2:-}" != "only" ]] && build "$@" - local mapper="${1}" - - echo "packaging mapper ${mapper}..." - - local image_name="${mapper}-mapper" - local tag=v1.0 - - local platform - if [[ "${ARM:-false}" == "true" ]]; then - echo "crossed packaging for linux/arm" - platform=("linux/arm") - elif [[ "${ARM64:-false}" == "true" ]]; then - echo "crossed packaging for linux/arm64" - platform=("linux/arm64") - else - local os="${OS:-$(go env GOOS)}" - local arch="${ARCH:-$(go env GOARCH)}" - platform=("${os}/${arch}") - fi - - pushd "${CURR_DIR}" >/dev/null 2>&1 - if [[ "${platform}" =~ darwin/* ]]; then - echo "package into Darwin OS image is unavailable, please use CROSS=true env to containerize multiple arch images or use OS=linux ARCH=amd64 env to containerize linux/amd64 image" - fi - - local image_tag="${image_name}:${tag}-${platform////-}" - echo "packaging ${image_tag}" - sudo docker build \ - --platform "${platform}" \ - -t "${image_tag}" . - popd >/dev/null 2>&1 - - echo "...done" -} - -function test() { - [[ "${2:-}" != "only" ]] && build "$@" - local mapper="${1}" - - echo "running unit tests for mapper ${mapper}..." - - local unit_test_targets=( - "${CURR_DIR}/config/..." - "${CURR_DIR}/configmap/..." - "${CURR_DIR}/device/..." - "${CURR_DIR}/driver/..." - ) - - local os="${OS:-$(go env GOOS)}" - local arch="${ARCH:-$(go env GOARCH)}" - if [[ "${arch}" == "arm" ]]; then - # NB(thxCode): race detector doesn't support `arm` arch, ref to: - # - https://golang.org/doc/articles/race_detector.html#Supported_Systems - GOOS=${os} GOARCH=${arch} CGO_ENABLED=1 go test \ - -cover -coverprofile "${CURR_DIR}/dist/coverage_${mapper}_${os}_${arch}.out" \ - "${unit_test_targets[@]}" - else - GOOS=${os} GOARCH=${arch} CGO_ENABLED=1 go test \ - -race \ - -cover -coverprofile "${CURR_DIR}/dist/coverage_${mapper}_${os}_${arch}.out" \ - "${unit_test_targets[@]}" - fi - - echo "...done" -} - -function clean() { - local mapper="${1}" - - echo "cleanup mapper ${mapper}..." - - rm -rf "${CURR_DIR}/bin/*" - - echo "...done" -} - -function entry() { - local mapper="${1:-}" - shift 1 - - local stages="${1:-build}" - shift $(($# > 0 ? 1 : 0)) - - IFS="," read -r -a stages <<<"${stages}" - local commands=$* - if [[ ${#stages[@]} -ne 1 ]]; then - commands="only" - fi - - for stage in "${stages[@]}"; do - echo "# make mapper ${mapper} ${stage} ${commands}" - case ${stage} in - m | mod) mod "${mapper}" "${commands}" ;; - l | lint) lint "${mapper}" "${commands}" ;; - b | build) build "${mapper}" "${commands}" ;; - p | pkg | package) package "${mapper}" "${commands}" ;; - t | test) test "${mapper}" "${commands}" ;; - c | clean) clean "${mapper}" "${commands}" ;; - *) echo "unknown action '${stage}', select from mod,lint,build,test,clean" ;; - esac - done -} - -echo $@ -entry "$@" diff --git a/config/config.go b/mappers/config/config.go similarity index 98% rename from config/config.go rename to mappers/config/config.go index 8086ba38..f67ac207 100644 --- a/config/config.go +++ b/mappers/config/config.go @@ -26,7 +26,7 @@ import ( "gopkg.in/yaml.v2" "k8s.io/klog/v2" - "github.com/kubeedge/mappers-go/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/common" ) // ErrConfigCert error of certification configuration. diff --git a/config/config.yaml b/mappers/config/config.yaml similarity index 100% rename from config/config.yaml rename to mappers/config/config.yaml diff --git a/config/config_test.go b/mappers/config/config_test.go similarity index 100% rename from config/config_test.go rename to mappers/config/config_test.go diff --git a/mappers/modbus-dmi/cmd/main.go b/mappers/modbus-dmi/cmd/main.go index b269c5c5..6ed57d9f 100644 --- a/mappers/modbus-dmi/cmd/main.go +++ b/mappers/modbus-dmi/cmd/main.go @@ -19,12 +19,12 @@ import ( "k8s.io/klog/v2" - "github.com/kubeedge/mappers-go/config" + "github.com/kubeedge/mappers-go/mappers/config" "github.com/kubeedge/mappers-go/mappers/modbus-dmi/device" - "github.com/kubeedge/mappers-go/pkg/common" - "github.com/kubeedge/mappers-go/pkg/grpcserver" - "github.com/kubeedge/mappers-go/pkg/util/grpcclient" - "github.com/kubeedge/mappers-go/pkg/util/parse" + "github.com/kubeedge/mappers-go/mappers/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/grpcserver" + "github.com/kubeedge/mappers-go/mappers/pkg/util/grpcclient" + "github.com/kubeedge/mappers-go/mappers/pkg/util/parse" ) func main() { diff --git a/mappers/modbus-dmi/device/device.go b/mappers/modbus-dmi/device/device.go index 657b5a48..c30bb0d8 100644 --- a/mappers/modbus-dmi/device/device.go +++ b/mappers/modbus-dmi/device/device.go @@ -28,10 +28,10 @@ import ( "k8s.io/klog/v2" - "github.com/kubeedge/mappers-go/config" - "github.com/kubeedge/mappers-go/pkg/common" - "github.com/kubeedge/mappers-go/pkg/driver/modbus" - "github.com/kubeedge/mappers-go/pkg/util/parse" + "github.com/kubeedge/mappers-go/mappers/config" + "github.com/kubeedge/mappers-go/mappers/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/driver/modbus" + "github.com/kubeedge/mappers-go/mappers/pkg/util/parse" ) type DevPanel struct { diff --git a/mappers/modbus-dmi/device/twindata.go b/mappers/modbus-dmi/device/twindata.go index b45cf1ac..0885f9f2 100644 --- a/mappers/modbus-dmi/device/twindata.go +++ b/mappers/modbus-dmi/device/twindata.go @@ -28,10 +28,10 @@ import ( "k8s.io/klog/v2" dmiapi "github.com/kubeedge/kubeedge/pkg/apis/dmi/v1alpha1" - "github.com/kubeedge/mappers-go/pkg/common" - "github.com/kubeedge/mappers-go/pkg/driver/modbus" - "github.com/kubeedge/mappers-go/pkg/util/grpcclient" - "github.com/kubeedge/mappers-go/pkg/util/parse" + "github.com/kubeedge/mappers-go/mappers/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/driver/modbus" + "github.com/kubeedge/mappers-go/mappers/pkg/util/grpcclient" + "github.com/kubeedge/mappers-go/mappers/pkg/util/parse" ) // TwinData is the timer structure for getting twin/data. diff --git a/pkg/common/configmaptype.go b/mappers/pkg/common/configmaptype.go similarity index 100% rename from pkg/common/configmaptype.go rename to mappers/pkg/common/configmaptype.go diff --git a/pkg/common/const.go b/mappers/pkg/common/const.go similarity index 100% rename from pkg/common/const.go rename to mappers/pkg/common/const.go diff --git a/pkg/common/data_converter.go b/mappers/pkg/common/data_converter.go similarity index 100% rename from pkg/common/data_converter.go rename to mappers/pkg/common/data_converter.go diff --git a/pkg/common/event.go b/mappers/pkg/common/event.go similarity index 100% rename from pkg/common/event.go rename to mappers/pkg/common/event.go diff --git a/pkg/common/event_test.go b/mappers/pkg/common/event_test.go similarity index 100% rename from pkg/common/event_test.go rename to mappers/pkg/common/event_test.go diff --git a/pkg/common/event_type.go b/mappers/pkg/common/event_type.go similarity index 100% rename from pkg/common/event_type.go rename to mappers/pkg/common/event_type.go diff --git a/pkg/common/timer.go b/mappers/pkg/common/timer.go similarity index 100% rename from pkg/common/timer.go rename to mappers/pkg/common/timer.go diff --git a/pkg/driver/modbus/client.go b/mappers/pkg/driver/modbus/client.go similarity index 98% rename from pkg/driver/modbus/client.go rename to mappers/pkg/driver/modbus/client.go index 22ace65a..b4c4bb52 100644 --- a/pkg/driver/modbus/client.go +++ b/mappers/pkg/driver/modbus/client.go @@ -23,7 +23,7 @@ import ( "k8s.io/klog/v2" - "github.com/kubeedge/mappers-go/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/common" "github.com/sailorvii/modbus" ) diff --git a/pkg/driver/modbus/client_test.go b/mappers/pkg/driver/modbus/client_test.go similarity index 98% rename from pkg/driver/modbus/client_test.go rename to mappers/pkg/driver/modbus/client_test.go index 268f6cca..43ce0335 100644 --- a/pkg/driver/modbus/client_test.go +++ b/mappers/pkg/driver/modbus/client_test.go @@ -32,7 +32,7 @@ import ( v12 "k8s.io/api/core/v1" "github.com/kubeedge/kubeedge/pkg/apis/devices/v1alpha2" - "github.com/kubeedge/mappers-go/pkg/util/parse" + "github.com/kubeedge/mappers-go/mappers/pkg/util/parse" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) diff --git a/pkg/driver/modbus/device_type.go b/mappers/pkg/driver/modbus/device_type.go similarity index 96% rename from pkg/driver/modbus/device_type.go rename to mappers/pkg/driver/modbus/device_type.go index 69c9f2a7..ac7417ff 100644 --- a/pkg/driver/modbus/device_type.go +++ b/mappers/pkg/driver/modbus/device_type.go @@ -1,7 +1,7 @@ package modbus import ( - "github.com/kubeedge/mappers-go/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/common" ) // ModbusDev is the modbus device configuration and client information. diff --git a/pkg/global/global.go b/mappers/pkg/global/global.go similarity index 84% rename from pkg/global/global.go rename to mappers/pkg/global/global.go index f6fbfced..4405a98a 100644 --- a/pkg/global/global.go +++ b/mappers/pkg/global/global.go @@ -1,8 +1,8 @@ package global import ( - "github.com/kubeedge/mappers-go/config" - "github.com/kubeedge/mappers-go/pkg/common" + "github.com/kubeedge/mappers-go/mappers/config" + "github.com/kubeedge/mappers-go/mappers/pkg/common" ) type DevPanel interface { diff --git a/pkg/grpcserver/device.go b/mappers/pkg/grpcserver/device.go similarity index 97% rename from pkg/grpcserver/device.go rename to mappers/pkg/grpcserver/device.go index e692f1a0..db0d9324 100644 --- a/pkg/grpcserver/device.go +++ b/mappers/pkg/grpcserver/device.go @@ -7,9 +7,9 @@ import ( "time" dmiapi "github.com/kubeedge/kubeedge/pkg/apis/dmi/v1alpha1" - "github.com/kubeedge/mappers-go/pkg/common" - "github.com/kubeedge/mappers-go/pkg/driver/modbus" - "github.com/kubeedge/mappers-go/pkg/util/parse" + "github.com/kubeedge/mappers-go/mappers/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/driver/modbus" + "github.com/kubeedge/mappers-go/mappers/pkg/util/parse" "k8s.io/klog/v2" ) diff --git a/pkg/grpcserver/server.go b/mappers/pkg/grpcserver/server.go similarity index 94% rename from pkg/grpcserver/server.go rename to mappers/pkg/grpcserver/server.go index fbb33f8f..589e3b36 100644 --- a/pkg/grpcserver/server.go +++ b/mappers/pkg/grpcserver/server.go @@ -11,8 +11,8 @@ import ( dmiapi "github.com/kubeedge/kubeedge/pkg/apis/dmi/v1alpha1" modbusdevice "github.com/kubeedge/mappers-go/mappers/modbus-dmi/device" - "github.com/kubeedge/mappers-go/pkg/common" - "github.com/kubeedge/mappers-go/pkg/global" + "github.com/kubeedge/mappers-go/mappers/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/global" ) type Config struct { diff --git a/pkg/grpcserver/upstream.go b/mappers/pkg/grpcserver/upstream.go similarity index 93% rename from pkg/grpcserver/upstream.go rename to mappers/pkg/grpcserver/upstream.go index cbbadb24..bfc766eb 100644 --- a/pkg/grpcserver/upstream.go +++ b/mappers/pkg/grpcserver/upstream.go @@ -7,8 +7,8 @@ import ( "k8s.io/klog/v2" dmiapi "github.com/kubeedge/kubeedge/pkg/apis/dmi/v1alpha1" - "github.com/kubeedge/mappers-go/pkg/common" - "github.com/kubeedge/mappers-go/pkg/driver/modbus" + "github.com/kubeedge/mappers-go/mappers/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/driver/modbus" ) func (s *Server) ReportDeviceStatus(ctx context.Context, request *dmiapi.ReportDeviceStatusRequest) (*dmiapi.ReportDeviceStatusResponse, error) { diff --git a/pkg/httpclient/httpclient.go b/mappers/pkg/httpclient/httpclient.go similarity index 100% rename from pkg/httpclient/httpclient.go rename to mappers/pkg/httpclient/httpclient.go diff --git a/pkg/util/grpcclient/config.go b/mappers/pkg/util/grpcclient/config.go similarity index 71% rename from pkg/util/grpcclient/config.go rename to mappers/pkg/util/grpcclient/config.go index 4c3417fd..f4aad8c3 100644 --- a/pkg/util/grpcclient/config.go +++ b/mappers/pkg/util/grpcclient/config.go @@ -1,7 +1,7 @@ package grpcclient import ( - "github.com/kubeedge/mappers-go/config" + "github.com/kubeedge/mappers-go/mappers/config" ) var cfg *config.Config diff --git a/pkg/util/grpcclient/register.go b/mappers/pkg/util/grpcclient/register.go similarity index 93% rename from pkg/util/grpcclient/register.go rename to mappers/pkg/util/grpcclient/register.go index 5903bcc8..19aeb27b 100644 --- a/pkg/util/grpcclient/register.go +++ b/mappers/pkg/util/grpcclient/register.go @@ -9,8 +9,8 @@ import ( "google.golang.org/grpc" dmiapi "github.com/kubeedge/kubeedge/pkg/apis/dmi/v1alpha1" - "github.com/kubeedge/mappers-go/config" - "github.com/kubeedge/mappers-go/pkg/common" + "github.com/kubeedge/mappers-go/mappers/config" + "github.com/kubeedge/mappers-go/mappers/pkg/common" ) // RegisterMapper if withData is true, edgecore will send device and model list. diff --git a/pkg/util/grpcclient/report.go b/mappers/pkg/util/grpcclient/report.go similarity index 100% rename from pkg/util/grpcclient/report.go rename to mappers/pkg/util/grpcclient/report.go diff --git a/pkg/util/parse/grpc.go b/mappers/pkg/util/parse/grpc.go similarity index 99% rename from pkg/util/parse/grpc.go rename to mappers/pkg/util/parse/grpc.go index 5a2320e6..94d83a96 100644 --- a/pkg/util/parse/grpc.go +++ b/mappers/pkg/util/parse/grpc.go @@ -9,7 +9,7 @@ import ( "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" dmiapi "github.com/kubeedge/kubeedge/pkg/apis/dmi/v1alpha1" - "github.com/kubeedge/mappers-go/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/common" ) func getProtocolNameFromGrpc(device *dmiapi.Device) (string, error) { diff --git a/pkg/util/parse/models.go b/mappers/pkg/util/parse/models.go similarity index 100% rename from pkg/util/parse/models.go rename to mappers/pkg/util/parse/models.go diff --git a/pkg/util/parse/parse.go b/mappers/pkg/util/parse/parse.go similarity index 96% rename from pkg/util/parse/parse.go rename to mappers/pkg/util/parse/parse.go index 467a8db4..d95bf2d6 100644 --- a/pkg/util/parse/parse.go +++ b/mappers/pkg/util/parse/parse.go @@ -23,9 +23,9 @@ import ( "k8s.io/klog/v2" - "github.com/kubeedge/mappers-go/config" - "github.com/kubeedge/mappers-go/pkg/common" - "github.com/kubeedge/mappers-go/pkg/util/grpcclient" + "github.com/kubeedge/mappers-go/mappers/config" + "github.com/kubeedge/mappers-go/mappers/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/util/grpcclient" ) var ErrEmptyData error = errors.New("device or device model list is empty") diff --git a/pkg/util/parse/type.go b/mappers/pkg/util/parse/type.go similarity index 99% rename from pkg/util/parse/type.go rename to mappers/pkg/util/parse/type.go index d7f0b24b..d0a613c0 100644 --- a/pkg/util/parse/type.go +++ b/mappers/pkg/util/parse/type.go @@ -10,7 +10,7 @@ import ( "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" "github.com/kubeedge/kubeedge/pkg/apis/devices/v1alpha2" dmiapi "github.com/kubeedge/kubeedge/pkg/apis/dmi/v1alpha1" - "github.com/kubeedge/mappers-go/pkg/common" + "github.com/kubeedge/mappers-go/mappers/pkg/common" ) func getProtocolName(device *v1alpha2.Device) (string, error) {