Skip to content

Add a temperature sensor mapper#135

Open
aAAaqwq wants to merge 1 commit intokubeedge:mainfrom
aAAaqwq:feat--add-temperature-sensor-mapper
Open

Add a temperature sensor mapper#135
aAAaqwq wants to merge 1 commit intokubeedge:mainfrom
aAAaqwq:feat--add-temperature-sensor-mapper

Conversation

@aAAaqwq
Copy link

@aAAaqwq aAAaqwq commented Jul 28, 2025

What type of PR is this?

/kind feat

What this PR does / why we need it:

To resolve issue #6315 :Optimize KubeEdge Device Management Practical Case Studies.

  1. Provides a temperature sensor mapper.

Which issue(s) this PR fixes:

Fixes #6315

Special notes for your reviewer:

Does this PR introduce a user-facing change?:


None

Signed-off-by: Daniel Li <2067089451@qq.com>
@kubeedge-bot
Copy link
Collaborator

@aAAaqwq: The label(s) kind/feat cannot be applied, because the repository doesn't have them

Details

In response to this:

What type of PR is this?

/kind feat

What this PR does / why we need it:

To resolve issue #6315 :Optimize KubeEdge Device Management Practical Case Studies.

  1. Provides a temperature sensor mapper.

Which issue(s) this PR fixes:

Fixes #6315

Special notes for your reviewer:

Does this PR introduce a user-facing change?:


None

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

@kubeedge-bot
Copy link
Collaborator

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
To complete the pull request process, please assign kevin-wangzefeng after the PR has been reviewed.
You can assign the PR to them by writing /assign @kevin-wangzefeng in a comment when ready.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@kubeedge-bot
Copy link
Collaborator

Welcome @aAAaqwq! It looks like this is your first PR to kubeedge/mappers-go 🎉

@kubeedge-bot kubeedge-bot added the size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label Jul 28, 2025
Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @aAAaqwq, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request delivers a complete solution for integrating Modbus temperature sensors into the KubeEdge ecosystem. It encompasses the core mapper logic, a flexible driver for Modbus communication, and extensive options for data handling, including persistence to various databases and publishing to external systems. The changes aim to optimize KubeEdge's device management capabilities for practical industrial use cases.

Highlights

  • New Temperature Sensor Mapper: Introduced a new KubeEdge mapper specifically designed for Modbus-based temperature sensors, enabling comprehensive device management at the edge.
  • Modbus Protocol Support: Implemented robust support for both Modbus TCP and RTU communication modes, allowing flexible integration with various industrial temperature sensors.
  • Extensive Data Persistence Options: Added capabilities to push collected temperature data to multiple database types, including InfluxDB2, MySQL, Redis, and TDengine, providing diverse storage solutions.
  • Flexible Data Publishing Methods: Enabled various methods for publishing device data, such as HTTP, MQTT, and OpenTelemetry, facilitating integration with different monitoring and analytics platforms.
  • Comprehensive Deployment Resources: Provided detailed Kubernetes Custom Resource Definitions (CRDs) for device models and instances, along with Dockerfiles, Makefiles, and Kubernetes YAMLs for streamlined build, deployment, and testing.
  • Modbus Simulator for Development: Included a basic Modbus TCP simulator to aid in local development and testing of the mapper without requiring physical hardware.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds a new temperature sensor mapper with extensive support for various data storage and publishing methods. The overall contribution is significant, but there are several critical issues across the new files that need to be addressed before merging.

The review has identified critical security vulnerabilities (SQL injection), race conditions from using global variables, and correctness bugs that will cause panics at runtime. Additionally, there are significant performance and image size issues in the Dockerfiles and client implementations. I've provided detailed comments and suggestions for each issue below.

Key areas for improvement:

  • Security: Address the SQL injection vulnerabilities in the tdengine client by using prepared statements.
  • Correctness: Fix several bugs that will lead to panics, such as improper error handling in the HTTP client, unsafe type assertions in the OTel handler, and incorrect data parsing in the Redis client. The core driver logic in GetDeviceData should be refactored to return structured data instead of a formatted string.
  • Concurrency: Refactor database clients (mysql, redis, tdengine) to avoid using global variables, which can lead to race conditions and make the code difficult to maintain and test.
  • Performance & Best Practices: The Dockerfiles, particularly Dockerfile_stream, need significant optimization to reduce image size and build time. The MQTT and HTTP clients should be refactored to reuse connections instead of creating new ones for each request.

Please review the detailed comments on each file. Addressing these points will greatly improve the quality, security, and robustness of the new mapper.

Comment on lines +72 to +76
deviceData := "TimeStamp: " + strconv.FormatInt(data.TimeStamp, 10) + " PropertyName: " + data.PropertyName + " data: " + data.Value
// Add data to ordered set. If the ordered set does not exist, it will be created.
_, err := RedisCli.ZAdd(ctx, data.DeviceName, &redis.Z{
Score: float64(data.TimeStamp),
Member: deviceData,

Choose a reason for hiding this comment

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

critical

The data is being stored in Redis as a concatenated, unstructured string. This makes it very difficult and brittle to parse later. It's much better to store structured data, like a JSON string, which can be easily marshalled and unmarshalled.

Furthermore, GetDataByDeviceID attempts to unmarshal this string as JSON, which will fail and cause a runtime error. This is a critical bug.

deviceData, err := json.Marshal(data)
	if err != nil {
		return err
	}
	// Add data to ordered set. If the ordered set does not exist, it will be created.
	_, err = RedisCli.ZAdd(ctx, data.DeviceName, &redis.Z{
		Score:  float64(data.TimeStamp),
		Member: deviceData,
	}).Result()

insertSQL := fmt.Sprintf("INSERT INTO %s USING %s TAGS ('%s') VALUES('%v','%s', '%s', '%s', '%s');",
legalTag, legalTable, legalTag, datatime, tableName, data.PropertyName, data.Value, data.Type)

rows, _ := DB.Query(stableName)

Choose a reason for hiding this comment

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

critical

The error returned from DB.Query is being ignored. This can hide important database errors and lead to unexpected behavior. The error must be checked and handled.

rows, err := DB.Query(stableName)
	if err != nil {
		klog.Errorf("query stable failed: %v", err)
		return err
	}

return fmt.Errorf("get device data fail: %v", err)
}

o.ObserveFloat64(gauge, data.(float64))

Choose a reason for hiding this comment

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

critical

This line performs a hard type assertion data.(float64). However, the GetDeviceData function in the driver returns a formatted string (e.g., "The data read from the device,Type:float32 Value:25.5"), not a float64. This will cause a runtime panic.

The driver's GetDeviceData method needs to be refactored to return the raw, normalized data value. After that, the value should be correctly converted here before being observed.

Comment on lines +50 to +53
if token := client.Connect(); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}

Choose a reason for hiding this comment

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

critical

Calling os.Exit(1) on an MQTT connection failure is too drastic. It will terminate the entire mapper process if the MQTT broker is temporarily unavailable. The error should be logged, and the connection should be retried, possibly with a backoff strategy.

Suggested change
if token := client.Connect(); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
if token := client.Connect(); token.Wait() && token.Error() != nil {
klog.Errorf("Failed to connect to MQTT broker: %v", token.Error())
return
}

@@ -0,0 +1,157 @@
package tdengine

Choose a reason for hiding this comment

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

medium

This file starts with a UTF-8 Byte Order Mark (BOM) character (U+FEFF), which can cause issues with some tools and compilers. Please remove it.

Suggested change
package tdengine
package tdengine

Comment on lines +21 to +48
// 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")
// }

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.


### 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

# name: mysecret
# key: token
image: temperature-mapper:v1.0
imagePullPolicy: Always

Choose a reason for hiding this comment

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

medium

Using imagePullPolicy: Always with a fixed tag like v1.0 can lead to unnecessary image pulls on every pod restart. It's better practice to use IfNotPresent for release tags. Always is typically used for latest tags or during active development.

          imagePullPolicy: IfNotPresent

@sailorvii
Copy link
Collaborator

Thanks for your contribution; however, the mapper is for a specific type of connection, like Modbus, Bluetooth, not for a special device. Maybe move your contriubtion to https://github.com/kubeedge/examples is better?

@wbc6080
Copy link
Collaborator

wbc6080 commented Jul 30, 2025

Thanks for your contribution; however, the mapper is for a specific type of connection, like Modbus, Bluetooth, not for a special device. Maybe move your contriubtion to https://github.com/kubeedge/examples is better?

This mapper is built based on the modbus protocol and can be renamed to modbus-mapper. In example repo, we will use this modbus mapper to manage the simulated temperature device.


## 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants