Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions build/crd-samples/devices/temperature-instance.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
apiVersion: devices.kubeedge.io/v1beta1
kind: Device
metadata:
name: temperature-instance
spec:
deviceModelRef:
name: temperature-model
protocol:
protocolName: modbus
# Custom protocol configuration
configData:
communicateMode: "TCP" # TCP/RTU
port: "5502" # replace the port with your modbus device port
slaveID: 1
ip: "127.0.0.1" # 1.replace the ip with your modbus device ip
nodeName: "kind-worker" # 2.replace the nodeName with your edge node name
properties:
- name: temperature
visitors:
protocolName: modbus
configData:
dataType: "float" # Define the output format, consistent with the model type definition Enum::int/float/double/string/boolean/bytes
register: "HoldingRegister" # Register Type Enum::CoilRegister/DiscreteInputRegister/HoldingRegister/InputRegister
offset: 0 # Register offset
limit: 1 # Number of registers to read
scale: 0.1 # Scaling factor for temperature values
isSwap: false # Whether to swap bytes
isRegisterSwap: false # Whether to swap registers
max: 100.0 # Maximum value for temperature
min: 1.0 # Minimum value for temperature
collectCycle: 10000
reportCycle: 10000
reportToCloud: true
# Enabling the push function requires deploying related services,like mosquitto broker
# pushMethod:
# mqtt:
# topic: "current temperature"
# qos: 0
# address: "tcp://172.18.0.3:31883" # replace the address with your mqtt broker address
# retained: false
- name: temperature-switch
collectCycle: 10000
reportCycle: 10000
reportToCloud: true
desired:
value: "1"
visitors:
protocolName: modbus
configData:
dataType: "int"
register: "CoilRegister"
offset: 0
limit: 1
scale: 1
isSwap: false
isRegisterSwap: false
methods:
- name: SwitchControl
description: control the switch of the device
propertyNames:
- temperature-switch
- name: UpdateTemperature
description: update the temperature of the device
propertyNames:
- temperature
19 changes: 19 additions & 0 deletions build/crd-samples/devices/temperature-model.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
apiVersion: devices.kubeedge.io/v1beta1
kind: DeviceModel
metadata:
name: temperature-model
namespace: default
spec:
protocol: modbus
properties:
- name: temperature
description: actual temperature
type: FLOAT # ENUM: INT,FLOAT,DOUBLE,STRING,BOOLEAN,BYTES
accessMode: ReadWrite
minimum: "0"
maximum: "100.0"
unit: "Celsius"
- name: temperature-switch
description: "the switch of device 0:off,1:on"
type: INT
accessMode: ReadWrite
Binary file added mappers/temperature-sensor/img/getTemp.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added mappers/temperature-sensor/img/mapper.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 19 additions & 0 deletions mappers/temperature-sensor/mapper/Dockerfile_nostream
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
FROM golang:1.23.3-alpine3.19 AS builder

WORKDIR /build

ENV GO111MODULE=on \
GOPROXY=https://goproxy.cn,direct

COPY . .

RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o main ./cmd/main.go

FROM ubuntu:22.04

RUN mkdir -p kubeedge

COPY --from=builder /build/main kubeedge/
COPY ./config.yaml kubeedge/

WORKDIR kubeedge
35 changes: 35 additions & 0 deletions mappers/temperature-sensor/mapper/Dockerfile_stream
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
FROM golang:1.23.3-bullseye AS builder

WORKDIR /build

ENV GO111MODULE=on \
GOPROXY=https://goproxy.cn,direct

COPY . .

RUN apt-get update && \
apt-get install -y bzip2 curl upx-ucl gcc-aarch64-linux-gnu libc6-dev-arm64-cross gcc-arm-linux-gnueabi libc6-dev-armel-cross libva-dev libva-drm2 libx11-dev libvdpau-dev libxext-dev libsdl1.2-dev libxcb1-dev libxau-dev libxdmcp-dev yasm

RUN curl -sLO https://ffmpeg.org/releases/ffmpeg-4.1.6.tar.bz2 && \
tar -jx --strip-components=1 -f ffmpeg-4.1.6.tar.bz2 && \
./configure && make && \
make install

RUN GOOS=linux go build -o main cmd/main.go

FROM ubuntu:18.04

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The base image ubuntu:18.04 has reached its End of Standard Support and is no longer receiving security updates. Using an EOL version poses a significant security risk. Please update to a supported version, such as ubuntu:22.04.


RUN mkdir -p kubeedge

RUN apt-get update && \
apt-get install -y bzip2 curl upx-ucl gcc-aarch64-linux-gnu libc6-dev-arm64-cross gcc-arm-linux-gnueabi libc6-dev-armel-cross libva-dev libva-drm2 libx11-dev libvdpau-dev libxext-dev libsdl1.2-dev libxcb1-dev libxau-dev libxdmcp-dev yasm

RUN curl -sLO https://ffmpeg.org/releases/ffmpeg-4.1.6.tar.bz2 && \
tar -jx --strip-components=1 -f ffmpeg-4.1.6.tar.bz2 && \
./configure && make && \
make install
Comment on lines +24 to +30

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The build dependencies and ffmpeg are being installed and compiled in the final image stage. This is highly inefficient and dramatically increases the final image size. These steps should only be performed in the builder stage.

The final stage should be minimal and only copy the necessary runtime dependencies and the compiled application binary from the builder stage. Re-installing all build tools and re-compiling ffmpeg here is redundant and should be removed.


COPY --from=builder /build/main kubeedge/
COPY ./config.yaml kubeedge/

WORKDIR kubeedge
71 changes: 71 additions & 0 deletions mappers/temperature-sensor/mapper/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
SHELL := /bin/bash

curr_dir := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST)))))
rest_args := $(wordlist 2, $(words $(MAKECMDGOALS)), $(MAKECMDGOALS))
$(eval $(rest_args):;@:)

help:
#
# Usage:
# make generate : generate a mapper based on a template.
# make mapper {mapper-name} <action> <parameter>: execute mapper building process.
#
# 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.
# - 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


.PHONY: clean deploy docker-build-push

DOCKER_REGISTRY ?= ""
TAG ?= v1.0

deploy: deploy-crds deploy-resource

clean: undeploy-crds undeploy-resource
build-app:
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o main ./cmd/main.go
docker-build:
docker build -f ./Dockerfile_nostream -t temperature-mapper:${TAG} .
docker-push:
ifeq ($(DOCKER_REGISTRY), "")
$(error DOCKER_REGISTRY is not set, please set it use "export DOCKER_REGISTRY=<your-registry> " first)
endif
docker push ${DOCKER_REGISTRY}/temperature-mapper:${TAG}
undeploy-crds:
kubectl delete -f./crds/temperature-instance.yaml
kubectl delete -f./crds/temperature-model.yaml
undeploy-resource:
kubectl delete -f./resource/deployment.yaml
kubectl delete -f./resource/configmap.yaml

deploy-resource:
kubectl apply -f ./resource/configmap.yaml
kubectl apply -f./resource/deployment.yaml
deploy-crds:
kubectl apply -f./crds/temperature-model.yaml
kubectl apply -f./crds/temperature-instance.yaml

deploy-mqtt:
kubectl apply -f./resource/mqtt.yaml
undeploy-mqtt:
kubectl delete -f./resource/mqtt.yaml
81 changes: 81 additions & 0 deletions mappers/temperature-sensor/mapper/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Temperature Sensor Modbus Mapper Plugin

This project is a Modbus protocol temperature sensor management plugin based on KubeEdge, which implements data collection, status reporting and control functions for temperature sensors.

## Functional Features

- Support Modbus TCP and RTU communication modes
- Implement temperature data collection and reporting
- Support temperature alarm threshold setting
- Provide RESTful API interface for device control and data query
- Support real-time monitoring of device status

## System Architecture

This plugin is developed based on KubeEdge's Mapper framework, and communicates with temperature sensors through the Modbus protocol to realize device data collection and control. The system architecture is as follows:

![](../img/mapper.png)

## Prerequisites

- KubeEdge environment (v1.12.0 or higher)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this mapper generated based on mapper-framework v1.21? If so, I suggest changing the version number here to v1.21 or higher.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

- Go 1.22.0 or higher
- Modbus Simulator

## Quick Start
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mappers-go should only contain the built-in mapper plugin, so the Quick Start only needs to describe how to deploy this mapper. You can add a sentence at the end: If you want to fully experience the mapper management of simulated temperature devices, you can refer to the example repo


### 1. Clone the repository to local
```
git clone https://github.com/aAAaqwq/temperature-sensor-mapper

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The git clone command points to a personal fork (aAAaqwq/temperature-sensor-mapper). This should be updated to point to the official repository path where this code will be merged. This ensures users clone from the correct, canonical source.

git clone https://github.com/kubeedge/kubeedge

```

### 2. Configure Modbus simulation software (if conditions permit, physical devices can be used)
```
Install modbus Slave (recommended)
- Create TCP/RTU device connection, mapper uses TCP protocol by default.
- Configure Modbus registers:
- Temperature register: holding register, address 4000, data type: uint16
- Working status register: coil register, address 1001, data type: uint16
```

### 3. Configure mapper plugin
- Configure /crds/temperature-instance.yaml
```
1. replace the ip with your modbus device ip
2. replace the nodeName with your edge node name
```
- Configure /resource/deployment.yaml
```
1. replace the nodeName with your edge node name
```
### 4. Build mapper plugin image at Edge
```
make docker-build
```

### 5. Deploy mapper and crds
```
make deploy
```
### 6. Verify plugin function
#### 6.1 View the synchronization of the reported field in the twins field:
```
kubectl get device -o yaml
```
#### 6.2 Access the REST API of the mapper plugin on the edgecore node
- Health check
```
curl 127.0.0.1:7777/api/v1/ping
```
- Get device status
```
curl <your_edge_ip>:30077/api/v1/device/<namespace>/<device_name>/<property_name>
```
<img src="../img/getTemp.png">

#### 6.3 View mapper logs

### 7. Uninstall the plugin
```
make clean
```
68 changes: 68 additions & 0 deletions mappers/temperature-sensor/mapper/cmd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package main

import (
"errors"

"k8s.io/klog/v2"

"github.com/kubeedge/mapper-framework/pkg/common"
"github.com/kubeedge/mapper-framework/pkg/config"
"github.com/kubeedge/mapper-framework/pkg/grpcclient"
"github.com/kubeedge/mapper-framework/pkg/grpcserver"
"github.com/kubeedge/mapper-framework/pkg/httpserver"

"github.com/kubeedge/temperature-sensor-mapper/data/device"
// modbus_simulator "github.com/kubeedge/temperature-sensor-mapper/modbus-simulator"
)

func main() {
var err error
var c *config.Config
// go modbus_simulator.InitModbusSimulator(":5502")

klog.InitFlags(nil)
defer klog.Flush()

if c, err = config.Parse(); err != nil {
klog.Fatal(err)
}
// klog.Infof("config: %+v", c)


klog.Infoln("Mapper will register to edgecore")
deviceList, deviceModelList, err := grpcclient.RegisterMapper(true)
if err != nil {
klog.Fatal(err)
}
klog.Infoln("Mapper register finished")

panel := device.NewDevPanel()
err = panel.DevInit(deviceList, deviceModelList)
if err != nil && !errors.Is(err, device.ErrEmptyData) {
klog.Fatal(err)
}
// if errors.Is(err, device.ErrEmptyData) {
// klog.Infoln("devInit finished,but no device data")
// }else{
// klog.Infoln("devInit finished")
// }
Comment on lines +21 to +48

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There are several blocks of commented-out code. This code should be removed before merging to improve readability and maintainability. If it's for debugging, it should not be part of the final PR.

go panel.DevStart()

// start http server
httpServer := httpserver.NewRestServer(panel, c.Common.HTTPPort)
go httpServer.StartServer()

// start grpc server
grpcServer := grpcserver.NewServer(
grpcserver.Config{
SockPath: c.GrpcServer.SocketPath,
Protocol: common.ProtocolCustomized,
},
panel,
)
defer grpcServer.Stop()
if err = grpcServer.Start(); err != nil {
klog.Fatal(err)
}

}
10 changes: 10 additions & 0 deletions mappers/temperature-sensor/mapper/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
grpc_server:
socket_path: /etc/kubeedge/temperature-sensor-mapper.sock
common:
name: Temperature-Sensor-Mapper-mapper
version: v1.13.0
api_version: v1.0.0
protocol: modbus

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This line contains a leftover TODO comment from a template. It should be removed.

  protocol: modbus

address: 127.0.0.1
# http_port: 7777 #change if neccessary
edgecore_sock: /etc/kubeedge/dmi.sock
Loading
Loading