Skip to content

feat(ModbusCrc16): add modbus crc-16 algorithm#560

Merged
ArgoZhang merged 15 commits intomasterfrom
refactor-socket
Aug 29, 2025
Merged

feat(ModbusCrc16): add modbus crc-16 algorithm#560
ArgoZhang merged 15 commits intomasterfrom
refactor-socket

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Aug 29, 2025

Link issues

fixes #559

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Add Modbus CRC-16 algorithm support and related tests; standardize callback naming in TCP socket client interfaces; enhance logging, activator exception handling, and hex conversion utilities.

New Features:

  • Introduce ModbusCrc16 utility class with Compute, Append, and Validate methods for CRC-16 support

Enhancements:

  • Rename ReceivedCallBack to ReceivedCallback across TCP socket client APIs and extensions
  • Add ReadOnlySpan overload to HexConverter for hex string conversion
  • Wrap Activator.CreateInstance calls with exception handling and log failures via SocketLogging
  • Improve SocketLogging.LogError to guard against null logger and format exception messages

Tests:

  • Add unit tests for ModbusCrc16 functionality (Compute, Append, Validate)
  • Add tests for ActivationExtensions, SocketLogging, HexConverter behavior, and DataConverter error handling

Copilot AI review requested due to automatic review settings August 29, 2025 07:23
@bb-auto bb-auto Bot added the enhancement New feature or request label Aug 29, 2025
@bb-auto bb-auto Bot added this to the v9.2.0 milestone Aug 29, 2025
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Aug 29, 2025

Reviewer's Guide

This PR adds a table-driven Modbus CRC-16 utility with performance optimizations, renames and harmonizes the ReceivedCallback member throughout the TCP client API, strengthens error logging and activator extension resilience, extends the HexConverter to support ReadOnlySpan, and covers all new behaviors with focused unit tests.

Class diagram for the new ModbusCrc16 utility

classDiagram
    class ModbusCrc16 {
        +ushort Compute(ReadOnlySpan<byte> data)
        +ReadOnlySpan<byte> Append(ReadOnlySpan<byte> data)
        +bool Validate(ReadOnlySpan<byte> dataWithCrc)
        -ushort[] CrcTable
    }
Loading

Class diagram for ITcpSocketClient and DefaultTcpSocketClient callback renaming

classDiagram
    class ITcpSocketClient {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallback
    }
    class DefaultTcpSocketClient {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallback
    }
    ITcpSocketClient <|.. DefaultTcpSocketClient
Loading

Class diagram for updated HexConverter

classDiagram
    class HexConverter {
        +string ToString(byte[]? bytes, string? separator = "-", bool upper = true)
        +string ToString(ReadOnlySpan<byte> span, string? separator = "-", bool upper = true)
    }
Loading

Class diagram for updated SocketLogging

classDiagram
    class SocketLogging {
        +void Init(ILogger logger)
        +void LogError(string message)
        +void LogError(Exception ex, string? message = null)
        -ILogger _logger
    }
Loading

Class diagram for updated ActivatorExtensions

classDiagram
    class ActivatorExtensions {
        +object? CreateInstance(this Type type, object?[]? args = null)
    }
Loading

File-Level Changes

Change Details Files
Introduce Modbus CRC-16 utility with compute, append, and validate functions
  • Added precomputed lookup table and Compute method iterating over data
  • Implemented Append with stackalloc for small payloads and array fallback
  • Implemented Validate method extracting and comparing CRC from data
  • Covered Compute, Append, and Validate in ModbusCrcTest unit tests
src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs
test/UnitTestTcpSocket/ModbusCrcTest.cs
Rename ReceivedCallBack to ReceivedCallback across TCP client API
  • Updated interface property and client implementation names
  • Adjusted extension methods to subscribe/unsubscribe ReceivedCallback
  • Fixed invocation in DefaultTcpSocketClient.ReceiveCoreAsync and tests
src/extensions/BootstrapBlazor.TcpSocket/ITcpSocketClient.cs
src/extensions/BootstrapBlazor.TcpSocket/DefaultTcpSocketClient.cs
src/extensions/BootstrapBlazor.TcpSocket/Extensions/ITcpSocketClientExtensions.cs
test/UnitTestTcpSocket/TcpSocketFactoryTest.cs
Enhance logging and activator extensions with error handling
  • Modified SocketLogging.LogError to null-check logger and use formatted message
  • Wrapped Activator.CreateInstance in try-catch and log failures
  • Added unit tests for SocketLogging and CreateInstance scenarios
src/extensions/BootstrapBlazor.Socket/Logging/SocketLogging.cs
src/extensions/BootstrapBlazor.Socket/Extensions/ActivatorExtensions.cs
test/UnitTestTcpSocket/SocketLoggingTest.cs
test/UnitTestTcpSocket/ActivationExtensionsTest.cs
Add ReadOnlySpan overload to HexConverter
  • Introduced ToString(ReadOnlySpan,…) delegating to existing array overload
  • Updated HexConverterTest to assert lower/upper case and span behavior
src/extensions/BootstrapBlazor.Socket/DataConverter/HexConverter.cs
test/UnitTestTcpSocket/HexConverterTest.cs
Add negative-path DataConverter test for parse errors
  • Created MockErrorDataConverter that throws in Parse override
  • Added TryConvertTo_Error test to assert false on exception
test/UnitTestTcpSocket/TcpSocketFactoryTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#559 Implement the Modbus CRC-16 algorithm in the codebase.
#559 Provide tests that verify the correctness of the Modbus CRC-16 implementation.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds a Modbus CRC-16 algorithm implementation to the BootstrapBlazor Socket library. The primary purpose is to provide CRC computation, validation, and data appending functionality for Modbus protocol communication.

Key changes include:

  • Implementation of ModbusCrc16 utility class with lookup table-based CRC calculation
  • Renaming of ReceivedCallBack to ReceivedCallback for consistency
  • Enhanced HexConverter with ReadOnlySpan support and case-sensitive formatting

Reviewed Changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs New ModbusCrc16 class implementing CRC-16 computation, validation, and data appending
src/extensions/BootstrapBlazor.Socket/DataConverter/HexConverter.cs Added ReadOnlySpan overload for hex string conversion
src/extensions/BootstrapBlazor.Socket/Logging/SocketLogging.cs Simplified LogError method with better parameter handling
ITcpSocketClient.cs and related files Renamed ReceivedCallBack to ReceivedCallback for proper spelling
test/UnitTestTcpSocket/ModbusCrcTest.cs Comprehensive unit tests for ModbusCrc16 functionality

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs
Comment thread src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs
Comment thread test/UnitTestTcpSocket/ModbusCrcTest.cs
Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • Renaming ReceivedCallBack to ReceivedCallback is a breaking change in the public ITcpSocketClient API—please ensure all consumers are updated (and consider a major version bump).
  • ModbusCrc16.Append still converts the stackalloc span to a heap array via ToArray—consider simplifying the API to directly return a byte[] to avoid extra allocations and make ownership clear.
  • ActivatorExtensions.CreateInstance swallows all exceptions and returns null—consider providing a TryCreateInstance pattern or surfacing the underlying error to aid debugging.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Renaming ReceivedCallBack to ReceivedCallback is a breaking change in the public ITcpSocketClient API—please ensure all consumers are updated (and consider a major version bump).
- ModbusCrc16.Append still converts the stackalloc span to a heap array via ToArray—consider simplifying the API to directly return a byte[] to avoid extra allocations and make ownership clear.
- ActivatorExtensions.CreateInstance swallows all exceptions and returns null—consider providing a TryCreateInstance pattern or surfacing the underlying error to aid debugging.

## Individual Comments

### Comment 1
<location> `src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs:69` </location>
<code_context>
+    /// </summary>
+    /// <param name="data">原始数据</param>
+    /// <returns>带 CRC 校验码的数据</returns>
+    public static ReadOnlySpan<byte> Append(ReadOnlySpan<byte> data)
+    {
+        ushort crc = Compute(data);
+
+        // 使用 stackalloc 避免堆分配(小数据时)
+        if (data.Length <= 256)
+        {
+            Span<byte> result = stackalloc byte[data.Length + 2];
+            data.CopyTo(result);
+            result[data.Length] = (byte)(crc & 0xFF);
+            result[data.Length + 1] = (byte)(crc >> 8);
+            return result.ToArray();
+        }
+        else
</code_context>

<issue_to_address>
Returning ToArray() from a stackalloc span defeats the purpose of stack allocation.

Returning result.ToArray() causes a heap allocation, which undermines the use of stackalloc. Consider returning the Span directly or consistently using arrays to avoid confusion.
</issue_to_address>

### Comment 2
<location> `src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs:105` </location>
<code_context>
+            return false;
+        }
+
+        ushort receivedCrc = (ushort)(dataWithCrc[^1] << 8 | dataWithCrc[^2]);
+        ushort calculatedCrc = Compute(dataWithCrc[..^2]);
+        return receivedCrc == calculatedCrc;
</code_context>

<issue_to_address>
Byte order for CRC extraction may be confusing.

Consider documenting the expected byte order or using BitConverter to make the endianness explicit and improve maintainability.
</issue_to_address>

### Comment 3
<location> `src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs:74` </location>
<code_context>
+        ushort crc = Compute(data);
+
+        // 使用 stackalloc 避免堆分配(小数据时)
+        if (data.Length <= 256)
+        {
+            Span<byte> result = stackalloc byte[data.Length + 2];
</code_context>

<issue_to_address>
Consider removing the stackalloc branch in Append and always use a single byte array allocation for simplicity.

Consider dropping the `stackalloc` + `ToArray()` branch entirely – it never actually saves you from a heap alloc, just adds extra code paths. A single `new byte[]` keeps everything straightforward:

```csharp
public static byte[] Append(ReadOnlySpan<byte> data)
{
    ushort crc = Compute(data);
    int len = data.Length;
    var result = new byte[len + 2];
    data.CopyTo(result);
    result[len]     = (byte)(crc & 0xFF);
    result[len + 1] = (byte)(crc >> 8);
    return result;
}
```

If you really want to keep the `ReadOnlySpan<byte>` signature, just return the array directly:

```csharp
public static ReadOnlySpan<byte> Append(ReadOnlySpan<byte> data)
{
    ushort crc = Compute(data);
    int len = data.Length;
    var result = new byte[len + 2];
    data.CopyTo(result);
    result[len]     = (byte)(crc & 0xFF);
    result[len + 1] = (byte)(crc >> 8);
    return result;
}
```

Both remove the extra branch, simplify the implementation, and preserve identical behavior.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs
Comment thread src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs
Comment thread src/extensions/BootstrapBlazor.Socket/Utility/ModbusCrc16.cs
@ArgoZhang ArgoZhang merged commit 78b6931 into master Aug 29, 2025
1 check passed
@ArgoZhang ArgoZhang deleted the refactor-socket branch August 29, 2025 07:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(ModbusCrc16): add modbus crc-16 algorithm

2 participants