A:调整数据监听方案

This commit is contained in:
jimmy committed 2025-12-11 14:44:58 +08:00
1 parent ea6103a596
commit 5b7f127bb5
2 files changed
+251

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
# Visual Studio
.vs/
bin/
obj/
[Dd]ebug/
[Rr]elease/
*.user
*.suo
*.userprefs
*.usertasks
*.sln.docstates
*.dll
*.pdb
*.exe
!src/**/bin/**/*.dll
!src/**/bin/**/*.pdb
!src/**/bin/**/*.exe
# Rider
.idea/
# Dotnet
project.lock.json
project.fragment.lock.json
artifacts/
# Other
Thumbs.db
Desktop.ini
+222
View File
@@ -0,0 +1,222 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Sharp-Basic is a modular C# .NET 8 framework for building enterprise applications with reusable components. It provides a comprehensive toolkit with emphasis on:
- **Modularity**: Independent, reusable libraries that can be used selectively
- **Desktop Applications**: WPF-based UI toolkit with MVVM infrastructure
- **Industrial IoT**: PLC integration (Siemens) and serial port communication
- **Configuration as Code**: Multi-format (JSON/XML/INI/TOML) with hot-reload
- **Functional Programming**: Result<T> pattern for railway-oriented error handling
**Language**: All comments and documentation are in Chinese (中文).
## Build Commands
### Build the entire solution
```bash
cd src/Sharp
dotnet build Sharp.sln
```
### Build specific project
```bash
cd src/Sharp
dotnet build Client/Client.csproj # WPF demo application
dotnet build Common/Common.csproj # Core utilities
dotnet build Config/Config.csproj # Configuration management
```
### Run tests
```bash
cd src/Sharp
dotnet test Sharp.sln # All tests
dotnet test ../../test/Common.Test # Specific test project
```
### Run the WPF Client application
```bash
cd src/Sharp
dotnet run --project Client/Client.csproj
```
### Clean build artifacts
```bash
cd src/Sharp
dotnet clean Sharp.sln
```
## Architecture Overview
### Project Structure
```
src/Sharp/ # All source projects
├── Common/ # Core foundation (Result<T>, Global container, utilities)
├── Config/ # Multi-format configuration with hot-reload
├── Sharp.Infrastructure/ # Infrastructure abstractions
├── Wpf/ # WPF UI toolkit (MVVM, dialogs, converters)
├── Data/ # EF Core wrapper with repository pattern
├── Repository/ # Repository implementations
├── Log/ # Serilog-based structured logging
├── NetClient/ # HTTP client with Polly resilience
├── NetServer/ # Lightweight HTTP server with middleware
├── Ports/ # Serial port abstraction (RS232/RS485)
├── Plc/ # PLC abstraction interface
├── Plc.Siemens/ # Siemens S7 PLC implementation (S7.NET+)
├── EventBus/ # Event pub/sub (planned)
├── Client/ # WPF demo application
└── Server/ # WPF server example
test/ # MSTest test projects
├── Common.Test/
├── Config.Test/
├── Data.Test/
├── Log.Test/
├── NetClient.Test/
└── NetServer.Test/
```
### Key Architectural Patterns
#### 1. Result<T> Pattern (Railway-Oriented Programming)
- Eliminates exceptions as control flow
- Provides chainable operations: `Map`, `Bind`, `Match`, `Where`, `OnSuccess`, `OnFailure`
- Synchronous and async wrappers: `Result.Try()`, `Result.TryAsync()`
- Example usage:
```csharp
Result.Try(() => int.Parse(input))
.Map(x => x * 2)
.Where(v => v > 100, "Value too small")
.OnSuccess(v => Console.WriteLine(v))
.OnFailure((ex, msg) => logger.LogError(msg));
```
#### 2. Dependency Injection (Hybrid Approach)
- **Primary**: Microsoft.Extensions.DependencyInjection for standard DI
- **Fallback**: Global service locator (Common.Global) for legacy/convenience
- Services registered in `DependencyInjection` folders within each module
- Client app startup (App.xaml.cs) orchestrates all service registration
#### 3. Configuration Management
- Multi-source configuration builder supporting JSON/XML/INI/TOML
- Hot-reload with change notifications
- Strong typing with DataAnnotations validation
- IOptions<T> pattern integration
- Environment variable overrides with optional prefix
#### 4. Repository Pattern with EF Core
- Generic `IRepository<TEntity>` abstraction
- Built-in entity types: `Entity`, `AuditableEntity`, `ISoftDeletable`
- Auto-audit tracking (CreatedAt, CreatedBy, UpdatedAt, UpdatedBy)
- Multi-database support: SQL Server, SQLite, PostgreSQL, MySQL, In-Memory
#### 5. MVVM for WPF
- `ViewModelBase` with INotifyPropertyChanged and IsBusy tracking
- `RelayCommand` and `AsyncCommand` implementations
- Services: `IDialogService`, `IFileDialogService`, `IDispatcherService`
- Converters: BoolToVisibility, InverseBooleanConverter, EnumToDescriptionConverter
- Global exception handling for UI/Task/AppDomain exceptions
#### 6. Middleware Pattern
- Custom HTTP server (NetServer) with ASP.NET Core-style pipeline
- Middleware: Authentication, CORS, Rate Limiting, Caching, Logging, Exception Handling
- Attribute-based routing with `RouteAttribute`
- Custom `IMiddleware` interface for extensibility
## Module Dependencies
**Core Layer** (no external dependencies):
- Common → (no dependencies)
**Configuration Layer**:
- Config → Microsoft.Extensions.Configuration.*, Tomlyn (TOML support)
**Data Layer**:
- Data → EF Core, Common
- Repository → Data
**Network Layer**:
- NetClient → Polly, Microsoft.Extensions.Http, Common
- NetServer → Common, Log
**WPF Layer**:
- Wpf → HandyControl (optional UI controls)
- Client → Wpf, Config, NetClient, NetServer, Log, Plc.Siemens, Ports
**Industrial IoT**:
- Ports → (serial port communication)
- Plc → (abstraction only)
- Plc.Siemens → Plc, S7.NET+ library
**Logging**:
- Log → Serilog, Microsoft.Extensions.Logging
## Common Development Workflows
### Adding a new module/library
1. Create project under `src/Sharp/`
2. Target `net8.0` (or `net8.0-windows` for WPF)
3. Enable nullable reference types: `<Nullable>enable</Nullable>`
4. Create `DependencyInjection` folder for service registration extensions
5. Add test project under `test/` with MSTest
6. Add to Sharp.sln: `dotnet sln add <ProjectPath>`
### Working with Result<T>
- Use `Result.Try()` to wrap exception-prone code
- Chain operations with `Map()` for transformations
- Use `Bind()` for operations that return Result<T>
- Extract values with `GetOrDefault()`, `GetOrThrow()`, or `Match()`
- Always handle both success and failure cases
### Using the Global container
- Register singletons: `Global.RegisterSingleton<T>(instance)` or `Global.RegisterSingleton<T>(() => new T())`
- Register transients: `Global.RegisterTransient<T>(() => new T())`
- Subscribe to changes: `Global.Subscribe<T>(e => { /* handle change */ })`
- Retrieve services: `Global.Get<T>()`
- Prefer standard DI (IServiceCollection) for new code
### Configuration workflow
1. Add config files to project root (appsettings.json, etc.)
2. Create strongly-typed options class with DataAnnotations
3. Build ConfigManager in App.xaml.cs OnStartup
4. Register with DI: `services.AddSingleton(cfg)` and `services.AddSingleton(cfg.Configuration)`
5. Use hot-reload callbacks: `cfg.OnReload(() => { /* refresh */ })`
### WPF Client startup flow
The Client application (App.xaml.cs) orchestrates initialization:
1. Register global exception handlers (UI, Task, AppDomain)
2. Build ConfigManager from appsettings.json
3. Setup ServiceCollection and register all services
4. Create ServiceProvider
5. Show LoginWindow (modal)
6. On successful login, show MainWindow
### Working with PLC (Siemens)
- Interface: `IPLC` in Plc project
- Implementation: Plc.Siemens using S7.NET+ library
- Supports: S7-1200, S7-1500, S7-300, S7-400
- Register with DI: Add Siemens PLC service with connection options
- Methods: Read/Write memory areas, data blocks, etc.
### Serial Port Communication
- Service: `ISerialPortService` in Ports module
- Discovery: `SerialPortDiscovery` for auto-detection
- Event-based data reception: `DataReceivedEventArgs`
- Configured with: baud rate, parity, stop bits, data bits
## Code Style
- **Target Framework**: .NET 8 (net8.0 / net8.0-windows)
- **Nullable**: Enabled (`#nullable enable`)
- **Implicit Usings**: Enabled
- **Namespace Convention**: `Sharp.*` (Common will migrate to `Sharp.Common`)
- **Language**: All comments, docs, and strings in Chinese
- **Backwards Compatibility**: Maintain for minor versions; breaking changes only in major versions
- **Testing**: MSTest with parallel execution enabled
## License
GNU AGPLv3 - Network services that use this framework must open source modifications. Contact author for alternative commercial licensing.