From c4165795079496b2190ed96a41e59d53c905e9db Mon Sep 17 00:00:00 2001 From: cli <377476583@qq.com> Date: Thu, 19 Dec 2024 16:07:07 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .editorconfig | 2 + .gitignore | 45 +- .../ICommandService.cs | 9 - ...he.CollectBus.Application.Contracts.csproj | 9 - .../CommandService.cs | 116 -- .../ServiceCollectionExtensions.cs | 36 - .../JiShe.CollectBus.Application.csproj | 19 - .../JiSheCollectBusApplicationModule.cs | 46 - JiShe.CollectBus.Application/Jobs/TestJob.cs | 30 - JiShe.CollectBus.Common/Enums/376Enums.cs | 173 -- .../Enums/CommandChunkEnum188.cs | 16 - .../Extensions/HexStringExtensions.cs | 757 -------- .../DependencyInjectionExtensions.cs | 92 - .../JiShe.CollectBus.Console.csproj | 60 - JiShe.CollectBus.Console/Program.cs | 72 - JiShe.CollectBus.Console/appsettings.json | 57 - .../JiShe.CollectBus.Network.csproj | 27 - .../JiSheCollectBusNetworkModule.cs | 50 - JiShe.CollectBus.Core/Plugins/TcpMonitor.cs | 109 -- .../AuditLogs/AuditLog.cs | 15 - .../CollectBusDbContext.cs | 29 - .../Device.cs | 26 - .../Entities/EntityBase.cs | 13 - .../Entities/FullAuditedEntity.cs | 19 - .../Entities/ICreationAudited.cs | 22 - .../Entities/IDeletionAudited.cs | 27 - .../Entities/IExtendableObject.cs | 20 - .../Entities/IModificationAudited.cs | 22 - .../Extensions/ExtendableObjectExtensions.cs | 153 -- ...iShe.CollectBus.EntityFrameworkCore.csproj | 25 - ...iSheCollectBusEntityFrameworkCoreModule.cs | 11 - .../20241022055227_Init.Designer.cs | 60 - .../Migrations/20241022055227_Init.cs | 44 - .../CollectBusDbContextModelSnapshot.cs | 57 - .../Repositories/IRepository.cs | 62 - .../Repositories/Repository.cs | 295 --- .../Controllers/CommandController.cs | 36 - .../ServiceCollectionExtensions.cs | 49 - .../JiShe.CollectBus.Host.csproj | 35 - .../JiSheCollectBusHostModule.cs | 26 - .../Models/GeneralIssuedInput.cs | 33 - JiShe.CollectBus.Host/Program.cs | 42 - JiShe.CollectBus.Host/Startup.cs | 90 - JiShe.CollectBus.Host/appsettings.json | 52 - JiShe.CollectBus.MongoDB/IMongoContext.cs | 37 - JiShe.CollectBus.MongoDB/IMongoRepository.cs | 176 -- JiShe.CollectBus.MongoDB/IUnitOfWork.cs | 25 - .../JiShe.CollectBus.MongoDB.csproj | 20 - .../JiSheCollectBusMongoDBModule.cs | 29 - .../MongoBaseRepository.cs | 352 ---- JiShe.CollectBus.MongoDB/MongoContext.cs | 93 - JiShe.CollectBus.MongoDB/UnitOfWork.cs | 43 - .../Interfaces/IProtocolPlugin.cs | 19 - .../JiShe.CollectBus.Protocol.Demo.csproj | 18 - .../JiSheCollectBusTestProtocolModule.cs | 20 - .../TestProtocolPlugin.cs | 27 - JiShe.CollectBus.RabbitMQ/INSender.cs | 22 - .../JiShe.CollectBus.MQ.Sender.csproj | 20 - .../JiSheCollectBusMQSenderModule.cs | 17 - JiShe.CollectBus.RabbitMQ/NSender.cs | 71 - .../JiShe.CollectBus.MQ.Consumer.csproj | 20 - .../JiSheCollectBusMQConsumerModule.cs | 87 - .../MessageIssuedConsumer.cs | 35 - .../MessageIssuedFaultConsumer.cs | 13 - .../MessageReceivedConsumer.cs | 39 - .../MessageReceivedFaultConsumer.cs | 13 - .../MessageReceivedHeartbeatConsumer.cs | 29 - .../MessageReceivedLoginConsumer.cs | 29 - JiShe.CollectBus.Test/BusUnitTest.cs | 71 - .../JiShe.CollectBus.Test.csproj | 29 - JiShe.CollectBus.abpmdl | 62 + JiShe.CollectBus.abpsln | 9 + JiShe.CollectBus.sln | 168 +- common.props | 27 + dockerfile | 21 - .../BaseResultDto.cs | 32 + .../CollectBusApplicationContractsModule.cs | 15 + .../CollectBusRemoteServiceConsts.cs | 8 + .../EnergySystem/Dto/ValveControlInput.cs | 40 + .../EnergySystem/Dto/ValveControlOutput.cs | 17 + .../EnergySystem/IEnergySystemAppService.cs | 15 + .../FodyWeavers.xml | 3 + .../ICollectWorker.cs | 5 +- ...up.CollectBus.Application.Contracts.csproj | 27 + ...he.CollectBus.Application.Contracts.abppkg | 3 + ...he.CollectBus.Application.Contracts.csproj | 25 + .../CollectBusPermissionDefinitionProvider.cs | 18 + .../Permissions/CollectBusPermissions.cs | 13 + .../Samples/ISampleAppService.cs | 11 + .../Samples/SampleDto.cs | 6 + .../Subscribers/ISubscriberAppService.cs | 15 + .../Ammeters/AmmeterInfo.cs | 99 + .../CollectBusAppService.cs | 18 + .../CollectBusApplicationAutoMapperProfile.cs | 13 + .../CollectBusApplicationModule.cs | 53 + .../Consumers/IssuedConsumer.cs | 64 + .../Consumers/IssuedFaultConsumer.cs | 15 + .../Consumers/ReceivedConsumer.cs | 58 + .../Consumers/ReceivedFaultConsumer.cs | 15 + .../Consumers/ReceivedHeartbeatConsumer.cs | 46 + .../Consumers/ReceivedLoginConsumer.cs | 47 + .../Exceptions/CloseException.cs | 4 +- .../FodyWeavers.xml | 3 + ...She - Backup.CollectBus.Application.csproj | 38 + .../JiShe.CollectBus.Application.abppkg | 3 + .../JiShe.CollectBus.Application.csproj | 34 + .../Plugins/CloseMonitor.cs | 6 +- .../Plugins/ServerMonitor.cs | 7 +- .../Plugins/TcpMonitor.cs | 177 ++ .../Plugins/UdpMonitor.cs | 3 +- .../Samples/SampleAppService.cs | 39 + .../Subscribers/SubscriberAppService.cs | 133 ++ .../Workers/EpiCollectWorker.cs | 29 + .../cmd3761Matching.txt | 272 +++ .../cmd3761TdcMatching.txt | 49 + .../Consts/RegexConst.cs | 0 src/JiShe.CollectBus.Common/Enums/188Enums.cs | 35 + src/JiShe.CollectBus.Common/Enums/376Enums.cs | 318 ++++ .../Enums/645Enums.cs | 0 .../Enums/CommandChunkEnum.cs | 0 .../Enums/F25DataItemEnum.cs | 0 .../Enums/MaskTypeEnum.cs | 0 .../Enums/SortEnum.cs | 0 .../Enums/TransparentForwardingFlagEnum.cs | 0 .../Extensions/CollectionExtensions.cs | 0 .../Extensions/ComparableExtensions.cs | 0 .../Extensions/DataTableExtensions.cs | 0 .../Extensions/DateTimeExtensions.cs | 0 .../Extensions/DayOfWeekExtensions.cs | 0 .../Extensions/DecimalOrIntExtensions.cs | 0 .../Extensions/DictionaryExtensions.cs | 0 .../Extensions/EnumerableExtensions.cs | 0 .../Extensions/EventHandlerExtensions.cs | 0 .../Extensions/ExceptionExtensions.cs | 0 .../Extensions/HexStringExtensions.cs | 1640 +++++++++++++++++ .../Extensions/HttpResponseExtensions.cs | 0 .../Extensions/IntExtensions.cs | 0 .../Extensions/ListExtensions.cs | 0 .../Extensions/LockExtensions.cs | 0 .../Extensions/ObjectExtensions.cs | 0 .../Extensions/StreamExtensions.cs | 0 .../Extensions/StringExtensions.cs | 29 + .../Extensions/XmlExtensions.cs | 0 .../Helpers/TypeHelper.cs | 0 .../JiShe.CollectBus.Common.csproj | 6 + .../JiShe.CollectBus.Common}/Jobs/IBaseJob.cs | 0 .../Models/CommandReuslt.cs | 0 .../Models/IssuedEventMessage.cs | 2 +- .../Models/ReqParameter.cs | 57 + .../CollectBusDbMigratorModule.cs | 14 + .../DbMigratorHostedService.cs | 51 + src/JiShe.CollectBus.DbMigrator/Dockerfile | 5 + .../FodyWeavers.xml | 3 + .../JiShe.CollectBus.DbMigrator.abppkg | 1 + .../JiShe.CollectBus.DbMigrator.csproj | 46 + src/JiShe.CollectBus.DbMigrator/Program.cs | 39 + .../appsettings.json | 5 + .../appsettings.secrets.json | 2 + .../CollectBusDomainSharedConsts.cs | 20 + .../CollectBusDomainSharedModule.cs | 45 + .../CollectBusErrorCodes.cs | 7 + .../CollectBusGlobalFeatureConfigurator.cs | 19 + .../CollectBusModuleExtensionConfigurator.cs | 69 + .../Enums/DeviceStatus.cs | 16 + .../FodyWeavers.xml | 3 + .../Interceptors/ProtocolInspectAttribute.cs | 13 + .../ProtocolInspectInterceptor.cs | 18 + .../ProtocolInspectInterceptorRegistrar.cs | 24 + .../Interfaces/IProtocolInfo.cs | 2 +- .../JiShe.CollectBus.Domain.Shared.abppkg | 3 + .../JiShe.CollectBus.Domain.Shared.csproj | 35 + .../Jobs/EPICollectArgs.cs | 12 + .../Localization/CollectBus/ar.json | 7 + .../Localization/CollectBus/cs.json | 7 + .../Localization/CollectBus/de.json | 7 + .../Localization/CollectBus/en-GB.json | 7 + .../Localization/CollectBus/en.json | 7 + .../Localization/CollectBus/es.json | 7 + .../Localization/CollectBus/fi.json | 7 + .../Localization/CollectBus/fr.json | 7 + .../Localization/CollectBus/hi.json | 7 + .../Localization/CollectBus/hr.json | 7 + .../Localization/CollectBus/hu.json | 7 + .../Localization/CollectBus/is.json | 7 + .../Localization/CollectBus/it.json | 7 + .../Localization/CollectBus/nl.json | 7 + .../Localization/CollectBus/pl-PL.json | 7 + .../Localization/CollectBus/pt-BR.json | 7 + .../Localization/CollectBus/ro-RO.json | 7 + .../Localization/CollectBus/ru.json | 7 + .../Localization/CollectBus/sk.json | 7 + .../Localization/CollectBus/sl.json | 7 + .../Localization/CollectBus/tr.json | 7 + .../Localization/CollectBus/vi.json | 7 + .../Localization/CollectBus/zh-Hans.json | 7 + .../Localization/CollectBus/zh-Hant.json | 7 + .../Localization/CollectBusResource.cs | 9 + .../Ammeters/AmmeterInfo.cs | 99 + .../CollectBusConsts.cs | 7 + .../CollectBusDbProperties.cs | 10 + .../CollectBusDomainModule.cs | 48 + .../Data/CollectBusDbMigrationService.cs | 55 + .../Data/ICollectBusDbSchemaMigrator.cs | 8 + .../Data/NullCollectBusDbSchemaMigrator.cs | 15 + src/JiShe.CollectBus.Domain/Devices/Device.cs | 55 + src/JiShe.CollectBus.Domain/FodyWeavers.xml | 3 + .../JiShe - Backup.CollectBus.Domain.csproj | 32 + .../JiShe.CollectBus.Domain.abppkg | 3 + .../JiShe.CollectBus.Domain.csproj | 29 + .../MessageIssueds/MessageIssued.cs | 18 + .../MessageReceiveds}/IReceived.cs | 2 +- .../MessageReceiveds/MessageReceived.cs | 11 +- .../PrepayModel/Vi_BaseAmmeterInfo.cs | 129 ++ .../Properties/AssemblyInfo.cs | 3 + .../Protocols}/ProtocolInfo.cs | 16 +- .../CollectBusSettingDefinitionProvider.cs | 12 + .../Settings/CollectBusSettings.cs | 9 + .../CollectBusDbContext.cs | 39 + .../CollectBusDbContextFactory.cs | 33 + ...CollectBusEfCoreEntityExtensionMappings.cs | 44 + .../CollectBusEntityFrameworkCoreModule.cs | 50 + ...FrameworkCoreCollectBusDbSchemaMigrator.cs | 33 + .../FodyWeavers.xml | 3 + ...iShe.CollectBus.EntityFrameworkCore.abppkg | 3 + ...iShe.CollectBus.EntityFrameworkCore.csproj | 40 + .../Properties/AssemblyInfo.cs | 2 + .../CollectBusFreeSqlModule.cs | 14 + src/JiShe.CollectBus.FreeSql/DbEnum.cs | 23 + .../FreeSqlProvider.cs | 37 + .../IFreeSqlProvider.cs | 12 + .../JiShe.CollectBus.FreeSql.csproj | 13 + .../CollectBusHostConst.cs | 16 + .../CollectBusHostModule.Configure.cs | 336 ++++ .../CollectBusHostModule.cs | 94 + .../Controllers/WeatherForecastController.cs | 33 + .../ServiceCollectionExtensions.cs | 0 .../Hangfire/JobRetryLastFilter.cs | 29 + .../HealthChecks/HealthCheckResponse.cs | 25 + .../JiShe.CollectBus.Host.csproj | 67 + .../JiShe.CollectBus.Host}/Plugins/ignore.txt | 0 src/JiShe.CollectBus.Host/Program.cs | 41 + .../Properties/launchSettings.json | 24 +- src/JiShe.CollectBus.Host/Startup.cs | 31 + .../Swaggers/EnumSchemaFilter.cs | 24 + .../Swaggers/HiddenAbpDefaultApiFilter.cs | 54 + .../Swaggers/SwaggerConfig.cs | 11 + src/JiShe.CollectBus.Host/WeatherForecast.cs | 13 + .../appsettings.Development.json | 0 src/JiShe.CollectBus.Host/appsettings.json | 84 + .../CollectBusController.cs | 12 + .../CollectBusHttpApiModule.cs | 40 + src/JiShe.CollectBus.HttpApi/FodyWeavers.xml | 3 + .../JiShe.CollectBus.HttpApi.abppkg | 3 + .../JiShe.CollectBus.HttpApi.csproj | 23 + .../Samples/SampleController.cs | 33 + src/JiShe.CollectBus.MongoDB/FodyWeavers.xml | 3 + .../JiShe.CollectBus.MongoDB.abppkg | 3 + .../JiShe.CollectBus.MongoDB.csproj | 23 + .../MongoDB/CollectBusDbSchemaMigrator.cs | 52 + .../MongoDB/CollectBusMongoDbContext.cs | 31 + .../CollectBusMongoDbContextExtensions.cs | 13 + .../MongoDB/CollectBusMongoDbModule.cs | 31 + .../MongoDB/ICollectBusMongoDbContext.cs | 12 + .../Abstracts/BaseProtocolPlugin.cs | 552 ++++-- .../StandardFixedHeaderDataHandlingAdapter.cs | 0 .../Attributes/ProtocolNameAttribute.cs | 0 .../Interfaces/IProtocolPlugin.cs | 23 + ...JiShe.CollectBus.Protocol.Contracts.csproj | 3 + .../Models/CustomFixedHeaderRequestInfo.cs | 0 .../Models/TB3761.cs | 54 + .../ProtocolConst.cs | 18 + .../QGDW3761Config.cs | 70 + .../JiShe.CollectBus.Protocol.csproj | 6 +- .../JiSheCollectBusProtocolModule.cs | 9 +- .../StandardProtocolPlugin.cs | 64 +- .../CollectBusApplicationTestBase.cs | 12 + .../CollectBusApplicationTestModule.cs | 12 + .../FodyWeavers.xml | 3 + .../JiShe.CollectBus.Application.Tests.abppkg | 3 + .../JiShe.CollectBus.Application.Tests.csproj | 17 + .../Samples/SampleAppService_Tests.cs | 31 + .../CollectBusDomainTestBase.cs | 12 + .../CollectBusDomainTestModule.cs | 12 + .../FodyWeavers.xml | 3 + .../JiShe.CollectBus.Domain.Tests.abppkg | 3 + .../JiShe.CollectBus.Domain.Tests.csproj | 21 + .../Samples/SampleManager_Tests.cs | 22 + .../EfCoreSampleAppService_Tests.cs | 9 + .../CollectBusEntityFrameworkCoreTestBase.cs | 9 + ...CollectBusEntityFrameworkCoreTestModule.cs | 45 + .../Domains/EfCoreSampleDomain_Tests.cs | 9 + .../Samples/SampleRepository_Tests.cs | 11 + .../FodyWeavers.xml | 3 + ...ollectBus.EntityFrameworkCore.Tests.abppkg | 3 + ...ollectBus.EntityFrameworkCore.Tests.csproj | 19 + .../FodyWeavers.xml | 3 + .../JiShe.CollectBus.MongoDB.Tests.abppkg | 3 + .../JiShe.CollectBus.MongoDB.Tests.csproj | 21 + .../MongoDBSampleAppService_Tests.cs | 11 + .../MongoDB/CollectBusMongoDbTestBase.cs | 9 + .../MongoDB/CollectBusMongoDbTestModule.cs | 21 + .../Domains/MongoDBSampleDomain_Tests.cs | 10 + .../MongoDB/MongoDbFixture.cs | 34 + .../MongoDB/MongoTestCollection.cs | 9 + .../MongoDB/Samples/SampleRepository_Tests.cs | 13 + .../CollectBusDataSeedContributor.cs | 32 + .../CollectBusTestBase.cs | 59 + .../CollectBusTestBaseModule.cs | 42 + .../JiShe.CollectBus.TestBase/FodyWeavers.xml | 3 + .../JiShe.CollectBus.TestBase.abppkg | 3 + .../JiShe.CollectBus.TestBase.csproj | 28 + .../Samples/SampleRepository_Tests.cs | 26 + .../Security/FakeCurrentPrincipalAccessor.cs | 27 + 313 files changed, 7701 insertions(+), 4608 deletions(-) create mode 100644 .editorconfig delete mode 100644 JiShe.CollectBus.Application.Contracts/ICommandService.cs delete mode 100644 JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.csproj delete mode 100644 JiShe.CollectBus.Application/CommandService.cs delete mode 100644 JiShe.CollectBus.Application/Extensions/ServiceCollections/ServiceCollectionExtensions.cs delete mode 100644 JiShe.CollectBus.Application/JiShe.CollectBus.Application.csproj delete mode 100644 JiShe.CollectBus.Application/JiSheCollectBusApplicationModule.cs delete mode 100644 JiShe.CollectBus.Application/Jobs/TestJob.cs delete mode 100644 JiShe.CollectBus.Common/Enums/376Enums.cs delete mode 100644 JiShe.CollectBus.Common/Enums/CommandChunkEnum188.cs delete mode 100644 JiShe.CollectBus.Common/Extensions/HexStringExtensions.cs delete mode 100644 JiShe.CollectBus.Console/Extensions/DependencyInjections/DependencyInjectionExtensions.cs delete mode 100644 JiShe.CollectBus.Console/JiShe.CollectBus.Console.csproj delete mode 100644 JiShe.CollectBus.Console/Program.cs delete mode 100644 JiShe.CollectBus.Console/appsettings.json delete mode 100644 JiShe.CollectBus.Core/JiShe.CollectBus.Network.csproj delete mode 100644 JiShe.CollectBus.Core/JiSheCollectBusNetworkModule.cs delete mode 100644 JiShe.CollectBus.Core/Plugins/TcpMonitor.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/AuditLogs/AuditLog.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/CollectBusDbContext.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Device.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Entities/EntityBase.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Entities/FullAuditedEntity.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Entities/ICreationAudited.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Entities/IDeletionAudited.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Entities/IExtendableObject.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Entities/IModificationAudited.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Extensions/ExtendableObjectExtensions.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.csproj delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/JiSheCollectBusEntityFrameworkCoreModule.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Migrations/20241022055227_Init.Designer.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Migrations/20241022055227_Init.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Migrations/CollectBusDbContextModelSnapshot.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Repositories/IRepository.cs delete mode 100644 JiShe.CollectBus.EntityFrameworkCore/Repositories/Repository.cs delete mode 100644 JiShe.CollectBus.Host/Controllers/CommandController.cs delete mode 100644 JiShe.CollectBus.Host/Extensions/ServiceCollections/ServiceCollectionExtensions.cs delete mode 100644 JiShe.CollectBus.Host/JiShe.CollectBus.Host.csproj delete mode 100644 JiShe.CollectBus.Host/JiSheCollectBusHostModule.cs delete mode 100644 JiShe.CollectBus.Host/Models/GeneralIssuedInput.cs delete mode 100644 JiShe.CollectBus.Host/Program.cs delete mode 100644 JiShe.CollectBus.Host/Startup.cs delete mode 100644 JiShe.CollectBus.Host/appsettings.json delete mode 100644 JiShe.CollectBus.MongoDB/IMongoContext.cs delete mode 100644 JiShe.CollectBus.MongoDB/IMongoRepository.cs delete mode 100644 JiShe.CollectBus.MongoDB/IUnitOfWork.cs delete mode 100644 JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.csproj delete mode 100644 JiShe.CollectBus.MongoDB/JiSheCollectBusMongoDBModule.cs delete mode 100644 JiShe.CollectBus.MongoDB/MongoBaseRepository.cs delete mode 100644 JiShe.CollectBus.MongoDB/MongoContext.cs delete mode 100644 JiShe.CollectBus.MongoDB/UnitOfWork.cs delete mode 100644 JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolPlugin.cs delete mode 100644 JiShe.CollectBus.Protocol.Test/JiShe.CollectBus.Protocol.Demo.csproj delete mode 100644 JiShe.CollectBus.Protocol.Test/JiSheCollectBusTestProtocolModule.cs delete mode 100644 JiShe.CollectBus.Protocol.Test/TestProtocolPlugin.cs delete mode 100644 JiShe.CollectBus.RabbitMQ/INSender.cs delete mode 100644 JiShe.CollectBus.RabbitMQ/JiShe.CollectBus.MQ.Sender.csproj delete mode 100644 JiShe.CollectBus.RabbitMQ/JiSheCollectBusMQSenderModule.cs delete mode 100644 JiShe.CollectBus.RabbitMQ/NSender.cs delete mode 100644 JiShe.CollectBus.Service/JiShe.CollectBus.MQ.Consumer.csproj delete mode 100644 JiShe.CollectBus.Service/JiSheCollectBusMQConsumerModule.cs delete mode 100644 JiShe.CollectBus.Service/MessageIssuedConsumer.cs delete mode 100644 JiShe.CollectBus.Service/MessageIssuedFaultConsumer.cs delete mode 100644 JiShe.CollectBus.Service/MessageReceivedConsumer.cs delete mode 100644 JiShe.CollectBus.Service/MessageReceivedFaultConsumer.cs delete mode 100644 JiShe.CollectBus.Service/MessageReceivedHeartbeatConsumer.cs delete mode 100644 JiShe.CollectBus.Service/MessageReceivedLoginConsumer.cs delete mode 100644 JiShe.CollectBus.Test/BusUnitTest.cs delete mode 100644 JiShe.CollectBus.Test/JiShe.CollectBus.Test.csproj create mode 100644 JiShe.CollectBus.abpmdl create mode 100644 JiShe.CollectBus.abpsln create mode 100644 common.props delete mode 100644 dockerfile create mode 100644 src/JiShe.CollectBus.Application.Contracts/BaseResultDto.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/CollectBusApplicationContractsModule.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/CollectBusRemoteServiceConsts.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/EnergySystem/Dto/ValveControlInput.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/EnergySystem/Dto/ValveControlOutput.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/EnergySystem/IEnergySystemAppService.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/FodyWeavers.xml rename JiShe.CollectBus.EntityFrameworkCore/Entities/IEntity.cs => src/JiShe.CollectBus.Application.Contracts/ICollectWorker.cs (53%) create mode 100644 src/JiShe.CollectBus.Application.Contracts/JiShe - Backup.CollectBus.Application.Contracts.csproj create mode 100644 src/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.abppkg create mode 100644 src/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.csproj create mode 100644 src/JiShe.CollectBus.Application.Contracts/Permissions/CollectBusPermissionDefinitionProvider.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/Permissions/CollectBusPermissions.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/Samples/ISampleAppService.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/Samples/SampleDto.cs create mode 100644 src/JiShe.CollectBus.Application.Contracts/Subscribers/ISubscriberAppService.cs create mode 100644 src/JiShe.CollectBus.Application/Ammeters/AmmeterInfo.cs create mode 100644 src/JiShe.CollectBus.Application/CollectBusAppService.cs create mode 100644 src/JiShe.CollectBus.Application/CollectBusApplicationAutoMapperProfile.cs create mode 100644 src/JiShe.CollectBus.Application/CollectBusApplicationModule.cs create mode 100644 src/JiShe.CollectBus.Application/Consumers/IssuedConsumer.cs create mode 100644 src/JiShe.CollectBus.Application/Consumers/IssuedFaultConsumer.cs create mode 100644 src/JiShe.CollectBus.Application/Consumers/ReceivedConsumer.cs create mode 100644 src/JiShe.CollectBus.Application/Consumers/ReceivedFaultConsumer.cs create mode 100644 src/JiShe.CollectBus.Application/Consumers/ReceivedHeartbeatConsumer.cs create mode 100644 src/JiShe.CollectBus.Application/Consumers/ReceivedLoginConsumer.cs rename {JiShe.CollectBus.Core => src/JiShe.CollectBus.Application}/Exceptions/CloseException.cs (54%) create mode 100644 src/JiShe.CollectBus.Application/FodyWeavers.xml create mode 100644 src/JiShe.CollectBus.Application/JiShe - Backup.CollectBus.Application.csproj create mode 100644 src/JiShe.CollectBus.Application/JiShe.CollectBus.Application.abppkg create mode 100644 src/JiShe.CollectBus.Application/JiShe.CollectBus.Application.csproj rename {JiShe.CollectBus.Core => src/JiShe.CollectBus.Application}/Plugins/CloseMonitor.cs (90%) rename {JiShe.CollectBus.Core => src/JiShe.CollectBus.Application}/Plugins/ServerMonitor.cs (86%) create mode 100644 src/JiShe.CollectBus.Application/Plugins/TcpMonitor.cs rename {JiShe.CollectBus.Core => src/JiShe.CollectBus.Application}/Plugins/UdpMonitor.cs (89%) create mode 100644 src/JiShe.CollectBus.Application/Samples/SampleAppService.cs create mode 100644 src/JiShe.CollectBus.Application/Subscribers/SubscriberAppService.cs create mode 100644 src/JiShe.CollectBus.Application/Workers/EpiCollectWorker.cs create mode 100644 src/JiShe.CollectBus.Application/cmd3761Matching.txt create mode 100644 src/JiShe.CollectBus.Application/cmd3761TdcMatching.txt rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Consts/RegexConst.cs (100%) create mode 100644 src/JiShe.CollectBus.Common/Enums/188Enums.cs create mode 100644 src/JiShe.CollectBus.Common/Enums/376Enums.cs rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Enums/645Enums.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Enums/CommandChunkEnum.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Enums/F25DataItemEnum.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Enums/MaskTypeEnum.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Enums/SortEnum.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Enums/TransparentForwardingFlagEnum.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/CollectionExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/ComparableExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/DataTableExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/DateTimeExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/DayOfWeekExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/DecimalOrIntExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/DictionaryExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/EnumerableExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/EventHandlerExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/ExceptionExtensions.cs (100%) create mode 100644 src/JiShe.CollectBus.Common/Extensions/HexStringExtensions.cs rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/HttpResponseExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/IntExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/ListExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/LockExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/ObjectExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/StreamExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/StringExtensions.cs (97%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Extensions/XmlExtensions.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Helpers/TypeHelper.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/JiShe.CollectBus.Common.csproj (82%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Jobs/IBaseJob.cs (100%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Models/CommandReuslt.cs (100%) rename JiShe.CollectBus.Common/Models/MessageIssuedEvent.cs => src/JiShe.CollectBus.Common/Models/IssuedEventMessage.cs (90%) rename {JiShe.CollectBus.Common => src/JiShe.CollectBus.Common}/Models/ReqParameter.cs (58%) create mode 100644 src/JiShe.CollectBus.DbMigrator/CollectBusDbMigratorModule.cs create mode 100644 src/JiShe.CollectBus.DbMigrator/DbMigratorHostedService.cs create mode 100644 src/JiShe.CollectBus.DbMigrator/Dockerfile create mode 100644 src/JiShe.CollectBus.DbMigrator/FodyWeavers.xml create mode 100644 src/JiShe.CollectBus.DbMigrator/JiShe.CollectBus.DbMigrator.abppkg create mode 100644 src/JiShe.CollectBus.DbMigrator/JiShe.CollectBus.DbMigrator.csproj create mode 100644 src/JiShe.CollectBus.DbMigrator/Program.cs create mode 100644 src/JiShe.CollectBus.DbMigrator/appsettings.json create mode 100644 src/JiShe.CollectBus.DbMigrator/appsettings.secrets.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/CollectBusDomainSharedConsts.cs create mode 100644 src/JiShe.CollectBus.Domain.Shared/CollectBusDomainSharedModule.cs create mode 100644 src/JiShe.CollectBus.Domain.Shared/CollectBusErrorCodes.cs create mode 100644 src/JiShe.CollectBus.Domain.Shared/CollectBusGlobalFeatureConfigurator.cs create mode 100644 src/JiShe.CollectBus.Domain.Shared/CollectBusModuleExtensionConfigurator.cs create mode 100644 src/JiShe.CollectBus.Domain.Shared/Enums/DeviceStatus.cs create mode 100644 src/JiShe.CollectBus.Domain.Shared/FodyWeavers.xml create mode 100644 src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectAttribute.cs create mode 100644 src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectInterceptor.cs create mode 100644 src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectInterceptorRegistrar.cs rename {JiShe.CollectBus.Protocol.Contracts => src/JiShe.CollectBus.Domain.Shared}/Interfaces/IProtocolInfo.cs (91%) create mode 100644 src/JiShe.CollectBus.Domain.Shared/JiShe.CollectBus.Domain.Shared.abppkg create mode 100644 src/JiShe.CollectBus.Domain.Shared/JiShe.CollectBus.Domain.Shared.csproj create mode 100644 src/JiShe.CollectBus.Domain.Shared/Jobs/EPICollectArgs.cs create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ar.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/cs.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/de.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/en-GB.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/en.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/es.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/fi.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/fr.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hi.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hr.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hu.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/is.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/it.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/nl.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/pl-PL.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/pt-BR.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ro-RO.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ru.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/sk.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/sl.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/tr.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/vi.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/zh-Hans.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/zh-Hant.json create mode 100644 src/JiShe.CollectBus.Domain.Shared/Localization/CollectBusResource.cs create mode 100644 src/JiShe.CollectBus.Domain/Ammeters/AmmeterInfo.cs create mode 100644 src/JiShe.CollectBus.Domain/CollectBusConsts.cs create mode 100644 src/JiShe.CollectBus.Domain/CollectBusDbProperties.cs create mode 100644 src/JiShe.CollectBus.Domain/CollectBusDomainModule.cs create mode 100644 src/JiShe.CollectBus.Domain/Data/CollectBusDbMigrationService.cs create mode 100644 src/JiShe.CollectBus.Domain/Data/ICollectBusDbSchemaMigrator.cs create mode 100644 src/JiShe.CollectBus.Domain/Data/NullCollectBusDbSchemaMigrator.cs create mode 100644 src/JiShe.CollectBus.Domain/Devices/Device.cs create mode 100644 src/JiShe.CollectBus.Domain/FodyWeavers.xml create mode 100644 src/JiShe.CollectBus.Domain/JiShe - Backup.CollectBus.Domain.csproj create mode 100644 src/JiShe.CollectBus.Domain/JiShe.CollectBus.Domain.abppkg create mode 100644 src/JiShe.CollectBus.Domain/JiShe.CollectBus.Domain.csproj create mode 100644 src/JiShe.CollectBus.Domain/MessageIssueds/MessageIssued.cs rename {JiShe.CollectBus.Common/Interfaces => src/JiShe.CollectBus.Domain/MessageReceiveds}/IReceived.cs (64%) rename JiShe.CollectBus.Common/Models/MessageReceivedEvent.cs => src/JiShe.CollectBus.Domain/MessageReceiveds/MessageReceived.cs (80%) create mode 100644 src/JiShe.CollectBus.Domain/PrepayModel/Vi_BaseAmmeterInfo.cs create mode 100644 src/JiShe.CollectBus.Domain/Properties/AssemblyInfo.cs rename {JiShe.CollectBus.Protocol.Contracts/Models => src/JiShe.CollectBus.Domain/Protocols}/ProtocolInfo.cs (67%) create mode 100644 src/JiShe.CollectBus.Domain/Settings/CollectBusSettingDefinitionProvider.cs create mode 100644 src/JiShe.CollectBus.Domain/Settings/CollectBusSettings.cs create mode 100644 src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusDbContext.cs create mode 100644 src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusDbContextFactory.cs create mode 100644 src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusEfCoreEntityExtensionMappings.cs create mode 100644 src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusEntityFrameworkCoreModule.cs create mode 100644 src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/EntityFrameworkCoreCollectBusDbSchemaMigrator.cs create mode 100644 src/JiShe.CollectBus.EntityFrameworkCore/FodyWeavers.xml create mode 100644 src/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.abppkg create mode 100644 src/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.csproj create mode 100644 src/JiShe.CollectBus.EntityFrameworkCore/Properties/AssemblyInfo.cs create mode 100644 src/JiShe.CollectBus.FreeSql/CollectBusFreeSqlModule.cs create mode 100644 src/JiShe.CollectBus.FreeSql/DbEnum.cs create mode 100644 src/JiShe.CollectBus.FreeSql/FreeSqlProvider.cs create mode 100644 src/JiShe.CollectBus.FreeSql/IFreeSqlProvider.cs create mode 100644 src/JiShe.CollectBus.FreeSql/JiShe.CollectBus.FreeSql.csproj create mode 100644 src/JiShe.CollectBus.Host/CollectBusHostConst.cs create mode 100644 src/JiShe.CollectBus.Host/CollectBusHostModule.Configure.cs create mode 100644 src/JiShe.CollectBus.Host/CollectBusHostModule.cs create mode 100644 src/JiShe.CollectBus.Host/Controllers/WeatherForecastController.cs rename {JiShe.CollectBus.Console => src/JiShe.CollectBus.Host}/Extensions/ServiceCollections/ServiceCollectionExtensions.cs (100%) create mode 100644 src/JiShe.CollectBus.Host/Hangfire/JobRetryLastFilter.cs create mode 100644 src/JiShe.CollectBus.Host/HealthChecks/HealthCheckResponse.cs create mode 100644 src/JiShe.CollectBus.Host/JiShe.CollectBus.Host.csproj rename {JiShe.CollectBus.Console => src/JiShe.CollectBus.Host}/Plugins/ignore.txt (100%) create mode 100644 src/JiShe.CollectBus.Host/Program.cs rename {JiShe.CollectBus.Host => src/JiShe.CollectBus.Host}/Properties/launchSettings.json (82%) create mode 100644 src/JiShe.CollectBus.Host/Startup.cs create mode 100644 src/JiShe.CollectBus.Host/Swaggers/EnumSchemaFilter.cs create mode 100644 src/JiShe.CollectBus.Host/Swaggers/HiddenAbpDefaultApiFilter.cs create mode 100644 src/JiShe.CollectBus.Host/Swaggers/SwaggerConfig.cs create mode 100644 src/JiShe.CollectBus.Host/WeatherForecast.cs rename {JiShe.CollectBus.Host => src/JiShe.CollectBus.Host}/appsettings.Development.json (100%) create mode 100644 src/JiShe.CollectBus.Host/appsettings.json create mode 100644 src/JiShe.CollectBus.HttpApi/CollectBusController.cs create mode 100644 src/JiShe.CollectBus.HttpApi/CollectBusHttpApiModule.cs create mode 100644 src/JiShe.CollectBus.HttpApi/FodyWeavers.xml create mode 100644 src/JiShe.CollectBus.HttpApi/JiShe.CollectBus.HttpApi.abppkg create mode 100644 src/JiShe.CollectBus.HttpApi/JiShe.CollectBus.HttpApi.csproj create mode 100644 src/JiShe.CollectBus.HttpApi/Samples/SampleController.cs create mode 100644 src/JiShe.CollectBus.MongoDB/FodyWeavers.xml create mode 100644 src/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.abppkg create mode 100644 src/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.csproj create mode 100644 src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusDbSchemaMigrator.cs create mode 100644 src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbContext.cs create mode 100644 src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbContextExtensions.cs create mode 100644 src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbModule.cs create mode 100644 src/JiShe.CollectBus.MongoDB/MongoDB/ICollectBusMongoDbContext.cs rename {JiShe.CollectBus.Protocol.Contracts => src/JiShe.CollectBus.Protocol.Contracts}/Abstracts/BaseProtocolPlugin.cs (52%) rename {JiShe.CollectBus.Protocol.Contracts => src/JiShe.CollectBus.Protocol.Contracts}/Adapters/StandardFixedHeaderDataHandlingAdapter.cs (100%) rename {JiShe.CollectBus.Protocol.Contracts => src/JiShe.CollectBus.Protocol.Contracts}/Attributes/ProtocolNameAttribute.cs (100%) create mode 100644 src/JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolPlugin.cs rename {JiShe.CollectBus.Protocol.Contracts => src/JiShe.CollectBus.Protocol.Contracts}/JiShe.CollectBus.Protocol.Contracts.csproj (78%) rename {JiShe.CollectBus.Protocol.Contracts => src/JiShe.CollectBus.Protocol.Contracts}/Models/CustomFixedHeaderRequestInfo.cs (100%) create mode 100644 src/JiShe.CollectBus.Protocol.Contracts/Models/TB3761.cs create mode 100644 src/JiShe.CollectBus.Protocol.Contracts/ProtocolConst.cs create mode 100644 src/JiShe.CollectBus.Protocol.Contracts/QGDW3761Config.cs rename {JiShe.CollectBus.Protocol => src/JiShe.CollectBus.Protocol}/JiShe.CollectBus.Protocol.csproj (74%) rename {JiShe.CollectBus.Protocol => src/JiShe.CollectBus.Protocol}/JiSheCollectBusProtocolModule.cs (63%) rename {JiShe.CollectBus.Protocol => src/JiShe.CollectBus.Protocol}/StandardProtocolPlugin.cs (71%) create mode 100644 test/JiShe.CollectBus.Application.Tests/CollectBusApplicationTestBase.cs create mode 100644 test/JiShe.CollectBus.Application.Tests/CollectBusApplicationTestModule.cs create mode 100644 test/JiShe.CollectBus.Application.Tests/FodyWeavers.xml create mode 100644 test/JiShe.CollectBus.Application.Tests/JiShe.CollectBus.Application.Tests.abppkg create mode 100644 test/JiShe.CollectBus.Application.Tests/JiShe.CollectBus.Application.Tests.csproj create mode 100644 test/JiShe.CollectBus.Application.Tests/Samples/SampleAppService_Tests.cs create mode 100644 test/JiShe.CollectBus.Domain.Tests/CollectBusDomainTestBase.cs create mode 100644 test/JiShe.CollectBus.Domain.Tests/CollectBusDomainTestModule.cs create mode 100644 test/JiShe.CollectBus.Domain.Tests/FodyWeavers.xml create mode 100644 test/JiShe.CollectBus.Domain.Tests/JiShe.CollectBus.Domain.Tests.abppkg create mode 100644 test/JiShe.CollectBus.Domain.Tests/JiShe.CollectBus.Domain.Tests.csproj create mode 100644 test/JiShe.CollectBus.Domain.Tests/Samples/SampleManager_Tests.cs create mode 100644 test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Applications/EfCoreSampleAppService_Tests.cs create mode 100644 test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/CollectBusEntityFrameworkCoreTestBase.cs create mode 100644 test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/CollectBusEntityFrameworkCoreTestModule.cs create mode 100644 test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Domains/EfCoreSampleDomain_Tests.cs create mode 100644 test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Samples/SampleRepository_Tests.cs create mode 100644 test/JiShe.CollectBus.EntityFrameworkCore.Tests/FodyWeavers.xml create mode 100644 test/JiShe.CollectBus.EntityFrameworkCore.Tests/JiShe.CollectBus.EntityFrameworkCore.Tests.abppkg create mode 100644 test/JiShe.CollectBus.EntityFrameworkCore.Tests/JiShe.CollectBus.EntityFrameworkCore.Tests.csproj create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/FodyWeavers.xml create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/JiShe.CollectBus.MongoDB.Tests.abppkg create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/JiShe.CollectBus.MongoDB.Tests.csproj create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Applications/MongoDBSampleAppService_Tests.cs create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/MongoDB/CollectBusMongoDbTestBase.cs create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/MongoDB/CollectBusMongoDbTestModule.cs create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Domains/MongoDBSampleDomain_Tests.cs create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/MongoDB/MongoDbFixture.cs create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/MongoDB/MongoTestCollection.cs create mode 100644 test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Samples/SampleRepository_Tests.cs create mode 100644 test/JiShe.CollectBus.TestBase/CollectBusDataSeedContributor.cs create mode 100644 test/JiShe.CollectBus.TestBase/CollectBusTestBase.cs create mode 100644 test/JiShe.CollectBus.TestBase/CollectBusTestBaseModule.cs create mode 100644 test/JiShe.CollectBus.TestBase/FodyWeavers.xml create mode 100644 test/JiShe.CollectBus.TestBase/JiShe.CollectBus.TestBase.abppkg create mode 100644 test/JiShe.CollectBus.TestBase/JiShe.CollectBus.TestBase.csproj create mode 100644 test/JiShe.CollectBus.TestBase/Samples/SampleRepository_Tests.cs create mode 100644 test/JiShe.CollectBus.TestBase/Security/FakeCurrentPrincipalAccessor.cs diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..3aa69ea --- /dev/null +++ b/.editorconfig @@ -0,0 +1,2 @@ +[*.csproj] +indent_size = 2 \ No newline at end of file diff --git a/.gitignore b/.gitignore index d392b0a..daafdc8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore # User-specific files *.rsuser @@ -29,7 +29,6 @@ x86/ bld/ [Bb]in/ [Oo]bj/ -[Oo]ut/ [Ll]og/ [Ll]ogs/ @@ -91,6 +90,7 @@ StyleCopReport.xml *.tmp_proj *_wpftmp.csproj *.log +*.tlog *.vspscc *.vssscc .builds @@ -294,6 +294,17 @@ node_modules/ # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts @@ -350,6 +361,9 @@ ASALocalRun/ # Local History for Visual Studio .localhistory/ +# Visual Studio History (VSHistory) files +.vshistory/ + # BeatPulse healthcheck temp database healthchecksdb @@ -361,4 +375,29 @@ MigrationBackup/ # Fody - auto-generated XML schema FodyWeavers.xsd -/JiShe.CollectBus.Console/Plugins/*.dll + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +**/.idea/ +*.sln.iml + +# ABP Studio +**/.abpstudio/ +/src/JiShe.CollectBus.Host/Plugins/*.dll diff --git a/JiShe.CollectBus.Application.Contracts/ICommandService.cs b/JiShe.CollectBus.Application.Contracts/ICommandService.cs deleted file mode 100644 index bb92045..0000000 --- a/JiShe.CollectBus.Application.Contracts/ICommandService.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace JiShe.CollectBus.Application.Contracts -{ - public interface ICommandService - { - Task AmmeterParameterSendAsync(); - bool AmmeterParameterReading(); - bool ActivePowerIndicationReading(); - } -} diff --git a/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.csproj b/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.csproj deleted file mode 100644 index fa71b7a..0000000 --- a/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net8.0 - enable - enable - - - diff --git a/JiShe.CollectBus.Application/CommandService.cs b/JiShe.CollectBus.Application/CommandService.cs deleted file mode 100644 index e60b893..0000000 --- a/JiShe.CollectBus.Application/CommandService.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using JiShe.CollectBus.Application.Contracts; -using JiShe.CollectBus.Common.Enums; -using JiShe.CollectBus.Common.Extensions; -using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.MQ.Sender; -using Microsoft.Extensions.Logging; -using Volo.Abp.DependencyInjection; - -namespace JiShe.CollectBus.Application -{ - public class CommandService: ICommandService,ISingletonDependency - { - private readonly ILogger _logger; - private readonly INSender _nSender; - - public async Task AmmeterParameterSendAsync() - { - - var listMeter = new List() - { - new AmmeterParameter() - { - Pn = 1, - BaudRate = 3, - Port = 2, - ProtocolType = CommunicationProtocolType.DLT6452007, - Address = "312408006642", - Password = "000000", - RateNumber = 4, - IntegerBitNumber = 4, - DecimalBitNumber = 4, - CollectorAddress = "000000000000", - UserCategoryNumber = 0, - UserSubclassNumber = 0 - } - }; - var bytes = HexStringExtensions.BuildAmmeterParameterSetSendCmd(new ReqParameter2() - { - AFN = AFN.设置参数, - FunCode = (int)CMasterStationFunCode.请求1级数据, - A = "322009872", - Seq = new Seq() - { - TpV = TpV.附加信息域中无时间标签, - FIRFIN = FIRFIN.单帧, - CON = CON.需要对该帧进行确认, - PRSEQ = 10, - }, - MSA = 13, - Pn = 0, - Fn = 10 - }, listMeter); - - await _nSender.SendToIssuedAsync(new MessageIssuedEvent { DeviceNo = "322009872", Message = bytes, Type = IssuedEventType.Data, MessageId = Guid.NewGuid().ToString() }); - return true; - } - - public bool AmmeterParameterReading() - { - HexStringExtensions.BuildAmmeterParameterReadingSendCmd(new ReqParameter2() - { - AFN = AFN.查询参数, - FunCode = (int)CMasterStationFunCode.请求2级数据, - A = "322009872", - Seq = new Seq() - { - TpV = TpV.附加信息域中无时间标签, - FIRFIN = FIRFIN.单帧, - CON = CON.不需要对该帧进行确认, - PRSEQ = 2, - }, - MSA = 13, - Pn = 0, - Fn = 10 - }, new List() { 1, 2 }); - - return true; - } - - public bool ActivePowerIndicationReading() - { - - //var str = "68A600A6006888203290261A0A6200000201010001000100621E426622082431000000000000040300000000000000CA16"; - //var cmdResult = new BuildCommand().AnalysisCmd(str); - //if(cmdResult != null) - //{ - // var list = new BuildCommand().AnalysisAFN04F10DataUnit(cmdResult.HexDatas); - //} - HexStringExtensions.BuildSendCommandBytes(new ReqParameter2() - { - AFN = AFN.请求实时数据, - FunCode = (int)CMasterStationFunCode.请求2级数据, - A = "322009872", - Seq = new Seq() - { - TpV = TpV.附加信息域中无时间标签, - FIRFIN = FIRFIN.单帧, - CON = CON.不需要对该帧进行确认, - PRSEQ = 2, - }, - MSA = 13, - Pn = 1, - Fn = 129 - }); - - //HexStringExtensions.AmmeterValveControl("312408006642", "", "000000", true); - - return true; - } - } -} diff --git a/JiShe.CollectBus.Application/Extensions/ServiceCollections/ServiceCollectionExtensions.cs b/JiShe.CollectBus.Application/Extensions/ServiceCollections/ServiceCollectionExtensions.cs deleted file mode 100644 index caae72a..0000000 --- a/JiShe.CollectBus.Application/Extensions/ServiceCollections/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Hangfire; -using Microsoft.Extensions.Configuration; -using System.Reflection; -using JiShe.CollectBus.Common.Jobs; - -// ReSharper disable once CheckNamespace -namespace Microsoft.Extensions.DependencyInjection -{ - public static class ServiceCollectionExtensions - { - /// - /// 添加TcpService服务。 - /// - public static IServiceCollection AddJobs(this IServiceCollection services, IConfiguration configuration) - { - - var interfaceType = typeof(IBaseJob); - var assembly = Assembly.GetExecutingAssembly(); - - var types = assembly.GetTypes(); - foreach (var type in types) - { - if (type.IsClass && type.GetInterfaces().Contains(interfaceType)) - { - var instance = services.GetServiceProviderOrNull().GetService(type); - - //var instance = services.GetObject(); - - //var instance = Activator.CreateInstance(type); - RecurringJob.AddOrUpdate(type.Name, () => type.GetMethod("Execute").Invoke(instance,null), Cron.Minutely); - } - } - return services; - } - } -} diff --git a/JiShe.CollectBus.Application/JiShe.CollectBus.Application.csproj b/JiShe.CollectBus.Application/JiShe.CollectBus.Application.csproj deleted file mode 100644 index f40c0e1..0000000 --- a/JiShe.CollectBus.Application/JiShe.CollectBus.Application.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - - - - - - diff --git a/JiShe.CollectBus.Application/JiSheCollectBusApplicationModule.cs b/JiShe.CollectBus.Application/JiSheCollectBusApplicationModule.cs deleted file mode 100644 index 4ff24bc..0000000 --- a/JiShe.CollectBus.Application/JiSheCollectBusApplicationModule.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Generic; -using System.Reflection; -using Hangfire; -using JiShe.CollectBus.Common.Jobs; -using JiShe.CollectBus.MQ.Sender; -using MassTransit; -using Microsoft.Extensions.DependencyInjection; -using Volo.Abp; -using Volo.Abp.Modularity; - -namespace JiShe.CollectBus.Application -{ - [DependsOn(typeof(JiSheCollectBusMqSenderModule))] - public class JiSheCollectBusApplicationModule: AbpModule - { - public override void ConfigureServices(ServiceConfigurationContext context) - { - - context.Services.AddSingleton(); - - //var configuration = context.Services.GetConfiguration(); - //context.Services.AddJobs(configuration); - } - - public override void OnPostApplicationInitialization(ApplicationInitializationContext context) - { - - var interfaceType = typeof(IBaseJob); - var assembly = Assembly.GetExecutingAssembly(); - - var types = assembly.GetTypes(); - foreach (var type in types) - { - if (type.IsClass && type.GetInterfaces().Contains(interfaceType)) - { - var instance = context.ServiceProvider.GetService(type); - - //var instance = services.GetObject(); - - //var instance = Activator.CreateInstance(type); - RecurringJob.AddOrUpdate(type.Name, () => type.GetMethod("Execute").Invoke(instance, null), Cron.Minutely); - } - } - } - } -} diff --git a/JiShe.CollectBus.Application/Jobs/TestJob.cs b/JiShe.CollectBus.Application/Jobs/TestJob.cs deleted file mode 100644 index bd98b37..0000000 --- a/JiShe.CollectBus.Application/Jobs/TestJob.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using JiShe.CollectBus.Common.Jobs; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Volo.Abp.DependencyInjection; - -namespace JiShe.CollectBus.Application.Jobs -{ - public class TestJob : IBaseJob,ISingletonDependency - { - private readonly ILogger _logger; - private readonly IConfiguration _configuration; - - public TestJob(ILogger logger, IConfiguration configuration) - { - _logger = logger; - _configuration = configuration; - } - - public async Task Execute() - { - //to do something - await Task.CompletedTask; - } - } -} diff --git a/JiShe.CollectBus.Common/Enums/376Enums.cs b/JiShe.CollectBus.Common/Enums/376Enums.cs deleted file mode 100644 index 593650c..0000000 --- a/JiShe.CollectBus.Common/Enums/376Enums.cs +++ /dev/null @@ -1,173 +0,0 @@ -namespace JiShe.CollectBus.Common.Enums -{ - /// - /// 规约标识 高位在前 D1+D0 - /// - public enum ProtocolIdentification - { - 禁用 = 00, - 电力负荷管理系统数据传输 = 01, - 本规约使用 = 10, - 保留 = 11 - } - - /// - /// 传输方向位 - /// - public enum DIR - { - 主站下行报文 = 0, - 终端上行报文 = 1 - } - - /// - /// 启动标识位 - /// - public enum PRM - { - 从动站报文 = 0, - 启动站报文 = 1, - } - - /// - /// 帧计数有效位 - /// - public enum FCV - { - FCB位无效 = 0, - FCB位有效 = 1 - } - - /// - /// 控制域(PRM=1)启动站功能码 - /// - public enum CMasterStationFunCode - { - 复位命令 = 1, - 用户数据 = 4, - 链路测试 = 9, - 请求1级数据 = 10, - 请求2级数据 = 11 - } - - /// - /// 控制域(PRM=0)从动站功能码 - /// - public enum CFromStationFunCode - { - 确认 = 0, - 用户数据 = 8, - 无所召唤的数据 = 9, - 链路数据 = 11 - } - - /// - /// 应用层功能码 - /// - public enum AFN - { - 确认或否认 = 00, - 复位 = 01, - 链路接口检测 = 02, - 中继站命令 = 03, - 设置参数 = 04, - 控制命令 = 05, - 身份认证及密钥协商 = 06, - 备用 = 07, - 请求被级联终端主动上报 = 08, - 请求终端配置 = 09, - 查询参数 = 10, - 请求任务数据 = 11, - 请求实时数据 = 12, - 请求历史数据 = 13, - 请求事件数据 = 14, - 文件传输 = 15, - 数据转发 = 16, - } - - /// - /// 帧时间标签有效位 - /// - public enum TpV - { - 附加信息域中无时间标签 = 0, - 附加信息域中带时间标签 = 1 - } - - /// - /// 首帧末帧标志 - /// - public enum FIRFIN - { - 中间帧 = 00, - 结束帧 = 01, - 第一帧 = 10, - 单帧 = 11 - } - - /// - /// 请求确认标志位 - /// - public enum CON - { - 不需要对该帧进行确认 = 0, - 需要对该帧进行确认 = 1 - } - - /// - /// 通信协议类型 数值0-255 - /// - public enum CommunicationProtocolType - { - DLT6451997 = 1, - 交流采样装置 = 2, - DLT6452007 = 30, - 串行接口连接窄带低压载波通讯 = 31 - } - - public enum BaudRate - { - Br300 = 0, - Br600 = 1, - Br1200 = 2, - Br2400 = 3, - Br4800 = 4, - Br7200 = 5, - Br9600 = 6, - Br19200 = 7 - } - public enum StopBit - { - Stop1 = 0, - Stop2 - } - public enum Parity - { - None = 0, - /// - /// 偶校验 - /// - Even, - /// - /// 奇校验 - /// - Odd - } - /// - /// 数据位 - /// - public enum DataBit - { - D5 = 0, - D6, - D7, - D8 - } - - public enum IssuedEventType - { - Heartbeat, - Login, - Data - } -} diff --git a/JiShe.CollectBus.Common/Enums/CommandChunkEnum188.cs b/JiShe.CollectBus.Common/Enums/CommandChunkEnum188.cs deleted file mode 100644 index 52f107b..0000000 --- a/JiShe.CollectBus.Common/Enums/CommandChunkEnum188.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JiShe.CollectBus.Common.Enums -{ - public enum CommandChunkEnum188 - { - - A = 2, - C=9, - L=10, - DI=11, - Data=14 - } -} diff --git a/JiShe.CollectBus.Common/Extensions/HexStringExtensions.cs b/JiShe.CollectBus.Common/Extensions/HexStringExtensions.cs deleted file mode 100644 index 2307a9e..0000000 --- a/JiShe.CollectBus.Common/Extensions/HexStringExtensions.cs +++ /dev/null @@ -1,757 +0,0 @@ -using JiShe.CollectBus.Common.Enums; -using JiShe.CollectBus.Common.Models; - -namespace JiShe.CollectBus.Common.Extensions -{ - public static class HexStringExtensions - { - //起始字符 - private const string startStr = "68"; - //结束字符 - private const string endStr = "16"; - //头部字节长度 - private const int hearderLen = 6; - //消息认证码字段长度 - private const int pWLen = 16; - - private const int tPLen = 6; - - private const int FixedLength = 18; - - public static object GetAnalyzeValue(this List hexStringList, CommandChunkEnum chunk) - { - if (hexStringList.Count < hearderLen || hexStringList[0] != startStr || hexStringList[5] != startStr || hexStringList.Count < FixedLength) - { - return null; - } - - switch (chunk) - { - case CommandChunkEnum.AFN: - var aFn = hexStringList[(int)CommandChunkEnum.AFN].HexToDec();//1字节 - return aFn; - case CommandChunkEnum.FN: - //(DT2*8)+DT1=fn - var dt1Bin = hexStringList[(int)CommandChunkEnum.FN - 1].HexToBin(); - var dt1 = dt1Bin != "0" ? dt1Bin.Length : 0; - var dt2 = hexStringList[(int)CommandChunkEnum.FN].HexToDec(); - var fn = dt2 * 8 + dt1; - return fn; - case CommandChunkEnum.A: - var aHexList = hexStringList.Skip((int)CommandChunkEnum.A).Take(5).ToList(); - var a1 = aHexList[1] + aHexList[0]; - var a2 = aHexList[3] + aHexList[2]; - var a2Dec = a2.HexToDec(); - var a3 = aHexList[4]; - var a = $"{a1}{a2Dec.ToString().PadLeft(5, '0')}"; - var a3Bin = aHexList[4].HexToBin().PadLeft(8, '0'); - var msa = a3Bin.Substring(0, 7).BinToDec(); - return new Tuple(a, msa); - case CommandChunkEnum.SEQ: - var seq = hexStringList[(int)CommandChunkEnum.SEQ].HexToBin().PadLeft(8, '0'); - var tpV = (TpV)Convert.ToInt32(seq.Substring(0, 1)); - var firfin = (FIRFIN)Convert.ToInt32(seq.Substring(1, 2)); - var con = (CON)Convert.ToInt32(seq.Substring(3, 1)); - var prseqBin = seq.Substring(4, 4); - return new Seq - { - CON = con, - FIRFIN = firfin, - PRSEQ = prseqBin.BinToDec(), - TpV = tpV - }; - case CommandChunkEnum.Data: - var lenIndex = (int)CommandChunkEnum.Len; - var lenBin = (hexStringList[lenIndex + 1]+hexStringList[lenIndex]).HexToBin(); - var len = lenBin.Remove(lenBin.Length - 2).BinToDec(); - - //验证长度 2=(帧校验和+结束字符) - if (hexStringList.Count - 2 != hearderLen + len) - return null; - - var dataHexList = hexStringList.Skip(FixedLength).Take(len + hearderLen - FixedLength).ToList(); - return dataHexList; - default: - throw new ArgumentOutOfRangeException(nameof(chunk), chunk, null); - } - } - - public static bool IsStartStr(this string str) - { - return str == startStr ? true : false; - } - - /// - /// 字节加33 - /// - /// - /// - public static List AddHex33(this List hexStringList) - { - for (int i = 0; i < hexStringList.Count; i++) - { - hexStringList[i] = (Convert.ToInt32(hexStringList[i], 16) + Convert.ToInt32("33", 16)).ToString("X2"); - if (hexStringList[i].Length > 2) - { - hexStringList[i] = hexStringList[i].Substring(hexStringList[i].Length - 2); - } - } - - return hexStringList; - } - - #region 376.1下行命令 - - /// - /// 构建电表参数设置-下发命令 - /// - /// - /// - /// - public static byte[] BuildAmmeterParameterSetSendCmd(ReqParameter reqParameter, List meterParameters) - { - var dataUnit = BuildAmmeterParameterSendDataUnit(meterParameters); - var bytes = BuildSendCommandBytes(reqParameter, dataUnit); - return bytes; - } - - /// - /// 构建电表参数读取-下发命令 - /// - /// - /// 对象序号 - public static void BuildAmmeterParameterReadingSendCmd(ReqParameter reqParameter, List meterNumberList) - { - var dataUnit = new List(); - var countHex = meterNumberList.Count().DecToHex().PadLeft(4, '0'); - var countHexPairs = countHex.StringToPairs(); - countHexPairs.Reverse(); - dataUnit.AddRange(countHexPairs); - - foreach (var number in meterNumberList) - { - var numberHex = number.DecToHex().PadLeft(4, '0'); - var numberHexPairs = numberHex.StringToPairs(); - numberHexPairs.Reverse(); - dataUnit.AddRange(numberHexPairs); - } - var bytes = BuildSendCommandBytes(reqParameter, dataUnit); - } - - - /// - /// 构建透明转发-下发数据单元 - /// - /// 终端通信端口 1~31 - /// 0~7 对应300,600,1200,2400,4800,7200,9600,19200 - /// 停止位 - /// 校验方式 - /// 数据位 - /// 等待报文超时时间/s - /// 等待字节超时时间/ms - /// 转发内容 - /// - public static List BuildTransparentForwardingSendDataUnit(int port, BaudRate baudRate, StopBit stopBit, Parity parity, DataBit dataBit, - int waitContentTimeout, int waitByteTimeout, List datas) - { - var dataUnit = new List(); - - var portHex = port.DecToHex().PadLeft(2, '0'); - dataUnit.Add(portHex); - - var baudRateBin = ((int)baudRate).DecToBin().PadLeft(3, '0'); - var stopBitBin = ((int)stopBit).DecToBin(); - var parityBin = parity != Parity.None ? $"1{((int)parity).DecToBin()}" : $"0{((int)parity).DecToBin()}"; - var dataBitBin = ((int)dataBit).DecToBin().PadLeft(2, '0'); - var controlHex = $"{baudRateBin}{stopBitBin}{parityBin}{dataBitBin}".BinToHex().PadLeft(2, '0'); ; - dataUnit.Add(controlHex); - - var waitContentTimeoutBin = $"1{waitContentTimeout.DecToBin().PadLeft(7, '0')}"; - var waitContentTimeoutHex = waitContentTimeoutBin.BinToHex().PadLeft(2, '0'); - var waitByteTimeoutHex = waitByteTimeout.DecToHex().PadLeft(2, '0'); - - dataUnit.Add(waitContentTimeoutHex); - dataUnit.Add(waitByteTimeoutHex); - - var countHex = datas.Count.DecToHex().PadLeft(4, '0'); - var countHexPairs = countHex.StringToPairs(); - countHexPairs.Reverse(); - dataUnit.AddRange(countHexPairs); - - dataUnit.AddRange(datas); - - return dataUnit; - } - - /// - /// 构建下发命令 - /// - /// - /// - /// - public static byte[] BuildSendCommandBytes(ReqParameter reqParameter, List? dataUnit = null) - { - var cmdStrList = new List(); - var userDatas = BuildUserData(reqParameter, dataUnit); - var hearders = BuildHeaders(userDatas.Count); - var cs = GetCS(userDatas); - cmdStrList.AddRange(hearders); - cmdStrList.AddRange(userDatas); - cmdStrList.Add(cs); - cmdStrList.Add(endStr); - var bytes = cmdStrList.Select(x => Convert.ToByte(x, 16)).ToArray(); - return bytes; - } - - /// - /// 构建电表参数设置-下发数据单元 - /// - /// - /// - private static List BuildAmmeterParameterSendDataUnit(List meterParameters) - { - var hexDatas = new List(); - - var countHex = meterParameters.Count().DecToHex().PadLeft(4, '0'); - hexDatas.Add(countHex); - - //TODO 优化代码:目标数据入参,返回类型为出参 - for (int i = 0; i <= meterParameters.Count - 1; i++) - { - var meter = meterParameters[i]; - - var indexHex = (i + 1).DecToHex().PadLeft(4, '0'); - hexDatas.Add(indexHex); - - var pnHex = meter.Pn.DecToHex().PadLeft(4, '0'); - hexDatas.Add(pnHex); - - var baudRateBin = meter.BaudRate.DecToBin().PadLeft(3, '0'); - var portBin = meter.Port.DecToBin().PadLeft(5, '0'); - var baudRateAndPortHex = $"{baudRateBin}{portBin}".BinToHex().PadLeft(2, '0'); - hexDatas.Add(baudRateAndPortHex); - - var protocolTypeHex = ((int)meter.ProtocolType).DecToHex().PadLeft(2, '0'); - hexDatas.Add(protocolTypeHex); - - hexDatas.Add(meter.Address); - - hexDatas.Add(meter.Password.PadLeft(12, '0')); - - var rateNumberBin = $"0000{meter.RateNumber.DecToBin().PadLeft(4, '0')}"; - var rateNumberHex = rateNumberBin.BinToHex().PadLeft(2, '0'); - hexDatas.Add(rateNumberHex); - - var intBitNumberBin = (meter.IntegerBitNumber - 4).DecToBin().PadLeft(2, '0'); - var decBitNumberBin = (meter.DecimalBitNumber - 1).DecToBin().PadLeft(2, '0'); - var intAndDecBitNumberBin = $"0000{intBitNumberBin}{decBitNumberBin}"; - var intAndDecBitNumberHex = intAndDecBitNumberBin.BinToHex().PadLeft(2, '0'); - hexDatas.Add(intAndDecBitNumberHex); - - hexDatas.Add(meter.CollectorAddress.PadLeft(12, '0')); - - var userCategoryNumberBin = meter.UserCategoryNumber.DecToBin().PadLeft(4, '0'); - var userSubclassNumberBin = meter.UserSubclassNumber.DecToBin().PadLeft(4, '0'); - var userNumberHex = $"{userCategoryNumberBin}{userSubclassNumberBin}".BinToHex().PadLeft(2, '0'); - hexDatas.Add(userNumberHex); - } - - //高位在前,低位在后 - var datas = new List(); - foreach (var hexData in hexDatas) - { - if (hexData.Length == 2) - datas.Add(hexData); - else - { - var lst = hexData.StringToPairs(); - lst.Reverse(); - datas.AddRange(lst); - } - } - datas.AddRange(GetPW()); - return datas; - } - - - //AUX=消息认证码字段(PW,16个字节) - private static List GetPW() - { - var str = "00"; - var pWList = Enumerable.Repeat(str, pWLen).ToList(); - return pWList; - } - - - /// - /// 帧校验和 - /// - /// 用户数据区 - /// - private static string GetCS(List userData) - { - byte sum = 0; - foreach (var d in userData) - { - var b = Convert.ToByte(d, 16); - sum += b; - } - return sum.ToString("X2"); - } - - /// - /// 用户数据区 - /// - /// - /// - private static List BuildUserData(ReqParameter reqParameter, List? dataUnit) - { - var c = BuildC(reqParameter.FunCode, reqParameter.PRM); - var a = BuildAList(reqParameter.A, reqParameter.MSA); - - var linkUserData = BuildLinkUserData(reqParameter.AFN, reqParameter.Seq, - ((ReqParameter2)reqParameter).Pn, ((ReqParameter2)reqParameter).Fn, dataUnit); - - var list = new List() { c }; - list.AddRange(a); - list.AddRange(linkUserData); - return list; - } - - /// - /// 固定长度的报文头 起始字符+长度+长度+起始字符 - /// - /// - /// - private static List BuildHeaders(int length) - { - var headers = new List(); - headers.Add(startStr); - var l = BuildLength(length); - headers.AddRange(l); - headers.AddRange(l); - headers.Add(startStr); - return headers; - } - - /// - /// 长度 2字节 [用户数据区长度] - /// - /// - private static List BuildLength(int length1) - { - var binaryLen = length1.DecToBin(); - var protocolIdentification = Enum.Format(typeof(ProtocolIdentification), - ProtocolIdentification.本规约使用, "d").PadLeft(2, '0'); - var lenStr = $"{binaryLen}{protocolIdentification}"; - var hexLen = lenStr.BinToHex(); - hexLen = hexLen.PadLeft(4, '0'); - var list = hexLen.StringToPairs(); - list.Reverse(); - return list; - } - - /// - /// 控制域 - /// - /// 功能码 - /// - /// - /// - private static string BuildC(int funCode, PRM pRM, int fcb = 0, FCV fcv = FCV.FCB位无效) - { - var cMasterStationFunCodeHex = funCode.DecToBin(); - cMasterStationFunCodeHex = cMasterStationFunCodeHex.ToString().PadLeft(4, '0'); - var strC = $"{(int)DIR.主站下行报文}{(int)pRM}{fcb}{(int)fcv}{cMasterStationFunCodeHex}"; - var hexC = strC.BinToHex().PadLeft(2, '0'); - return hexC; - } - - - /// - /// 地址域 3220 09872 - /// - /// 行政区划码 BCD码 3220=2032 - /// 逻辑地址 BIN 09872=2690=>9026 - /// 主站地址 BIN 0~127 - /// - private static List BuildAList(string a, int mSA) - { - var list = new List(); - - var a1 = a.Substring(0, 4); - var a1Pairs = a1.StringToPairs(); - a1Pairs.Reverse(); - list.AddRange(a1Pairs); - - var a2 = Convert.ToInt32(a.Substring(4)); - var decA2 = a2.DecToHex(); - var a2Pairs = decA2.PadLeft(4, '0').StringToPairs(); - a2Pairs.Reverse(); - list.AddRange(a2Pairs); - - //TODO:主站地址和组地址标志 - var a3Bin = $"{mSA.DecToBin().PadLeft(7, '0')}0"; - list.Add(a3Bin.BinToHex().PadLeft(2, '0')); - - return list; - } - - private static List BuildLinkUserData(AFN aFN, Seq seq, int pn, int fn, List? dataUnit) - { - var aFNValue = ((int)aFN).DecToHex().PadLeft(2, '0'); - var sEQ = BuildSEQ(seq.TpV, seq.FIRFIN, seq.CON, seq.PRSEQ); - var dA = BuildDA(pn); - var dT = BuildDT(fn); - var list = new List() { aFNValue, sEQ }; - list.AddRange(dA); - list.AddRange(dT); - - if (dataUnit != null) - { - list.AddRange(dataUnit); - } - //list.AddRange(GetDataUnit(aFN,seq)); - - if (seq.TpV == TpV.附加信息域中带时间标签) - list.AddRange(BuildTp("00")); - - return list; - } - - /// - /// 帧序列域 - /// - /// - /// - /// - /// - private static string BuildSEQ(TpV tpV, FIRFIN fIRFIN, CON cON, int pRSEQ) - { - var tpVValue = Enum.Format(typeof(TpV), - tpV, "d"); - var fIRFINValue = Enum.Format(typeof(FIRFIN), - fIRFIN, "d"); - var cONValue = (int)cON; - var sEQBin = $"{tpVValue}{fIRFINValue}{cONValue}{pRSEQ.DecToBin().PadLeft(4, '0')}"; - var hexSEQ = sEQBin.BinToHex().PadLeft(2, '0'); - return hexSEQ; - } - - /// - /// 信息点标识 - /// - /// 计量点 - /// - private static List BuildDA(int pn) - { - if (pn == 0) - return new List() { "00", "00" }; - var dA2 = (pn - 1) / 8 + 1;//信息点组从1开始 第几组 - var dA1 = pn - (dA2 - 1) * 8;//pn % 8 - var dA1Hex = "1".PadRight(dA1, '0').BinToHex();//对位信息 第几位 二进制有效位 - var dA2Hex = dA2.DecToHex(); - return new List() { dA1Hex.PadLeft(2, '0'), dA2Hex.PadLeft(2, '0') }; - - } - - /// - /// 数据单元标识 - /// - /// - /// - private static List BuildDT(int fn) - { - var dT2 = (fn - 1) / 8;//从零开始 第几组 - var dT1 = fn - dT2 * 8; - var dT1Hex = "1".PadRight(dT1, '0').BinToHex();//对位信息 第几位 二进制有效位 - var dT2Hex = dT2.DecToHex(); - return new List() { dT1Hex.PadLeft(2, '0'), dT2Hex.PadLeft(2, '0') }; - } - - /// - /// 时间标签 - /// - /// 启动帧帧序号计数器PFC 1字节 - /// 允许发送传输延时时间 min 1字节 - /// - private static List BuildTp(string pFC = "00", int delayTime = 0) - { - var now = DateTime.Now; // 获取当前时间 - var seconds = now.Second.ToString().PadLeft(2, '0'); // 获取当前秒数 - var minutes = now.Minute.ToString().PadLeft(2, '0'); // 获取当前分钟数 - var hours = now.Hour.ToString().PadLeft(2, '0'); // 获取当前小时数 - var day = now.Day.ToString().PadLeft(2, '0'); // 获取当前日期的日数 - return new List() { pFC, seconds, minutes, hours, day, delayTime.ToString().PadLeft(2, '0') }; - } - - #endregion - - - #region 645下行命令 - - - /// - /// 构建电表阀控下发数据单元 - /// - /// 电表地址 - /// 特殊控制码 - /// 密码 - /// 是否为开阀 - /// 型号码 - /// - public static List BuildAmmeterValveControlSendDataUnit(string address, string specialControlCode, string password, bool state, string modelCode = "") - { - var code = string.Empty; - - if (state) - { - if (string.IsNullOrEmpty(specialControlCode)) - code = "1B"; - else - code = specialControlCode == "1B" || specialControlCode == "1C" ? specialControlCode : "1C"; - } - else - code = "1A";//跳闸 - - if (specialControlCode == "1W") - { - if (state) - code = "1A"; - else - code = "1C"; - } - - var pwdLevel = "02"; - if (modelCode == "HL_DTSU2625" || modelCode == "DDZY9866") - pwdLevel = "04"; - else if (modelCode == "DDS2705") - pwdLevel = "03"; //不带安全认证密级 - - if (!string.IsNullOrWhiteSpace(password) && password.Contains("|")) - { - var sp = password.Split('|'); - pwdLevel = sp[1]; - password = sp[0]; - } - - var strDate = DateTime.Now.AddYears(3).ToString("000012ddMMyy").StrAddSpan();//命令有效截止时间 - if (specialControlCode == "1D" || modelCode == "SZBD_DDZY1225") - strDate = "FF FF FF FF FF FF"; - var strP = password.StrAddSpan().StrReverseOrder(); - var strSJY = " " + pwdLevel + " " + strP + " 01 00 00 00 " + code + " 00 " + strDate; - var dataUnit = strSJY.Replace(" ", "").StringToPairs(); - var dataList = Build645SendCommand(address, "1C", dataUnit); - return dataList; - - //string strLen = (strSJY.Replace(" ", "").Length / 2).ToString("X2"); - //string strReturn = "68 " + address.StrAddSpan().StrReverseOrder() + " 68 1C " + strLen + " " + strSJY.StrAddHex33() + " "; - //string strSum = strReturn.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(i => Convert.ToInt32(i, 16)).Sum().ToString("X"); - //strReturn += strSum.Substring(strSum.Length - 2) + " 16"; - //return strReturn.Split(' ').ToList(); - } - - /// - /// 构建电表保电下发数据单元 - /// - /// 电表地址 - /// - /// true 保电 false 保电解除 - /// 型号码 - /// - public static List BuildAmmeterLockSendDataUnit(string address, string password, bool state, string modelCode = "") - { - var code = state ? "3A" : "3B"; - - var strDate = (code + DateTime.Now.AddDays(1).ToString("00000012ddMMyy")).StrAddSpan(); - - if (modelCode == "SZBD_DDZY1225") - strDate = $"{code} 00 FF FF FF FF FF FF"; - - var strP = password.StrAddSpan().StrReverseOrder(); - var strSJY = " 02 " + strP + " 01 00 00 00 " + strDate; - - var dataUnit = strSJY.Replace(" ", "").StringToPairs(); - var dataList = Build645SendCommand(address, "1C", dataUnit); - return dataList; - } - - /// - /// 构建645协议下发命令 - /// - /// 电表地址 - /// 控制码 - /// 数据域 发送方按字节进行加33处理,接收方按字节减33 - /// - public static List Build645SendCommand(string ammeterAddress, string controlCode, List? dataUnit) - { - var cmdStrList = new List(); - cmdStrList.Add(startStr); - - ammeterAddress = ammeterAddress.PadLeft(12, '0'); - var addressList = ammeterAddress.StringToPairs(); - addressList.Reverse(); - cmdStrList.AddRange(addressList); - - cmdStrList.Add(startStr); - - var len = dataUnit != null ? dataUnit.Count.DecToHex().PadLeft(2, '0') : "00"; - cmdStrList.Add(len); - if (dataUnit != null) - { - cmdStrList.AddRange(dataUnit.AddHex33()); - } - - var strSum = cmdStrList.Select(i => Convert.ToInt32(i, 16)).Sum().ToString("X"); - strSum = strSum.Substring(strSum.Length - 2); - cmdStrList.Add(strSum); - cmdStrList.Add(endStr); - - return cmdStrList; - } - - /// - /// 构建写数据 TODO:待优化 - /// - /// - public static List AssembleWrite(string address, string password, string Di0_3, string[] data) - { - var address_str = address.StrAddSpan().StrReverseOrder(); - var L = (12 + data.Length).ToString("X2"); - var m = "00 11 22 33"; - var Di0_3_str = Di0_3.StrAddSpan().StrReverseOrder(); - var pwd_str = password.StrAddSpan().StrReverseOrder(); - var data_str = string.Join(" ", data); - var data_add33 = (Di0_3_str + " 02 " + pwd_str + " " + m + " " + data_str).StrAddHex33(); - var frame = $"68 {address_str} 68 14 {L} {data_add33}"; - string strSum = frame.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(i => Convert.ToInt32(i, 16)).Sum().ToString("X"); - var cs = strSum.Substring(strSum.Length - 2); - return $"{frame} {cs} 16".Split(' ').ToList(); - } - - #endregion - - #region 188 下行命令 - - /// - /// 标准 188协议阀控 WaterMeterSend - /// - /// - /// 表计类型 - /// - public static List BuildConfirm188WaterValve(string waterMeterAddress, bool state, string mtype = "10") - { - if (string.IsNullOrWhiteSpace(waterMeterAddress)) return null; - - var dataUnit = new List() { "A0", "17", "00", state ? "55" : "99" }; - - var dataList = Build188SendCommand(waterMeterAddress, "04", dataUnit); - - return dataList; - } - - /// - /// 构建188水表抄读下发数据单元 - /// - /// - /// - public static List Build188WaterMeterReadingSendDataUnit(string waterMeterAddress) - { - //TODO:90 1F 还是1F 90 - var dataUnit = new List() { "90", "1F", "00" }; - var dataList = Build188SendCommand(waterMeterAddress, "01", dataUnit); - - return dataList; - } - - - /// - /// 构建188协议下发命令 - /// - /// 水表地址 - /// 控制码 - /// 数据域 - /// 表类型 - /// - public static List Build188SendCommand(string waterMeterAddress, string controlCode, List? dataUnit = null, string meterType = "10") - { - var cmdStrList = new List(); - cmdStrList.Add(startStr); - cmdStrList.Add(meterType); - - waterMeterAddress = waterMeterAddress.PadLeft(14, '0'); - var addressList = waterMeterAddress.StringToPairs(); - addressList.Reverse(); - cmdStrList.AddRange(addressList); - - //控制码 - cmdStrList.Add(controlCode); - - var len = dataUnit != null ? dataUnit.Count.DecToHex().PadLeft(2, '0') : "00"; - cmdStrList.Add(len); - if (dataUnit != null) - { - cmdStrList.AddRange(dataUnit); - } - - var strSum = cmdStrList.Select(i => Convert.ToInt32(i, 16)).Sum().ToString("X"); - strSum = strSum.Substring(strSum.Length - 2); - cmdStrList.Add(strSum); - cmdStrList.Add(endStr); - - return cmdStrList; - } - - public static string GetCRC(List inputFrm, int startIndex = 0) - { - int sum = 0; - for (int i = startIndex; i < inputFrm.Count; i++) - { - sum += (Convert.ToInt32(inputFrm[i], 16)); - } - var sum16 = Convert.ToString(sum, 16); - return sum16.Substring(sum16.Length - 2, 2).ToUpper(); - } - - public static object GetAnalyzeValue(this List hexStringList, CommandChunkEnum188 chunk) - { - if (hexStringList.Count < 11) - { - return null; - } - - switch (chunk) - { - case CommandChunkEnum188.A: - var aHexList = hexStringList[(int)CommandChunkEnum188.A].Take(7).ToList(); - aHexList.Reverse(); - return string.Join("", aHexList.Skip(1).Take(6).ToList()); - case CommandChunkEnum188.C: - var cHex = hexStringList[(int)CommandChunkEnum188.C]; - return cHex; - case CommandChunkEnum188.Data: - var lenIndex = (int)CommandChunkEnum188.L; - var len = hexStringList[lenIndex].HexToDec(); - - //验证长度 2=(帧校验和+结束字符) - if (hexStringList.Count - 2 != 11 + len) - return null; - - var dataHexList = hexStringList.Skip(11).Take(len).ToList(); - return dataHexList; - default: - throw new ArgumentOutOfRangeException(nameof(chunk), chunk, null); - } - } - - //public double AnalyzeCurrentTotalRate(List hexList) - //{ - // var str = string.Join("", hexList); - // var number = Convert.ToInt32(str) * 0.01; - // return number; - //} - - #endregion - - } -} diff --git a/JiShe.CollectBus.Console/Extensions/DependencyInjections/DependencyInjectionExtensions.cs b/JiShe.CollectBus.Console/Extensions/DependencyInjections/DependencyInjectionExtensions.cs deleted file mode 100644 index e30f2a1..0000000 --- a/JiShe.CollectBus.Console/Extensions/DependencyInjections/DependencyInjectionExtensions.cs +++ /dev/null @@ -1,92 +0,0 @@ -//using JiShe.CollectBus.Common.Extensions.DependencyInjections; -//using JiShe.CollectBus.Protocol.Contracts.Attributes; -//using System.Reflection; -//using TouchSocket.Core; -//using System; -//using Serilog; - -//// ReSharper disable once CheckNamespace -//namespace Microsoft.Extensions.DependencyInjection -//{ -// public static class DependencyInjectionExtensions -// { -// public static void PluginServiceRegister(this IServiceCollection services, string pluginPath = "") -// { -// if (pluginPath.IsNullOrWhiteSpace()) -// { -// pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"); -// } -// var assemblies = GetAssembliesFromFolder(pluginPath); - -// foreach (var assembly in assemblies) -// { -// var allTypes = assembly.GetTypes(); -// foreach (var type in allTypes) -// { -// if (typeof(ISingletonDependency).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false }) -// { -// var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ISingletonDependency")); -// foreach (var interfaceType in interfaceTypes) -// { -// var attr = type.GetCustomAttribute(); -// if (attr == null) continue; -// Log.Logger.Information($"正在加载插件{attr.Name}..."); -// var serviceDescriptor = new ServiceDescriptor(interfaceType, attr.Name, type, ServiceLifetime.Singleton); -// services.Add(serviceDescriptor); -// } -// } - -// if (typeof(ITransientDependency).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false }) -// { -// var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("ITransientDependency")); -// foreach (var interfaceType in interfaceTypes) -// { -// var attr = type.GetCustomAttribute(); -// if (attr == null) continue; -// Log.Logger.Information($"正在加载插件{attr.Name}..."); -// var serviceDescriptor = new ServiceDescriptor(interfaceType, attr.Name, type, ServiceLifetime.Transient); -// services.Add(serviceDescriptor); -// } -// } - -// if (typeof(IScopedDependency).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false }) -// { -// var interfaceTypes = type.GetInterfaces().Where(p => p.FullName != null && !p.FullName.Contains("IScopedDependency")); -// foreach (var interfaceType in interfaceTypes) -// { -// var attr = type.GetCustomAttribute(); -// if (attr == null) continue; -// Log.Logger.Information($"正在加载插件{attr.Name}..."); -// var serviceDescriptor = new ServiceDescriptor(interfaceType, attr.Name, type, ServiceLifetime.Scoped); -// services.Add(serviceDescriptor); -// } -// } -// } -// } -// } - -// private static IEnumerable GetAssembliesFromFolder(string folderPath) -// { -// var directory = new DirectoryInfo(folderPath); -// if (!directory.Exists) return []; - -// var files = directory.GetFiles("*.dll"); - -// var assemblies = new List(); -// foreach (var file in files) -// { -// try -// { -// var assembly = Assembly.LoadFrom(file.FullName); -// assemblies.Add(assembly); -// } -// catch (Exception ex) -// { -// Console.WriteLine($"Error loading assembly from {file.FullName}: {ex.Message}"); -// } -// } - -// return assemblies; -// } -// } -//} diff --git a/JiShe.CollectBus.Console/JiShe.CollectBus.Console.csproj b/JiShe.CollectBus.Console/JiShe.CollectBus.Console.csproj deleted file mode 100644 index fa6fdd3..0000000 --- a/JiShe.CollectBus.Console/JiShe.CollectBus.Console.csproj +++ /dev/null @@ -1,60 +0,0 @@ - - - - Exe - net8.0 - enable - enable - true - true - true - - - - - - - - - - Always - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - - - - - - - Always - - - Always - - - - diff --git a/JiShe.CollectBus.Console/Program.cs b/JiShe.CollectBus.Console/Program.cs deleted file mode 100644 index 362f62d..0000000 --- a/JiShe.CollectBus.Console/Program.cs +++ /dev/null @@ -1,72 +0,0 @@ -using JiShe.CollectBus.MQ.Consumer; -using JiShe.CollectBus.Network; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Serilog; -using Volo.Abp; - -namespace JiShe.CollectBus.Console -{ - internal class Program - { - - static void Main(string[] args) - { - try - { - Log.Logger = new LoggerConfiguration() - .WriteTo.Console() - .CreateLogger(); - - - CreateHostBuilder(args).Build().Run(); - - } - catch (Exception ex) - { - Log.Fatal(ex, "Application terminated unexpectedly"); - } - finally - { - Log.CloseAndFlush(); - } - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureAppConfiguration(ConfigureAppConfiguration) - .ConfigureServices((hostContext, services) => { ConfigureServices(services, hostContext); }); - - - private static void ConfigureAppConfiguration(HostBuilderContext hostContext, IConfigurationBuilder config) - { - var env = hostContext.HostingEnvironment; - config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); - config.AddEnvironmentVariables(); - } - - - private static void ConfigureServices(IServiceCollection services, HostBuilderContext hostContext) - { - var configuration = hostContext.Configuration; - - services.AddSerilog((context, lc) => - { - lc.ReadFrom.Configuration(configuration) - .ReadFrom.Services(context); - }); - services.AddApplication(); - - services.AddApplication(); - - services.AddPluginApplications(); - services.AddStackExchangeRedisCache(options => - { - options.Configuration = configuration["RedisCache:ConnectionString"]; - options.InstanceName = configuration["RedisCache:InstanceName"]; - }); - } - } -} - diff --git a/JiShe.CollectBus.Console/appsettings.json b/JiShe.CollectBus.Console/appsettings.json deleted file mode 100644 index bb33117..0000000 --- a/JiShe.CollectBus.Console/appsettings.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "Serilog": { - "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], - "MinimumLevel": "Information", - "Override": { - "Microsoft": "Warning", - "System": "Warning" - }, - "WriteTo": [ - { "Name": "Console" }, - { - "Name": "File", - "Args": { - "path": "Logs/log-.txt", - "rollingInterval": "Day" - //"rollOnFileSizeLimit": true, - //"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact" - } - } - ], - "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], - - "Properties": { - "Application": "CollectBus", - "Environment": "Development" - } - }, - - "ConnectionStrings": { - "Default": "Data Source=192.168.111.248;Port=3306;Database=JiSheCollectBus;uid=root;pwd=123456abcD;charset=utf8mb4;Allow User Variables=true;AllowLoadLocalInfile=true" - }, - "MongoSettings": { - "Connection": "mongodb://backups_admin:jishe_mongodb_backups@118.190.144.92:27037", - "DatabaseName": "JiSheCollectBus" - }, - "TCP": { - "Port": 10500 - }, - "UDP": { - "Port": 10500 - }, - "RedisCache": { - "ConnectionString": "123456@qwer@localhost:6379", - "InstanceName": "CollectBus" - }, - "MQ": { - "Host": "118.190.144.92", - "Port": "5672", - "VirtualHost": "/", - "UserName": "collectbus", - "Password": "123456", - "Queue": { - "Received": "Received_Command", - "Issued": "Issued_Command" - } - } -} \ No newline at end of file diff --git a/JiShe.CollectBus.Core/JiShe.CollectBus.Network.csproj b/JiShe.CollectBus.Core/JiShe.CollectBus.Network.csproj deleted file mode 100644 index fc52e4a..0000000 --- a/JiShe.CollectBus.Core/JiShe.CollectBus.Network.csproj +++ /dev/null @@ -1,27 +0,0 @@ - - - - net8.0 - enable - enable - preview - - - - - - - - - - - - - - - - - - - - diff --git a/JiShe.CollectBus.Core/JiSheCollectBusNetworkModule.cs b/JiShe.CollectBus.Core/JiSheCollectBusNetworkModule.cs deleted file mode 100644 index d2233b7..0000000 --- a/JiShe.CollectBus.Core/JiSheCollectBusNetworkModule.cs +++ /dev/null @@ -1,50 +0,0 @@ -using JiShe.CollectBus.MongoDB; -using JiShe.CollectBus.MQ.Sender; -using JiShe.CollectBus.Network.Plugins; -using Microsoft.Extensions.DependencyInjection; -using TouchSocket.Core; -using TouchSocket.Sockets; -using Volo.Abp; -using Volo.Abp.Modularity; -using ServerMonitor = JiShe.CollectBus.Network.Plugins.ServerMonitor; - -namespace JiShe.CollectBus.Network -{ - [DependsOn(typeof(JiSheCollectBusMongoDbModule), - typeof(JiSheCollectBusMqSenderModule))] - public class JiSheCollectBusNetworkModule : AbpModule - { - public override async void ConfigureServices(ServiceConfigurationContext context) - { - var configuration = context.Services.GetConfiguration(); - context.Services.AddTcpService(config => - { - config.SetListenIPHosts(int.Parse(configuration["TCP:ClientPort"] ?? "10500")) - //.SetTcpDataHandlingAdapter(()=>new StandardFixedHeaderDataHandlingAdapter()) - .ConfigurePlugins(a => - { - a.Add(); - a.Add(); - a.Add(); - }); - }); - - context.Services.AddUdpSession(config => - { - config.SetBindIPHost(int.Parse(configuration["UDP:ClientPort"] ?? "10500")) - .ConfigurePlugins(a => - { - a.Add(); - a.Add(); - }) - .UseBroadcast() - .SetUdpDataHandlingAdapter(() => new NormalUdpDataHandlingAdapter()); - }); - } - - public override void OnApplicationInitialization(ApplicationInitializationContext context) - { - - } - } -} diff --git a/JiShe.CollectBus.Core/Plugins/TcpMonitor.cs b/JiShe.CollectBus.Core/Plugins/TcpMonitor.cs deleted file mode 100644 index 006af86..0000000 --- a/JiShe.CollectBus.Core/Plugins/TcpMonitor.cs +++ /dev/null @@ -1,109 +0,0 @@ -using JiShe.CollectBus.Common.Enums; -using JiShe.CollectBus.Common.Extensions; -using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.MongoDB; -using JiShe.CollectBus.MQ.Sender; -using MassTransit; -using Microsoft.Extensions.Logging; -using TouchSocket.Core; -using TouchSocket.Sockets; - -namespace JiShe.CollectBus.Network.Plugins -{ - public partial class TcpMonitor( - INSender nSender, - ILogger logger, - IMongoRepository mongoHeartbeatRepository, - IMongoRepository mongoLoginRepository) - : PluginBase - { - [GeneratorPlugin(typeof(ITcpReceivedPlugin))] - public async Task OnTcpReceived(ITcpSessionClient client, ReceivedDataEventArgs e) - { - var messageHexString = Convert.ToHexString(e.ByteBlock.Span); - var hexStringList = messageHexString.StringToPairs(); - var aFn = (int?)hexStringList.GetAnalyzeValue(CommandChunkEnum.AFN); - var fn = (int?)hexStringList.GetAnalyzeValue(CommandChunkEnum.FN); - var aTuple = (Tuple)hexStringList.GetAnalyzeValue(CommandChunkEnum.A); - - if (aFn.HasValue && fn.HasValue) - { - if ((AFN)aFn == AFN.链路接口检测) - { - switch (fn) - { - case 1://登录 - - var messageReceivedLoginEvent = new MessageReceivedLoginEvent - { - ClientId = client.Id, - ClientIp = client.IP, - ClientPort = client.Port, - MessageHexString = messageHexString, - DeviceNo = aTuple.Item1, - MessageId = NewId.NextGuid().ToString() - }; - await mongoLoginRepository.AddAsync(messageReceivedLoginEvent); - await nSender.SendToReceivedLoginAsync(messageReceivedLoginEvent); - break; - case 3://心跳 - var messageReceivedHeartbeatEvent = new MessageReceivedHeartbeatEvent - { - ClientId = client.Id, - ClientIp = client.IP, - ClientPort = client.Port, - MessageHexString = messageHexString, - DeviceNo = aTuple.Item1, - MessageId = NewId.NextGuid().ToString() - }; - await mongoHeartbeatRepository.AddAsync(messageReceivedHeartbeatEvent); - await nSender.SendToReceivedHeartbeatAsync(messageReceivedHeartbeatEvent); - break; - default: - logger.LogError($"指令初步解析失败,指令内容:{messageHexString}"); - break; - } - } - else - { - await nSender.SendToReceivedAsync(new MessageReceivedEvent - { - ClientId = client.Id, - ClientIp = client.IP, - ClientPort = client.Port, - MessageHexString = messageHexString, - DeviceNo = aTuple.Item1, - MessageId = NewId.NextGuid().ToString() - }); - } - } - else - { - logger.LogError($"指令初步解析失败,指令内容:{messageHexString}"); - } - - await e.InvokeNext(); - } - - [GeneratorPlugin(typeof(ITcpConnectingPlugin))] - public async Task OnTcpConnecting(ITcpSessionClient client,ConnectingEventArgs e) - { - logger.LogInformation($"[TCP] ID:{client.Id} IP:{client.GetIPPort()}正在连接中..."); - await e.InvokeNext(); - } - - [GeneratorPlugin(typeof(ITcpConnectedPlugin))] - public async Task OnTcpConnected(ITcpSessionClient client,ConnectedEventArgs e) - { - logger.LogInformation($"[TCP] ID:{client.Id} IP:{client.GetIPPort()}已连接"); - await e.InvokeNext(); - } - - [GeneratorPlugin(typeof(ITcpClosedPlugin))] - public async Task OnTcpClosed(ITcpSessionClient client, ClosedEventArgs e) - { - logger.LogInformation($"[TCP] ID:{client.Id} IP:{client.GetIPPort()}已关闭连接"); - await e.InvokeNext(); - } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/AuditLogs/AuditLog.cs b/JiShe.CollectBus.EntityFrameworkCore/AuditLogs/AuditLog.cs deleted file mode 100644 index f84ec99..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/AuditLogs/AuditLog.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using JiShe.CollectBus.EntityFrameworkCore.Entities; - -namespace JiShe.CollectBus.EntityFrameworkCore.AuditLogs -{ - public class AuditLog : EntityBase,ICreationAudited - { - public long? CreatorId { get; set; } - public DateTime CreationTime { get; set; } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/CollectBusDbContext.cs b/JiShe.CollectBus.EntityFrameworkCore/CollectBusDbContext.cs deleted file mode 100644 index 0a1cb22..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/CollectBusDbContext.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.Extensions.Configuration; - -namespace JiShe.CollectBus.EntityFrameworkCore -{ - public class CollectBusDbContext : DbContext - { - private readonly IConfiguration _configuration; - - - private DbSet Devices { set; get; } - - public CollectBusDbContext(IConfiguration configuration) - { - _configuration = configuration; - } - - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseMySql(_configuration.GetConnectionString("Default"),ServerVersion.AutoDetect(_configuration.GetConnectionString("Default"))); - } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Device.cs b/JiShe.CollectBus.EntityFrameworkCore/Device.cs deleted file mode 100644 index 853de5c..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Device.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using JiShe.CollectBus.EntityFrameworkCore.Entities; - -namespace JiShe.CollectBus.EntityFrameworkCore -{ - public class Device : EntityBase, ICreationAudited, IModificationAudited - { - public string DeviceNo { get; set; } - public DeviceStatusEnum DeviceStatus { get; set; } - public long? CreatorId { get; set; } - public DateTime CreationTime { get; set; } - public long? LastModifierId { get; set; } - public DateTime? LastModificationTime { get; set; } - } - - public enum DeviceStatusEnum - { - Unknown = 0, - Online = 1, - Offline = 2, - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Entities/EntityBase.cs b/JiShe.CollectBus.EntityFrameworkCore/Entities/EntityBase.cs deleted file mode 100644 index 0fd328e..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Entities/EntityBase.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JiShe.CollectBus.EntityFrameworkCore.Entities -{ - public class EntityBase : IEntity - { - public TKey Id { get; set; } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Entities/FullAuditedEntity.cs b/JiShe.CollectBus.EntityFrameworkCore/Entities/FullAuditedEntity.cs deleted file mode 100644 index 203c475..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Entities/FullAuditedEntity.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JiShe.CollectBus.EntityFrameworkCore.Entities -{ - public class FullAuditedEntity : EntityBase, ICreationAudited, IModificationAudited, IDeletionAudited - { - public TUser CreatorId { get; set; } - public DateTime CreationTime { get; set; } - public TUser LastModifierId { get; set; } - public DateTime? LastModificationTime { get; set; } - public TUser DeleterId { get; set; } - public bool IsDeleted { get; set; } - public DateTime? DeletionTime { get; set; } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Entities/ICreationAudited.cs b/JiShe.CollectBus.EntityFrameworkCore/Entities/ICreationAudited.cs deleted file mode 100644 index 2ce1d52..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Entities/ICreationAudited.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JiShe.CollectBus.EntityFrameworkCore.Entities -{ - public interface ICreationAudited : IHasCreator, IHasCreationTime - { - } - - public interface IHasCreator - { - TUser CreatorId { get; set; } - } - - public interface IHasCreationTime - { - DateTime CreationTime { get; set; } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Entities/IDeletionAudited.cs b/JiShe.CollectBus.EntityFrameworkCore/Entities/IDeletionAudited.cs deleted file mode 100644 index 027f987..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Entities/IDeletionAudited.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JiShe.CollectBus.EntityFrameworkCore.Entities -{ - public interface IDeletionAudited : IHasDeleter, ISoftDelete, IHasDeletionTime - { - } - - public interface ISoftDelete - { - bool IsDeleted { get; set; } - } - - public interface IHasDeleter - { - TUser DeleterId { get; set; } - } - - public interface IHasDeletionTime - { - DateTime? DeletionTime { get; set; } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Entities/IExtendableObject.cs b/JiShe.CollectBus.EntityFrameworkCore/Entities/IExtendableObject.cs deleted file mode 100644 index 79c857b..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Entities/IExtendableObject.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JiShe.CollectBus.EntityFrameworkCore.Entities -{ - public interface IExtendableObject - { - /// - /// Gets or sets the extension data. - /// - /// - /// The extension data. - /// - string ExtensionData { get; set; } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Entities/IModificationAudited.cs b/JiShe.CollectBus.EntityFrameworkCore/Entities/IModificationAudited.cs deleted file mode 100644 index 8db2e32..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Entities/IModificationAudited.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JiShe.CollectBus.EntityFrameworkCore.Entities -{ - public interface IModificationAudited : IHasLastModifier, IHasLastModificationTime - { - } - - public interface IHasLastModifier - { - TUser LastModifierId { get; set; } - } - - public interface IHasLastModificationTime - { - DateTime? LastModificationTime { get; set; } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Extensions/ExtendableObjectExtensions.cs b/JiShe.CollectBus.EntityFrameworkCore/Extensions/ExtendableObjectExtensions.cs deleted file mode 100644 index 74f8916..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Extensions/ExtendableObjectExtensions.cs +++ /dev/null @@ -1,153 +0,0 @@ -using JiShe.CollectBus.EntityFrameworkCore.Entities; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml; -using JetBrains.Annotations; -using JiShe.CollectBus.Common.Helpers; -using Newtonsoft.Json.Linq; -using Formatting = Newtonsoft.Json.Formatting; - -namespace JiShe.CollectBus.EntityFrameworkCore.Extensions -{ - public static class ExtendableObjectExtensions - { - public static T GetData(this IExtendableObject extendableObject, string name, bool handleType = false) - { - return extendableObject.GetData( - name, - handleType - ? new JsonSerializer { TypeNameHandling = TypeNameHandling.All } - : JsonSerializer.CreateDefault() - ); - } - - public static T GetData(this IExtendableObject extendableObject, string name, JsonSerializer? jsonSerializer) - { - if (extendableObject.ExtensionData == null) - { - return default(T); - } - - var json = JObject.Parse(extendableObject.ExtensionData); - - var prop = json[name]; - if (prop == null) - { - return default(T); - } - - if (TypeHelper.IsPrimitiveExtendedIncludingNullable(typeof(T))) - { - return prop.Value(); - } - else - { - return (T)prop.ToObject(typeof(T), jsonSerializer ?? JsonSerializer.CreateDefault()); - } - } - - - - public static void SetData(this IExtendableObject extendableObject, string name, T? value, bool handleType = false) - { - extendableObject.SetData( - name, - value, - handleType - ? new JsonSerializer { TypeNameHandling = TypeNameHandling.All } - : JsonSerializer.CreateDefault() - ); - } - - public static void SetData(this IExtendableObject extendableObject, string name, T? value, JsonSerializer? jsonSerializer) - { - if (extendableObject == null) - { - throw new ArgumentNullException(nameof(extendableObject)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (jsonSerializer == null) - { - jsonSerializer = JsonSerializer.CreateDefault(); - } - - if (extendableObject.ExtensionData == null) - { - if (EqualityComparer.Default.Equals(value, default(T))) - { - return; - } - - extendableObject.ExtensionData = "{}"; - } - - var json = JObject.Parse(extendableObject.ExtensionData); - - if (value == null || EqualityComparer.Default.Equals(value, default(T))) - { - if (json[name] != null) - { - json.Remove(name); - } - } - else if (TypeHelper.IsPrimitiveExtendedIncludingNullable(value.GetType())) - { - json[name] = new JValue(value); - } - else - { - json[name] = JToken.FromObject(value, jsonSerializer); - } - - var data = json.ToString(Formatting.None); - if (data == "{}") - { - data = null; - } - - extendableObject.ExtensionData = data; - } - - public static bool RemoveData(this IExtendableObject extendableObject, string name) - { - if (extendableObject == null) - { - throw new ArgumentNullException(nameof(extendableObject)); - } - - if (extendableObject.ExtensionData == null) - { - return false; - } - - var json = JObject.Parse(extendableObject.ExtensionData); - - var token = json[name]; - if (token == null) - { - return false; - } - - json.Remove(name); - - var data = json.ToString(Formatting.None); - if (data == "{}") - { - data = null; - } - - extendableObject.ExtensionData = data; - - return true; - } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.csproj b/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.csproj deleted file mode 100644 index 6764619..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.csproj +++ /dev/null @@ -1,25 +0,0 @@ - - - - net8.0 - enable - enable - preview - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - diff --git a/JiShe.CollectBus.EntityFrameworkCore/JiSheCollectBusEntityFrameworkCoreModule.cs b/JiShe.CollectBus.EntityFrameworkCore/JiSheCollectBusEntityFrameworkCoreModule.cs deleted file mode 100644 index 3b9b93e..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/JiSheCollectBusEntityFrameworkCoreModule.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Volo.Abp.Modularity; - -namespace JiShe.CollectBus.EntityFrameworkCore -{ - public class JiSheCollectBusEntityFrameworkCoreModule: AbpModule - { - public override void ConfigureServices(ServiceConfigurationContext context) - { - } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Migrations/20241022055227_Init.Designer.cs b/JiShe.CollectBus.EntityFrameworkCore/Migrations/20241022055227_Init.Designer.cs deleted file mode 100644 index f235302..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Migrations/20241022055227_Init.Designer.cs +++ /dev/null @@ -1,60 +0,0 @@ -// -using System; -using JiShe.CollectBus.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -#nullable disable - -namespace JiShe.CollectBus.EntityFrameworkCore.Migrations -{ - [DbContext(typeof(CollectBusDbContext))] - [Migration("20241022055227_Init")] - partial class Init - { - /// - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "8.0.10") - .HasAnnotation("Relational:MaxIdentifierLength", 64); - - MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); - - modelBuilder.Entity("JiShe.CollectBus.EntityFrameworkCore.Device", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("char(36)"); - - b.Property("CreationTime") - .HasColumnType("datetime(6)"); - - b.Property("CreatorId") - .HasColumnType("bigint"); - - b.Property("DeviceNo") - .IsRequired() - .HasColumnType("longtext"); - - b.Property("DeviceStatus") - .HasColumnType("int"); - - b.Property("LastModificationTime") - .HasColumnType("datetime(6)"); - - b.Property("LastModifierId") - .HasColumnType("bigint"); - - b.HasKey("Id"); - - b.ToTable("Devices"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Migrations/20241022055227_Init.cs b/JiShe.CollectBus.EntityFrameworkCore/Migrations/20241022055227_Init.cs deleted file mode 100644 index c6a8a4f..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Migrations/20241022055227_Init.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace JiShe.CollectBus.EntityFrameworkCore.Migrations -{ - /// - public partial class Init : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.AlterDatabase() - .Annotation("MySql:CharSet", "utf8mb4"); - - migrationBuilder.CreateTable( - name: "Devices", - columns: table => new - { - Id = table.Column(type: "char(36)", nullable: false, collation: "ascii_general_ci"), - DeviceNo = table.Column(type: "longtext", nullable: false) - .Annotation("MySql:CharSet", "utf8mb4"), - DeviceStatus = table.Column(type: "int", nullable: false), - CreatorId = table.Column(type: "bigint", nullable: true), - CreationTime = table.Column(type: "datetime(6)", nullable: false), - LastModifierId = table.Column(type: "bigint", nullable: true), - LastModificationTime = table.Column(type: "datetime(6)", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Devices", x => x.Id); - }) - .Annotation("MySql:CharSet", "utf8mb4"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Devices"); - } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Migrations/CollectBusDbContextModelSnapshot.cs b/JiShe.CollectBus.EntityFrameworkCore/Migrations/CollectBusDbContextModelSnapshot.cs deleted file mode 100644 index 6976aaf..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Migrations/CollectBusDbContextModelSnapshot.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -using System; -using JiShe.CollectBus.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; - -#nullable disable - -namespace JiShe.CollectBus.EntityFrameworkCore.Migrations -{ - [DbContext(typeof(CollectBusDbContext))] - partial class CollectBusDbContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "8.0.10") - .HasAnnotation("Relational:MaxIdentifierLength", 64); - - MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); - - modelBuilder.Entity("JiShe.CollectBus.EntityFrameworkCore.Device", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("char(36)"); - - b.Property("CreationTime") - .HasColumnType("datetime(6)"); - - b.Property("CreatorId") - .HasColumnType("bigint"); - - b.Property("DeviceNo") - .IsRequired() - .HasColumnType("longtext"); - - b.Property("DeviceStatus") - .HasColumnType("int"); - - b.Property("LastModificationTime") - .HasColumnType("datetime(6)"); - - b.Property("LastModifierId") - .HasColumnType("bigint"); - - b.HasKey("Id"); - - b.ToTable("Devices"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Repositories/IRepository.cs b/JiShe.CollectBus.EntityFrameworkCore/Repositories/IRepository.cs deleted file mode 100644 index 8f3a2f0..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Repositories/IRepository.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; -using System.Threading.Tasks; -using JiShe.CollectBus.EntityFrameworkCore.Entities; - -namespace JiShe.CollectBus.EntityFrameworkCore.Repositories -{ - public interface IRepository where TEntity : class, IEntity - { - IQueryable GetAll(params Expression>[] propertySelectors); - - IQueryable GetAll(Expression> expression, - params Expression>[] propertySelectors); - - TEntity Find(TPrimaryKey id); - - Task FindAsync(TPrimaryKey id); - - TEntity Get(Expression> expression, - params Expression>[] propertySelectors); - - Task GetAsync(Expression> expression, - params Expression>[] propertySelectors); - - void Insert(TEntity entity, bool autoSave = true); - - Task InsertAsync(TEntity entity, bool autoSave = true); - - Task InsertAndGetIdAsync(TEntity entity, bool autoSave = true); - - void InsertList(List entities, bool autoSave = true); - - Task InsertListAsync(List entities, bool autoSave = true); - - void Update(TEntity entity, bool autoSave = true); - - Task UpdateAsync(TEntity entity, bool autoSave = true); - - void UpdateList(IEnumerable entities); - - Task UpdateListAsync(IEnumerable entities); - - void Delete(TPrimaryKey id, bool autoSave = true); - - Task DeleteAsync(TPrimaryKey id, bool autoSave = true); - - void Delete(TEntity entity, bool autoSave = true); - - Task DeleteAsync(TEntity entity, bool autoSave = true); - - void HardDelete(TPrimaryKey id, bool autoSave = true); - - Task HardDeleteAsync(TPrimaryKey id, bool autoSave = true); - - void HardDelete(TEntity entity, bool autoSave = true); - - Task HardDeleteAsync(TEntity entity, bool autoSave = true); - } -} diff --git a/JiShe.CollectBus.EntityFrameworkCore/Repositories/Repository.cs b/JiShe.CollectBus.EntityFrameworkCore/Repositories/Repository.cs deleted file mode 100644 index 5d12a8a..0000000 --- a/JiShe.CollectBus.EntityFrameworkCore/Repositories/Repository.cs +++ /dev/null @@ -1,295 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; -using System.Threading.Tasks; -using JiShe.CollectBus.Common.Extensions; -using JiShe.CollectBus.EntityFrameworkCore.Entities; -using Microsoft.EntityFrameworkCore; - -namespace JiShe.CollectBus.EntityFrameworkCore.Repositories -{ - public class Repository : IRepository - where TEntity : class, IEntity - { - public virtual CollectBusDbContext DbContext { private set; get; } - - public virtual DbSet Table => DbContext.Set(); - - public Repository(CollectBusDbContext dbContext) - { - DbContext = dbContext; - } - - public virtual IQueryable GetAll(params Expression>[] propertySelectors) - { - var query = Table.AsNoTracking(); - if (!propertySelectors.IsNullOrEmpty()) - { - foreach (var propertySelector in propertySelectors) - { - query = query.Include(propertySelector); - } - } - return query; - } - - public virtual IQueryable GetAll(Expression> expression, params Expression>[] propertySelectors) - { - var query = Table.Where(expression); - if (!propertySelectors.IsNullOrEmpty()) - { - foreach (var propertySelector in propertySelectors) - { - query = query.Include(propertySelector); - } - } - return query; - } - - public virtual TEntity Find(TPrimaryKey id) - { - return Table.Find(id); - } - - public virtual async Task FindAsync(TPrimaryKey id) - { - return await Table.FindAsync(id); - } - - public virtual TEntity Get(Expression> expression, params Expression>[] propertySelectors) - { - var query = GetAll(); - if (!propertySelectors.IsNullOrEmpty()) - { - foreach (var propertySelector in propertySelectors) - { - query = query.Include(propertySelector); - } - return query.FirstOrDefault(expression); - } - return Table.FirstOrDefault(expression); - } - - public virtual async Task GetAsync(Expression> expression, params Expression>[] propertySelectors) - { - var query = GetAll(); - if (!propertySelectors.IsNullOrEmpty()) - { - foreach (var propertySelector in propertySelectors) - { - query = query.Include(propertySelector); - } - return await query.FirstOrDefaultAsync(expression); - } - return await Table.FirstOrDefaultAsync(expression); - } - - public virtual void Insert(TEntity entity, bool autoSave = true) - { - var hasCreationTime = typeof(IHasCreationTime).IsAssignableFrom(typeof(TEntity)); - if (hasCreationTime) - { - ((IHasCreationTime)entity).CreationTime = DateTime.Now; - } - ((IHasCreationTime)entity).CreationTime = DateTime.Now; - Table.Add(entity); - if (autoSave) - { - DbContext.SaveChanges(); - } - } - - public virtual async Task InsertAsync(TEntity entity, bool autoSave = true) - { - var hasCreationTime = typeof(IHasCreationTime).IsAssignableFrom(typeof(TEntity)); - if (hasCreationTime) - { - ((IHasCreationTime)entity).CreationTime = DateTime.Now; - } - await Table.AddAsync(entity); - if (autoSave) - { - await DbContext.SaveChangesAsync(); - } - } - - public virtual async Task InsertAndGetIdAsync(TEntity entity, bool autoSave = true) - { - var hasCreationTime = typeof(IHasCreationTime).IsAssignableFrom(typeof(TEntity)); - if (hasCreationTime) - { - ((IHasCreationTime)entity).CreationTime = DateTime.Now; - } - await Table.AddAsync(entity); - if (autoSave) - { - await DbContext.SaveChangesAsync(); - } - return entity.Id; - } - - public virtual void InsertList(List entities, bool autoSave = true) - { - var hasCreationTime = typeof(IHasCreationTime).IsAssignableFrom(typeof(TEntity)); - if (hasCreationTime) - { - foreach (var entity in entities) - { - ((IHasCreationTime)entity).CreationTime = DateTime.Now; - } - } - Table.AddRange(entities); - if (autoSave) - { - DbContext.SaveChanges(); - } - } - - public virtual async Task InsertListAsync(List entities, bool autoSave = true) - { - var hasCreationTime = typeof(IHasCreationTime).IsAssignableFrom(typeof(TEntity)); - if (hasCreationTime) - { - foreach (var entity in entities) - { - ((IHasCreationTime)entity).CreationTime = DateTime.Now; - } - } - await Table.AddRangeAsync(entities); - if (autoSave) - { - await DbContext.SaveChangesAsync(); - } - } - - public virtual void Update(TEntity entity, bool autoSave = true) - { - var hasLastModificationTime = typeof(IHasLastModificationTime).IsAssignableFrom(typeof(TEntity)); - if (hasLastModificationTime) - { - ((IHasLastModificationTime)entity).LastModificationTime = DateTime.Now; - } - Table.Update(entity); - if (autoSave) - { - DbContext.SaveChanges(); - } - } - - public virtual async Task UpdateAsync(TEntity entity, bool autoSave = true) - { - var hasLastModificationTime = typeof(IHasLastModificationTime).IsAssignableFrom(typeof(TEntity)); - if (hasLastModificationTime) - { - ((IHasLastModificationTime)entity).LastModificationTime = DateTime.Now; - } - Table.Update(entity); - if (autoSave) - { - await DbContext.SaveChangesAsync(); - } - } - - public virtual void UpdateList(IEnumerable entities) - { - Table.UpdateRange(entities); - DbContext.SaveChanges(); - } - - public virtual async Task UpdateListAsync(IEnumerable entities) - { - Table.UpdateRange(entities); - await DbContext.SaveChangesAsync(); - } - - public virtual void Delete(TPrimaryKey id, bool autoSave = true) - { - var entity = Find(id); - if (entity == null) - { - throw new ArgumentNullException(); - } - Delete(entity, autoSave); - } - - public virtual async Task DeleteAsync(TPrimaryKey id, bool autoSave = true) - { - var entity = await FindAsync(id); - if (entity == null) - { - throw new ArgumentNullException(); - } - await DeleteAsync(entity, autoSave); - } - - public virtual void Delete(TEntity entity, bool autoSave = true) - { - var hasDeletionTime = typeof(IHasDeletionTime).IsAssignableFrom(typeof(TEntity)); - if (hasDeletionTime) - { - ((IHasDeletionTime)entity).DeletionTime = DateTime.Now; - } - var isDeleteEntity = typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)); - if (isDeleteEntity) - { - ((ISoftDelete)entity).IsDeleted = true; - } - Update(entity, autoSave); - } - - public virtual async Task DeleteAsync(TEntity entity, bool autoSave = true) - { - var hasDeletionTime = typeof(IHasDeletionTime).IsAssignableFrom(typeof(TEntity)); - if (hasDeletionTime) - { - ((IHasDeletionTime)entity).DeletionTime = DateTime.Now; - } - var isDeleteEntity = typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)); - if (isDeleteEntity) - { - ((ISoftDelete)entity).IsDeleted = true; - } - await UpdateAsync(entity, autoSave); - } - - public virtual void HardDelete(TPrimaryKey id, bool autoSave = true) - { - var entity = Find(id); - if (entity == null) - { - throw new ArgumentNullException(); - } - HardDelete(entity, autoSave); - } - - public async Task HardDeleteAsync(TPrimaryKey id, bool autoSave = true) - { - var entity = await FindAsync(id); - if (entity == null) - { - throw new ArgumentNullException(); - } - await HardDeleteAsync(entity, autoSave); - } - - public virtual void HardDelete(TEntity entity, bool autoSave = true) - { - Table.Remove(entity); - if (autoSave) - { - DbContext.SaveChanges(); - } - } - - public virtual async Task HardDeleteAsync(TEntity entity, bool autoSave = true) - { - Table.Remove(entity); - if (autoSave) - { - await DbContext.SaveChangesAsync(); - } - } - } -} diff --git a/JiShe.CollectBus.Host/Controllers/CommandController.cs b/JiShe.CollectBus.Host/Controllers/CommandController.cs deleted file mode 100644 index 4fce45b..0000000 --- a/JiShe.CollectBus.Host/Controllers/CommandController.cs +++ /dev/null @@ -1,36 +0,0 @@ -using JiShe.CollectBus.Application.Contracts; -using Volo.Abp.AspNetCore.Mvc; - -namespace JiShe.CollectBus.Host.Controllers -{ - public class CommandController : AbpController - { - private readonly ILogger _logger; - private readonly ICommandService _commandService; - - public CommandController(ILogger logger, ICommandService commandService) - { - _logger = logger; - _commandService = commandService; - } - - public async Task AmmeterParameterSendAsync() - { - - return await _commandService.AmmeterParameterSendAsync(); - } - - public bool AmmeterParameterReading() - { - return _commandService.AmmeterParameterReading(); - } - - public bool ActivePowerIndicationReading() - { - - return _commandService.ActivePowerIndicationReading(); - - } - - } -} diff --git a/JiShe.CollectBus.Host/Extensions/ServiceCollections/ServiceCollectionExtensions.cs b/JiShe.CollectBus.Host/Extensions/ServiceCollections/ServiceCollectionExtensions.cs deleted file mode 100644 index dab9401..0000000 --- a/JiShe.CollectBus.Host/Extensions/ServiceCollections/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Reflection; -using Volo.Abp.Modularity; - -// ReSharper disable once CheckNamespace -namespace Microsoft.Extensions.DependencyInjection -{ - public static class ServiceCollectionExtensions - { - public static void AddPluginApplications(this IServiceCollection services, string pluginPath = "") - { - if (string.IsNullOrWhiteSpace(pluginPath)) - { - pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"); - } - var assemblies = GetAssembliesFromFolder(pluginPath); - - foreach (var assembly in assemblies) - { - var applicationServiceType = assembly.GetTypes() - .FirstOrDefault(a => a.IsClass && !a.IsAbstract && typeof(AbpModule).IsAssignableFrom(a)); - services.AddApplication(applicationServiceType); - } - } - - private static IEnumerable GetAssembliesFromFolder(string folderPath) - { - var directory = new DirectoryInfo(folderPath); - if (!directory.Exists) return []; - - var files = directory.GetFiles("*.dll"); - - var assemblies = new List(); - foreach (var file in files) - { - try - { - var assembly = Assembly.LoadFrom(file.FullName); - assemblies.Add(assembly); - } - catch (Exception ex) - { - Console.WriteLine($"Error loading assembly from {file.FullName}: {ex.Message}"); - } - } - - return assemblies; - } - } -} \ No newline at end of file diff --git a/JiShe.CollectBus.Host/JiShe.CollectBus.Host.csproj b/JiShe.CollectBus.Host/JiShe.CollectBus.Host.csproj deleted file mode 100644 index a5ac8e9..0000000 --- a/JiShe.CollectBus.Host/JiShe.CollectBus.Host.csproj +++ /dev/null @@ -1,35 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/JiShe.CollectBus.Host/JiSheCollectBusHostModule.cs b/JiShe.CollectBus.Host/JiSheCollectBusHostModule.cs deleted file mode 100644 index 7b78fed..0000000 --- a/JiShe.CollectBus.Host/JiSheCollectBusHostModule.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Abp.Dependency; -using DeviceDetectorNET.Parser.Device; -using Serilog; -using Volo.Abp.Modularity; - -namespace JiShe.CollectBus.Host -{ - public class JiSheCollectBusHostModule : AbpModule - { - public override void ConfigureServices(ServiceConfigurationContext context) - { - var services = context.Services; - var configuration = IocManager.Instance.Resolve(); - //services.AddApplication(); - - //services.AddApplication(); - - services.AddPluginApplications(); - services.AddStackExchangeRedisCache(options => - { - options.Configuration = configuration["RedisCache:ConnectionString"]; - options.InstanceName = configuration["RedisCache:InstanceName"]; - }); - } - } -} diff --git a/JiShe.CollectBus.Host/Models/GeneralIssuedInput.cs b/JiShe.CollectBus.Host/Models/GeneralIssuedInput.cs deleted file mode 100644 index 16ff06a..0000000 --- a/JiShe.CollectBus.Host/Models/GeneralIssuedInput.cs +++ /dev/null @@ -1,33 +0,0 @@ -using JiShe.CollectBus.Common.Enums; - -namespace JiShe.CollectBus.Host.Models -{ - public class GeneralIssuedInput - { - /// - /// 测量点号 0~2040 为0被删除 - /// - public int Pn { get; set; } - - /// - /// 波特率600起 1~7 - /// - public int BaudRate { get; set; } - - /// - /// 端口号 1-31 - /// - public int Port { get; set; } - - public CommunicationProtocolType ProtocolType { get; set; } - /// - /// 通信地址 0~999999999999 - /// - public string Address { get; set; } - - /// - /// 通信密码 - /// - public string Password { get; set; } = "000000"; - } -} diff --git a/JiShe.CollectBus.Host/Program.cs b/JiShe.CollectBus.Host/Program.cs deleted file mode 100644 index 9f3a6da..0000000 --- a/JiShe.CollectBus.Host/Program.cs +++ /dev/null @@ -1,42 +0,0 @@ -using JiShe.CollectBus.Host; -using Serilog; - -public class Program -{ - public static void Main(string[] args) - { - try - { - Log.Logger = new LoggerConfiguration() - .WriteTo.Console() - .CreateLogger(); - - - CreateHostBuilder(args).Build().Run(); - - } - catch (Exception ex) - { - Log.Fatal(ex, "Application terminated unexpectedly"); - } - finally - { - Log.CloseAndFlush(); - } - - } - - private static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .UseContentRoot(Directory.GetCurrentDirectory()) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.ConfigureKestrel((context, options) => { options.Limits.MaxRequestBodySize = 1024 * 50; }); - webBuilder.UseStartup(); - }) - .UseSerilog((context, loggerConfiguration) => - { - loggerConfiguration.ReadFrom.Configuration(context.Configuration); - }); -} - diff --git a/JiShe.CollectBus.Host/Startup.cs b/JiShe.CollectBus.Host/Startup.cs deleted file mode 100644 index e28c135..0000000 --- a/JiShe.CollectBus.Host/Startup.cs +++ /dev/null @@ -1,90 +0,0 @@ -using Hangfire; -using Hangfire.Dashboard.BasicAuthorization; -using Hangfire.HttpJob; -using Hangfire.MySql; -using JiShe.CollectBus.Application; - -namespace JiShe.CollectBus.Host -{ - public class Startup(IConfiguration configuration) - { - public void ConfigureServices(IServiceCollection services) - { - services.AddControllers(); - services.AddApplication(); - services.AddEndpointsApiExplorer(); - services.AddSwaggerGen(); - services.AddHangfire(config => - { - config.SetDataCompatibilityLevel(CompatibilityLevel.Version_180) - .UseSimpleAssemblyNameTypeSerializer() - .UseRecommendedSerializerSettings(); - - config.UseStorage( - new MySqlStorage( - configuration.GetConnectionString("Default"), - new MySqlStorageOptions - { - QueuePollInterval = TimeSpan.FromSeconds(15), //- 作业队列轮询间隔。默认值为15秒。 - JobExpirationCheckInterval = TimeSpan.FromHours(1), //- 作业到期检查间隔(管理过期记录)。默认值为1小时。 - CountersAggregateInterval = TimeSpan.FromMinutes(5), //- 聚合计数器的间隔。默认为5分钟。 - PrepareSchemaIfNecessary = true, //- 如果设置为true,则创建数据库表。默认是true。 - DashboardJobListLimit = 50000, //- 仪表板作业列表限制。默认值为50000。 - TransactionTimeout = TimeSpan.FromMinutes(1), //- 交易超时。默认为1分钟。 - })); - config.UseHangfireHttpJob(); - }); - services.AddHangfireServer(); - } - - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - app.UseSwagger(); - app.UseSwaggerUI(); - } - - app.UseHttpsRedirection(); - app.UseStaticFiles(); - - app.UseRouting(); - - app.UseAuthorization(); - - var dashboardOptions = new DashboardOptions(); - - if (env.IsProduction()) - dashboardOptions = new DashboardOptions - { - Authorization = new[] - { - new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions - { - SslRedirect = false, - RequireSsl = false, - LoginCaseSensitive = false, - Users = - [ - new BasicAuthAuthorizationUser - { - Login = "admin", - PasswordClear = "lixiao1980" - } - ] - }) - } - }; - app.UseHangfireDashboard("/hangfire", dashboardOptions); - - //app.UseEndpoints(endpoints => - //{ - // endpoints.MapRazorPages(); - //}); - app.UseConfiguredEndpoints(); - } - } - -} diff --git a/JiShe.CollectBus.Host/appsettings.json b/JiShe.CollectBus.Host/appsettings.json deleted file mode 100644 index f2183ed..0000000 --- a/JiShe.CollectBus.Host/appsettings.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "Serilog": { - "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], - "MinimumLevel": "Information", - "Override": { - "Microsoft": "Warning", - "System": "Warning" - }, - "WriteTo": [ - { "Name": "Console" }, - { - "Name": "File", - "Args": { - "path": "Logs/log-.txt", - "rollingInterval": "Day" - //"rollOnFileSizeLimit": true, - //"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact" - } - } - ], - "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], - - "Properties": { - "Application": "CollectBus", - "Environment": "Development" - } - }, - - "ConnectionStrings": { - "Default": "Data Source=192.168.111.248;Port=3306;Database=JiSheCollectBus;uid=root;pwd=123456abcD;charset=utf8mb4;Allow User Variables=true;AllowLoadLocalInfile=true", - //"Default": "Data Source=localhost;Port=3306;Database=JiSheCollectBus;uid=root;pwd=123456abcD;charset=utf8mb4;Allow User Variables=true;AllowLoadLocalInfile=true" - }, - "MongoSettings": { - "Connection": "mongodb://backups_admin:jishe_mongodb_backups@118.190.144.92:27037", - "DatabaseName": "JiSheCollectBus" - }, - "RedisCache": { - "ConnectionString": "123456@qwer@localhost:6379", - "InstanceName": "CollectBus" - }, - "MQ": { - "Host": "118.190.144.92", - "Port": "5672", - "VirtualHost": "/", - "UserName": "collectbus", - "Password": "123456", - "Queue": { - "Received": "Received_Command", - "Issued": "Issued_Command" - } - } -} \ No newline at end of file diff --git a/JiShe.CollectBus.MongoDB/IMongoContext.cs b/JiShe.CollectBus.MongoDB/IMongoContext.cs deleted file mode 100644 index 70dcaec..0000000 --- a/JiShe.CollectBus.MongoDB/IMongoContext.cs +++ /dev/null @@ -1,37 +0,0 @@ -using MongoDB.Driver; - -namespace JiShe.CollectBus.MongoDB -{ - public interface IMongoContext : IDisposable - { - /// - /// 添加命令操作 - /// - /// 委托 方法接受一个 Func 委托作为参数,该委托表示一个需要 IClientSessionHandle 对象作为参数并返回一个异步任务的方法 - /// - Task AddCommandAsync(Func func); - - /// - /// 提交更改并返回受影响的行数 - /// TODO:MongoDB单机服务器不支持事务【使用MongoDB事务会报错:Standalone servers do not support transactions】,只有在集群情况下才支持事务 - /// 原因:MongoDB在使用分布式事务时需要进行多节点之间的协调和通信,而单机环境下无法实现这样的分布式协调和通信机制。但是,在MongoDB部署为一个集群(cluster)后,将多个计算机连接为一个整体,通过协调和通信机制实现了分布式事务的正常使用。从数据一致性和可靠性的角度来看,在分布式系统中实现事务处理是至关重要的。而在单机环境下不支持事务,只有在集群情况下才支持事务的设计方式是为了保证数据一致性和可靠性,并且也符合分布式系统的设计思想。 - /// - /// MongoDB 会话(session)对象 - /// - Task SaveChangesAsync(IClientSessionHandle session); - - /// - /// 初始化Mongodb会话对象session - /// - /// - Task StartSessionAsync(); - - /// - /// 获取集合数据 - /// - /// - /// - /// - IMongoCollection GetCollection(string name); - } -} diff --git a/JiShe.CollectBus.MongoDB/IMongoRepository.cs b/JiShe.CollectBus.MongoDB/IMongoRepository.cs deleted file mode 100644 index 10e25eb..0000000 --- a/JiShe.CollectBus.MongoDB/IMongoRepository.cs +++ /dev/null @@ -1,176 +0,0 @@ -using MongoDB.Driver; -using System.Linq.Expressions; - -namespace JiShe.CollectBus.MongoDB -{ - public interface IMongoRepository where T : class, new() - { - #region 事务操作示例 - - /// - /// 事务添加数据 - /// - /// MongoDB 会话(session)对象 - /// 添加数据 - /// - Task AddTransactionsAsync(IClientSessionHandle session, T objData); - - /// - /// 事务数据删除 - /// - /// MongoDB 会话(session)对象 - /// objectId - /// - Task DeleteTransactionsAsync(IClientSessionHandle session, string id); - - /// - /// 事务异步局部更新(仅更新一条记录) - /// - /// MongoDB 会话(session)对象 - /// 过滤器 - /// 更新条件 - /// - Task UpdateTransactionsAsync(IClientSessionHandle session, FilterDefinition filter, UpdateDefinition update); - - #endregion - - #region 添加相关操作 - - /// - /// 添加数据 - /// - /// 添加数据 - /// - Task AddAsync(T objData); - - /// - /// 批量插入 - /// - /// 实体集合 - /// - Task InsertManyAsync(List objDatas); - - #endregion - - #region 删除相关操作 - - /// - /// 数据删除 - /// - /// objectId - /// - Task DeleteAsync(string id); - - /// - /// 异步删除多条数据 - /// - /// 删除的条件 - /// - Task DeleteManyAsync(FilterDefinition filter); - - #endregion - - #region 修改相关操作 - - /// - /// 指定对象异步修改一条数据 - /// - /// 要修改的对象 - /// 修改条件 - /// - Task UpdateAsync(T obj, string id); - - /// - /// 局部更新(仅更新一条记录) - /// x.Id == 1 && x.Age > 18 && x.Gender == 0]]> - /// new T{ RealName = "Ray", Gender = 1}]]> - /// - /// 筛选条件 - /// 更新条件 - /// - Task UpdateAsync(Expression> expression, Expression> entity); - - /// - /// 异步局部更新(仅更新一条记录) - /// - /// 过滤器 - /// 更新条件 - /// - Task UpdateAsync(FilterDefinition filter, UpdateDefinition update); - - /// - /// 异步局部更新(仅更新多条记录) - /// - /// 筛选条件 - /// 更新条件 - /// - Task UpdateManyAsync(Expression> expression, UpdateDefinition update); - - /// - /// 异步批量修改数据 - /// - /// 要修改的字段 - /// 更新条件 - /// - Task UpdateManayAsync(Dictionary dic, FilterDefinition filter); - - #endregion - - #region 查询统计相关操作 - - /// - /// 通过ID主键获取数据 - /// - /// objectId - /// - Task GetByIdAsync(string id); - /// - /// 获取所有数据 - /// - /// - Task> GetAllAsync(); - - /// - /// 获取记录数 - /// - /// 筛选条件 - /// - Task CountAsync(Expression> expression); - - /// - /// 获取记录数 - /// - /// 过滤器 - /// - Task CountAsync(FilterDefinition filter); - - /// - /// 判断是否存在 - /// - /// 条件 - /// - Task ExistsAsync(Expression> predicate); - - /// - /// 异步查询集合 - /// - /// 查询条件 - /// 要查询的字段,不写时查询全部 - /// 要排序的字段 - /// - Task> FindListAsync(FilterDefinition filter, string[]? field = null, SortDefinition? sort = null); - - /// - /// 异步分页查询集合 - /// - /// 查询条件 - /// 当前页 - /// 页容量 - /// 要查询的字段,不写时查询全部 - /// 要排序的字段 - /// - Task> FindListByPageAsync(FilterDefinition filter, int pageIndex, int pageSize, string[]? field = null, SortDefinition? sort = null); - - #endregion - } -} diff --git a/JiShe.CollectBus.MongoDB/IUnitOfWork.cs b/JiShe.CollectBus.MongoDB/IUnitOfWork.cs deleted file mode 100644 index 8ecadb0..0000000 --- a/JiShe.CollectBus.MongoDB/IUnitOfWork.cs +++ /dev/null @@ -1,25 +0,0 @@ -using MongoDB.Driver; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JiShe.CollectBus.MongoDB -{ - public interface IUnitOfWork : IDisposable - { - /// - /// 提交保存更改 - /// - /// MongoDB 会话(session)对象 - /// - Task Commit(IClientSessionHandle session); - - /// - /// 初始化MongoDB会话对象session - /// - /// - Task InitTransaction(); - } -} diff --git a/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.csproj b/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.csproj deleted file mode 100644 index c144b6f..0000000 --- a/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - - - - - - - diff --git a/JiShe.CollectBus.MongoDB/JiSheCollectBusMongoDBModule.cs b/JiShe.CollectBus.MongoDB/JiSheCollectBusMongoDBModule.cs deleted file mode 100644 index cd8998c..0000000 --- a/JiShe.CollectBus.MongoDB/JiSheCollectBusMongoDBModule.cs +++ /dev/null @@ -1,29 +0,0 @@ -using JiShe.CollectBus.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Volo.Abp.Modularity; -using Volo.Abp.Timing; - -namespace JiShe.CollectBus.MongoDB -{ - [DependsOn(typeof(AbpTimingModule), - typeof(JiSheCollectBusEntityFrameworkCoreModule))] - public class JiSheCollectBusMongoDbModule: AbpModule - { - public override void PreConfigureServices(ServiceConfigurationContext context) - { - - } - - public override void ConfigureServices(ServiceConfigurationContext context) - { - context.Services.AddSingleton(); - context.Services.AddSingleton(); - context.Services.AddSingleton(typeof(IMongoRepository<>), typeof(MongoBaseRepository<>)); - - Configure(options => - { - options.Kind = DateTimeKind.Local; - }); - } - } -} diff --git a/JiShe.CollectBus.MongoDB/MongoBaseRepository.cs b/JiShe.CollectBus.MongoDB/MongoBaseRepository.cs deleted file mode 100644 index 5df6aea..0000000 --- a/JiShe.CollectBus.MongoDB/MongoBaseRepository.cs +++ /dev/null @@ -1,352 +0,0 @@ -using MongoDB.Bson; -using MongoDB.Driver; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using JiShe.CollectBus.Common.Interfaces; -using JiShe.CollectBus.EntityFrameworkCore; -using Volo.Abp.Timing; - -namespace JiShe.CollectBus.MongoDB -{ - public class MongoBaseRepository : IMongoRepository where T : class, new() - { - private readonly IMongoContext _context; - private readonly IMongoCollection _dbSet; - private readonly IClock _clock; - - public MongoBaseRepository(IMongoContext context, IClock clock) - { - _context = context; - _clock = clock; - var collectionName = typeof(T).GetCustomAttribute()?.Name ?? typeof(T).Name; - _dbSet = _context.GetCollection(collectionName); - } - - #region 事务操作示例 - - /// - /// 事务添加数据 - /// - /// MongoDB 会话(session)对象 - /// 添加数据 - /// - public async Task AddTransactionsAsync(IClientSessionHandle session, T objData) - { - await _context.AddCommandAsync(async (session) => await _dbSet.InsertOneAsync(objData)); - } - - /// - /// 事务数据删除 - /// - /// MongoDB 会话(session)对象 - /// objectId - /// - public async Task DeleteTransactionsAsync(IClientSessionHandle session, string id) - { - await _context.AddCommandAsync((session) => _dbSet.DeleteOneAsync(Builders.Filter.Eq(" _id ", id))); - } - - /// - /// 事务异步局部更新(仅更新一条记录) - /// - /// MongoDB 会话(session)对象 - /// 过滤器 - /// 更新条件 - /// - public async Task UpdateTransactionsAsync(IClientSessionHandle session, FilterDefinition filter, UpdateDefinition update) - { - await _context.AddCommandAsync((session) => _dbSet.UpdateOneAsync(filter, update)); - } - - #endregion - - #region 添加相关操作 - - /// - /// 添加数据 - /// - /// 添加数据 - /// - public async Task AddAsync(T objData) - { - if (typeof(IReceived).IsAssignableFrom(typeof(T))) - { - (objData as IReceived)!.ReceivedTime = $"{_clock.Now:yyyy-MM-dd HH:mm:ss}"; - } - await _dbSet.InsertOneAsync(objData); - } - - /// - /// 批量插入 - /// - /// 实体集合 - /// - public async Task InsertManyAsync(List objDatas) - { - await _dbSet.InsertManyAsync(objDatas); - } - - #endregion - - #region 删除相关操作 - - /// - /// 数据删除 - /// - /// objectId - /// - public async Task DeleteAsync(string id) - { - await _dbSet.DeleteOneAsync(Builders.Filter.Eq("_id", new ObjectId(id))); - } - - /// - /// 异步删除多条数据 - /// - /// 删除的条件 - /// - public async Task DeleteManyAsync(FilterDefinition filter) - { - return await _dbSet.DeleteManyAsync(filter); - } - - #endregion - - #region 修改相关操作 - - /// - /// 指定对象异步修改一条数据 - /// - /// 要修改的对象 - /// 修改条件 - /// - public async Task UpdateAsync(T obj, string id) - { - //修改条件 - FilterDefinition filter = Builders.Filter.Eq("_id", new ObjectId(id)); - //要修改的字段 - var list = new List>(); - foreach (var item in obj.GetType().GetProperties()) - { - if (item.Name.ToLower() == "id") continue; - list.Add(Builders.Update.Set(item.Name, item.GetValue(obj))); - } - var updatefilter = Builders.Update.Combine(list); - await _dbSet.UpdateOneAsync(filter, updatefilter); - } - - /// - /// 局部更新(仅更新一条记录) - /// x.Id == 1 && x.Age > 18 && x.Gender == 0]]> - /// new T{ RealName = "Ray", Gender = 1}]]> - /// - /// 筛选条件 - /// 更新条件 - /// - public async Task UpdateAsync(Expression> expression, Expression> entity) - { - var fieldList = new List>(); - - if (entity.Body is MemberInitExpression param) - { - foreach (var item in param.Bindings) - { - var propertyName = item.Member.Name; - object propertyValue = null; - - if (item is not MemberAssignment memberAssignment) continue; - - if (memberAssignment.Expression.NodeType == ExpressionType.Constant) - { - if (memberAssignment.Expression is ConstantExpression constantExpression) - propertyValue = constantExpression.Value; - } - else - { - propertyValue = Expression.Lambda(memberAssignment.Expression, null).Compile().DynamicInvoke(); - } - - if (propertyName != "_id") //实体键_id不允许更新 - { - fieldList.Add(Builders.Update.Set(propertyName, propertyValue)); - } - } - } - - await _dbSet.UpdateOneAsync(expression, Builders.Update.Combine(fieldList)); - } - - /// - /// 异步局部更新(仅更新一条记录) - /// - /// 过滤器 - /// 更新条件 - /// - public async Task UpdateAsync(FilterDefinition filter, UpdateDefinition update) - { - await _dbSet.UpdateOneAsync(filter, update); - } - - /// - /// 异步局部更新(仅更新多条记录) - /// - /// 筛选条件 - /// 更新条件 - /// - public async Task UpdateManyAsync(Expression> expression, UpdateDefinition update) - { - await _dbSet.UpdateManyAsync(expression, update); - } - - /// - /// 异步批量修改数据 - /// - /// 要修改的字段 - /// 更新条件 - /// - public async Task UpdateManayAsync(Dictionary dic, FilterDefinition filter) - { - T t = new T(); - //要修改的字段 - var list = new List>(); - foreach (var item in t.GetType().GetProperties()) - { - if (!dic.ContainsKey(item.Name)) continue; - var value = dic[item.Name]; - list.Add(Builders.Update.Set(item.Name, value)); - } - var updatefilter = Builders.Update.Combine(list); - return await _dbSet.UpdateManyAsync(filter, updatefilter); - } - - #endregion - - #region 查询统计相关操作 - - /// - /// 通过ID主键获取数据 - /// - /// objectId - /// - public async Task GetByIdAsync(string id) - { - var queryData = await _dbSet.FindAsync(Builders.Filter.Eq("_id", new ObjectId(id))); - return queryData.FirstOrDefault(); - } - - /// - /// 获取所有数据 - /// - /// - public async Task> GetAllAsync() - { - var queryAllData = await _dbSet.FindAsync(Builders.Filter.Empty); - return queryAllData.ToList(); - } - - /// - /// 获取记录数 - /// - /// 筛选条件 - /// - public async Task CountAsync(Expression> expression) - { - return await _dbSet.CountDocumentsAsync(expression); - } - - /// - /// 获取记录数 - /// - /// 过滤器 - /// - public async Task CountAsync(FilterDefinition filter) - { - return await _dbSet.CountDocumentsAsync(filter); - } - - /// - /// 判断是否存在 - /// - /// 条件 - /// - public async Task ExistsAsync(Expression> predicate) - { - return await Task.FromResult(_dbSet.AsQueryable().Any(predicate)); - } - - /// - /// 异步查询集合 - /// - /// 查询条件 - /// 要查询的字段,不写时查询全部 - /// 要排序的字段 - /// - public async Task> FindListAsync(FilterDefinition filter, string[]? field = null, SortDefinition? sort = null) - { - //不指定查询字段 - if (field == null || field.Length == 0) - { - if (sort == null) return await _dbSet.Find(filter).ToListAsync(); - return await _dbSet.Find(filter).Sort(sort).ToListAsync(); - } - - //指定查询字段 - var fieldList = new List>(); - for (int i = 0; i < field.Length; i++) - { - fieldList.Add(Builders.Projection.Include(field[i].ToString())); - } - var projection = Builders.Projection.Combine(fieldList); - fieldList?.Clear(); - - //不排序 - if (sort == null) return await _dbSet.Find(filter).Project(projection).ToListAsync(); - - //排序查询 - return await _dbSet.Find(filter).Sort(sort).Project(projection).ToListAsync(); - } - - /// - /// 异步分页查询集合 - /// - /// 查询条件 - /// 当前页 - /// 页容量 - /// 要查询的字段,不写时查询全部 - /// 要排序的字段 - /// - public async Task> FindListByPageAsync(FilterDefinition filter, int pageIndex, int pageSize, string[]? field = null, SortDefinition? sort = null) - { - //不指定查询字段 - if (field == null || field.Length == 0) - { - if (sort == null) return await _dbSet.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); - //进行排序 - return await _dbSet.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); - } - - //指定查询字段 - var fieldList = new List>(); - for (int i = 0; i < field.Length; i++) - { - fieldList.Add(Builders.Projection.Include(field[i].ToString())); - } - var projection = Builders.Projection.Combine(fieldList); - fieldList?.Clear(); - - //不排序 - if (sort == null) return await _dbSet.Find(filter).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); - - //排序查询 - return await _dbSet.Find(filter).Sort(sort).Project(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToListAsync(); - } - - #endregion - } -} diff --git a/JiShe.CollectBus.MongoDB/MongoContext.cs b/JiShe.CollectBus.MongoDB/MongoContext.cs deleted file mode 100644 index 7491027..0000000 --- a/JiShe.CollectBus.MongoDB/MongoContext.cs +++ /dev/null @@ -1,93 +0,0 @@ -using Microsoft.Extensions.Configuration; -using MongoDB.Driver; - -namespace JiShe.CollectBus.MongoDB -{ - public class MongoContext : IMongoContext - { - private readonly IMongoDatabase _database; - private readonly MongoClient _mongoClient; - - //这里将 _commands 中的每个元素都定义为一个 Func 委托,此委托表示一个需要 IClientSessionHandle 对象作为参数并返回一个异步任务的方法 - //每个委托都表示一个MongoDB 会话(session)对象和要执行的命令 - private readonly List> _commands = []; - - public MongoContext(IConfiguration configuration) - { - _mongoClient = new MongoClient(configuration["MongoSettings:Connection"]); - _database = _mongoClient.GetDatabase(configuration["MongoSettings:DatabaseName"]); - } - - /// - /// 添加命令操作 - /// - /// 方法接受一个 Func 委托作为参数,该委托表示一个需要 IClientSessionHandle 对象作为参数并返回一个异步任务的方法 - /// - public async Task AddCommandAsync(Func func) - { - _commands.Add(func); - await Task.CompletedTask; - } - - /// - /// 提交更改并返回受影响的行数 - /// TODO:MongoDB单机服务器不支持事务【使用MongoDB事务会报错:Standalone servers do not support transactions】,只有在集群情况下才支持事务 - /// 原因:MongoDB在使用分布式事务时需要进行多节点之间的协调和通信,而单机环境下无法实现这样的分布式协调和通信机制。但是,在MongoDB部署为一个集群(cluster)后,将多个计算机连接为一个整体,通过协调和通信机制实现了分布式事务的正常使用。从数据一致性和可靠性的角度来看,在分布式系统中实现事务处理是至关重要的。而在单机环境下不支持事务,只有在集群情况下才支持事务的设计方式是为了保证数据一致性和可靠性,并且也符合分布式系统的设计思想。 - /// - /// MongoDB 会话(session)对象 - /// - public async Task SaveChangesAsync(IClientSessionHandle session) - { - try - { - session.StartTransaction();//开始事务 - - foreach (var command in _commands) - { - await command(session); - } - - await session.CommitTransactionAsync();//提交事务 - return _commands.Count; - } - catch (Exception ex) - { - await session.AbortTransactionAsync();//回滚事务 - return 0; - } - finally - { - _commands.Clear();//清空_commands列表中的元素 - } - } - - /// - /// 初始化Mongodb会话对象session - /// - /// - public async Task StartSessionAsync() - { - var session = await _mongoClient.StartSessionAsync(); - return session; - } - - /// - /// 获取MongoDB集合 - /// - /// - /// 集合名称 - /// - public IMongoCollection GetCollection(string name) - { - return _database.GetCollection(name); - } - - /// - /// 释放上下文 - /// - public void Dispose() - { - GC.SuppressFinalize(this); - } - } -} diff --git a/JiShe.CollectBus.MongoDB/UnitOfWork.cs b/JiShe.CollectBus.MongoDB/UnitOfWork.cs deleted file mode 100644 index 6b7b523..0000000 --- a/JiShe.CollectBus.MongoDB/UnitOfWork.cs +++ /dev/null @@ -1,43 +0,0 @@ -using MongoDB.Driver; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JiShe.CollectBus.MongoDB -{ - public class UnitOfWork : IUnitOfWork - { - private readonly IMongoContext _context; - - public UnitOfWork(IMongoContext context) - { - _context = context; - } - - /// - /// 提交保存更改 - /// - /// MongoDB 会话(session)对象 - /// - public async Task Commit(IClientSessionHandle session) - { - return await _context.SaveChangesAsync(session) > 0; - } - - /// - /// 初始化MongoDB会话对象session - /// - /// - public async Task InitTransaction() - { - return await _context.StartSessionAsync(); - } - - public void Dispose() - { - _context.Dispose(); - } - } -} diff --git a/JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolPlugin.cs b/JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolPlugin.cs deleted file mode 100644 index 52330e9..0000000 --- a/JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolPlugin.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Threading.Tasks; -using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.Protocol.Contracts.Models; -using TouchSocket.Sockets; - -namespace JiShe.CollectBus.Protocol.Contracts.Interfaces -{ - public interface IProtocolPlugin - { - Task GetAsync(); - - Task AnalyzeAsync(MessageReceivedEvent messageReceivedEvent, Action? sendAction = null); - - Task LoginAsync(MessageReceivedLoginEvent messageReceivedEvent, Action? sendAction = null); - - Task HeartbeatAsync(MessageReceivedHeartbeatEvent messageReceivedEvent, Action? sendAction = null); - } -} diff --git a/JiShe.CollectBus.Protocol.Test/JiShe.CollectBus.Protocol.Demo.csproj b/JiShe.CollectBus.Protocol.Test/JiShe.CollectBus.Protocol.Demo.csproj deleted file mode 100644 index 10623dc..0000000 --- a/JiShe.CollectBus.Protocol.Test/JiShe.CollectBus.Protocol.Demo.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - net8.0 - enable - enable - preview - - - - - - - - - - - diff --git a/JiShe.CollectBus.Protocol.Test/JiSheCollectBusTestProtocolModule.cs b/JiShe.CollectBus.Protocol.Test/JiSheCollectBusTestProtocolModule.cs deleted file mode 100644 index 63a75e9..0000000 --- a/JiShe.CollectBus.Protocol.Test/JiSheCollectBusTestProtocolModule.cs +++ /dev/null @@ -1,20 +0,0 @@ -using JiShe.CollectBus.Protocol.Contracts.Interfaces; -using Microsoft.Extensions.DependencyInjection; -using Volo.Abp; -using Volo.Abp.Modularity; - -namespace JiShe.CollectBus.Protocol.Demo -{ - public class JiSheCollectBusTestProtocolModule : AbpModule - { - public override void ConfigureServices(ServiceConfigurationContext context) - { - context.Services.AddKeyedSingleton("Test"); - } - - public override void OnApplicationInitialization(ApplicationInitializationContext context) - { - - } - } -} diff --git a/JiShe.CollectBus.Protocol.Test/TestProtocolPlugin.cs b/JiShe.CollectBus.Protocol.Test/TestProtocolPlugin.cs deleted file mode 100644 index 5f53960..0000000 --- a/JiShe.CollectBus.Protocol.Test/TestProtocolPlugin.cs +++ /dev/null @@ -1,27 +0,0 @@ -using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.Protocol.Contracts.Abstracts; -using JiShe.CollectBus.Protocol.Contracts.Attributes; -using JiShe.CollectBus.Protocol.Contracts.Models; -using Microsoft.Extensions.Logging; - -namespace JiShe.CollectBus.Protocol.Demo -{ - [ProtocolName("TestProtocol")] - public class TestProtocolPlugin : BaseProtocolPlugin - { - public TestProtocolPlugin(ILogger logger) : base(logger) - { - } - - public override async Task GetAsync() - { - var info = new ProtocolInfo("Test", "376.1", "TCP", "376.1协议", "DTS1980"); - return await Task.FromResult(info); - } - - public override Task AnalyzeAsync(MessageReceivedEvent messageReceivedEvent, Action? sendAction = null) - { - throw new NotImplementedException(); - } - } -} diff --git a/JiShe.CollectBus.RabbitMQ/INSender.cs b/JiShe.CollectBus.RabbitMQ/INSender.cs deleted file mode 100644 index 24b520d..0000000 --- a/JiShe.CollectBus.RabbitMQ/INSender.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace JiShe.CollectBus.MQ.Sender -{ - public interface INSender - { - Task SendToIssuedAsync(T message, CancellationToken cancellationToken = default) where T : class; - Task SendToIssuedAsync(object message, CancellationToken cancellationToken = default); - Task SendToReceivedAsync(T message, CancellationToken cancellationToken = default) where T : class; - Task SendToReceivedAsync(object message, CancellationToken cancellationToken = default); - Task SendToReceivedLoginAsync(T message, CancellationToken cancellationToken = default) where T : class; - Task SendToReceivedLoginAsync(object message, CancellationToken cancellationToken = default); - Task SendToReceivedHeartbeatAsync(T message, CancellationToken cancellationToken = default) where T : class; - Task SendToReceivedHeartbeatAsync(object message, CancellationToken cancellationToken = default); - Task SendAsync(string queueKey, object message, CancellationToken cancellationToken = default); - - } -} diff --git a/JiShe.CollectBus.RabbitMQ/JiShe.CollectBus.MQ.Sender.csproj b/JiShe.CollectBus.RabbitMQ/JiShe.CollectBus.MQ.Sender.csproj deleted file mode 100644 index f676e4e..0000000 --- a/JiShe.CollectBus.RabbitMQ/JiShe.CollectBus.MQ.Sender.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - net8.0 - enable - enable - preview - true - - - - - - - - - - - - diff --git a/JiShe.CollectBus.RabbitMQ/JiSheCollectBusMQSenderModule.cs b/JiShe.CollectBus.RabbitMQ/JiSheCollectBusMQSenderModule.cs deleted file mode 100644 index a050078..0000000 --- a/JiShe.CollectBus.RabbitMQ/JiSheCollectBusMQSenderModule.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Volo.Abp; -using Volo.Abp.Modularity; - -namespace JiShe.CollectBus.MQ.Sender -{ - public class JiSheCollectBusMqSenderModule: AbpModule - { - public override void ConfigureServices(ServiceConfigurationContext context) - { - - } - - public override void OnApplicationInitialization(ApplicationInitializationContext context) - { - } - } -} diff --git a/JiShe.CollectBus.RabbitMQ/NSender.cs b/JiShe.CollectBus.RabbitMQ/NSender.cs deleted file mode 100644 index 58f2237..0000000 --- a/JiShe.CollectBus.RabbitMQ/NSender.cs +++ /dev/null @@ -1,71 +0,0 @@ -using MassTransit; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Volo.Abp.DependencyInjection; - -namespace JiShe.CollectBus.MQ.Sender -{ - public class NSender : INSender, ISingletonDependency - { - private readonly ServiceProvider _serviceProvider; - private readonly string _issuedKey; - private readonly string _receivedKey; - - - public NSender(IConfiguration configuration, ServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - _issuedKey = configuration["MQ:Queue:Issued"]!; - _receivedKey = configuration["MQ:Queue:Received"]!; - } - - public async Task SendToIssuedAsync(T message, CancellationToken cancellationToken = default) where T : class - { - await SendAsync(_issuedKey, message, cancellationToken); - } - - public async Task SendToIssuedAsync(object message, CancellationToken cancellationToken = default) - { - await SendAsync(_issuedKey, message, cancellationToken); - } - - public async Task SendToReceivedAsync(T message, CancellationToken cancellationToken = default) where T : class - { - await SendAsync(_receivedKey, message, cancellationToken); - } - - public async Task SendToReceivedAsync(object message, CancellationToken cancellationToken = default) - { - await SendAsync(_receivedKey, message, cancellationToken); - } - - public async Task SendToReceivedLoginAsync(T message, CancellationToken cancellationToken = default) where T : class - { - await SendAsync($"{_receivedKey}_Login", message, cancellationToken); - } - - public async Task SendToReceivedLoginAsync(object message, CancellationToken cancellationToken = default) - { - await SendAsync($"{_receivedKey}_Login", message, cancellationToken); - } - - public async Task SendToReceivedHeartbeatAsync(T message, CancellationToken cancellationToken = default) where T : class - { - await SendAsync($"{_receivedKey}_Heartbeat", message, cancellationToken); - } - - public async Task SendToReceivedHeartbeatAsync(object message, CancellationToken cancellationToken = default) - { - await SendAsync($"{_receivedKey}_Heartbeat", message, cancellationToken); - } - - - public async Task SendAsync(string queueKey, object message, CancellationToken cancellationToken = default) - { - using var scope = _serviceProvider.CreateScope(); - var scopedService = scope.ServiceProvider.GetRequiredService(); - var endpoint = await scopedService.GetSendEndpoint(new Uri($"queue:{queueKey}")); - await endpoint.Send(message, cancellationToken); - } - } -} diff --git a/JiShe.CollectBus.Service/JiShe.CollectBus.MQ.Consumer.csproj b/JiShe.CollectBus.Service/JiShe.CollectBus.MQ.Consumer.csproj deleted file mode 100644 index 8ffd136..0000000 --- a/JiShe.CollectBus.Service/JiShe.CollectBus.MQ.Consumer.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - - - - - - - diff --git a/JiShe.CollectBus.Service/JiSheCollectBusMQConsumerModule.cs b/JiShe.CollectBus.Service/JiSheCollectBusMQConsumerModule.cs deleted file mode 100644 index e28ee9f..0000000 --- a/JiShe.CollectBus.Service/JiSheCollectBusMQConsumerModule.cs +++ /dev/null @@ -1,87 +0,0 @@ -using JiShe.CollectBus.Network; -using MassTransit; -using Microsoft.Extensions.DependencyInjection; -using Volo.Abp; -using Volo.Abp.Modularity; - -namespace JiShe.CollectBus.MQ.Consumer -{ - [DependsOn(typeof(JiSheCollectBusNetworkModule))] - public class JiSheCollectBusMqConsumerModule: AbpModule - { - public override void ConfigureServices(ServiceConfigurationContext context) - { - var configuration = context.Services.GetConfiguration(); - context.Services.AddMassTransit(x => - { - x.AddConsumer(cfg => - { - cfg.Options(options => options - .SetMessageLimit(100) - .SetTimeLimit(s: 1) - .SetTimeLimitStart(BatchTimeLimitStart.FromLast) - //.GroupBy(x => x.CustomerId) - .SetConcurrencyLimit(10)); - }); - x.AddConsumer(); - x.AddConsumer(); - x.AddConsumer(); - - x.AddConfigureEndpointsCallback((c, name, cfg) => - { - cfg.UseDelayedRedelivery(r => r.Intervals(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(30))); - cfg.UseMessageRetry(r => r.Immediate(5)); - cfg.UseInMemoryOutbox(c); - - //cfg.UseMessageRetry(r => - //{ - // r.Immediate(5); - // r.Handle(x => x.Message.Contains("SQL")); - //}); - }); - - x.UsingRabbitMq((c, cfg) => - { - cfg.Host(configuration["MQ:Host"], ushort.Parse(configuration["MQ:Port"] ?? string.Empty), configuration["MQ:VirtualHost"], h => - { - h.Username(configuration["MQ:UserName"] ?? string.Empty); - h.Password(configuration["MQ:Password"] ?? string.Empty); - }); - - // 消息接收队列 - cfg.ReceiveEndpoint(configuration["MQ:Queue:Received"] ?? string.Empty, configurator => - { - configurator.ConfigureConsumeTopology = false; - configurator.Consumer(c); - configurator.Durable = true; - }); - // 登录 - cfg.ReceiveEndpoint($"{configuration["MQ:Queue:Received"]}_Login", configurator => - { - configurator.ConfigureConsumeTopology = false; - configurator.Consumer(c); - configurator.Durable = true; - }); - // 心跳 - cfg.ReceiveEndpoint($"{configuration["MQ:Queue:Received"]}_Heartbeat", configurator => - { - configurator.ConfigureConsumeTopology = false; - configurator.Consumer(c); - configurator.Durable = true; - }); - // 消息下发队列 - cfg.ReceiveEndpoint(configuration["MQ:Queue:Issued"] ?? string.Empty, configurator => - { - configurator.ConfigureConsumeTopology = false; - configurator.Consumer(c); - configurator.Durable = true; - }); - }); - }); - } - - public override void OnApplicationInitialization(ApplicationInitializationContext context) - { - } - } -} diff --git a/JiShe.CollectBus.Service/MessageIssuedConsumer.cs b/JiShe.CollectBus.Service/MessageIssuedConsumer.cs deleted file mode 100644 index e2a5921..0000000 --- a/JiShe.CollectBus.Service/MessageIssuedConsumer.cs +++ /dev/null @@ -1,35 +0,0 @@ -using JiShe.CollectBus.Common.Enums; -using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.MongoDB; -using MassTransit; -using Microsoft.Extensions.Logging; -using TouchSocket.Sockets; - -namespace JiShe.CollectBus.MQ.Consumer -{ - public class MessageIssuedConsumer( - ILogger logger, - ITcpService tcpService, - IMongoRepository mongoHeartbeatRepository, - IMongoRepository mongoLoginRepository) - : IConsumer - { - public async Task Consume(ConsumeContext context) - { - switch (context.Message.Type) - { - case IssuedEventType.Heartbeat: - await mongoHeartbeatRepository.UpdateAsync(a => a.MessageId == context.Message.MessageId, b => new MessageReceivedHeartbeatEvent { IsAck = true, AckTime = DateTime.Now }); - break; - case IssuedEventType.Login: - await mongoLoginRepository.UpdateAsync(a => a.MessageId == context.Message.MessageId, b => new MessageReceivedLoginEvent { IsAck = true, AckTime = DateTime.Now }); - break; - case IssuedEventType.Data: - break; - default: - throw new ArgumentOutOfRangeException(); - } - await tcpService.SendAsync(context.Message.ClientId, context.Message.Message); - } - } -} diff --git a/JiShe.CollectBus.Service/MessageIssuedFaultConsumer.cs b/JiShe.CollectBus.Service/MessageIssuedFaultConsumer.cs deleted file mode 100644 index 8c03a44..0000000 --- a/JiShe.CollectBus.Service/MessageIssuedFaultConsumer.cs +++ /dev/null @@ -1,13 +0,0 @@ -using JiShe.CollectBus.Common.Models; -using MassTransit; - -namespace JiShe.CollectBus.MQ.Consumer -{ - public class MessageIssuedFaultConsumer : IConsumer> - { - public Task Consume(ConsumeContext> context) - { - throw new NotImplementedException(); - } - } -} diff --git a/JiShe.CollectBus.Service/MessageReceivedConsumer.cs b/JiShe.CollectBus.Service/MessageReceivedConsumer.cs deleted file mode 100644 index 2e9c511..0000000 --- a/JiShe.CollectBus.Service/MessageReceivedConsumer.cs +++ /dev/null @@ -1,39 +0,0 @@ -using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.MongoDB; -using JiShe.CollectBus.Protocol.Contracts.Interfaces; -using MassTransit; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace JiShe.CollectBus.MQ.Consumer -{ - /// - /// Batch 一次最多 100 个,最多 10 个并发批次 - /// - public class MessageReceivedConsumer( - ILogger logger, - IServiceProvider serviceProvider, - IMongoRepository mongoReceivedRepository) - : IConsumer> - { - public async Task Consume(ConsumeContext> context) - { - const string protocolType = "Standard"; - var protocolPlugin = serviceProvider.GetKeyedService(protocolType); - if (protocolPlugin == null) - { - logger.LogError("协议不存在!"); - } - else - { - var list = new List(); - foreach (var contextItem in context.Message) - { - await protocolPlugin.AnalyzeAsync(contextItem.Message); - list.Add(contextItem.Message); - } - await mongoReceivedRepository.InsertManyAsync(list); - } - } - } -} diff --git a/JiShe.CollectBus.Service/MessageReceivedFaultConsumer.cs b/JiShe.CollectBus.Service/MessageReceivedFaultConsumer.cs deleted file mode 100644 index 5d9c999..0000000 --- a/JiShe.CollectBus.Service/MessageReceivedFaultConsumer.cs +++ /dev/null @@ -1,13 +0,0 @@ -using JiShe.CollectBus.Common.Models; -using MassTransit; - -namespace JiShe.CollectBus.MQ.Consumer -{ - public class MessageReceivedFaultConsumer: IConsumer>> - { - public Task Consume(ConsumeContext>> context) - { - throw new NotImplementedException(); - } - } -} diff --git a/JiShe.CollectBus.Service/MessageReceivedHeartbeatConsumer.cs b/JiShe.CollectBus.Service/MessageReceivedHeartbeatConsumer.cs deleted file mode 100644 index 77d27a2..0000000 --- a/JiShe.CollectBus.Service/MessageReceivedHeartbeatConsumer.cs +++ /dev/null @@ -1,29 +0,0 @@ -using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.Protocol.Contracts.Interfaces; -using MassTransit; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace JiShe.CollectBus.MQ.Consumer -{ - public class MessageReceivedHeartbeatConsumer( - ILogger logger, - IServiceProvider serviceProvider) - : IConsumer - { - public async Task Consume(ConsumeContext context) - { - logger.LogInformation("心跳消费队列开始处理"); - var protocolPlugin = serviceProvider.GetKeyedService("Standard"); - if (protocolPlugin == null) - { - logger.LogError("【心跳消费队列开始处理】协议不存在!"); - } - else - { - await protocolPlugin.HeartbeatAsync(context.Message); - logger.LogInformation("心跳消费队列完成处理"); - } - } - } -} diff --git a/JiShe.CollectBus.Service/MessageReceivedLoginConsumer.cs b/JiShe.CollectBus.Service/MessageReceivedLoginConsumer.cs deleted file mode 100644 index aacec81..0000000 --- a/JiShe.CollectBus.Service/MessageReceivedLoginConsumer.cs +++ /dev/null @@ -1,29 +0,0 @@ -using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.Protocol.Contracts.Interfaces; -using MassTransit; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace JiShe.CollectBus.MQ.Consumer -{ - public class MessageReceivedLoginConsumer( - ILogger logger, - IServiceProvider serviceProvider) - : IConsumer - { - public async Task Consume(ConsumeContext context) - { - logger.LogInformation("登录消费队列开始处理"); - var protocolPlugin = serviceProvider.GetKeyedService("Standard"); - if (protocolPlugin == null) - { - logger.LogError("【登录消费队列开始处理】协议不存在!"); - } - else - { - await protocolPlugin.LoginAsync(context.Message); - logger.LogInformation("登录消费队列完成处理"); - } - } - } -} diff --git a/JiShe.CollectBus.Test/BusUnitTest.cs b/JiShe.CollectBus.Test/BusUnitTest.cs deleted file mode 100644 index 6f1a462..0000000 --- a/JiShe.CollectBus.Test/BusUnitTest.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data.Common; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using JiShe.CollectBus.Common.Enums; -using JiShe.CollectBus.Common.Extensions; -using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.MQ.Sender; -using JiShe.CollectBus.Protocol.Contracts.Models; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Moq; -using Xunit.Abstractions; - -namespace JiShe.CollectBus.Test -{ - public class BusUnitTest - { - private INSender _nSender; - - public BusUnitTest() - { - _nSender = new Mock().Object; - } - - [Fact] - public async void AmmeterParameterSend() - { - var listMeter = new List() - { - new() - { - Pn = 1, - BaudRate = 3, - Port = 2, - ProtocolType = CommunicationProtocolType.DLT6452007, - Address = "312408006642", - Password = "000000", - RateNumber = 4, - IntegerBitNumber = 4, - DecimalBitNumber = 4, - CollectorAddress = "000000000000", - UserCategoryNumber = 0, - UserSubclassNumber = 0 - } - }; - var bytes = HexStringExtensions.BuildAmmeterParameterSetSendCmd(new ReqParameter2() - { - AFN = AFN.设置参数, - FunCode = (int)CMasterStationFunCode.请求1级数据, - A = "322009872", - Seq = new Seq() - { - TpV = TpV.附加信息域中无时间标签, - FIRFIN = FIRFIN.单帧, - CON = CON.需要对该帧进行确认, - PRSEQ = 10, - }, - MSA = 13, - Pn = 0, - Fn = 10 - }, listMeter); - Assert.NotEmpty(bytes); - - await _nSender.SendToIssuedAsync(new MessageIssuedEvent { DeviceNo = "322009872", Message = bytes, Type = IssuedEventType.Data, MessageId = Guid.NewGuid().ToString() }); - } - - } -} diff --git a/JiShe.CollectBus.Test/JiShe.CollectBus.Test.csproj b/JiShe.CollectBus.Test/JiShe.CollectBus.Test.csproj deleted file mode 100644 index 5c59917..0000000 --- a/JiShe.CollectBus.Test/JiShe.CollectBus.Test.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - net8.0 - enable - enable - - false - true - - - - - - - - - - - - - - - - - - - - diff --git a/JiShe.CollectBus.abpmdl b/JiShe.CollectBus.abpmdl new file mode 100644 index 0000000..2bfc382 --- /dev/null +++ b/JiShe.CollectBus.abpmdl @@ -0,0 +1,62 @@ +{ + "folders": { + "items": { + "src": {}, + "test": {} + } + }, + "packages": { + "JiShe.CollectBus.Domain": { + "path": "src/JiShe.CollectBus.Domain/JiShe.CollectBus.Domain.abppkg", + "folder": "src" + }, + "JiShe.CollectBus.Application.Contracts": { + "path": "src/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.abppkg", + "folder": "src" + }, + "JiShe.CollectBus.Application": { + "path": "src/JiShe.CollectBus.Application/JiShe.CollectBus.Application.abppkg", + "folder": "src" + }, + "JiShe.CollectBus.EntityFrameworkCore": { + "path": "src/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.abppkg", + "folder": "src" + }, + "JiShe.CollectBus.MongoDB": { + "path": "src/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.abppkg", + "folder": "src" + }, + "JiShe.CollectBus.HttpApi": { + "path": "src/JiShe.CollectBus.HttpApi/JiShe.CollectBus.HttpApi.abppkg", + "folder": "src" + }, + "JiShe.CollectBus.HttpApi.Client": { + "path": "src/JiShe.CollectBus.HttpApi.Client/JiShe.CollectBus.HttpApi.Client.abppkg", + "folder": "src" + }, + "JiShe.CollectBus.TestBase": { + "path": "test/JiShe.CollectBus.TestBase/JiShe.CollectBus.TestBase.abppkg", + "folder": "test" + }, + "JiShe.CollectBus.EntityFrameworkCore.Tests": { + "path": "test/JiShe.CollectBus.EntityFrameworkCore.Tests/JiShe.CollectBus.EntityFrameworkCore.Tests.abppkg", + "folder": "test" + }, + "JiShe.CollectBus.MongoDB.Tests": { + "path": "test/JiShe.CollectBus.MongoDB.Tests/JiShe.CollectBus.MongoDB.Tests.abppkg", + "folder": "test" + }, + "JiShe.CollectBus.Domain.Tests": { + "path": "test/JiShe.CollectBus.Domain.Tests/JiShe.CollectBus.Domain.Tests.abppkg", + "folder": "test" + }, + "JiShe.CollectBus.Application.Tests": { + "path": "test/JiShe.CollectBus.Application.Tests/JiShe.CollectBus.Application.Tests.abppkg", + "folder": "test" + }, + "JiShe.CollectBus.Domain.Shared": { + "path": "src/JiShe.CollectBus.Domain.Shared/JiShe.CollectBus.Domain.Shared.abppkg", + "folder": "src" + } + } +} diff --git a/JiShe.CollectBus.abpsln b/JiShe.CollectBus.abpsln new file mode 100644 index 0000000..a2c182e --- /dev/null +++ b/JiShe.CollectBus.abpsln @@ -0,0 +1,9 @@ +{ + "id": "ff9a1137-9bbc-4a8f-9b0b-0765c3bfc2e0", + "template": "empty", + "modules": { + "JiShe.CollectBus": { + "path": "JiShe.CollectBus.abpmdl" + } + } +} \ No newline at end of file diff --git a/JiShe.CollectBus.sln b/JiShe.CollectBus.sln index 71613ea..5a41cab 100644 --- a/JiShe.CollectBus.sln +++ b/JiShe.CollectBus.sln @@ -3,41 +3,31 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.9.34728.123 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Network", "JiShe.CollectBus.Core\JiShe.CollectBus.Network.csproj", "{F1360C93-5B6B-4E65-9D81-1DA38740F32D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Domain.Shared", "src\JiShe.CollectBus.Domain.Shared\JiShe.CollectBus.Domain.Shared.csproj", "{D64C1577-4929-4B60-939E-96DE1534891A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Console", "JiShe.CollectBus.Console\JiShe.CollectBus.Console.csproj", "{40C4F834-3080-451B-9510-6FE7BC4F801F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Domain", "src\JiShe.CollectBus.Domain\JiShe.CollectBus.Domain.csproj", "{F2840BC7-0188-4606-9126-DADD0F5ABF7A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Protocol", "JiShe.CollectBus.Protocol\JiShe.CollectBus.Protocol.csproj", "{B2C476F1-AE32-419D-BDA2-291FCE639CF6}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Application.Contracts", "src\JiShe.CollectBus.Application.Contracts\JiShe.CollectBus.Application.Contracts.csproj", "{BD65D04F-08D5-40C1-8C24-77CA0BACB877}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Protocol.Contracts", "JiShe.CollectBus.Protocol.Contracts\JiShe.CollectBus.Protocol.Contracts.csproj", "{4468B52D-3AAE-4918-B4D6-E6E8F000825D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Application", "src\JiShe.CollectBus.Application\JiShe.CollectBus.Application.csproj", "{78040F9E-3501-4A40-82DF-00A597710F35}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Common", "JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj", "{1D3A5A4E-B977-4E33-A1AF-62508110C3B7}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{649A3FFA-182F-4E56-9717-E6A9A2BEC545}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "3.test", "3.test", "{3A04FB29-EA75-4499-BBF3-AF24C7D46A1D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.MongoDB", "src\JiShe.CollectBus.MongoDB\JiShe.CollectBus.MongoDB.csproj", "{F1C58097-4C08-4D88-8976-6B3389391481}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2.core", "2.core", "{C7DEC9FB-3F75-4584-85B0-16EA3CB222E5}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.HttpApi", "src\JiShe.CollectBus.HttpApi\JiShe.CollectBus.HttpApi.csproj", "{077AA5F8-8B61-420C-A6B5-0150A66FDB34}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Protocol.Demo", "JiShe.CollectBus.Protocol.Test\JiShe.CollectBus.Protocol.Demo.csproj", "{289196B4-FFBE-4E40-A3A1-FCFADBE945ED}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Host", "src\JiShe.CollectBus.Host\JiShe.CollectBus.Host.csproj", "{35829A15-4127-4F69-8BDE-9405DEAACA9A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.EntityFrameworkCore", "JiShe.CollectBus.EntityFrameworkCore\JiShe.CollectBus.EntityFrameworkCore.csproj", "{16D42BCF-EDB8-4153-B37D-0B10FB6DF36C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Common", "src\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj", "{AD2F1928-4411-4511-B564-5FB996EC08B9}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.MQ.Sender", "JiShe.CollectBus.RabbitMQ\JiShe.CollectBus.MQ.Sender.csproj", "{DB46D90E-304D-48B7-9ED6-F4DCC95D3824}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Protocol", "src\JiShe.CollectBus.Protocol\JiShe.CollectBus.Protocol.csproj", "{C62EFF95-5C32-435F-BD78-6977E828F894}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.MongoDB", "JiShe.CollectBus.MongoDB\JiShe.CollectBus.MongoDB.csproj", "{223DBDB1-6CD3-4D4E-8795-42550BC0A871}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Protocol.Contracts", "src\JiShe.CollectBus.Protocol.Contracts\JiShe.CollectBus.Protocol.Contracts.csproj", "{38C1808B-009A-418B-B17B-AB3626341B5D}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1.host", "1.host", "{B68027BA-BD9D-4110-A383-708B87BC425D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.DbMigrator", "src\JiShe.CollectBus.DbMigrator\JiShe.CollectBus.DbMigrator.csproj", "{8BA01C3D-297D-42DF-BD63-EF07202A0A67}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Host", "JiShe.CollectBus.Host\JiShe.CollectBus.Host.csproj", "{FFA010F6-F33A-4705-8A42-B0FA3B3D2131}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "4.demo", "4.demo", "{43E8E19B-555A-4633-9926-B4F3C01D972A}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.Test", "JiShe.CollectBus.Test\JiShe.CollectBus.Test.csproj", "{6ED66F52-B4A0-403E-AE89-8E9A679C0885}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JiShe.CollectBus.Application", "JiShe.CollectBus.Application\JiShe.CollectBus.Application.csproj", "{2760AC98-D2FA-4074-8396-FAE10BE20A3C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JiShe.CollectBus.Application.Contracts", "JiShe.CollectBus.Application.Contracts\JiShe.CollectBus.Application.Contracts.csproj", "{47B9A51B-70B5-42ED-A92A-FFEFB864CB14}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JiShe.CollectBus.MQ.Consumer", "JiShe.CollectBus.Service\JiShe.CollectBus.MQ.Consumer.csproj", "{024086CC-49D0-436E-8B84-A67766A30CDE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiShe.CollectBus.FreeSql", "src\JiShe.CollectBus.FreeSql\JiShe.CollectBus.FreeSql.csproj", "{FE0457D9-4038-4A17-8808-DCAD06CFC0A0}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -45,83 +35,73 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {F1360C93-5B6B-4E65-9D81-1DA38740F32D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F1360C93-5B6B-4E65-9D81-1DA38740F32D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F1360C93-5B6B-4E65-9D81-1DA38740F32D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F1360C93-5B6B-4E65-9D81-1DA38740F32D}.Release|Any CPU.Build.0 = Release|Any CPU - {40C4F834-3080-451B-9510-6FE7BC4F801F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {40C4F834-3080-451B-9510-6FE7BC4F801F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {40C4F834-3080-451B-9510-6FE7BC4F801F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {40C4F834-3080-451B-9510-6FE7BC4F801F}.Release|Any CPU.Build.0 = Release|Any CPU - {B2C476F1-AE32-419D-BDA2-291FCE639CF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B2C476F1-AE32-419D-BDA2-291FCE639CF6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B2C476F1-AE32-419D-BDA2-291FCE639CF6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B2C476F1-AE32-419D-BDA2-291FCE639CF6}.Release|Any CPU.Build.0 = Release|Any CPU - {4468B52D-3AAE-4918-B4D6-E6E8F000825D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4468B52D-3AAE-4918-B4D6-E6E8F000825D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4468B52D-3AAE-4918-B4D6-E6E8F000825D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4468B52D-3AAE-4918-B4D6-E6E8F000825D}.Release|Any CPU.Build.0 = Release|Any CPU - {1D3A5A4E-B977-4E33-A1AF-62508110C3B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1D3A5A4E-B977-4E33-A1AF-62508110C3B7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1D3A5A4E-B977-4E33-A1AF-62508110C3B7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1D3A5A4E-B977-4E33-A1AF-62508110C3B7}.Release|Any CPU.Build.0 = Release|Any CPU - {289196B4-FFBE-4E40-A3A1-FCFADBE945ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {289196B4-FFBE-4E40-A3A1-FCFADBE945ED}.Debug|Any CPU.Build.0 = Debug|Any CPU - {289196B4-FFBE-4E40-A3A1-FCFADBE945ED}.Release|Any CPU.ActiveCfg = Release|Any CPU - {289196B4-FFBE-4E40-A3A1-FCFADBE945ED}.Release|Any CPU.Build.0 = Release|Any CPU - {16D42BCF-EDB8-4153-B37D-0B10FB6DF36C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {16D42BCF-EDB8-4153-B37D-0B10FB6DF36C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {16D42BCF-EDB8-4153-B37D-0B10FB6DF36C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {16D42BCF-EDB8-4153-B37D-0B10FB6DF36C}.Release|Any CPU.Build.0 = Release|Any CPU - {DB46D90E-304D-48B7-9ED6-F4DCC95D3824}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DB46D90E-304D-48B7-9ED6-F4DCC95D3824}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DB46D90E-304D-48B7-9ED6-F4DCC95D3824}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DB46D90E-304D-48B7-9ED6-F4DCC95D3824}.Release|Any CPU.Build.0 = Release|Any CPU - {223DBDB1-6CD3-4D4E-8795-42550BC0A871}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {223DBDB1-6CD3-4D4E-8795-42550BC0A871}.Debug|Any CPU.Build.0 = Debug|Any CPU - {223DBDB1-6CD3-4D4E-8795-42550BC0A871}.Release|Any CPU.ActiveCfg = Release|Any CPU - {223DBDB1-6CD3-4D4E-8795-42550BC0A871}.Release|Any CPU.Build.0 = Release|Any CPU - {FFA010F6-F33A-4705-8A42-B0FA3B3D2131}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FFA010F6-F33A-4705-8A42-B0FA3B3D2131}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FFA010F6-F33A-4705-8A42-B0FA3B3D2131}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FFA010F6-F33A-4705-8A42-B0FA3B3D2131}.Release|Any CPU.Build.0 = Release|Any CPU - {6ED66F52-B4A0-403E-AE89-8E9A679C0885}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6ED66F52-B4A0-403E-AE89-8E9A679C0885}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6ED66F52-B4A0-403E-AE89-8E9A679C0885}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6ED66F52-B4A0-403E-AE89-8E9A679C0885}.Release|Any CPU.Build.0 = Release|Any CPU - {2760AC98-D2FA-4074-8396-FAE10BE20A3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2760AC98-D2FA-4074-8396-FAE10BE20A3C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2760AC98-D2FA-4074-8396-FAE10BE20A3C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2760AC98-D2FA-4074-8396-FAE10BE20A3C}.Release|Any CPU.Build.0 = Release|Any CPU - {47B9A51B-70B5-42ED-A92A-FFEFB864CB14}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {47B9A51B-70B5-42ED-A92A-FFEFB864CB14}.Debug|Any CPU.Build.0 = Debug|Any CPU - {47B9A51B-70B5-42ED-A92A-FFEFB864CB14}.Release|Any CPU.ActiveCfg = Release|Any CPU - {47B9A51B-70B5-42ED-A92A-FFEFB864CB14}.Release|Any CPU.Build.0 = Release|Any CPU - {024086CC-49D0-436E-8B84-A67766A30CDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {024086CC-49D0-436E-8B84-A67766A30CDE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {024086CC-49D0-436E-8B84-A67766A30CDE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {024086CC-49D0-436E-8B84-A67766A30CDE}.Release|Any CPU.Build.0 = Release|Any CPU + {D64C1577-4929-4B60-939E-96DE1534891A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D64C1577-4929-4B60-939E-96DE1534891A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D64C1577-4929-4B60-939E-96DE1534891A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D64C1577-4929-4B60-939E-96DE1534891A}.Release|Any CPU.Build.0 = Release|Any CPU + {F2840BC7-0188-4606-9126-DADD0F5ABF7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F2840BC7-0188-4606-9126-DADD0F5ABF7A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F2840BC7-0188-4606-9126-DADD0F5ABF7A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F2840BC7-0188-4606-9126-DADD0F5ABF7A}.Release|Any CPU.Build.0 = Release|Any CPU + {BD65D04F-08D5-40C1-8C24-77CA0BACB877}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BD65D04F-08D5-40C1-8C24-77CA0BACB877}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BD65D04F-08D5-40C1-8C24-77CA0BACB877}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BD65D04F-08D5-40C1-8C24-77CA0BACB877}.Release|Any CPU.Build.0 = Release|Any CPU + {78040F9E-3501-4A40-82DF-00A597710F35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {78040F9E-3501-4A40-82DF-00A597710F35}.Debug|Any CPU.Build.0 = Debug|Any CPU + {78040F9E-3501-4A40-82DF-00A597710F35}.Release|Any CPU.ActiveCfg = Release|Any CPU + {78040F9E-3501-4A40-82DF-00A597710F35}.Release|Any CPU.Build.0 = Release|Any CPU + {F1C58097-4C08-4D88-8976-6B3389391481}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F1C58097-4C08-4D88-8976-6B3389391481}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F1C58097-4C08-4D88-8976-6B3389391481}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F1C58097-4C08-4D88-8976-6B3389391481}.Release|Any CPU.Build.0 = Release|Any CPU + {077AA5F8-8B61-420C-A6B5-0150A66FDB34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {077AA5F8-8B61-420C-A6B5-0150A66FDB34}.Debug|Any CPU.Build.0 = Debug|Any CPU + {077AA5F8-8B61-420C-A6B5-0150A66FDB34}.Release|Any CPU.ActiveCfg = Release|Any CPU + {077AA5F8-8B61-420C-A6B5-0150A66FDB34}.Release|Any CPU.Build.0 = Release|Any CPU + {35829A15-4127-4F69-8BDE-9405DEAACA9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {35829A15-4127-4F69-8BDE-9405DEAACA9A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {35829A15-4127-4F69-8BDE-9405DEAACA9A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {35829A15-4127-4F69-8BDE-9405DEAACA9A}.Release|Any CPU.Build.0 = Release|Any CPU + {AD2F1928-4411-4511-B564-5FB996EC08B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AD2F1928-4411-4511-B564-5FB996EC08B9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AD2F1928-4411-4511-B564-5FB996EC08B9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AD2F1928-4411-4511-B564-5FB996EC08B9}.Release|Any CPU.Build.0 = Release|Any CPU + {C62EFF95-5C32-435F-BD78-6977E828F894}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C62EFF95-5C32-435F-BD78-6977E828F894}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C62EFF95-5C32-435F-BD78-6977E828F894}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C62EFF95-5C32-435F-BD78-6977E828F894}.Release|Any CPU.Build.0 = Release|Any CPU + {38C1808B-009A-418B-B17B-AB3626341B5D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {38C1808B-009A-418B-B17B-AB3626341B5D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {38C1808B-009A-418B-B17B-AB3626341B5D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {38C1808B-009A-418B-B17B-AB3626341B5D}.Release|Any CPU.Build.0 = Release|Any CPU + {8BA01C3D-297D-42DF-BD63-EF07202A0A67}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8BA01C3D-297D-42DF-BD63-EF07202A0A67}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8BA01C3D-297D-42DF-BD63-EF07202A0A67}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8BA01C3D-297D-42DF-BD63-EF07202A0A67}.Release|Any CPU.Build.0 = Release|Any CPU + {FE0457D9-4038-4A17-8808-DCAD06CFC0A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FE0457D9-4038-4A17-8808-DCAD06CFC0A0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FE0457D9-4038-4A17-8808-DCAD06CFC0A0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FE0457D9-4038-4A17-8808-DCAD06CFC0A0}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {F1360C93-5B6B-4E65-9D81-1DA38740F32D} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} - {40C4F834-3080-451B-9510-6FE7BC4F801F} = {B68027BA-BD9D-4110-A383-708B87BC425D} - {B2C476F1-AE32-419D-BDA2-291FCE639CF6} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} - {4468B52D-3AAE-4918-B4D6-E6E8F000825D} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} - {1D3A5A4E-B977-4E33-A1AF-62508110C3B7} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} - {289196B4-FFBE-4E40-A3A1-FCFADBE945ED} = {43E8E19B-555A-4633-9926-B4F3C01D972A} - {16D42BCF-EDB8-4153-B37D-0B10FB6DF36C} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} - {DB46D90E-304D-48B7-9ED6-F4DCC95D3824} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} - {223DBDB1-6CD3-4D4E-8795-42550BC0A871} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} - {FFA010F6-F33A-4705-8A42-B0FA3B3D2131} = {B68027BA-BD9D-4110-A383-708B87BC425D} - {6ED66F52-B4A0-403E-AE89-8E9A679C0885} = {3A04FB29-EA75-4499-BBF3-AF24C7D46A1D} - {2760AC98-D2FA-4074-8396-FAE10BE20A3C} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} - {47B9A51B-70B5-42ED-A92A-FFEFB864CB14} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} - {024086CC-49D0-436E-8B84-A67766A30CDE} = {C7DEC9FB-3F75-4584-85B0-16EA3CB222E5} + {D64C1577-4929-4B60-939E-96DE1534891A} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {F2840BC7-0188-4606-9126-DADD0F5ABF7A} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {BD65D04F-08D5-40C1-8C24-77CA0BACB877} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {78040F9E-3501-4A40-82DF-00A597710F35} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {F1C58097-4C08-4D88-8976-6B3389391481} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {077AA5F8-8B61-420C-A6B5-0150A66FDB34} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {35829A15-4127-4F69-8BDE-9405DEAACA9A} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {AD2F1928-4411-4511-B564-5FB996EC08B9} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {C62EFF95-5C32-435F-BD78-6977E828F894} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {38C1808B-009A-418B-B17B-AB3626341B5D} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {8BA01C3D-297D-42DF-BD63-EF07202A0A67} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} + {FE0457D9-4038-4A17-8808-DCAD06CFC0A0} = {649A3FFA-182F-4E56-9717-E6A9A2BEC545} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {33261859-9CD1-4A43-B181-AB75C247D1CD} + SolutionGuid = {4324B3B4-B60B-4E3C-91D8-59576B4E26DD} EndGlobalSection EndGlobal diff --git a/common.props b/common.props new file mode 100644 index 0000000..6af0c73 --- /dev/null +++ b/common.props @@ -0,0 +1,27 @@ + + + latest + 1.0.0 + $(NoWarn);CS1591 + module + + + + + + All + runtime; build; native; contentfiles; analyzers + + + + + + $(NoWarn);0436 + + + + + + + + \ No newline at end of file diff --git a/dockerfile b/dockerfile deleted file mode 100644 index 9839af5..0000000 --- a/dockerfile +++ /dev/null @@ -1,21 +0,0 @@ -FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base -WORKDIR /app -EXPOSE 10500 -EXPOSE 443 -ENV TZ=Asia/Shanghai -ENV ASPNETCORE_ENVIRONMENT=Production - -FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build -WORKDIR /src -COPY . . -WORKDIR "/src/JiShe.CollectBus.Console" -RUN dotnet build "JiShe.CollectBus.Console.csproj" -c Release -o /app/build - -FROM build AS publish -RUN dotnet publish "JiShe.CollectBus.Console.csproj" -c Release -o /app/publish /p:UseAppHost=false - -FROM base AS final -WORKDIR /app -COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "JiShe.CollectBus.Console.dll"] - diff --git a/src/JiShe.CollectBus.Application.Contracts/BaseResultDto.cs b/src/JiShe.CollectBus.Application.Contracts/BaseResultDto.cs new file mode 100644 index 0000000..55c0339 --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/BaseResultDto.cs @@ -0,0 +1,32 @@ +namespace JiShe.CollectBus; + +/// +/// BaseResultDto +/// +/// +public class BaseResultDto where T : class +{ + /// + /// Gets or sets a value indicating whether this is status. + /// + /// + /// true if status; otherwise, false. + /// + public bool Status { get; set; } + + /// + /// Gets or sets the MSG. + /// + /// + /// The MSG. + /// + public string Msg { get; set; } + + /// + /// Gets or sets the data. + /// + /// + /// The data. + /// + public T Data { get; set; } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Application.Contracts/CollectBusApplicationContractsModule.cs b/src/JiShe.CollectBus.Application.Contracts/CollectBusApplicationContractsModule.cs new file mode 100644 index 0000000..932231c --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/CollectBusApplicationContractsModule.cs @@ -0,0 +1,15 @@ +using Volo.Abp.Application; +using Volo.Abp.Modularity; +using Volo.Abp.Authorization; + +namespace JiShe.CollectBus; + +[DependsOn( + typeof(CollectBusDomainSharedModule), + typeof(AbpDddApplicationContractsModule), + typeof(AbpAuthorizationModule) + )] +public class CollectBusApplicationContractsModule : AbpModule +{ + +} diff --git a/src/JiShe.CollectBus.Application.Contracts/CollectBusRemoteServiceConsts.cs b/src/JiShe.CollectBus.Application.Contracts/CollectBusRemoteServiceConsts.cs new file mode 100644 index 0000000..396140d --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/CollectBusRemoteServiceConsts.cs @@ -0,0 +1,8 @@ +namespace JiShe.CollectBus; + +public class CollectBusRemoteServiceConsts +{ + public const string RemoteServiceName = "CollectBus"; + + public const string ModuleName = "collectBus"; +} diff --git a/src/JiShe.CollectBus.Application.Contracts/EnergySystem/Dto/ValveControlInput.cs b/src/JiShe.CollectBus.Application.Contracts/EnergySystem/Dto/ValveControlInput.cs new file mode 100644 index 0000000..d056764 --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/EnergySystem/Dto/ValveControlInput.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.EnergySystem.Dto +{ + /// + /// 阀控输入 + /// + public class ValveControlInput + { + /// + /// 集中器区位码 + /// + public string AreaCode { get; set; } + /// + /// 集中器地址 + /// + public string Address { get; set; } + /// + /// 表号 + /// + public int AmmeterId { get; set; } + /// + /// 0 合闸,开阀, 1 断开、跳闸,关阀 + /// + public int TripState { get; set; } + /// + /// 采集端端口号 + /// + public string GatherCode { get; set; } + /// + /// 表:1,水表:2,燃气表:3,热能表:4 水表流量计:5,燃气表流量计:6,特殊电表:7 + /// + public int MeterType { get; set; } + } + +} diff --git a/src/JiShe.CollectBus.Application.Contracts/EnergySystem/Dto/ValveControlOutput.cs b/src/JiShe.CollectBus.Application.Contracts/EnergySystem/Dto/ValveControlOutput.cs new file mode 100644 index 0000000..7bf35df --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/EnergySystem/Dto/ValveControlOutput.cs @@ -0,0 +1,17 @@ +namespace JiShe.CollectBus.EnergySystem.Dto +{ + /// + /// 阀控输入 + /// + public class ValveControlOutput + { + /// + /// true: 成功,false:失败 + /// + public bool ValidData { get; set; } + /// + /// 备注(业务系统未使用) + /// + public string Remark { get; set; } + } +} diff --git a/src/JiShe.CollectBus.Application.Contracts/EnergySystem/IEnergySystemAppService.cs b/src/JiShe.CollectBus.Application.Contracts/EnergySystem/IEnergySystemAppService.cs new file mode 100644 index 0000000..e9be20a --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/EnergySystem/IEnergySystemAppService.cs @@ -0,0 +1,15 @@ +using System.Threading.Tasks; +using JiShe.CollectBus.EnergySystem.Dto; +using Volo.Abp.Application.Services; + +namespace JiShe.CollectBus.EnergySystem; + +public interface IEnergySystemAppService : IApplicationService +{ + /// + /// 电表阀控、水表阀控 + /// + /// The input. + /// + Task> ValveControl(ValveControlInput input); +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Application.Contracts/FodyWeavers.xml b/src/JiShe.CollectBus.Application.Contracts/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/JiShe.CollectBus.EntityFrameworkCore/Entities/IEntity.cs b/src/JiShe.CollectBus.Application.Contracts/ICollectWorker.cs similarity index 53% rename from JiShe.CollectBus.EntityFrameworkCore/Entities/IEntity.cs rename to src/JiShe.CollectBus.Application.Contracts/ICollectWorker.cs index 88f25ed..b6fc3d5 100644 --- a/JiShe.CollectBus.EntityFrameworkCore/Entities/IEntity.cs +++ b/src/JiShe.CollectBus.Application.Contracts/ICollectWorker.cs @@ -4,10 +4,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace JiShe.CollectBus.EntityFrameworkCore.Entities +namespace JiShe.CollectBus { - public interface IEntity + public interface ICollectWorker { - TKey Id { get; } } } diff --git a/src/JiShe.CollectBus.Application.Contracts/JiShe - Backup.CollectBus.Application.Contracts.csproj b/src/JiShe.CollectBus.Application.Contracts/JiShe - Backup.CollectBus.Application.Contracts.csproj new file mode 100644 index 0000000..9ea207e --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/JiShe - Backup.CollectBus.Application.Contracts.csproj @@ -0,0 +1,27 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + True + + + + + + + + + + + + + + + + + + diff --git a/src/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.abppkg b/src/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.abppkg new file mode 100644 index 0000000..4903279 --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.application-contracts" +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.csproj b/src/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.csproj new file mode 100644 index 0000000..0a28849 --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/JiShe.CollectBus.Application.Contracts.csproj @@ -0,0 +1,25 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + True + + + + + + + + + + + + + + + + diff --git a/src/JiShe.CollectBus.Application.Contracts/Permissions/CollectBusPermissionDefinitionProvider.cs b/src/JiShe.CollectBus.Application.Contracts/Permissions/CollectBusPermissionDefinitionProvider.cs new file mode 100644 index 0000000..6cf366b --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/Permissions/CollectBusPermissionDefinitionProvider.cs @@ -0,0 +1,18 @@ +using JiShe.CollectBus.Localization; +using Volo.Abp.Authorization.Permissions; +using Volo.Abp.Localization; + +namespace JiShe.CollectBus.Permissions; + +public class CollectBusPermissionDefinitionProvider : PermissionDefinitionProvider +{ + public override void Define(IPermissionDefinitionContext context) + { + var myGroup = context.AddGroup(CollectBusPermissions.GroupName, L("Permission:CollectBus")); + } + + private static LocalizableString L(string name) + { + return LocalizableString.Create(name); + } +} diff --git a/src/JiShe.CollectBus.Application.Contracts/Permissions/CollectBusPermissions.cs b/src/JiShe.CollectBus.Application.Contracts/Permissions/CollectBusPermissions.cs new file mode 100644 index 0000000..7d71651 --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/Permissions/CollectBusPermissions.cs @@ -0,0 +1,13 @@ +using Volo.Abp.Reflection; + +namespace JiShe.CollectBus.Permissions; + +public class CollectBusPermissions +{ + public const string GroupName = "CollectBus"; + + public static string[] GetAll() + { + return ReflectionHelper.GetPublicConstantsRecursively(typeof(CollectBusPermissions)); + } +} diff --git a/src/JiShe.CollectBus.Application.Contracts/Samples/ISampleAppService.cs b/src/JiShe.CollectBus.Application.Contracts/Samples/ISampleAppService.cs new file mode 100644 index 0000000..49ce813 --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/Samples/ISampleAppService.cs @@ -0,0 +1,11 @@ +using System.Threading.Tasks; +using Volo.Abp.Application.Services; + +namespace JiShe.CollectBus.Samples; + +public interface ISampleAppService : IApplicationService +{ + Task GetAsync(); + + Task GetAuthorizedAsync(); +} diff --git a/src/JiShe.CollectBus.Application.Contracts/Samples/SampleDto.cs b/src/JiShe.CollectBus.Application.Contracts/Samples/SampleDto.cs new file mode 100644 index 0000000..02a9f19 --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/Samples/SampleDto.cs @@ -0,0 +1,6 @@ +namespace JiShe.CollectBus.Samples; + +public class SampleDto +{ + public int Value { get; set; } +} diff --git a/src/JiShe.CollectBus.Application.Contracts/Subscribers/ISubscriberAppService.cs b/src/JiShe.CollectBus.Application.Contracts/Subscribers/ISubscriberAppService.cs new file mode 100644 index 0000000..bf7dec1 --- /dev/null +++ b/src/JiShe.CollectBus.Application.Contracts/Subscribers/ISubscriberAppService.cs @@ -0,0 +1,15 @@ +using System.Threading.Tasks; +using JiShe.CollectBus.Common.Models; +using JiShe.CollectBus.MessageReceiveds; +using Volo.Abp.Application.Services; + +namespace JiShe.CollectBus.Subscribers +{ + public interface ISubscriberAppService : IApplicationService + { + Task IssuedEvent(IssuedEventMessage issuedEventMessage); + Task ReceivedEvent(MessageReceived receivedMessage); + Task ReceivedHeartbeatEvent(MessageReceivedHeartbeat receivedHeartbeatMessage); + Task ReceivedLoginEvent(MessageReceivedLogin receivedLoginMessage); + } +} diff --git a/src/JiShe.CollectBus.Application/Ammeters/AmmeterInfo.cs b/src/JiShe.CollectBus.Application/Ammeters/AmmeterInfo.cs new file mode 100644 index 0000000..e9bc4b5 --- /dev/null +++ b/src/JiShe.CollectBus.Application/Ammeters/AmmeterInfo.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Ammeters +{ + public class AmmeterInfo + { + public int ID { get; set; } + public string Name { get; set; } + public int FocusID { get; set; } + public string Address { get; set; } + public string AreaCode { get; set; } + /// + /// 电表类别 (1单相、2三相三线、3三相四线), + /// 07协议: 开合闸指令(1A开闸断电,1C单相表合闸,1B多相表合闸) 645 2007 表 + /// 97协议://true(合闸);false(跳闸) 545 1997 没有单相多相 之分 "true" ? "9966" : "3355" + /// + public int TypeName { get; set; } + /// + /// 跳合闸状态字段: 0 合闸,1 跳闸 + /// 电表:TripState (0 合闸-通电, 1 断开、跳闸); + /// + public int TripState { get; set; } + /// + /// 规约 -电表default(30) 1:97协议,30:07协议 + /// + public int? Protocol { get; set; } + /// + /// 一个集中器下的[MeteringCode]必须唯一。 PN + /// + public int MeteringCode { get; set; } + /// + /// 电表通信地址 + /// + public string AmmerterAddress { get; set; } + /// + /// 波特率 default(2400) + /// + public int Baudrate { get; set; } + /// + /// MeteringPort 端口就几个可以枚举。 + /// + public int MeteringPort { get; set; } + /// + /// 电表密码 + /// + public string Password { get; set; } + /// + /// 采集时间间隔(分钟,如15) + /// + public int TimeDensity { get; set; } + /// + /// 该电表方案下采集项,如:0D_80 + /// + public string ItemCodes { get; set; } + /// + /// State表状态: + /// 0新装(未下发),1运行(档案下发成功时设置状态值1), 2暂停, 100销表(销表后是否重新启用) + /// 特定:State -1 已删除 + /// + public int State { get; set; } + /// + /// 是否自动采集(0:主动采集,1:自动采集) + /// + public int AutomaticReport { get; set; } + /// + /// 该电表方案下采集项编号 + /// + public string DataTypes { get; set; } + /// + /// 品牌型号 + /// + public string BrandType { get; set; } + /// + /// 采集器编号 + /// + public string GatherCode { get; set; } + /// + /// 是否特殊表 + /// + public int Special { get; set; } + /// + /// 费率类型,单、多 (SingleRate :单费率(单相表1),多费率(其他0) ,与TypeName字段无关) + /// SingleRate ? "单" : "复" + /// [SingleRate] --0 复费率 false , 1 单费率 true (与PayPlanID保持一致) + ///对应 TB_PayPlan.Type: 1复费率,2单费率 + /// + public bool SingleRate { get; set; } + public int ProjectID { get; set; } + /// + /// 是否异常集中器 0:正常,1异常 + /// + public int AbnormalState { get; set; } + public DateTime LastTime { get; set; } + } +} diff --git a/src/JiShe.CollectBus.Application/CollectBusAppService.cs b/src/JiShe.CollectBus.Application/CollectBusAppService.cs new file mode 100644 index 0000000..4a45327 --- /dev/null +++ b/src/JiShe.CollectBus.Application/CollectBusAppService.cs @@ -0,0 +1,18 @@ +using JiShe.CollectBus.FreeSql; +using JiShe.CollectBus.Localization; +using Microsoft.AspNetCore.Mvc; +using Volo.Abp.Application.Services; + +namespace JiShe.CollectBus; + +[ApiExplorerSettings(GroupName = CollectBusDomainSharedConsts.Business)] +public abstract class CollectBusAppService : ApplicationService +{ + public IFreeSqlProvider SqlProvider => LazyServiceProvider.LazyGetRequiredService(); + + protected CollectBusAppService() + { + LocalizationResource = typeof(CollectBusResource); + ObjectMapperContext = typeof(CollectBusApplicationModule); + } +} diff --git a/src/JiShe.CollectBus.Application/CollectBusApplicationAutoMapperProfile.cs b/src/JiShe.CollectBus.Application/CollectBusApplicationAutoMapperProfile.cs new file mode 100644 index 0000000..e5c2dc9 --- /dev/null +++ b/src/JiShe.CollectBus.Application/CollectBusApplicationAutoMapperProfile.cs @@ -0,0 +1,13 @@ +using AutoMapper; + +namespace JiShe.CollectBus; + +public class CollectBusApplicationAutoMapperProfile : Profile +{ + public CollectBusApplicationAutoMapperProfile() + { + /* You can configure your AutoMapper mapping configuration here. + * Alternatively, you can split your mapping configurations + * into multiple profile classes for a better organization. */ + } +} diff --git a/src/JiShe.CollectBus.Application/CollectBusApplicationModule.cs b/src/JiShe.CollectBus.Application/CollectBusApplicationModule.cs new file mode 100644 index 0000000..ab38baa --- /dev/null +++ b/src/JiShe.CollectBus.Application/CollectBusApplicationModule.cs @@ -0,0 +1,53 @@ +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.AutoMapper; +using Volo.Abp.Modularity; +using Volo.Abp.Application; +using Volo.Abp.BackgroundWorkers; +using System.Threading.Tasks; +using Volo.Abp; +using System.Reflection; +using JiShe.CollectBus.FreeSql; +using System; +using Volo.Abp.AspNetCore.Mvc.AntiForgery; + +namespace JiShe.CollectBus; + +[DependsOn( + typeof(CollectBusDomainModule), + typeof(CollectBusApplicationContractsModule), + typeof(AbpDddApplicationModule), + typeof(AbpAutoMapperModule), + typeof(AbpBackgroundWorkersModule), + typeof(CollectBusFreeSqlModule) + )] +public class CollectBusApplicationModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + context.Services.AddAutoMapperObjectMapper(); + Configure(options => + { + options.AddMaps(validate: true); + }); + + Configure(options => + { + options.TokenCookie.Expiration = TimeSpan.FromDays(365); + options.AutoValidateIgnoredHttpMethods.Add("POST"); + }); + } + + public override async Task OnApplicationInitializationAsync( + ApplicationInitializationContext context) + { + var assembly = Assembly.GetExecutingAssembly(); + var types = assembly.GetTypes().Where(t => typeof(ICollectWorker).IsAssignableFrom(t) && !t.IsInterface).ToList(); + + foreach (var type in types) + { + await context.AddBackgroundWorkerAsync(type); + } + } + +} diff --git a/src/JiShe.CollectBus.Application/Consumers/IssuedConsumer.cs b/src/JiShe.CollectBus.Application/Consumers/IssuedConsumer.cs new file mode 100644 index 0000000..710a268 --- /dev/null +++ b/src/JiShe.CollectBus.Application/Consumers/IssuedConsumer.cs @@ -0,0 +1,64 @@ +using System; +using System.Threading.Tasks; +using JiShe.CollectBus.Common.Enums; +using JiShe.CollectBus.MessageIssueds; +using JiShe.CollectBus.MessageReceiveds; +using MassTransit; +using Microsoft.Extensions.Logging; +using TouchSocket.Sockets; +using Volo.Abp.Domain.Repositories; + +namespace JiShe.CollectBus.Consumers +{ + public class IssuedConsumer: IConsumer + { + private readonly ILogger _logger; + private readonly ITcpService _tcpService; + private readonly IRepository _messageReceivedLoginEventRepository; + private readonly IRepository _messageReceivedHeartbeatEventRepository; + + /// + /// IssuedConsumer + /// + /// + /// + /// + /// + public IssuedConsumer(ILogger logger, + ITcpService tcpService, + IRepository messageReceivedLoginEventRepository, + IRepository messageReceivedHeartbeatEventRepository) + { + _logger = logger; + _tcpService = tcpService; + _messageReceivedLoginEventRepository = messageReceivedLoginEventRepository; + _messageReceivedHeartbeatEventRepository = messageReceivedHeartbeatEventRepository; + } + + + public async Task Consume(ConsumeContext context) + { + switch (context.Message.Type) + { + case IssuedEventType.Heartbeat: + _logger.LogInformation($"IssuedEvent:{context.Message.MessageId}"); + var heartbeatEntity = await _messageReceivedHeartbeatEventRepository.GetAsync(a => a.MessageId == context.Message.MessageId); + heartbeatEntity.AckTime = DateTime.Now; + heartbeatEntity.IsAck = true; + await _messageReceivedHeartbeatEventRepository.UpdateAsync(heartbeatEntity); + break; + case IssuedEventType.Login: + var loginEntity = await _messageReceivedLoginEventRepository.GetAsync(a => a.MessageId == context.Message.MessageId); + loginEntity.AckTime = DateTime.Now; + loginEntity.IsAck = true; + await _messageReceivedLoginEventRepository.UpdateAsync(loginEntity); + break; + case IssuedEventType.Data: + break; + default: + throw new ArgumentOutOfRangeException(); + } + await _tcpService.SendAsync(context.Message.ClientId, context.Message.Message); + } + } +} diff --git a/src/JiShe.CollectBus.Application/Consumers/IssuedFaultConsumer.cs b/src/JiShe.CollectBus.Application/Consumers/IssuedFaultConsumer.cs new file mode 100644 index 0000000..903beac --- /dev/null +++ b/src/JiShe.CollectBus.Application/Consumers/IssuedFaultConsumer.cs @@ -0,0 +1,15 @@ +using System; +using System.Threading.Tasks; +using JiShe.CollectBus.MessageIssueds; +using MassTransit; + +namespace JiShe.CollectBus.Consumers +{ + public class IssuedFaultConsumer : IConsumer> + { + public Task Consume(ConsumeContext> context) + { + throw new NotImplementedException(); + } + } +} diff --git a/src/JiShe.CollectBus.Application/Consumers/ReceivedConsumer.cs b/src/JiShe.CollectBus.Application/Consumers/ReceivedConsumer.cs new file mode 100644 index 0000000..3dc22e3 --- /dev/null +++ b/src/JiShe.CollectBus.Application/Consumers/ReceivedConsumer.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using JiShe.CollectBus.MessageReceiveds; +using JiShe.CollectBus.Protocol.Contracts.Interfaces; +using MassTransit; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Volo.Abp.Domain.Repositories; + +namespace JiShe.CollectBus.Consumers +{ + /// + /// Batch 一次最多 100 个,最多 10 个并发批次 + /// + public class ReceivedConsumer: IConsumer> + { + private readonly ILogger _logger; + private readonly IServiceProvider _serviceProvider; + private readonly IRepository _messageReceivedEventRepository; + + /// + /// MessageReceivedConsumer + /// + /// + /// + /// + public ReceivedConsumer(ILogger logger, + IServiceProvider serviceProvider, + IRepository messageReceivedEventRepository) + { + _logger = logger; + _serviceProvider = serviceProvider; + _messageReceivedEventRepository = messageReceivedEventRepository; + } + + + public async Task Consume(ConsumeContext> context) + { + const string protocolType = "Standard"; + var protocolPlugin = _serviceProvider.GetKeyedService(protocolType); + if (protocolPlugin == null) + { + _logger.LogError("协议不存在!"); + } + else + { + var list = new List(); + foreach (var contextItem in context.Message) + { + await protocolPlugin.AnalyzeAsync(contextItem.Message); + list.Add(contextItem.Message); + } + await _messageReceivedEventRepository.InsertManyAsync(list); + } + } + } +} diff --git a/src/JiShe.CollectBus.Application/Consumers/ReceivedFaultConsumer.cs b/src/JiShe.CollectBus.Application/Consumers/ReceivedFaultConsumer.cs new file mode 100644 index 0000000..e569769 --- /dev/null +++ b/src/JiShe.CollectBus.Application/Consumers/ReceivedFaultConsumer.cs @@ -0,0 +1,15 @@ +using System; +using System.Threading.Tasks; +using JiShe.CollectBus.MessageReceiveds; +using MassTransit; + +namespace JiShe.CollectBus.Consumers +{ + public class ReceivedFaultConsumer: IConsumer>> + { + public Task Consume(ConsumeContext>> context) + { + throw new NotImplementedException(); + } + } +} diff --git a/src/JiShe.CollectBus.Application/Consumers/ReceivedHeartbeatConsumer.cs b/src/JiShe.CollectBus.Application/Consumers/ReceivedHeartbeatConsumer.cs new file mode 100644 index 0000000..ce5233c --- /dev/null +++ b/src/JiShe.CollectBus.Application/Consumers/ReceivedHeartbeatConsumer.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using JiShe.CollectBus.Common.Models; +using JiShe.CollectBus.MessageReceiveds; +using JiShe.CollectBus.Protocol.Contracts.Interfaces; +using MassTransit; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace JiShe.CollectBus.Consumers +{ + public class ReceivedHeartbeatConsumer:IConsumer + { + private readonly ILogger _logger; + private readonly IServiceProvider _serviceProvider; + + /// + /// + /// + /// + /// + public ReceivedHeartbeatConsumer(IServiceProvider serviceProvider, ILogger logger) + { + this._serviceProvider = serviceProvider; + this._logger = logger; + } + + public async Task Consume(ConsumeContext context) + { + _logger.LogInformation("心跳消费队列开始处理"); + var protocolPlugin = _serviceProvider.GetKeyedService("Standard"); + if (protocolPlugin == null) + { + _logger.LogError("【心跳消费队列开始处理】协议不存在!"); + } + else + { + await protocolPlugin.HeartbeatAsync(context.Message); + _logger.LogInformation("心跳消费队列完成处理"); + } + } + } +} diff --git a/src/JiShe.CollectBus.Application/Consumers/ReceivedLoginConsumer.cs b/src/JiShe.CollectBus.Application/Consumers/ReceivedLoginConsumer.cs new file mode 100644 index 0000000..f17fe8e --- /dev/null +++ b/src/JiShe.CollectBus.Application/Consumers/ReceivedLoginConsumer.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using JiShe.CollectBus.Common.Models; +using JiShe.CollectBus.MessageReceiveds; +using JiShe.CollectBus.Protocol.Contracts.Interfaces; +using MassTransit; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace JiShe.CollectBus.Consumers +{ + public class ReceivedLoginConsumer : IConsumer + { + private readonly ILogger _logger; + private readonly IServiceProvider _serviceProvider; + + /// + /// + /// + /// + /// + public ReceivedLoginConsumer(ILogger logger, IServiceProvider serviceProvider) + { + _logger = logger; + _serviceProvider = serviceProvider; + } + + public async Task Consume(ConsumeContext context) + { + _logger.LogInformation("登录消费队列开始处理"); + var protocolPlugin = _serviceProvider.GetKeyedService("Standard"); + if (protocolPlugin == null) + { + _logger.LogError("【登录消费队列开始处理】协议不存在!"); + } + else + { + await protocolPlugin.LoginAsync(context.Message); + _logger.LogInformation("登录消费队列完成处理"); + } + await Task.CompletedTask; + } + } +} diff --git a/JiShe.CollectBus.Core/Exceptions/CloseException.cs b/src/JiShe.CollectBus.Application/Exceptions/CloseException.cs similarity index 54% rename from JiShe.CollectBus.Core/Exceptions/CloseException.cs rename to src/JiShe.CollectBus.Application/Exceptions/CloseException.cs index 00a9ec1..f813b25 100644 --- a/JiShe.CollectBus.Core/Exceptions/CloseException.cs +++ b/src/JiShe.CollectBus.Application/Exceptions/CloseException.cs @@ -1,4 +1,6 @@ -namespace JiShe.CollectBus.Network.Exceptions +using System; + +namespace JiShe.CollectBus.Exceptions { public class CloseException(string msg) : Exception(msg); } diff --git a/src/JiShe.CollectBus.Application/FodyWeavers.xml b/src/JiShe.CollectBus.Application/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/src/JiShe.CollectBus.Application/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/JiShe.CollectBus.Application/JiShe - Backup.CollectBus.Application.csproj b/src/JiShe.CollectBus.Application/JiShe - Backup.CollectBus.Application.csproj new file mode 100644 index 0000000..f535004 --- /dev/null +++ b/src/JiShe.CollectBus.Application/JiShe - Backup.CollectBus.Application.csproj @@ -0,0 +1,38 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/JiShe.CollectBus.Application/JiShe.CollectBus.Application.abppkg b/src/JiShe.CollectBus.Application/JiShe.CollectBus.Application.abppkg new file mode 100644 index 0000000..412567a --- /dev/null +++ b/src/JiShe.CollectBus.Application/JiShe.CollectBus.Application.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.application" +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Application/JiShe.CollectBus.Application.csproj b/src/JiShe.CollectBus.Application/JiShe.CollectBus.Application.csproj new file mode 100644 index 0000000..8bd63d9 --- /dev/null +++ b/src/JiShe.CollectBus.Application/JiShe.CollectBus.Application.csproj @@ -0,0 +1,34 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + True + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/JiShe.CollectBus.Core/Plugins/CloseMonitor.cs b/src/JiShe.CollectBus.Application/Plugins/CloseMonitor.cs similarity index 90% rename from JiShe.CollectBus.Core/Plugins/CloseMonitor.cs rename to src/JiShe.CollectBus.Application/Plugins/CloseMonitor.cs index bc65ea3..19b66d8 100644 --- a/JiShe.CollectBus.Core/Plugins/CloseMonitor.cs +++ b/src/JiShe.CollectBus.Application/Plugins/CloseMonitor.cs @@ -1,9 +1,11 @@ -using JiShe.CollectBus.Network.Exceptions; +using System; +using System.Threading.Tasks; +using JiShe.CollectBus.Exceptions; using Microsoft.Extensions.Logging; using TouchSocket.Core; using TouchSocket.Sockets; -namespace JiShe.CollectBus.Network.Plugins +namespace JiShe.CollectBus.Plugins { public partial class TcpCloseMonitor(ILogger logger) : PluginBase { diff --git a/JiShe.CollectBus.Core/Plugins/ServerMonitor.cs b/src/JiShe.CollectBus.Application/Plugins/ServerMonitor.cs similarity index 86% rename from JiShe.CollectBus.Core/Plugins/ServerMonitor.cs rename to src/JiShe.CollectBus.Application/Plugins/ServerMonitor.cs index 997cd31..39174db 100644 --- a/JiShe.CollectBus.Core/Plugins/ServerMonitor.cs +++ b/src/JiShe.CollectBus.Application/Plugins/ServerMonitor.cs @@ -1,8 +1,9 @@ -using Microsoft.Extensions.Logging; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using TouchSocket.Core; using TouchSocket.Sockets; -namespace JiShe.CollectBus.Network.Plugins +namespace JiShe.CollectBus.Plugins { public partial class ServerMonitor(ILogger logger) : PluginBase { @@ -21,7 +22,7 @@ namespace JiShe.CollectBus.Network.Plugins break; } case UdpSession session: - logger.LogInformation($"UDP {session.Monitor.IPHost}"); + //logger.LogInformation($"UDP {session.Monitor.IPHost}"); break; } diff --git a/src/JiShe.CollectBus.Application/Plugins/TcpMonitor.cs b/src/JiShe.CollectBus.Application/Plugins/TcpMonitor.cs new file mode 100644 index 0000000..b40273a --- /dev/null +++ b/src/JiShe.CollectBus.Application/Plugins/TcpMonitor.cs @@ -0,0 +1,177 @@ +using System; +using System.Threading.Tasks; +using DotNetCore.CAP; +using JiShe.CollectBus.Ammeters; +using JiShe.CollectBus.Common.Enums; +using JiShe.CollectBus.Common.Extensions; +using JiShe.CollectBus.Devices; +using JiShe.CollectBus.Enums; +using JiShe.CollectBus.Interceptors; +using JiShe.CollectBus.MessageReceiveds; +using JiShe.CollectBus.Protocol.Contracts; +using MassTransit; +using Microsoft.Extensions.Logging; +using TouchSocket.Core; +using TouchSocket.Sockets; +using Volo.Abp.Caching; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Domain.Entities; +using Volo.Abp.Domain.Repositories; + +namespace JiShe.CollectBus.Plugins +{ + public partial class TcpMonitor : PluginBase, ITransientDependency + { + private readonly ICapPublisher _capBus; + private readonly ILogger _logger; + private readonly IRepository _deviceRepository; + private readonly IDistributedCache _ammeterInfoCache; + + /// + /// + /// + /// + /// + /// + /// + public TcpMonitor(ICapPublisher capBus, + ILogger logger, + IRepository deviceRepository, + IDistributedCache ammeterInfoCache) + { + _capBus = capBus; + _logger = logger; + _deviceRepository = deviceRepository; + _ammeterInfoCache = ammeterInfoCache; + } + + [GeneratorPlugin(typeof(ITcpReceivedPlugin))] + public async Task OnTcpReceived(ITcpSessionClient client, ReceivedDataEventArgs e) + { + var messageHexString = Convert.ToHexString(e.ByteBlock.Span); + var hexStringList = messageHexString.StringToPairs(); + var aFn = (int?)hexStringList.GetAnalyzeValue(CommandChunkEnum.AFN); + var fn = (int?)hexStringList.GetAnalyzeValue(CommandChunkEnum.FN); + var aTuple = (Tuple)hexStringList.GetAnalyzeValue(CommandChunkEnum.A); + if (aFn.HasValue && fn.HasValue) + { + if ((AFN)aFn == AFN.链路接口检测) + { + switch (fn) + { + case 1: + await OnTcpLoginReceived(client, messageHexString, aTuple.Item1); + break; + case 3: + await OnTcpHeartbeatReceived(client, messageHexString, aTuple.Item1); + break; + default: + _logger.LogError($"指令初步解析失败,指令内容:{messageHexString}"); + break; + } + } + else + { + await OnTcpNormalReceived(client, messageHexString, aTuple.Item1); + } + } + else + { + _logger.LogError($"指令初步解析失败,指令内容:{messageHexString}"); + } + + await e.InvokeNext(); + } + + [GeneratorPlugin(typeof(ITcpConnectingPlugin))] + public async Task OnTcpConnecting(ITcpSessionClient client, ConnectingEventArgs e) + { + _logger.LogInformation($"[TCP] ID:{client.Id} IP:{client.GetIPPort()}正在连接中..."); + await e.InvokeNext(); + } + + [GeneratorPlugin(typeof(ITcpConnectedPlugin))] + public async Task OnTcpConnected(ITcpSessionClient client, ConnectedEventArgs e) + { + _logger.LogInformation($"[TCP] ID:{client.Id} IP:{client.GetIPPort()}已连接"); + await e.InvokeNext(); + } + + [GeneratorPlugin(typeof(ITcpClosedPlugin))] + public async Task OnTcpClosed(ITcpSessionClient client, ClosedEventArgs e) + { + var entity = await _deviceRepository.FindAsync(a=>a.ClientId == client.Id); + if (entity != null) + { + entity.UpdateByOnClosed(); + await _deviceRepository.UpdateAsync(entity); + } + else + { + _logger.LogWarning($"[TCP] ID:{client.Id} IP:{client.GetIPPort()}已关闭连接,但采集程序检索失败"); + } + + await e.InvokeNext(); + } + private async Task OnTcpLoginReceived(ITcpSessionClient client, string messageHexString, string deviceNo) + { + var messageReceivedLoginEvent = new MessageReceivedLogin + { + ClientId = client.Id, + ClientIp = client.IP, + ClientPort = client.Port, + MessageHexString = messageHexString, + DeviceNo = deviceNo, + MessageId = NewId.NextGuid().ToString() + }; + await _capBus.PublishAsync(ProtocolConst.SubscriberReceivedLoginEventName, messageReceivedLoginEvent); + var entity = await _deviceRepository.FindAsync(a => a.Number == deviceNo); + if (entity == null) + { + await _deviceRepository.InsertAsync(new Device(deviceNo, client.Id, DateTime.Now, DateTime.Now, DeviceStatus.Online)); + } + else + { + entity.UpdateByLoginAndHeartbeat(client.Id); + await _deviceRepository.UpdateAsync(entity); + } + } + + private async Task OnTcpHeartbeatReceived(ITcpSessionClient client, string messageHexString, string deviceNo) + { + var messageReceivedHeartbeatEvent = new MessageReceivedHeartbeat + { + ClientId = client.Id, + ClientIp = client.IP, + ClientPort = client.Port, + MessageHexString = messageHexString, + DeviceNo = deviceNo, + MessageId = NewId.NextGuid().ToString() + }; + await _capBus.PublishAsync(ProtocolConst.SubscriberReceivedHeartbeatEventName, messageReceivedHeartbeatEvent); + var entity = await _deviceRepository.FindAsync(a => a.Number == deviceNo); + if (entity == null) + { + await _deviceRepository.InsertAsync(new Device(deviceNo, client.Id, DateTime.Now, DateTime.Now, DeviceStatus.Online)); + } + else + { + entity.UpdateByLoginAndHeartbeat(client.Id); + await _deviceRepository.UpdateAsync(entity); + } + } + + private async Task OnTcpNormalReceived(ITcpSessionClient client, string messageHexString, string deviceNo) + { + await _capBus.PublishAsync(ProtocolConst.SubscriberReceivedEventName, new MessageReceived + { + ClientId = client.Id, + ClientIp = client.IP, + ClientPort = client.Port, + MessageHexString = messageHexString, + DeviceNo = deviceNo, + MessageId = NewId.NextGuid().ToString() + }); + } + } +} diff --git a/JiShe.CollectBus.Core/Plugins/UdpMonitor.cs b/src/JiShe.CollectBus.Application/Plugins/UdpMonitor.cs similarity index 89% rename from JiShe.CollectBus.Core/Plugins/UdpMonitor.cs rename to src/JiShe.CollectBus.Application/Plugins/UdpMonitor.cs index 976ce7a..f975a03 100644 --- a/JiShe.CollectBus.Core/Plugins/UdpMonitor.cs +++ b/src/JiShe.CollectBus.Application/Plugins/UdpMonitor.cs @@ -1,8 +1,9 @@ using System.Text; +using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Sockets; -namespace JiShe.CollectBus.Network.Plugins +namespace JiShe.CollectBus.Plugins { public partial class UdpMonitor : PluginBase { diff --git a/src/JiShe.CollectBus.Application/Samples/SampleAppService.cs b/src/JiShe.CollectBus.Application/Samples/SampleAppService.cs new file mode 100644 index 0000000..5c0dae8 --- /dev/null +++ b/src/JiShe.CollectBus.Application/Samples/SampleAppService.cs @@ -0,0 +1,39 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using JiShe.CollectBus.FreeSql; +using JiShe.CollectBus.PrepayModel; +using Microsoft.AspNetCore.Authorization; + +namespace JiShe.CollectBus.Samples; + +public class SampleAppService : CollectBusAppService, ISampleAppService +{ + public Task GetAsync() + { + return Task.FromResult( + new SampleDto + { + Value = 42 + } + ); + } + + [Authorize] + public Task GetAuthorizedAsync() + { + return Task.FromResult( + new SampleDto + { + Value = 42 + } + ); + } + + [AllowAnonymous] + public async Task> Test() + { + + var ammeterList = await SqlProvider.Instance.Change(DbEnum.PrepayDB).Select().Where(d => d.TB_CustomerID == 5).Take(10).ToListAsync(); + return ammeterList; + } +} diff --git a/src/JiShe.CollectBus.Application/Subscribers/SubscriberAppService.cs b/src/JiShe.CollectBus.Application/Subscribers/SubscriberAppService.cs new file mode 100644 index 0000000..cea6c1b --- /dev/null +++ b/src/JiShe.CollectBus.Application/Subscribers/SubscriberAppService.cs @@ -0,0 +1,133 @@ +using System; +using System.Threading.Tasks; +using DotNetCore.CAP; +using JiShe.CollectBus.Common.Enums; +using JiShe.CollectBus.Common.Models; +using JiShe.CollectBus.Devices; +using JiShe.CollectBus.MessageReceiveds; +using JiShe.CollectBus.Protocol.Contracts; +using JiShe.CollectBus.Protocol.Contracts.Interfaces; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using TouchSocket.Sockets; +using Volo.Abp.Domain.Repositories; + +namespace JiShe.CollectBus.Subscribers +{ + public class SubscriberAppService : CollectBusAppService, ISubscriberAppService,ICapSubscribe + { + private readonly ILogger _logger; + private readonly ITcpService _tcpService; + private readonly IServiceProvider _serviceProvider; + private readonly IRepository _messageReceivedLoginEventRepository; + private readonly IRepository _messageReceivedHeartbeatEventRepository; + private readonly IRepository _messageReceivedEventRepository; + private readonly IRepository _deviceRepository; + + /// + /// Initializes a new instance of the class. + /// + /// The logger. + /// The TCP service. + /// The service provider. + /// The message received login event repository. + /// The message received heartbeat event repository. + /// The message received event repository. + /// The device repository. + public SubscriberAppService(ILogger logger, + ITcpService tcpService, IServiceProvider serviceProvider, + IRepository messageReceivedLoginEventRepository, + IRepository messageReceivedHeartbeatEventRepository, + IRepository messageReceivedEventRepository, + IRepository deviceRepository) + { + _logger = logger; + _tcpService = tcpService; + _serviceProvider = serviceProvider; + _messageReceivedLoginEventRepository = messageReceivedLoginEventRepository; + _messageReceivedHeartbeatEventRepository = messageReceivedHeartbeatEventRepository; + _messageReceivedEventRepository = messageReceivedEventRepository; + _deviceRepository = deviceRepository; + } + + [CapSubscribe(ProtocolConst.SubscriberIssuedEventName)] + public async Task IssuedEvent(IssuedEventMessage issuedEventMessage) + { + switch (issuedEventMessage.Type) + { + case IssuedEventType.Heartbeat: + _logger.LogInformation($"IssuedEvent:{issuedEventMessage.MessageId}"); + var heartbeatEntity = await _messageReceivedHeartbeatEventRepository.GetAsync(a => a.MessageId == issuedEventMessage.MessageId); + heartbeatEntity.AckTime = Clock.Now; + heartbeatEntity.IsAck = true; + await _messageReceivedHeartbeatEventRepository.UpdateAsync(heartbeatEntity); + break; + case IssuedEventType.Login: + var loginEntity = await _messageReceivedLoginEventRepository.GetAsync(a => a.MessageId == issuedEventMessage.MessageId); + loginEntity.AckTime = Clock.Now; + loginEntity.IsAck = true; + await _messageReceivedLoginEventRepository.UpdateAsync(loginEntity); + break; + case IssuedEventType.Data: + break; + default: + throw new ArgumentOutOfRangeException(); + } + var device = await _deviceRepository.FindAsync(a => a.Number == issuedEventMessage.DeviceNo); + if (device!=null) + { + await _tcpService.SendAsync(device.ClientId, issuedEventMessage.Message); + } + } + + [CapSubscribe(ProtocolConst.SubscriberReceivedEventName)] + public async Task ReceivedEvent(MessageReceived receivedMessage) + { + var protocolPlugin = _serviceProvider.GetKeyedService("StandardProtocolPlugin"); + if (protocolPlugin == null) + { + _logger.LogError("协议不存在!"); + } + else + { + await protocolPlugin.AnalyzeAsync(receivedMessage); + await _messageReceivedEventRepository.InsertAsync(receivedMessage); + } + } + + [CapSubscribe(ProtocolConst.SubscriberReceivedHeartbeatEventName)] + public async Task ReceivedHeartbeatEvent(MessageReceivedHeartbeat receivedHeartbeatMessage) + { + _logger.LogInformation("心跳消费队列开始处理"); + var protocolPlugin = _serviceProvider.GetKeyedService("StandardProtocolPlugin"); + if (protocolPlugin == null) + { + _logger.LogError("【心跳消费队列开始处理】协议不存在!"); + } + else + { + await protocolPlugin.HeartbeatAsync(receivedHeartbeatMessage); + await _messageReceivedHeartbeatEventRepository.InsertAsync(receivedHeartbeatMessage); + + _logger.LogInformation($"心跳消费队列完成处理:{receivedHeartbeatMessage.MessageId}"); + } + } + + [CapSubscribe(ProtocolConst.SubscriberReceivedLoginEventName)] + public async Task ReceivedLoginEvent(MessageReceivedLogin receivedLoginMessage) + { + _logger.LogInformation("登录消费队列开始处理"); + var protocolPlugin = _serviceProvider.GetKeyedService("StandardProtocolPlugin"); + if (protocolPlugin == null) + { + _logger.LogError("【登录消费队列开始处理】协议不存在!"); + } + else + { + await protocolPlugin.LoginAsync(receivedLoginMessage); + await _messageReceivedLoginEventRepository.InsertAsync(receivedLoginMessage); + _logger.LogInformation("登录消费队列完成处理"); + } + } + } +} diff --git a/src/JiShe.CollectBus.Application/Workers/EpiCollectWorker.cs b/src/JiShe.CollectBus.Application/Workers/EpiCollectWorker.cs new file mode 100644 index 0000000..bbbee85 --- /dev/null +++ b/src/JiShe.CollectBus.Application/Workers/EpiCollectWorker.cs @@ -0,0 +1,29 @@ +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Volo.Abp.BackgroundWorkers.Hangfire; +using Volo.Abp.DependencyInjection; + +namespace JiShe.CollectBus.Workers +{ + public class EpiCollectWorker : HangfireBackgroundWorkerBase, ITransientDependency,ICollectWorker + { + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public EpiCollectWorker(ILogger logger) + { + _logger = logger; + } + + + public override Task DoWorkAsync(CancellationToken cancellationToken = new CancellationToken()) + { + _logger.LogInformation("Executed MyLogWorker..!"); + return Task.CompletedTask; + } + } +} diff --git a/src/JiShe.CollectBus.Application/cmd3761Matching.txt b/src/JiShe.CollectBus.Application/cmd3761Matching.txt new file mode 100644 index 0000000..2c1afb5 --- /dev/null +++ b/src/JiShe.CollectBus.Application/cmd3761Matching.txt @@ -0,0 +1,272 @@ +[ + { + "Id": 0, + "AFN": 12, + "FnList": [ + { + "Id": 0, + "Fn": 49, + "Text": "相位角", + "UpList": [ + { + "Id": 1, + "Name": "UabUa相位角", + "DataType": "A05", + "DataIndex": 0, + "DataCount": 2, + "Sort": 1 + }, + { + "Id": 2, + "Name": "Ub相位角", + "DataType": "A05", + "DataIndex": 2, + "DataCount": 2, + "Sort": 2 + }, + { + "Id": 3, + "Name": "UcbUc相位角", + "DataType": "A05", + "DataIndex": 4, + "DataCount": 2, + "Sort": 3 + }, + { + "Id": 4, + "Name": "Ia相位角", + "DataType": "A05", + "DataIndex": 6, + "DataCount": 2, + "Sort": 4 + }, + { + "Id": 5, + "Name": "Ib相位角", + "DataType": "A05", + "DataIndex": 8, + "DataCount": 2, + "Sort": 5 + }, + { + "Id": 6, + "Name": "Ic相位角", + "DataType": "A05", + "DataIndex": 10, + "DataCount": 2, + "Sort": 6 + } + ] + }, + { + "Id": 0, + "Fn": 129, + "Text": "当前正向有功电能示值", + "UpList": [ + { + "Id": 1, + "Name": "终端抄表时间", + "DataType": "A15", + "DataIndex": 0, + "DataCount": 5, + "Sort": 1 + }, + { + "Id": 2, + "Name": "费率数M", + "DataType": "BIN", + "DataIndex": 5, + "DataCount": 1, + "Sort": 2 + }, + { + "Id": 3, + "Name": "正向有功总电能示值", + "DataType": "A14", + "DataIndex": 6, + "DataCount": 5, + "Sort": 3, + "Tb3761UpChildlList": [ + { + "Id": 0, + "Name": "费率{0}正向有功总电能示值", + "DataType": "A14", + "DataIndex": 0, + "DataCount": 5, + "Sort": 0 + } + ] + } + ] + }, + { + "Id": 0, + "Fn": 149, + "Text": "当月正向有功最大需量", + "UpList": [ + { + "Id": 1, + "Name": "终端抄表时间", + "DataType": "A15", + "DataIndex": 0, + "DataCount": 5, + "Sort": 1 + }, + { + "Id": 2, + "Name": "费率数M", + "DataType": "BIN", + "DataIndex": 5, + "DataCount": 1, + "Sort": 2 + }, + { + "Id": 3, + "Name": "正向有功总最大需量", + "DataType": "A23", + "DataIndex": 6, + "DataCount": 3, + "Sort": 3, + "Tb3761UpChildlList": [ + { + "Id": 0, + "Name": "正向有功费率{0}最大需量", + "DataType": "A23", + "DataIndex": 0, + "DataCount": 3, + "Sort": 0 + } + ] + }, + { + "Id": 4, + "Name": "正向有功总最大需量发生时间", + "DataType": "A17", + "DataIndex": 0, + "DataCount": 4, + "Sort": 3, + "Tb3761UpChildlList": [ + { + "Id": 0, + "Name": "正向有功费率{0}最大需量发生时间", + "DataType": "A23", + "DataIndex": 0, + "DataCount": 4, + "Sort": 0 + } + ] + } + ] + } + ] + }, + { + "Id": 0, + "AFN": 13, + "FnList": [ + { + "Id": 0, + "Fn": 3, + "Text": "日冻结正向有无功最大需量及发生时间", + "UpList": [ + { + "Id": 1, + "Name": "日冻结类数据时标Td_d", + "DataType": "ATd_d", + "DataIndex": 0, + "DataCount": 3, + "Sort": 1 + }, + { + "Id": 2, + "Name": "终端抄表时间", + "DataType": "A15", + "DataIndex": 3, + "DataCount": 5, + "Sort": 2 + }, + { + "Id": 3, + "Name": "费率数M", + "DataType": "BIN", + "DataIndex": 8, + "DataCount": 1, + "Sort": 3 + }, + { + "Id": 4, + "Name": "正向有功总最大需量", + "DataType": "A23", + "DataIndex": 9, + "DataCount": 3, + "Sort": 4, + "Tb3761UpChildlList": [ + { + "Id": 0, + "Name": "费率{0}正向有功最大需量", + "DataType": "A23", + "DataIndex": 0, + "DataCount": 3, + "Sort": 0 + } + ] + }, + { + "Id": 5, + "Name": "正向有功总最大需量发生时间", + "DataType": "A17", + "DataIndex": 0, + "DataCount": 4, + "Sort": 5, + "Tb3761UpChildlList": [ + { + "Id": 0, + "Name": "费率{0}正向有功最大需量发生时间", + "DataType": "A23", + "DataIndex": 0, + "DataCount": 4, + "Sort": 0 + } + ] + }, + { + "Id": 6, + "Name": "正向无功总最大需量", + "DataType": "A23", + "DataIndex": 9, + "DataCount": 3, + "Sort": 6, + "Tb3761UpChildlList": [ + { + "Id": 0, + "Name": "费率{0}正向无功最大需量", + "DataType": "A23", + "DataIndex": 0, + "DataCount": 3, + "Sort": 0 + } + ] + }, + { + "Id": 7, + "Name": "正向无功总最大需量发生时间", + "DataType": "A17", + "DataIndex": 0, + "DataCount": 4, + "Sort": 7, + "Tb3761UpChildlList": [ + { + "Id": 0, + "Name": "费率{0}正向无功最大需量发生时间", + "DataType": "A23", + "DataIndex": 0, + "DataCount": 4, + "Sort": 0 + } + ] + } + ] + } + ] + } +] \ No newline at end of file diff --git a/src/JiShe.CollectBus.Application/cmd3761TdcMatching.txt b/src/JiShe.CollectBus.Application/cmd3761TdcMatching.txt new file mode 100644 index 0000000..3557ca2 --- /dev/null +++ b/src/JiShe.CollectBus.Application/cmd3761TdcMatching.txt @@ -0,0 +1,49 @@ +[ + { + "Id": 0, + "AFN": 13, + "FnList": [ + { + "Id": 0, + "Fn": 81, + "Text": "总有功功率", + "UpList": [ + { + "Id": 1, + "Name": "起始时间", + "DataType": "A15", + "DataIndex": 0, + "DataCount": 5, + "Sort": 1 + }, + { + "Id": 2, + "Name": "数据冻结密度m", + "DataType": "BIN", + "DataIndex": 5, + "DataCount": 1, + "Sort": 2 + }, + { + "Id": 3, + "Name": "数据点数", + "DataType": "BIN", + "DataIndex": 6, + "DataCount": 1, + "Sort": 3, + "Tb3761UpChildlList": [ + { + "Id": 0, + "Name": "有功功率{0}", + "DataType": "A09", + "DataIndex": 0, + "DataCount": 3, + "Sort": 0 + } + ] + } + ] + } + ] + } +] \ No newline at end of file diff --git a/JiShe.CollectBus.Common/Consts/RegexConst.cs b/src/JiShe.CollectBus.Common/Consts/RegexConst.cs similarity index 100% rename from JiShe.CollectBus.Common/Consts/RegexConst.cs rename to src/JiShe.CollectBus.Common/Consts/RegexConst.cs diff --git a/src/JiShe.CollectBus.Common/Enums/188Enums.cs b/src/JiShe.CollectBus.Common/Enums/188Enums.cs new file mode 100644 index 0000000..83f45a6 --- /dev/null +++ b/src/JiShe.CollectBus.Common/Enums/188Enums.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Common.Enums +{ + public enum WaterMeterReadEnum + { + Type = 1, + Address = 2, + ControlCode = 9, + Len = 10, + DI = 11, + SER = 13, + [Description("累计流量")] + AccumulativeWaterflow = 14, + [Description("当月流量")] + MonthlyWaterflow = 19, + [Description("实时时间")] + RealTimeTime = 24, + } + + public enum CommandChunkEnum188 + { + + A = 2, + C = 9, + L = 10, + DI = 11, + Data = 14 + } +} diff --git a/src/JiShe.CollectBus.Common/Enums/376Enums.cs b/src/JiShe.CollectBus.Common/Enums/376Enums.cs new file mode 100644 index 0000000..4120a93 --- /dev/null +++ b/src/JiShe.CollectBus.Common/Enums/376Enums.cs @@ -0,0 +1,318 @@ +using System.ComponentModel; +using System.Reflection.Metadata; + +namespace JiShe.CollectBus.Common.Enums +{ + /// + /// 规约标识 高位在前 D1+D0 + /// + public enum ProtocolIdentification + { + 禁用 = 00, + 电力负荷管理系统数据传输 = 01, + 本规约使用 = 10, + 保留 = 11 + } + + /// + /// 传输方向位 + /// + public enum DIR + { + 主站下行报文 = 0, + 终端上行报文 = 1 + } + + /// + /// 启动标识位 + /// + public enum PRM + { + 从动站报文 = 0, + 启动站报文 = 1, + } + + /// + /// 帧计数有效位 + /// + public enum FCV + { + FCB位无效 = 0, + FCB位有效 = 1 + } + + /// + /// 控制域(PRM=1)启动站功能码 + /// + public enum CMasterStationFunCode + { + 复位命令 = 1, + 用户数据 = 4, + 链路测试 = 9, + 请求1级数据 = 10, + 请求2级数据 = 11 + } + + /// + /// 控制域(PRM=0)从动站功能码 + /// + public enum CFromStationFunCode + { + 确认 = 0, + 用户数据 = 8, + 无所召唤的数据 = 9, + 链路数据 = 11 + } + + /// + /// 应用层功能码 + /// + public enum AFN + { + 确认或否认 = 00, + 复位 = 01, + 链路接口检测 = 02, + 中继站命令 = 03, + 设置参数 = 04, + 控制命令 = 05, + 身份认证及密钥协商 = 06, + 备用 = 07, + 请求被级联终端主动上报 = 08, + 请求终端配置 = 09, + 查询参数 = 10, + 请求任务数据 = 11, + [Description("请求一类数据")] + 请求实时数据 = 12, + [Description("请求二类数据")] + 请求历史数据 = 13, + 请求事件数据 = 14, + 文件传输 = 15, + 数据转发 = 16, + } + + /// + /// 帧时间标签有效位 + /// + public enum TpV + { + 附加信息域中无时间标签 = 0, + 附加信息域中带时间标签 = 1 + } + + /// + /// 首帧末帧标志 + /// + public enum FIRFIN + { + 中间帧 = 00, + 结束帧 = 01, + 第一帧 = 10, + 单帧 = 11 + } + + /// + /// 请求确认标志位 + /// + public enum CON + { + 不需要对该帧进行确认 = 0, + 需要对该帧进行确认 = 1 + } + + /// + /// 通信协议类型 数值0-255 + /// + public enum CommunicationProtocolType + { + DLT6451997 = 1, + 交流采样装置 = 2, + DLT6452007 = 30, + 串行接口连接窄带低压载波通讯 = 31 + } + + public enum BaudRate + { + Br300 = 0, + Br600 = 1, + Br1200 = 2, + Br2400 = 3, + Br4800 = 4, + Br7200 = 5, + Br9600 = 6, + Br19200 = 7 + } + public enum StopBit + { + Stop1 = 0, + Stop2 + } + public enum Parity + { + None = 0, + /// + /// 偶校验 + /// + Even, + /// + /// 奇校验 + /// + Odd + } + public enum DataBit + { + D5 = 0, + D6, + D7, + D8 + } + + public enum IssuedEventType + { + Heartbeat, + Login, + Data + } + + /// + /// 查询参数数据项 + /// + public enum QueryParameterDataItems + { + 尖峰平谷时段=94, + 电网频率 =97, + + } + + /// + /// 一类数据项 + /// + public enum ATypeOfDataItems + { + 相位角=49, + 当前正向有功电能示值=129, + 上月最大需量=149, + } + + /// + /// 二类数据项 + /// + public enum IIdataTypeItems + { + [Description("Td_d")] + 日最大需量=3, + [Description("Td_c")] + 总有功功率 =81, + [Description("Td_c")] + A相有功功率 =82, + [Description("Td_c")] + B相有功功率 = 83, + [Description("Td_c")] + C相有功功率 = 84, + [Description("Td_c")] + 总无功功率 =85, + [Description("Td_c")] + A相无功功率 =86, + [Description("Td_c")] + B相无功功率 =87, + [Description("Td_c")] + C相无功功率 =88, + [Description("Td_c")] + A相电压 =89, + [Description("Td_c")] + B相电压 = 90, + [Description("Td_c")] + C相电压 = 91, + [Description("Td_c")] + A相电流 =92, + [Description("Td_c")] + B相电流 = 93, + [Description("Td_c")] + C相电流 = 94, + [Description("Td_c")] + 正向有功电量 =97, + [Description("Td_c")] + 正向无功电量 =98, + [Description("Td_c")] + 反向有功电量 =99, + [Description("Td_c")] + 反向无功电量 =100, + [Description("Td_c")] + 正向有功电量示值 =101, + [Description("Td_c")] + 正向无功电量示值 =102, + [Description("Td_c")] + 反向有功电量示值 =103, + [Description("Td_c")] + 反向无功电量示值 =104, + [Description("Td_c")] + 总功率因数 =105, + [Description("Td_c")] + A相功率因数 =106, + [Description("Td_c")] + B相功率因数 =107, + [Description("Td_c")] + C相功率因数 =108, + [Description("Td_c")] + 一象限无功 =145, + [Description("Td_c")] + 四象限无功 =146, + [Description("Td_c")] + 二象限无功 =147, + [Description("Td_c")] + 三象限无功 =148, + [Description("Td_c")] + 日冻结电量示值 = 161, + [Description("Td_c")] + 日冻结反向电量示值 =163, + [Description("Td_m")] + 月冻结电量示值 =177, + [Description("Td_m")] + 月冻结反向电量示值 =179, + } + + /// + /// 冻结密度 + /// + public enum FreezeDensity + { + [Description("不冻结")] + No = 0, + //冻结时刻 + [Description("15分,30分,45分,0分")] + Min15=1, + [Description("30分,0分")] + Min30 =2, + [Description("0分")] + Min60 =3, + [Description("5分,10分,15,...,0")] + Min5 =254, + [Description("1分,2分,3,...,0")] + Min1 =255, + } + + /// + /// 相位角 + /// + public enum ATypeOfDataItems49 + { + UabUa=0, + Ub=2, + UcbUc=4, + Ia=6, + Ib=8, + Ic=10 + } + + /// + /// 数据时标 + /// + public enum TdType + { + [Description("曲线类")] + Td_c, + [Description("日冻结类")] + Td_d, + [Description("月冻结类")] + Td_m, + } +} diff --git a/JiShe.CollectBus.Common/Enums/645Enums.cs b/src/JiShe.CollectBus.Common/Enums/645Enums.cs similarity index 100% rename from JiShe.CollectBus.Common/Enums/645Enums.cs rename to src/JiShe.CollectBus.Common/Enums/645Enums.cs diff --git a/JiShe.CollectBus.Common/Enums/CommandChunkEnum.cs b/src/JiShe.CollectBus.Common/Enums/CommandChunkEnum.cs similarity index 100% rename from JiShe.CollectBus.Common/Enums/CommandChunkEnum.cs rename to src/JiShe.CollectBus.Common/Enums/CommandChunkEnum.cs diff --git a/JiShe.CollectBus.Common/Enums/F25DataItemEnum.cs b/src/JiShe.CollectBus.Common/Enums/F25DataItemEnum.cs similarity index 100% rename from JiShe.CollectBus.Common/Enums/F25DataItemEnum.cs rename to src/JiShe.CollectBus.Common/Enums/F25DataItemEnum.cs diff --git a/JiShe.CollectBus.Common/Enums/MaskTypeEnum.cs b/src/JiShe.CollectBus.Common/Enums/MaskTypeEnum.cs similarity index 100% rename from JiShe.CollectBus.Common/Enums/MaskTypeEnum.cs rename to src/JiShe.CollectBus.Common/Enums/MaskTypeEnum.cs diff --git a/JiShe.CollectBus.Common/Enums/SortEnum.cs b/src/JiShe.CollectBus.Common/Enums/SortEnum.cs similarity index 100% rename from JiShe.CollectBus.Common/Enums/SortEnum.cs rename to src/JiShe.CollectBus.Common/Enums/SortEnum.cs diff --git a/JiShe.CollectBus.Common/Enums/TransparentForwardingFlagEnum.cs b/src/JiShe.CollectBus.Common/Enums/TransparentForwardingFlagEnum.cs similarity index 100% rename from JiShe.CollectBus.Common/Enums/TransparentForwardingFlagEnum.cs rename to src/JiShe.CollectBus.Common/Enums/TransparentForwardingFlagEnum.cs diff --git a/JiShe.CollectBus.Common/Extensions/CollectionExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/CollectionExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/CollectionExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/CollectionExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/ComparableExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/ComparableExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/ComparableExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/ComparableExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/DataTableExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/DataTableExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/DataTableExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/DataTableExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/DateTimeExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/DateTimeExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/DateTimeExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/DateTimeExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/DayOfWeekExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/DayOfWeekExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/DayOfWeekExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/DayOfWeekExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/DecimalOrIntExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/DecimalOrIntExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/DecimalOrIntExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/DecimalOrIntExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/DictionaryExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/DictionaryExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/DictionaryExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/DictionaryExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/EnumerableExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/EnumerableExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/EnumerableExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/EnumerableExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/EventHandlerExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/EventHandlerExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/EventHandlerExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/EventHandlerExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/ExceptionExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/ExceptionExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/ExceptionExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/ExceptionExtensions.cs diff --git a/src/JiShe.CollectBus.Common/Extensions/HexStringExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/HexStringExtensions.cs new file mode 100644 index 0000000..4af9d45 --- /dev/null +++ b/src/JiShe.CollectBus.Common/Extensions/HexStringExtensions.cs @@ -0,0 +1,1640 @@ +using System.ComponentModel.DataAnnotations; +using JiShe.CollectBus.Common.Enums; +using JiShe.CollectBus.Common.Models; +using System.Reflection; + +namespace JiShe.CollectBus.Common.Extensions +{ + public static class HexStringExtensions + { + //起始字符 + private const string startStr = "68"; + //结束字符 + private const string endStr = "16"; + //头部字节长度 + private const int hearderLen = 6; + //消息认证码字段长度 + private const int pWLen = 16; + + private const int tPLen = 6; + + private const int FixedLength = 18; + + static object locker = new object(); + static List MSA = new List(); + static Dictionary> usingMSA = new Dictionary>(); + + static HexStringExtensions() + { + for (int i = 1; i <= 127; i++) + { + MSA.Add(i); + } + } + /// + /// Gets the msa. + /// + /// 集中器地址 + /// + public static int GetMSA(string mark) + { + lock (locker) + { + if (!usingMSA.Keys.Contains(mark)) + usingMSA.Add(mark, new List()); + + int msa = MSA.Except(usingMSA[mark]).FirstOrDefault(); + //if (msa == 1) msa = 2;//msa=1为自定义指令保留 + usingMSA[mark].Add(msa); + + if (msa == 127) + usingMSA[mark].RemoveAll(m => true); + + return msa; + } + } + + public static object GetAnalyzeValue(this List hexStringList, CommandChunkEnum chunk) + { + if (hexStringList.Count < hearderLen || hexStringList[0] != startStr || hexStringList[5] != startStr || hexStringList.Count < FixedLength) + { + return null; + } + + switch (chunk) + { + case CommandChunkEnum.AFN: + var aFn = hexStringList[(int)CommandChunkEnum.AFN].HexToDec();//1字节 + return aFn; + case CommandChunkEnum.FN: + //(DT2*8)+DT1=fn + var dt1Bin = hexStringList[(int)CommandChunkEnum.FN - 1].HexToBin(); + var dt1 = dt1Bin != "0" ? dt1Bin.Length : 0; + var dt2 = hexStringList[(int)CommandChunkEnum.FN].HexToDec(); + var fn = dt2 * 8 + dt1; + return fn; + case CommandChunkEnum.A: + var aHexList = hexStringList.Skip((int)CommandChunkEnum.A).Take(5).ToList(); + var a1 = aHexList[1] + aHexList[0]; + var a2 = aHexList[3] + aHexList[2]; + var a2Dec = a2.HexToDec(); + var a3 = aHexList[4]; + var a = $"{a1}{a2Dec.ToString().PadLeft(5, '0')}"; + var a3Bin = aHexList[4].HexToBin().PadLeft(8, '0'); + var msa = a3Bin.Substring(0, 7).BinToDec(); + return new Tuple(a, msa); + case CommandChunkEnum.SEQ: + var seq = hexStringList[(int)CommandChunkEnum.SEQ].HexToBin().PadLeft(8, '0'); + var tpV = (TpV)Convert.ToInt32(seq.Substring(0, 1)); + var firfin = (FIRFIN)Convert.ToInt32(seq.Substring(1, 2)); + var con = (CON)Convert.ToInt32(seq.Substring(3, 1)); + var prseqBin = seq.Substring(4, 4); + return new Seq + { + CON = con, + FIRFIN = firfin, + PRSEQ = prseqBin.BinToDec(), + TpV = tpV + }; + case CommandChunkEnum.Data: + var lenIndex = (int)CommandChunkEnum.Len; + var lenBin = (hexStringList[lenIndex + 1]+hexStringList[lenIndex]).HexToBin(); + var len = lenBin.Remove(lenBin.Length - 2).BinToDec(); + + //验证长度 2=(帧校验和+结束字符) + if (hexStringList.Count - 2 != hearderLen + len) + return null; + + var dataHexList = hexStringList.Skip(FixedLength).Take(len + hearderLen - FixedLength).ToList(); + return dataHexList; + default: + throw new ArgumentOutOfRangeException(nameof(chunk), chunk, null); + } + } + + public static bool IsStartStr(this string str) + { + return str == startStr ? true : false; + } + + /// + /// 字节加33 + /// + /// + /// + public static List AddHex33(this List hexStringList) + { + for (int i = 0; i < hexStringList.Count; i++) + { + hexStringList[i] = (Convert.ToInt32(hexStringList[i], 16) + Convert.ToInt32("33", 16)).ToString("X2"); + if (hexStringList[i].Length > 2) + { + hexStringList[i] = hexStringList[i].Substring(hexStringList[i].Length - 2); + } + } + + return hexStringList; + } + + #region 376.1下行命令 + + /// + /// 构建电表参数设置-下发命令 + /// + /// 集中器地址 + /// + /// + public static byte[] BuildAmmeterParameterSetSendCmd(string address, List meterParameters) + { + var dataUnit = BuildAmmeterParameterSendDataUnit(meterParameters); + var reqParameter = new ReqParameter2() + { + AFN = AFN.设置参数, + FunCode = (int)CMasterStationFunCode.请求1级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.需要对该帧进行确认, + PRSEQ = 10, + }, + MSA = GetMSA(address), + Pn = 0, + Fn = 10 + }; + var bytes = BuildSendCommandBytes(reqParameter, dataUnit); + return bytes; + } + + /// + /// 构建电表参数读取-下发命令 + /// + /// 集中器地址 + /// 对象序号 + public static void BuildAmmeterParameterReadingSendCmd(string address, List meterNumberList) + { + var dataUnit = new List(); + var countHex = meterNumberList.Count().DecToHex().PadLeft(4, '0'); + var countHexPairs = countHex.StringToPairs(); + countHexPairs.Reverse(); + dataUnit.AddRange(countHexPairs); + + foreach (var number in meterNumberList) + { + var numberHex = number.DecToHex().PadLeft(4, '0'); + var numberHexPairs = numberHex.StringToPairs(); + numberHexPairs.Reverse(); + dataUnit.AddRange(numberHexPairs); + } + + var reqParameter = new ReqParameter2() + { + AFN = AFN.查询参数, + FunCode = (int)CMasterStationFunCode.请求2级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.不需要对该帧进行确认, + PRSEQ = 0, + }, + MSA = GetMSA(address), + Pn = 0, + Fn = 10 + }; + var bytes = BuildSendCommandBytes(reqParameter, dataUnit); + } + + /// + /// 构建电表抄读一类数据-下发命令 + /// + /// + /// + /// 一类数据项 + public static void BuildAmmeterReadRealTimeDataSendCmd(string address, int pn, ATypeOfDataItems aTypeOfDataItems) + { + var reqParameter = new ReqParameter2() + { + AFN = AFN.请求实时数据, + FunCode = (int)CMasterStationFunCode.请求2级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.不需要对该帧进行确认, + PRSEQ = 2, + }, + MSA = GetMSA(address), + Pn = pn, + Fn = (int)aTypeOfDataItems + }; + var bytes = HexStringExtensions.BuildSendCommandBytes(reqParameter); + } + + /// + /// 构建电表抄读日冻结正向有功电能示值-下发命令 + /// + /// + /// + /// + public static void BuildAmmeterReadDailyFreezingDataSendCmd(string address, int pn, DateTime time) + { + var dataUnit = time.ToString("yy-MM-dd").Split('-').ToList(); + dataUnit.Reverse(); + var reqParameter = new ReqParameter2() + { + AFN = AFN.请求历史数据, + FunCode = (int)CMasterStationFunCode.请求2级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.不需要对该帧进行确认, + PRSEQ = 2, + }, + MSA = GetMSA(address), + Pn = pn, + Fn = 161 + }; + var bytes = HexStringExtensions.BuildSendCommandBytes(reqParameter, dataUnit); + } + + /// + /// 构建电表抄读实时电流-下发命令 + /// + /// + /// + public static void BuildAmmeterRealTimeCurrentDataSendCmd(string address, int pn) + { + var reqParameter = new ReqParameter2() + { + AFN = AFN.请求实时数据, + FunCode = (int)CMasterStationFunCode.请求2级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.不需要对该帧进行确认, + PRSEQ = 2, + }, + MSA = GetMSA(address), + Pn = pn, + Fn = 25 + }; + var bytes = HexStringExtensions.BuildSendCommandBytes(reqParameter); + } + + + /// + /// 构建电表读取二类数据-下发命令 + /// + /// + /// + /// fn + /// 冻结密度 + /// 冻结点数 + public static void BuildAmmeterReadingIIdataTypeItemsSendCmd(string address, int pn, IIdataTypeItems iIDataTypeItems, FreezeDensity density,int points) + { + var queryDate = DateTime.Today.AddDays(-1); + var dataUnit = queryDate.ToString("yyMMddHHmm").StringToPairs(); + dataUnit.Reverse(); + + //冻结密度 + dataUnit.Add(((int)density).DecToHex()); + + dataUnit.Add(points.DecToHex()); + + var reqParameter = new ReqParameter2() + { + AFN = AFN.请求历史数据, + FunCode = (int)CMasterStationFunCode.请求2级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.不需要对该帧进行确认, + PRSEQ = 2, + }, + MSA = GetMSA(address), + Pn = pn, + Fn = (int)iIDataTypeItems + }; + var bytes = HexStringExtensions.BuildSendCommandBytes(reqParameter, dataUnit); + } + + /// + /// 构建电表读取二类数据-下发命令 + /// + /// + /// + /// fn + /// 数据时标 + public static void BuildAmmeterReadingBaseDataSendCmd(string address, int pn, IIdataTypeItems iIDataTypeItems,TdType tdType) + { + var queryDate = DateTime.Today.AddDays(-1); + List? dataUnit = null; + switch (tdType) + { + case TdType.Td_d: + dataUnit = queryDate.ToString("yyMMdd").StringToPairs(); + break; + case TdType.Td_m: + dataUnit = queryDate.ToString("yyMM").StringToPairs(); + break; + } + + if(dataUnit == null) return; + + dataUnit.Reverse(); + var reqParameter = new ReqParameter2() + { + AFN = AFN.请求历史数据, + FunCode = (int)CMasterStationFunCode.请求2级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.不需要对该帧进行确认, + PRSEQ = 2, + }, + MSA = GetMSA(address), + Pn = pn, + Fn = (int)iIDataTypeItems + }; + var bytes = HexStringExtensions.BuildSendCommandBytes(reqParameter, dataUnit); + } + + + /// + /// 组装有/无功电量 + /// + /// + /// + /// + public static void BuildAmmeterReadingElectricityDataSendCmd(string address, int pn,int cmdType) + { + var reqParameter = new ReqParameter2() + { + AFN = AFN.请求实时数据, + FunCode = (int)CMasterStationFunCode.请求2级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.不需要对该帧进行确认, + PRSEQ = 2, + }, + MSA = GetMSA(address), + Pn = pn, + Fn = cmdType + }; + var bytes = HexStringExtensions.BuildSendCommandBytes(reqParameter); + } + + /// + /// 构建超功率设置-下发命令 + /// + /// + /// + /// + /// + /// + /// + public static void BuildAmmeterSuperpowerSettingSendCmd(string address, string password,string modelCode, int port, BaudRate baudRate, decimal power) + { + if (power > 0) + { + + WsOnSupperPower(address, password, modelCode, true, port, baudRate); + + //TODO:连续发几条嘛? + string dataMark; + //如果是多回路电表,地址只取前面部分 例如:564880000001_01 取564880000001 + if (address.IndexOf('_') > 0) + { + var addressSplit = address.Split('_'); + address = addressSplit[0]; + var loop = Convert.ToInt32(addressSplit[1]); + if (loop == 1) { dataMark = "0E300101"; } + else if (loop == 2) { dataMark = "0E300201"; } + else + return; + } + else + { + dataMark = "0E300101"; + } + + var turnData = AssembleWsSupperPower(address, password, dataMark, power); + if (turnData != null) + { + var bytes = BuildTransparentForwardingSendCmd(address, port, baudRate, turnData); + } + } + else + { + WsOnSupperPower(address, password, modelCode, false, port, baudRate); + } + + } + + /// + /// 构建恶性负载绝对功率设置-下发命令 + /// + /// + /// + /// + /// + /// + public static void BuildAmmeterAbsolutePowerSettingSendCmd(string address, string password, int port, BaudRate baudRate, decimal power) + { + if (power <= 0) + { + power = 99;//等于小0 代表关闭 + } + + string dataMark; + //如果是多回路电表,地址只取前面部分 例如:564880000001_01 取564880000001 + if (address.IndexOf('_') > 0) + { + var addressSplit = address.Split('_'); + address = addressSplit[0]; + + var loop = Convert.ToInt32(addressSplit[1]); + if (loop == 1) { dataMark = "0E300103"; } + else if (loop == 2) { dataMark = "0E300203"; } + else + return; + } + else + { + dataMark = "0E300103"; + } + + var turnData = AssembleWsAbsolutePowerSetting(address, password, dataMark, power); + if (turnData != null) + { + var bytes = BuildTransparentForwardingSendCmd(address, port, baudRate, turnData); + } + } + + /// + /// 构建恶性负载功率因数设置-下发命令 + /// + /// + /// + /// + /// + /// + public static void BuildAmmeterPowerFactorSettingSendCmd(string address, string password, int port, BaudRate baudRate, decimal power) + { + string dataMark; + //如果是多回路电表,地址只取前面部分 例如:564880000001_01 取564880000001 + if (address.IndexOf('_') > 0) + { + var addressSplit = address.Split('_'); + address = addressSplit[0]; + + var loop = Convert.ToInt32(addressSplit[1]); + if (loop == 1) { dataMark = "0E300104"; } + else if (loop == 2) { dataMark = "0E300204"; } + else + return; + } + else + { + dataMark = "0E300104"; + } + + var turnData = AssembleWsPowerFactor(address, password, dataMark, power); + if (turnData != null) + { + var bytes = BuildTransparentForwardingSendCmd(address, port, baudRate, turnData); + } + } + + /// + /// 超功率开关 + /// + /// + /// + /// + /// + /// + public static void WsOnSupperPower(string address,string password,string modelCode,bool isOn,int port,BaudRate baudRate) + { + + List modelCodes = new List() { "DDS3102-S2", "DDS71", "DDZY71", "DTZY71", "DSZY71" }; + //这些型号需进入软编程 + if (modelCodes.Contains(modelCode)) + { + var dataUnit1 = SoftProgram(address, modelCode, password); + BuildTransparentForwardingSendCmd(address, port, baudRate, dataUnit1); + } + + var dataUnit2 = AssembleWsOnSupperPower(address, password, isOn); + BuildTransparentForwardingSendCmd(address, port, baudRate, dataUnit2); + } + + + /// + /// 构建水表参数设置-下发命令 + /// + /// 集中器地址 + /// + /// + public static byte[] BuildWaterMeterParameterSetSendCmd(string address, List meterParameters) + { + var dataUnit = BuildWaterMeterParameterSendDataUnit(meterParameters); + var reqParameter = new ReqParameter2() + { + AFN = AFN.设置参数, + FunCode = (int)CMasterStationFunCode.请求1级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.需要对该帧进行确认, + PRSEQ = 10, + }, + MSA = GetMSA(address), + Pn = 0, + Fn = 10 + }; + var bytes = BuildSendCommandBytes(reqParameter, dataUnit); + return bytes; + } + + /// + /// 构建透明转发-下发命令 + /// + /// 集中器地址 + /// 终端通信端口 1~31 + /// 0~7 对应300,600,1200,2400,4800,7200,9600,19200 + /// 转发内容 + /// 停止位 + /// 校验方式 + /// 数据位 + /// 等待报文超时时间/s + /// 等待字节超时时间/ms + public static byte[] BuildTransparentForwardingSendCmd(string address, int port, BaudRate baudRate, List datas, StopBit stopBit = StopBit.Stop1, Parity parity = Parity.Even, DataBit dataBit = DataBit.D8, + int waitContentTimeout = 100, int waitByteTimeout = 100) + { + var dataUnit = BuildTransparentForwardingSendDataUnit(port, baudRate, datas, stopBit, parity, dataBit, waitContentTimeout, waitByteTimeout); + dataUnit.AddRange(GetPW()); + var reqParameter = new ReqParameter2() + { + AFN = AFN.数据转发, + FunCode = (int)CMasterStationFunCode.请求2级数据, + A = address, + Seq = new Seq() + { + TpV = TpV.附加信息域中无时间标签, + FIRFIN = FIRFIN.单帧, + CON = CON.不需要对该帧进行确认, + PRSEQ = 0 + }, + MSA = GetMSA(address), + Pn = 0, + Fn = 1 + }; + var bytes = BuildSendCommandBytes(reqParameter, dataUnit); + return bytes; + } + + [Obsolete] + public static List AmmeterValveControl(string address, string specialnocode, string password, bool state, string modelCode = "") + { + address = address.Trim().TrimStart('0'); + if (address.Length < 12) address = address.PadLeft(12, '0'); + string Code = string.Empty; + + if (state) + { + if (string.IsNullOrEmpty(specialnocode)) + Code = "1B"; + else + Code = specialnocode == "1B" || specialnocode == "1C" ? specialnocode : "1C"; + } + else + Code = "1A";//跳闸 + + if (specialnocode == "1W") + { + if (state) + Code = "1A"; + else + Code = "1C"; + } + + var pwdLevel = "02"; + if (modelCode == "HL_DTSU2625" || modelCode == "DDZY9866") + pwdLevel = "04"; + else if (modelCode == "DDS2705") + pwdLevel = "03"; + + if (!string.IsNullOrWhiteSpace(password) && password.Contains("|")) + { + var sp = password.Split('|'); + pwdLevel = sp[1]; + password = sp[0]; + } + + string strDate = DateTime.Now.AddYears(3).ToString("000012ddMMyy").StrAddSpan(); + if (specialnocode == "1D" || modelCode == "SZBD_DDZY1225") + strDate = "FF FF FF FF FF FF"; + string strP = password.StrAddSpan().StrReverseOrder(); + string strSJY = " " + pwdLevel + " " + strP + " 01 00 00 00 " + Code + " 00 " + strDate; + string strLen = (strSJY.Replace(" ", "").Length / 2).ToString("X2"); + string strReturn = "68 " + address.StrAddSpan().StrReverseOrder() + " 68 1C " + strLen + " " + strSJY.StrAddHex33() + " "; + string strSum = strReturn.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(i => Convert.ToInt32(i, 16)).Sum().ToString("X"); + strReturn += strSum.Substring(strSum.Length - 2) + " 16"; + + return strReturn.Split(' ').ToList(); + } + + + /// + /// 构建透明转发-下发数据单元 + /// + /// 终端通信端口 1~31 + /// 0~7 对应300,600,1200,2400,4800,7200,9600,19200 + /// 转发内容 + /// 停止位 + /// 校验方式 + /// 数据位 + /// 等待报文超时时间/s + /// 等待字节超时时间/ms + /// + private static List BuildTransparentForwardingSendDataUnit(int port, BaudRate baudRate, List datas, StopBit stopBit = StopBit.Stop1, Parity parity = Parity.Even, DataBit dataBit = DataBit.D8, + int waitContentTimeout = 100, int waitByteTimeout = 100) + { + var dataUnit = new List(); + + var portHex = port.DecToHex().PadLeft(2, '0'); + dataUnit.Add(portHex); + + var baudRateBin = ((int)baudRate).DecToBin().PadLeft(3, '0'); + var stopBitBin = ((int)stopBit).DecToBin(); + var parityBin = parity != Parity.None ? $"1{((int)parity).DecToBin()}" : "00"; + var dataBitBin = ((int)dataBit).DecToBin().PadLeft(2, '0'); + var controlHex = $"{baudRateBin}{stopBitBin}{parityBin}{dataBitBin}".BinToHex().PadLeft(2, '0'); ; + dataUnit.Add(controlHex); + + var waitContentTimeoutBin = $"1{waitContentTimeout.DecToBin().PadLeft(7, '0')}"; + var waitContentTimeoutHex = waitContentTimeoutBin.BinToHex().PadLeft(2, '0'); + var waitByteTimeoutHex = waitByteTimeout.DecToHex().PadLeft(2, '0'); + + dataUnit.Add(waitContentTimeoutHex); + dataUnit.Add(waitByteTimeoutHex); + + var countHex = datas.Count.DecToHex().PadLeft(4, '0'); + var countHexPairs = countHex.StringToPairs(); + countHexPairs.Reverse(); + dataUnit.AddRange(countHexPairs); + + dataUnit.AddRange(datas); + + return dataUnit; + } + + /// + /// 构建下发命令 + /// + /// + /// + /// + public static byte[] BuildSendCommandBytes(ReqParameter reqParameter, List? dataUnit = null) + { + var cmdStrList = new List(); + var userDatas = BuildUserData(reqParameter, dataUnit); + var hearders = BuildHeaders(userDatas.Count); + var cs = GetCS(userDatas); + cmdStrList.AddRange(hearders); + cmdStrList.AddRange(userDatas); + cmdStrList.Add(cs); + cmdStrList.Add(endStr); + Console.WriteLine(string.Join(" ", cmdStrList)); + var bytes = cmdStrList.Select(x => Convert.ToByte(x, 16)).ToArray(); + return bytes; + } + + /// + /// 构建电表参数设置-下发数据单元 + /// + /// + /// + private static List BuildAmmeterParameterSendDataUnit(List meterParameters) + { + var hexDatas = new List(); + + var countHex = meterParameters.Count().DecToHex().PadLeft(4, '0'); + hexDatas.Add(countHex); + + //TODO 优化代码:目标数据入参,返回类型为出参 + for (int i = 0; i <= meterParameters.Count - 1; i++) + { + var meter = meterParameters[i]; + + var indexHex = (i + 1).DecToHex().PadLeft(4, '0'); + hexDatas.Add(indexHex); + + var pnHex = meter.Pn.DecToHex().PadLeft(4, '0'); + hexDatas.Add(pnHex); + + var baudRateBin = meter.BaudRate.DecToBin().PadLeft(3, '0'); + var portBin = meter.Port.DecToBin().PadLeft(5, '0'); + var baudRateAndPortHex = $"{baudRateBin}{portBin}".BinToHex().PadLeft(2, '0'); + hexDatas.Add(baudRateAndPortHex); + + var protocolTypeHex = ((int)meter.ProtocolType).DecToHex().PadLeft(2, '0'); + hexDatas.Add(protocolTypeHex); + + hexDatas.Add(meter.Address); + + hexDatas.Add(meter.Password.PadLeft(12, '0')); + + var rateNumberBin = $"0000{meter.RateNumber.DecToBin().PadLeft(4, '0')}"; + var rateNumberHex = rateNumberBin.BinToHex().PadLeft(2, '0'); + hexDatas.Add(rateNumberHex); + + var intBitNumberBin = (meter.IntegerBitNumber - 4).DecToBin().PadLeft(2, '0'); + var decBitNumberBin = (meter.DecimalBitNumber - 1).DecToBin().PadLeft(2, '0'); + var intAndDecBitNumberBin = $"0000{intBitNumberBin}{decBitNumberBin}"; + var intAndDecBitNumberHex = intAndDecBitNumberBin.BinToHex().PadLeft(2, '0'); + hexDatas.Add(intAndDecBitNumberHex); + + hexDatas.Add(meter.CollectorAddress.PadLeft(12, '0')); + + var userCategoryNumberBin = meter.UserCategoryNumber.DecToBin().PadLeft(4, '0'); + var userSubclassNumberBin = meter.UserSubclassNumber.DecToBin().PadLeft(4, '0'); + var userNumberHex = $"{userCategoryNumberBin}{userSubclassNumberBin}".BinToHex().PadLeft(2, '0'); + hexDatas.Add(userNumberHex); + } + + //高位在前,低位在后 + var datas = new List(); + foreach (var hexData in hexDatas) + { + if (hexData.Length == 2) + datas.Add(hexData); + else + { + var lst = hexData.StringToPairs(); + lst.Reverse(); + datas.AddRange(lst); + } + } + datas.AddRange(GetPW()); + return datas; + } + + /// + /// 构建水表参数设置-下发数据单元 + /// + /// + /// + private static List BuildWaterMeterParameterSendDataUnit(List meterParameters) + { + var hexDatas = new List(); + + var countHex = meterParameters.Count().DecToHex().PadLeft(4, '0'); + hexDatas.Add(countHex); + + for (int i = 0; i <= meterParameters.Count - 1; i++) + { + + var meter = meterParameters[i]; + var protocolType = (int)meter.ProtocolType; + + var currentProtocolType = protocolType; + if (protocolType == 43) + currentProtocolType = 1; + else if (protocolType > 32) currentProtocolType = 32; + + //TODO:无线水表 小数位 + if (currentProtocolType == 32 && meter.Address.Substring(0, 2) != "00") + { + var ejz = meter.Address.Substring(0, 2).HexToBin().PadLeft(8, '0'); + var xs = ejz.Substring(6, 2).BinToDec(); + var zs = ejz.Substring(0, 6).BinToDec(); + //userData.Add(new QGDW3671UserData() { Name = "整数位无线水表", Value = zs }); + //userData.Add(new QGDW3671UserData() { Name = "小数位无线水表", Value = xs }); + } + + var userCategoryNumber = meter.UserCategoryNumber; + var userSubclassNumber = meter.UserSubclassNumber; + + if (protocolType == 32) + userCategoryNumber = 1; + else if (protocolType == 45) + { + userCategoryNumber = 1; + userSubclassNumber = 9; + } + else if (protocolType == 1) + userSubclassNumber = 1; + + var indexHex = (i + 1).DecToHex().PadLeft(4, '0'); + hexDatas.Add(indexHex); + + var pnHex = meter.Pn.DecToHex().PadLeft(4, '0'); + hexDatas.Add(pnHex); + + var baudRateBin = meter.BaudRate.DecToBin().PadLeft(3, '0'); + var portBin = meter.Port.DecToBin().PadLeft(5, '0'); + var baudRateAndPortHex = $"{baudRateBin}{portBin}".BinToHex().PadLeft(2, '0'); + hexDatas.Add(baudRateAndPortHex); + + var protocolTypeHex = currentProtocolType.DecToHex().PadLeft(2, '0'); + hexDatas.Add(protocolTypeHex); + + hexDatas.Add(meter.Address); + + hexDatas.Add(meter.Password.PadLeft(12, '0')); + + var rateNumberBin = $"0000{meter.RateNumber.DecToBin().PadLeft(4, '0')}"; + var rateNumberHex = rateNumberBin.BinToHex().PadLeft(2, '0'); + hexDatas.Add(rateNumberHex); + + var intBitNumberBin = meter.IntegerBitNumber.DecToBin().PadLeft(2, '0'); + var decBitNumberBin = meter.DecimalBitNumber.DecToBin().PadLeft(2, '0'); + var intAndDecBitNumberBin = $"0000{intBitNumberBin}{decBitNumberBin}"; + var intAndDecBitNumberHex = intAndDecBitNumberBin.BinToHex().PadLeft(2, '0'); + hexDatas.Add(intAndDecBitNumberHex); + + hexDatas.Add(meter.CollectorAddress.PadLeft(12, '0')); + + var userCategoryNumberBin = userCategoryNumber.DecToBin().PadLeft(4, '0'); + var userSubclassNumberBin = userSubclassNumber.DecToBin().PadLeft(4, '0'); + var userNumberHex = $"{userCategoryNumberBin}{userSubclassNumberBin}".BinToHex().PadLeft(2, '0'); + hexDatas.Add(userNumberHex); + } + + //高位在前,低位在后 + var datas = new List(); + foreach (var hexData in hexDatas) + { + if (hexData.Length == 2) + datas.Add(hexData); + else + { + var lst = hexData.StringToPairs(); + lst.Reverse(); + datas.AddRange(lst); + } + } + datas.AddRange(GetPW()); + return datas; + } + + //AUX=消息认证码字段(PW,16个字节) + private static List GetPW() + { + var str = "00"; + var pWList = Enumerable.Repeat(str, pWLen).ToList(); + return pWList; + } + + + /// + /// 帧校验和 + /// + /// 用户数据区 + /// + private static string GetCS(List userData) + { + byte sum = 0; + foreach (var d in userData) + { + var b = Convert.ToByte(d, 16); + sum += b; + } + return sum.ToString("X2"); + } + + /// + /// 用户数据区 + /// + /// + /// + private static List BuildUserData(ReqParameter reqParameter, List? dataUnit) + { + var c = BuildC(reqParameter.FunCode, reqParameter.PRM); + var a = BuildAList(reqParameter.A, reqParameter.MSA); + + var linkUserData = BuildLinkUserData(reqParameter.AFN, reqParameter.Seq, + ((ReqParameter2)reqParameter).Pn, ((ReqParameter2)reqParameter).Fn, dataUnit); + + var list = new List() { c }; + list.AddRange(a); + list.AddRange(linkUserData); + return list; + } + + /// + /// 固定长度的报文头 起始字符+长度+长度+起始字符 + /// + /// + /// + private static List BuildHeaders(int length) + { + var headers = new List(); + headers.Add(startStr); + var l = BuildLength(length); + headers.AddRange(l); + headers.AddRange(l); + headers.Add(startStr); + return headers; + } + + /// + /// 长度 2字节 [用户数据区长度] + /// + /// + private static List BuildLength(int length1) + { + var binaryLen = length1.DecToBin(); + var protocolIdentification = Enum.Format(typeof(ProtocolIdentification), + ProtocolIdentification.本规约使用, "d").PadLeft(2, '0'); + var lenStr = $"{binaryLen}{protocolIdentification}"; + var hexLen = lenStr.BinToHex(); + hexLen = hexLen.PadLeft(4, '0'); + var list = hexLen.StringToPairs(); + list.Reverse(); + return list; + } + + /// + /// 控制域 + /// + /// 功能码 + /// + /// + /// + private static string BuildC(int funCode, PRM pRM, int fcb = 0, FCV fcv = FCV.FCB位无效) + { + var cMasterStationFunCodeHex = funCode.DecToBin(); + cMasterStationFunCodeHex = cMasterStationFunCodeHex.ToString().PadLeft(4, '0'); + var strC = $"{(int)DIR.主站下行报文}{(int)pRM}{fcb}{(int)fcv}{cMasterStationFunCodeHex}"; + var hexC = strC.BinToHex().PadLeft(2, '0'); + return hexC; + } + + + /// + /// 地址域 3220 09872 + /// + /// 行政区划码 BCD码 3220=2032 + /// 逻辑地址 BIN 09872=2690=>9026 + /// 主站地址 BIN 0~127 + /// + private static List BuildAList(string a, int mSA) + { + var list = new List(); + + var a1 = a.Substring(0, 4); + var a1Pairs = a1.StringToPairs(); + a1Pairs.Reverse(); + list.AddRange(a1Pairs); + + var a2 = Convert.ToInt32(a.Substring(4)); + var decA2 = a2.DecToHex(); + var a2Pairs = decA2.PadLeft(4, '0').StringToPairs(); + a2Pairs.Reverse(); + list.AddRange(a2Pairs); + + //TODO:主站地址和组地址标志 + var a3Bin = $"{mSA.DecToBin().PadLeft(7, '0')}0"; + list.Add(a3Bin.BinToHex().PadLeft(2, '0')); + + return list; + } + + private static List BuildLinkUserData(AFN aFN, Seq seq, int pn, int fn, List? dataUnit) + { + var aFNValue = ((int)aFN).DecToHex().PadLeft(2, '0'); + var sEQ = BuildSEQ(seq.TpV, seq.FIRFIN, seq.CON, seq.PRSEQ); + var dA = BuildDA(pn); + var dT = BuildDT(fn); + var list = new List() { aFNValue, sEQ }; + list.AddRange(dA); + list.AddRange(dT); + + if (dataUnit != null) + { + list.AddRange(dataUnit); + } + //list.AddRange(GetDataUnit(aFN,seq)); + + if (seq.TpV == TpV.附加信息域中带时间标签) + list.AddRange(BuildTp("00")); + + return list; + } + + /// + /// 帧序列域 + /// + /// + /// + /// + /// + private static string BuildSEQ(TpV tpV, FIRFIN fIRFIN, CON cON, int pRSEQ) + { + var tpVValue = Enum.Format(typeof(TpV), + tpV, "d"); + var fIRFINValue = Enum.Format(typeof(FIRFIN), + fIRFIN, "d"); + var cONValue = (int)cON; + var sEQBin = $"{tpVValue}{fIRFINValue}{cONValue}{pRSEQ.DecToBin().PadLeft(4, '0')}"; + var hexSEQ = sEQBin.BinToHex().PadLeft(2, '0'); + return hexSEQ; + } + + /// + /// 信息点标识 + /// + /// 计量点 + /// + private static List BuildDA(int pn) + { + if (pn == 0) + return new List() { "00", "00" }; + var dA2 = (pn - 1) / 8 + 1;//信息点组从1开始 第几组 + var dA1 = pn - (dA2 - 1) * 8;//pn % 8 + var dA1Hex = "1".PadRight(dA1, '0').BinToHex();//对位信息 第几位 二进制有效位 + var dA2Hex = dA2.DecToHex(); + return new List() { dA1Hex.PadLeft(2, '0'), dA2Hex.PadLeft(2, '0') }; + + } + + /// + /// 数据单元标识 + /// + /// + /// + private static List BuildDT(int fn) + { + var dT2 = (fn - 1) / 8;//从零开始 第几组 + var dT1 = fn - dT2 * 8; + var dT1Hex = "1".PadRight(dT1, '0').BinToHex();//对位信息 第几位 二进制有效位 + var dT2Hex = dT2.DecToHex(); + return new List() { dT1Hex.PadLeft(2, '0'), dT2Hex.PadLeft(2, '0') }; + } + + /// + /// 时间标签 + /// + /// 启动帧帧序号计数器PFC 1字节 + /// 允许发送传输延时时间 min 1字节 + /// + private static List BuildTp(string pFC = "00", int delayTime = 0) + { + var now = DateTime.Now; // 获取当前时间 + var seconds = now.Second.ToString().PadLeft(2, '0'); // 获取当前秒数 + var minutes = now.Minute.ToString().PadLeft(2, '0'); // 获取当前分钟数 + var hours = now.Hour.ToString().PadLeft(2, '0'); // 获取当前小时数 + var day = now.Day.ToString().PadLeft(2, '0'); // 获取当前日期的日数 + return new List() { pFC, seconds, minutes, hours, day, delayTime.ToString().PadLeft(2, '0') }; + } + + #endregion + + #region 645下行命令 + + + /// + /// 构建电表阀控下发数据单元 + /// + /// 电表地址 + /// 特殊控制码 + /// 密码 + /// 是否为开阀 + /// 型号码 + /// + public static List BuildAmmeterValveControlSendDataUnit(string address, string specialControlCode, string password, bool state, string modelCode = "") + { + var code = string.Empty; + + if (state) + { + if (string.IsNullOrEmpty(specialControlCode)) + code = "1B"; + else + code = specialControlCode == "1B" || specialControlCode == "1C" ? specialControlCode : "1C"; + } + else + code = "1A";//跳闸 + + if (specialControlCode == "1W") + { + if (state) + code = "1A"; + else + code = "1C"; + } + + var pwdLevel = "02"; + if (modelCode == "HL_DTSU2625" || modelCode == "DDZY9866") + pwdLevel = "04"; + else if (modelCode == "DDS2705") + pwdLevel = "03"; //不带安全认证密级 + + if (!string.IsNullOrWhiteSpace(password) && password.Contains("|")) + { + var sp = password.Split('|'); + pwdLevel = sp[1]; + password = sp[0]; + } + + var strDate = DateTime.Now.AddYears(3).ToString("000012ddMMyy").StrAddSpan();//命令有效截止时间 + if (specialControlCode == "1D" || modelCode == "SZBD_DDZY1225") + strDate = "FF FF FF FF FF FF"; + var strP = password.StrAddSpan().StrReverseOrder(); + var strSJY = " " + pwdLevel + " " + strP + " 01 00 00 00 " + code + " 00 " + strDate; + var dataUnit = strSJY.Replace(" ", "").StringToPairs(); + var dataList = Build645SendCommand(address, "1C", dataUnit); + return dataList; + + //string strLen = (strSJY.Replace(" ", "").Length / 2).ToString("X2"); + //string strReturn = "68 " + address.StrAddSpan().StrReverseOrder() + " 68 1C " + strLen + " " + strSJY.StrAddHex33() + " "; + //string strSum = strReturn.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(i => Convert.ToInt32(i, 16)).Sum().ToString("X"); + //strReturn += strSum.Substring(strSum.Length - 2) + " 16"; + //return strReturn.Split(' ').ToList(); + } + + /// + /// 构建电表保电下发数据单元 + /// + /// 电表地址 + /// + /// true 保电 false 保电解除 + /// 型号码 + /// + public static List BuildAmmeterLockSendDataUnit(string address, string password, bool state, string modelCode = "") + { + var code = state ? "3A" : "3B"; + + var strDate = (code + DateTime.Now.AddDays(1).ToString("00000012ddMMyy")).StrAddSpan(); + + if (modelCode == "SZBD_DDZY1225") + strDate = $"{code} 00 FF FF FF FF FF FF"; + + var strP = password.StrAddSpan().StrReverseOrder(); + var strSJY = " 02 " + strP + " 01 00 00 00 " + strDate; + + var dataUnit = strSJY.Replace(" ", "").StringToPairs(); + var dataList = Build645SendCommand(address, "1C", dataUnit); + return dataList; + } + + /// + /// 构建电表认证下发数据单元 + /// + /// 电表地址 + /// + /// + /// + public static List BuildAmmeterIdentitySendDataUnit(string address, string ramDon, string maco) + { + var codeList = "070004FF".StringToPairs(); + codeList.Reverse(); + + var ramDonList = ramDon.StringToPairs(); + ramDonList.Reverse(); + + var macoList = maco.StringToPairs(); + macoList.Reverse(); + + var dataUnit = new List(); + dataUnit.AddRange(codeList); + dataUnit.AddRange(ramDonList); + dataUnit.AddRange(macoList); + var dataList = Build645SendCommand(address, "03", dataUnit); + return dataList; + } + + /// + /// 构建电表清零下发数据单元 + /// + /// 电表地址 + /// + /// + public static List BuildAmmterClearSendDataUnit(string address, string password) + { + var strP = password.StrAddSpan().StrReverseOrder(); + var strSJY = " 02 " + strP + " 01 00 00 00 "; + var dataUnit = strSJY.Replace(" ", "").StringToPairs(); + var dataList = Build645SendCommand(address, "1A", dataUnit); + return dataList; + } + + /// + /// 构建645协议下发命令 + /// + /// 电表地址 + /// 控制码 + /// 数据域 发送方按字节进行加33处理,接收方按字节减33 + /// + public static List Build645SendCommand(string ammeterAddress, string controlCode, List? dataUnit) + { + var cmdStrList = new List(); + cmdStrList.Add(startStr); + + ammeterAddress = ammeterAddress.PadLeft(12, '0'); + var addressList = ammeterAddress.StringToPairs(); + addressList.Reverse(); + cmdStrList.AddRange(addressList); + + cmdStrList.Add(startStr); + + cmdStrList.Add(controlCode); + + var len = dataUnit != null ? dataUnit.Count.DecToHex().PadLeft(2, '0') : "00"; + cmdStrList.Add(len); + + if (dataUnit != null) + { + cmdStrList.AddRange(dataUnit.AddHex33()); + } + + var strSum = cmdStrList.Select(i => Convert.ToInt32(i, 16)).Sum().ToString("X"); + strSum = strSum.Substring(strSum.Length - 2); + cmdStrList.Add(strSum); + cmdStrList.Add(endStr); + + return cmdStrList; + } + + /// + /// 威胜表的超功率(第一路恶性负载超功率判断阀值) + /// + /// + /// + /// + /// + /// + public static List? AssembleWsSupperPower(string address, string password, string dataMark, decimal power) + { + power = Math.Round(power, 4); + if (power > (decimal)99.9999) return null; + var strPower = power < 10 ? $"0{power}" : power.ToString(); + var pStr = strPower.Replace(".", "").PadRight(6, '0'); + var data = new string[] { pStr[4] + "" + pStr[5], pStr[2] + "" + pStr[3], pStr[0] + "" + pStr[1] }; + return AssembleWrite(address, password, dataMark, data); + } + /// + /// 威胜表的超功率(超功率开关) + /// + /// + /// + /// + /// + public static List AssembleWsOnSupperPower(string address, string password, bool isOn = true) + { + var data = new string[] { (isOn ? "01" : "00") }; + return AssembleWrite(address, password, "0E400001", data); + } + /// + /// 威胜表的超功率(第一路恶性负载绝对功率判断阈值) + /// + /// + /// + /// + /// + /// + public static List? AssembleWsAbsolutePowerSetting(string address, string password, string dataMark, decimal power) + { + power = Math.Round(power, 4); + if (power > (decimal)99.9999) return null; + var strPower = power < 10 ? $"0{power}" : power.ToString(); + var pStr = strPower.Replace(".", "").PadRight(6, '0'); + var data = new string[] { pStr[4] + "" + pStr[5], pStr[2] + "" + pStr[3], pStr[0] + "" + pStr[1] }; + return AssembleWrite(address, password, dataMark, data); + } + /// + /// 威胜表的超功率(第一路恶性负载功率因数判断阀值) + /// + /// + /// + /// + /// + /// + public static List? AssembleWsPowerFactor(string address, string password, string dataMark, decimal factor) + { + factor = Math.Round(factor, 3); + if (factor >= (decimal)1.0 || factor <= 0) return null; + var strFactor = factor.ToString(); + var pStr = strFactor.Replace(".", "").PadRight(4, '0'); + var data = new string[] { pStr[2] + "" + pStr[3], pStr[0] + "" + pStr[1] }; + return AssembleWrite(address, password, dataMark, data); + } + + /// + /// 构建写数据 + /// + /// + /// + /// + /// + /// + public static List AssembleWrite(string address, string password, string di0_3, string[] data) + { + var returnList = new List(); + returnList.Add(startStr); + + var addressList = address.StringToPairs(); + addressList.Reverse(); + returnList.AddRange(addressList); + + returnList.Add(startStr); + returnList.Add("14"); + + var len = (12 + data.Length).ToString("X2"); + returnList.Add(len); + + + var di03List = di0_3.StringToPairs(); + di03List.Reverse(); + di03List.Add("02"); + + var pwdList = password.StringToPairs(); + pwdList.Reverse(); + di03List.AddRange(pwdList); + + var mList = new List() { "00", "11", "22", "33" }; + di03List.AddRange(mList); + di03List.AddRange(data); + var listAdd33 = di03List.AddHex33(); + + returnList.AddRange(listAdd33); + + var strSum = returnList.Select(i => Convert.ToInt32(i, 16)).Sum().ToString("X"); + var cs = strSum.Substring(strSum.Length - 2); + returnList.Add(cs); + returnList.Add(endStr); + + return returnList; + } + + /// + /// 生成软编程指令 + /// 型号编码 + /// + /// + private static List SoftProgram(string address,string modelCode,string password) + { + string bccmd = string.Empty; + if (modelCode == "DDS71") + { + + bccmd = "68 AA AA AA AA AA AA 68 04 07 4E F4 35 BB BB BB 32"; + } + else + { + bccmd = "68 AA AA AA AA AA AA 68 14 10 41 35 33 41 37 33 33 33 34 33 33 33 77 66 55 44"; + } + + //替换密码 + var passwordList = password.StringToPairs(); + passwordList.Reverse(); + passwordList = passwordList.AddHex33(); + var passwordStr = string.Join(" ", passwordList); + bccmd = bccmd.Replace("BB BB BB", passwordStr); + //替换表地址 + var addressList = address.StringToPairs(); + addressList.Reverse(); + var addressStr = string.Join(" ", addressList); + bccmd = bccmd.Replace("AA AA AA AA AA AA", addressStr); + var fm = bccmd.Split(' ').ToList(); + //生成CRC + var cRC = GetCRC(fm); + fm.Add(cRC); + fm.Add("16"); + + return fm; + } + + #endregion + + #region 188 下行命令 + + /// + /// 标准 188协议阀控 + /// + /// + /// 表计类型 + /// + public static List BuildConfirm188WaterValve(string waterMeterAddress, bool state, string mtype = "10") + { + if (string.IsNullOrWhiteSpace(waterMeterAddress)) return null; + + var dataUnit = new List() { "A0", "17", "00", state ? "55" : "99" }; + + var dataList = Build188SendCommand(waterMeterAddress, "04", dataUnit); + + return dataList; + } + + /// + /// 构建188水表抄读下发数据单元 + /// + /// + /// + public static List Build188WaterMeterReadingSendDataUnit(string waterMeterAddress) + { + + var dataUnit = new List() { "1F", "90", "00" }; + var dataList = Build188SendCommand(waterMeterAddress, "01", dataUnit); + + return dataList; + } + + /// + /// 构建188协议下发命令 + /// + /// 水表地址 + /// 控制码 + /// 数据域 + /// 表类型 + /// + public static List Build188SendCommand(string waterMeterAddress, string controlCode, List? dataUnit = null, string meterType = "10") + { + //address.Substring(address.Length - 12, 12) + var cmdStrList = new List(); + cmdStrList.Add(startStr); + cmdStrList.Add(meterType); + + waterMeterAddress = waterMeterAddress.PadLeft(14, '0'); + var addressList = waterMeterAddress.StringToPairs(); + addressList.Reverse(); + cmdStrList.AddRange(addressList); + + //控制码 + cmdStrList.Add(controlCode); + + var len = dataUnit != null ? dataUnit.Count.DecToHex().PadLeft(2, '0') : "00"; + cmdStrList.Add(len); + if (dataUnit != null) + { + cmdStrList.AddRange(dataUnit); + } + + var strSum = cmdStrList.Select(i => Convert.ToInt32(i, 16)).Sum().ToString("X"); + strSum = strSum.Substring(strSum.Length - 2); + cmdStrList.Add(strSum); + cmdStrList.Add(endStr); + + return cmdStrList; + } + + /// + /// 组装水表阀控 + /// + /// 水表地址 + /// The password. + /// The poprotocol. + /// if set to true [isopenvalve]. + /// + public static List? WaterMeterValveControl(string waterMeterAddress, string password, int protocol, bool state) + { + List? turnData = null; + if (protocol == 1) + turnData = GetControlCode97(waterMeterAddress.Substring(waterMeterAddress.Length - 12, 12), password, state ? "3355" : "9966");//开阀/关阀 + else if (protocol == 30) + turnData = GetControlCode07(waterMeterAddress.Substring(waterMeterAddress.Length - 12, 12), password, state ? "3355" : "9966");//开阀/关阀 + return turnData; + } + + private static List GetControlCode97(string waterMeterAddress, string password, string valueCode) + { + var dataList = new List(); + var passwordList = password.StringToPairs(); + passwordList.Reverse(); + + var valueCodeList = valueCode.StringToPairs(); + valueCodeList.Reverse(); + + dataList.AddRange(valueCodeList); + dataList.AddRange(passwordList); + dataList.AddRange(valueCodeList); + + return GetCode(waterMeterAddress, "04", dataList); + } + + private static List GetControlCode07(string waterMeterAddress, string password, string valueCode) + { + var dataList = new List(); + dataList.Add("02"); + + var passwordList = password.StringToPairs(); + passwordList.Reverse(); + dataList.AddRange(passwordList); + dataList.AddRange("01000000".StringToPairs()); + + dataList.AddRange(valueCode.StringToPairs()); + + dataList.Add("00"); + + var time = DateTime.Now.AddDays(1).ToString("yyMMddHHmmss"); + var timeList = time.StringToPairs(); + timeList.Reverse(); + dataList.AddRange(timeList); + + return GetCode(waterMeterAddress, "1C", dataList); + } + + public static List GetCode(string waterMeterAddress, string controlCode, List childDataList) + { + var dataList = new List { startStr }; + + waterMeterAddress = waterMeterAddress.PadLeft(12, '0'); + var addressList = waterMeterAddress.StringToPairs(); + addressList.Reverse(); + dataList.AddRange(addressList); + + dataList.Add(startStr); + dataList.Add(controlCode); + + var num = childDataList.Count; + dataList.Add(num.ToString("X2")); + + dataList.AddRange(childDataList.AddHex33()); + + var cs = dataList.Select(it => Convert.ToInt32(it, 16)).Sum().ToString("X2"); + cs = cs.Substring(cs.Length - 2, 2); + dataList.Add(cs); + + dataList.Add(endStr); + + return dataList; + } + + public static string GetCRC(List inputFrm, int startIndex = 0) + { + int sum = 0; + for (int i = startIndex; i < inputFrm.Count; i++) + { + sum += (Convert.ToInt32(inputFrm[i], 16)); + } + var sum16 = Convert.ToString(sum, 16); + return sum16.Substring(sum16.Length - 2, 2).ToUpper(); + } + + public static object GetAnalyzeValue(this List hexStringList, CommandChunkEnum188 chunk) + { + if (hexStringList.Count < 11) + { + return null; + } + + switch (chunk) + { + case CommandChunkEnum188.A: + var aHexList = hexStringList[(int)CommandChunkEnum188.A].Take(7).ToList(); + aHexList.Reverse(); + return string.Join("", aHexList.Skip(1).Take(6).ToList()); + case CommandChunkEnum188.C: + var cHex = hexStringList[(int)CommandChunkEnum188.C]; + return cHex; + case CommandChunkEnum188.Data: + var lenIndex = (int)CommandChunkEnum188.L; + var len = hexStringList[lenIndex].HexToDec(); + + //验证长度 2=(帧校验和+结束字符) + if (hexStringList.Count - 2 != 11 + len) + return null; + + var dataHexList = hexStringList.Skip(11).Take(len).ToList(); + return dataHexList; + default: + throw new ArgumentOutOfRangeException(nameof(chunk), chunk, null); + } + } + + //public double AnalyzeCurrentTotalRate(List hexList) + //{ + // var str = string.Join("", hexList); + // var number = Convert.ToInt32(str) * 0.01; + // return number; + //} + + #endregion + + } + + + + + +} diff --git a/JiShe.CollectBus.Common/Extensions/HttpResponseExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/HttpResponseExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/HttpResponseExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/HttpResponseExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/IntExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/IntExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/IntExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/IntExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/ListExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/ListExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/ListExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/ListExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/LockExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/LockExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/LockExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/LockExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/ObjectExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/ObjectExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/ObjectExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/ObjectExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/StreamExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/StreamExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/StreamExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/StreamExtensions.cs diff --git a/JiShe.CollectBus.Common/Extensions/StringExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/StringExtensions.cs similarity index 97% rename from JiShe.CollectBus.Common/Extensions/StringExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/StringExtensions.cs index 0588093..8921f18 100644 --- a/JiShe.CollectBus.Common/Extensions/StringExtensions.cs +++ b/src/JiShe.CollectBus.Common/Extensions/StringExtensions.cs @@ -11,6 +11,7 @@ using System.Text; using System.Text.RegularExpressions; using JiShe.CollectBus.Common.Consts; using JiShe.CollectBus.Common.Enums; +using Newtonsoft.Json; namespace JiShe.CollectBus.Common.Extensions { @@ -1200,6 +1201,19 @@ namespace JiShe.CollectBus.Common.Extensions return false; } + public static List CutStr(this string str, int cutdigit, bool isReverse = false) + { + if (string.IsNullOrWhiteSpace(str)) return null; + if (str.Length % cutdigit != 0) str = "0" + str; + List rlist = new List(); + for (int i = 0; i < str.Length / cutdigit; i++) + { + rlist.Add(str.Substring(i * cutdigit, cutdigit)); + } + if (isReverse) rlist.Reverse(); + return rlist; + } + private static string AddHex33(this string strGet) { string result; @@ -1219,6 +1233,21 @@ namespace JiShe.CollectBus.Common.Extensions return result; } + public static T FromJson(this string strJson) + { + if (string.IsNullOrWhiteSpace(strJson)) + return default(T); + + try + { + return JsonConvert.DeserializeObject(strJson); + } + catch (Exception ex) + { + return default(T); + } + } + private static void CreateAlphaNumMask(StringBuilder buffer, string source, char mask, int length) { for (int i = 0; i < length; i++) diff --git a/JiShe.CollectBus.Common/Extensions/XmlExtensions.cs b/src/JiShe.CollectBus.Common/Extensions/XmlExtensions.cs similarity index 100% rename from JiShe.CollectBus.Common/Extensions/XmlExtensions.cs rename to src/JiShe.CollectBus.Common/Extensions/XmlExtensions.cs diff --git a/JiShe.CollectBus.Common/Helpers/TypeHelper.cs b/src/JiShe.CollectBus.Common/Helpers/TypeHelper.cs similarity index 100% rename from JiShe.CollectBus.Common/Helpers/TypeHelper.cs rename to src/JiShe.CollectBus.Common/Helpers/TypeHelper.cs diff --git a/JiShe.CollectBus.Common/JiShe.CollectBus.Common.csproj b/src/JiShe.CollectBus.Common/JiShe.CollectBus.Common.csproj similarity index 82% rename from JiShe.CollectBus.Common/JiShe.CollectBus.Common.csproj rename to src/JiShe.CollectBus.Common/JiShe.CollectBus.Common.csproj index 4e5a504..8b0b7af 100644 --- a/JiShe.CollectBus.Common/JiShe.CollectBus.Common.csproj +++ b/src/JiShe.CollectBus.Common/JiShe.CollectBus.Common.csproj @@ -18,8 +18,14 @@ + + + + + + diff --git a/JiShe.CollectBus.Common/Jobs/IBaseJob.cs b/src/JiShe.CollectBus.Common/Jobs/IBaseJob.cs similarity index 100% rename from JiShe.CollectBus.Common/Jobs/IBaseJob.cs rename to src/JiShe.CollectBus.Common/Jobs/IBaseJob.cs diff --git a/JiShe.CollectBus.Common/Models/CommandReuslt.cs b/src/JiShe.CollectBus.Common/Models/CommandReuslt.cs similarity index 100% rename from JiShe.CollectBus.Common/Models/CommandReuslt.cs rename to src/JiShe.CollectBus.Common/Models/CommandReuslt.cs diff --git a/JiShe.CollectBus.Common/Models/MessageIssuedEvent.cs b/src/JiShe.CollectBus.Common/Models/IssuedEventMessage.cs similarity index 90% rename from JiShe.CollectBus.Common/Models/MessageIssuedEvent.cs rename to src/JiShe.CollectBus.Common/Models/IssuedEventMessage.cs index bc182d1..45e1a7c 100644 --- a/JiShe.CollectBus.Common/Models/MessageIssuedEvent.cs +++ b/src/JiShe.CollectBus.Common/Models/IssuedEventMessage.cs @@ -2,7 +2,7 @@ namespace JiShe.CollectBus.Common.Models { - public class MessageIssuedEvent + public class IssuedEventMessage { public string ClientId { get; set; } public byte[] Message { get; set; } diff --git a/JiShe.CollectBus.Common/Models/ReqParameter.cs b/src/JiShe.CollectBus.Common/Models/ReqParameter.cs similarity index 58% rename from JiShe.CollectBus.Common/Models/ReqParameter.cs rename to src/JiShe.CollectBus.Common/Models/ReqParameter.cs index 96e2542..1ab3b2e 100644 --- a/JiShe.CollectBus.Common/Models/ReqParameter.cs +++ b/src/JiShe.CollectBus.Common/Models/ReqParameter.cs @@ -87,5 +87,62 @@ namespace JiShe.CollectBus.Common.Models public int UserSubclassNumber { get; set; } } + public class WaterMeterParameter + { + /// + /// 测量点号 0~2040 为0被删除 + /// + public int Pn { get; set; } + /// + /// 波特率600起 1~7 + /// + public int BaudRate { get; set; } + + /// + /// 端口号 1-31 + /// + public int Port { get; set; } + + public CommunicationProtocolType ProtocolType { get; set; } + /// + /// 通信地址 0~999999999999 + /// + public string Address { get; set; } + + /// + /// 通信密码 + /// + public string Password { get; set; } = "000000"; + + /// + /// 费率个数 + /// + public int RateNumber { get; set; } + + /// + /// 整数位个数 0~3 对应4~7位整数 + /// + public int IntegerBitNumber { get; set; } + + /// + /// 小数位个数0~3 对应1~4位小数 + /// + public int DecimalBitNumber { get; set; } + + /// + /// 所属采集器通信地址 + /// + public string CollectorAddress { get; set; } + + /// + /// 用户大类号 0~15 + /// + public int UserCategoryNumber { get; set; } + + /// + /// 用户小类号 0~15 + /// + public int UserSubclassNumber { get; set; } + } } diff --git a/src/JiShe.CollectBus.DbMigrator/CollectBusDbMigratorModule.cs b/src/JiShe.CollectBus.DbMigrator/CollectBusDbMigratorModule.cs new file mode 100644 index 0000000..3767b52 --- /dev/null +++ b/src/JiShe.CollectBus.DbMigrator/CollectBusDbMigratorModule.cs @@ -0,0 +1,14 @@ +using JiShe.CollectBus.MongoDB; +using Volo.Abp.Autofac; +using Volo.Abp.Modularity; + +namespace JiShe.CollectBus.DbMigrator; + +[DependsOn( + typeof(AbpAutofacModule), + typeof(CollectBusMongoDbModule), + typeof(CollectBusApplicationContractsModule) +)] +public class CollectBusDbMigratorModule : AbpModule +{ +} diff --git a/src/JiShe.CollectBus.DbMigrator/DbMigratorHostedService.cs b/src/JiShe.CollectBus.DbMigrator/DbMigratorHostedService.cs new file mode 100644 index 0000000..46f1edb --- /dev/null +++ b/src/JiShe.CollectBus.DbMigrator/DbMigratorHostedService.cs @@ -0,0 +1,51 @@ +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using JiShe.CollectBus.Data; +using Serilog; +using Volo.Abp; +using Volo.Abp.Data; + +namespace JiShe.CollectBus.DbMigrator; + +public class DbMigratorHostedService : IHostedService +{ + private readonly IHostApplicationLifetime _hostApplicationLifetime; + private readonly IConfiguration _configuration; + + public DbMigratorHostedService(IHostApplicationLifetime hostApplicationLifetime, IConfiguration configuration) + { + _hostApplicationLifetime = hostApplicationLifetime; + _configuration = configuration; + } + + public async Task StartAsync(CancellationToken cancellationToken) + { + using (var application = await AbpApplicationFactory.CreateAsync(options => + { + options.Services.ReplaceConfiguration(_configuration); + options.UseAutofac(); + options.Services.AddLogging(c => c.AddSerilog()); + options.AddDataMigrationEnvironment(); + })) + { + await application.InitializeAsync(); + + await application + .ServiceProvider + .GetRequiredService() + .MigrateAsync(); + + await application.ShutdownAsync(); + + _hostApplicationLifetime.StopApplication(); + } + } + + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } +} diff --git a/src/JiShe.CollectBus.DbMigrator/Dockerfile b/src/JiShe.CollectBus.DbMigrator/Dockerfile new file mode 100644 index 0000000..e4602bc --- /dev/null +++ b/src/JiShe.CollectBus.DbMigrator/Dockerfile @@ -0,0 +1,5 @@ +FROM mcr.microsoft.com/dotnet/aspnet:8.0 +COPY bin/Release/net8.0/publish/ app/ +WORKDIR /app +ENV ASPNETCORE_URLS=http://+:80 +ENTRYPOINT ["dotnet", "JiShe.CollectBus.DbMigrator.dll"] \ No newline at end of file diff --git a/src/JiShe.CollectBus.DbMigrator/FodyWeavers.xml b/src/JiShe.CollectBus.DbMigrator/FodyWeavers.xml new file mode 100644 index 0000000..00e1d9a --- /dev/null +++ b/src/JiShe.CollectBus.DbMigrator/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/JiShe.CollectBus.DbMigrator/JiShe.CollectBus.DbMigrator.abppkg b/src/JiShe.CollectBus.DbMigrator/JiShe.CollectBus.DbMigrator.abppkg new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/src/JiShe.CollectBus.DbMigrator/JiShe.CollectBus.DbMigrator.abppkg @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/src/JiShe.CollectBus.DbMigrator/JiShe.CollectBus.DbMigrator.csproj b/src/JiShe.CollectBus.DbMigrator/JiShe.CollectBus.DbMigrator.csproj new file mode 100644 index 0000000..a333f5a --- /dev/null +++ b/src/JiShe.CollectBus.DbMigrator/JiShe.CollectBus.DbMigrator.csproj @@ -0,0 +1,46 @@ + + + + + + Exe + net8.0 + enable + + + + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + Always + + + + PreserveNewest + Always + + + + diff --git a/src/JiShe.CollectBus.DbMigrator/Program.cs b/src/JiShe.CollectBus.DbMigrator/Program.cs new file mode 100644 index 0000000..0efbd99 --- /dev/null +++ b/src/JiShe.CollectBus.DbMigrator/Program.cs @@ -0,0 +1,39 @@ +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Events; + +namespace JiShe.CollectBus.DbMigrator; + +class Program +{ + static async Task Main(string[] args) + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning) +#if DEBUG + .MinimumLevel.Override("JiShe.CollectBus", LogEventLevel.Debug) +#else + .MinimumLevel.Override("JiShe.CollectBus", LogEventLevel.Information) +#endif + .Enrich.FromLogContext() + .WriteTo.Async(c => c.File("Logs/logs.txt")) + .WriteTo.Async(c => c.Console()) + .CreateLogger(); + + await CreateHostBuilder(args).RunConsoleAsync(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .AddAppSettingsSecretsJson() + .ConfigureLogging((context, logging) => logging.ClearProviders()) + .ConfigureServices((hostContext, services) => + { + services.AddHostedService(); + }); +} diff --git a/src/JiShe.CollectBus.DbMigrator/appsettings.json b/src/JiShe.CollectBus.DbMigrator/appsettings.json new file mode 100644 index 0000000..90ea5ae --- /dev/null +++ b/src/JiShe.CollectBus.DbMigrator/appsettings.json @@ -0,0 +1,5 @@ +{ + "ConnectionStrings": { + "Default": "mongodb://admin:collectbus_mongodb_jishe@118.190.144.92:37017/JiSheCollectBus?authSource=admin" + } +} diff --git a/src/JiShe.CollectBus.DbMigrator/appsettings.secrets.json b/src/JiShe.CollectBus.DbMigrator/appsettings.secrets.json new file mode 100644 index 0000000..2c63c08 --- /dev/null +++ b/src/JiShe.CollectBus.DbMigrator/appsettings.secrets.json @@ -0,0 +1,2 @@ +{ +} diff --git a/src/JiShe.CollectBus.Domain.Shared/CollectBusDomainSharedConsts.cs b/src/JiShe.CollectBus.Domain.Shared/CollectBusDomainSharedConsts.cs new file mode 100644 index 0000000..8c06a44 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/CollectBusDomainSharedConsts.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus +{ + public class CollectBusDomainSharedConsts + { + /// 名称空间 + public const string NameSpace = "JiShe.CollectBus"; + /// 默认语言 + public const string DefaultCultureName = "zh-Hans"; + + public const string Basic = "Basic"; + public const string Business = "Business"; + + } +} diff --git a/src/JiShe.CollectBus.Domain.Shared/CollectBusDomainSharedModule.cs b/src/JiShe.CollectBus.Domain.Shared/CollectBusDomainSharedModule.cs new file mode 100644 index 0000000..ad19eb4 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/CollectBusDomainSharedModule.cs @@ -0,0 +1,45 @@ +using Volo.Abp.Modularity; +using Volo.Abp.Localization; +using JiShe.CollectBus.Localization; +using Volo.Abp.Domain; +using Volo.Abp.Localization.ExceptionHandling; +using Volo.Abp.Validation; +using Volo.Abp.Validation.Localization; +using Volo.Abp.VirtualFileSystem; +using JiShe.CollectBus.Interceptors; +using Microsoft.Extensions.DependencyInjection; + +namespace JiShe.CollectBus; + +[DependsOn( + typeof(AbpValidationModule), + typeof(AbpDddDomainSharedModule) +)] +public class CollectBusDomainSharedModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => + { + options.FileSets.AddEmbedded(); + }); + + Configure(options => + { + options.Resources + .Add("en") + .AddBaseTypes(typeof(AbpValidationResource)) + .AddVirtualJson("/Localization/CollectBus"); + }); + + Configure(options => + { + options.MapCodeNamespace("CollectBus", typeof(CollectBusResource)); + }); + } + + public override void PreConfigureServices(ServiceConfigurationContext context) + { + context.Services.OnRegistered(ProtocolInspectInterceptorRegistrar.RegisterIfNeeded); + } +} diff --git a/src/JiShe.CollectBus.Domain.Shared/CollectBusErrorCodes.cs b/src/JiShe.CollectBus.Domain.Shared/CollectBusErrorCodes.cs new file mode 100644 index 0000000..b310a99 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/CollectBusErrorCodes.cs @@ -0,0 +1,7 @@ +namespace JiShe.CollectBus; + +public static class CollectBusErrorCodes +{ + //Add your business exception error codes here... +} + diff --git a/src/JiShe.CollectBus.Domain.Shared/CollectBusGlobalFeatureConfigurator.cs b/src/JiShe.CollectBus.Domain.Shared/CollectBusGlobalFeatureConfigurator.cs new file mode 100644 index 0000000..4b04ece --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/CollectBusGlobalFeatureConfigurator.cs @@ -0,0 +1,19 @@ +using Volo.Abp.Threading; + +namespace JiShe.CollectBus; + +public static class CollectBusGlobalFeatureConfigurator +{ + private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + + public static void Configure() + { + OneTimeRunner.Run(() => + { + /* You can configure (enable/disable) global features of the used modules here. + * Please refer to the documentation to learn more about the Global Features System: + * https://docs.abp.io/en/abp/latest/Global-Features + */ + }); + } +} diff --git a/src/JiShe.CollectBus.Domain.Shared/CollectBusModuleExtensionConfigurator.cs b/src/JiShe.CollectBus.Domain.Shared/CollectBusModuleExtensionConfigurator.cs new file mode 100644 index 0000000..088a2e2 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/CollectBusModuleExtensionConfigurator.cs @@ -0,0 +1,69 @@ +using System.ComponentModel.DataAnnotations; +using Volo.Abp.Threading; + +namespace JiShe.CollectBus; + +public static class CollectBusModuleExtensionConfigurator +{ + private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + + public static void Configure() + { + OneTimeRunner.Run(() => + { + ConfigureExistingProperties(); + ConfigureExtraProperties(); + }); + } + + private static void ConfigureExistingProperties() + { + /* You can change max lengths for properties of the + * entities defined in the modules used by your application. + * + * Example: Change user and role name max lengths + + AbpUserConsts.MaxNameLength = 99; + IdentityRoleConsts.MaxNameLength = 99; + + * Notice: It is not suggested to change property lengths + * unless you really need it. Go with the standard values wherever possible. + * + * If you are using EF Core, you will need to run the add-migration command after your changes. + */ + } + + private static void ConfigureExtraProperties() + { + /* You can configure extra properties for the + * entities defined in the modules used by your application. + * + * This class can be used to define these extra properties + * with a high level, easy to use API. + * + * Example: Add a new property to the user entity of the identity module + + ObjectExtensionManager.Instance.Modules() + .ConfigureIdentity(identity => + { + identity.ConfigureUser(user => + { + user.AddOrUpdateProperty( //property type: string + "SocialSecurityNumber", //property name + property => + { + //validation rules + property.Attributes.Add(new RequiredAttribute()); + property.Attributes.Add(new StringLengthAttribute(64) {MinimumLength = 4}); + + //...other configurations for this property + } + ); + }); + }); + + * See the documentation for more: + * https://docs.abp.io/en/abp/latest/Module-Entity-Extensions + */ + } +} diff --git a/src/JiShe.CollectBus.Domain.Shared/Enums/DeviceStatus.cs b/src/JiShe.CollectBus.Domain.Shared/Enums/DeviceStatus.cs new file mode 100644 index 0000000..982563f --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Enums/DeviceStatus.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Enums +{ + public enum DeviceStatus + { + Unknown = 0, + Online= 1, + Offline= 2, + Blackout = 3 + } +} diff --git a/src/JiShe.CollectBus.Domain.Shared/FodyWeavers.xml b/src/JiShe.CollectBus.Domain.Shared/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectAttribute.cs b/src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectAttribute.cs new file mode 100644 index 0000000..057e966 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectAttribute.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Interceptors +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] + public class ProtocolInspectAttribute : Attribute + { + } +} diff --git a/src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectInterceptor.cs b/src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectInterceptor.cs new file mode 100644 index 0000000..4e06d30 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectInterceptor.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Volo.Abp.DependencyInjection; +using Volo.Abp.DynamicProxy; + +namespace JiShe.CollectBus.Interceptors +{ + public class ProtocolInspectInterceptor : AbpInterceptor, ITransientDependency + { + public override async Task InterceptAsync(IAbpMethodInvocation invocation) + { + await invocation.ProceedAsync(); + } + } +} diff --git a/src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectInterceptorRegistrar.cs b/src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectInterceptorRegistrar.cs new file mode 100644 index 0000000..c56b03b --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Interceptors/ProtocolInspectInterceptorRegistrar.cs @@ -0,0 +1,24 @@ +using Microsoft.Extensions.Options; +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Volo.Abp.DependencyInjection; +using Volo.Abp.DynamicProxy; + +namespace JiShe.CollectBus.Interceptors +{ + public static class ProtocolInspectInterceptorRegistrar + { + public static void RegisterIfNeeded(IOnServiceRegistredContext context) + { + if (context.ImplementationType.GetMethods().Any(a=>a.IsDefined(typeof(ProtocolInspectAttribute), true))) + { + context.Interceptors.TryAdd(); + } + } + } +} diff --git a/JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolInfo.cs b/src/JiShe.CollectBus.Domain.Shared/Interfaces/IProtocolInfo.cs similarity index 91% rename from JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolInfo.cs rename to src/JiShe.CollectBus.Domain.Shared/Interfaces/IProtocolInfo.cs index 35b7998..5fe5d8b 100644 --- a/JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolInfo.cs +++ b/src/JiShe.CollectBus.Domain.Shared/Interfaces/IProtocolInfo.cs @@ -1,4 +1,4 @@ -namespace JiShe.CollectBus.Protocol.Contracts.Interfaces +namespace JiShe.CollectBus.Interfaces { public interface IProtocolInfo { diff --git a/src/JiShe.CollectBus.Domain.Shared/JiShe.CollectBus.Domain.Shared.abppkg b/src/JiShe.CollectBus.Domain.Shared/JiShe.CollectBus.Domain.Shared.abppkg new file mode 100644 index 0000000..8b3de05 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/JiShe.CollectBus.Domain.Shared.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.domain-shared" +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/JiShe.CollectBus.Domain.Shared.csproj b/src/JiShe.CollectBus.Domain.Shared/JiShe.CollectBus.Domain.Shared.csproj new file mode 100644 index 0000000..0552858 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/JiShe.CollectBus.Domain.Shared.csproj @@ -0,0 +1,35 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + true + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/JiShe.CollectBus.Domain.Shared/Jobs/EPICollectArgs.cs b/src/JiShe.CollectBus.Domain.Shared/Jobs/EPICollectArgs.cs new file mode 100644 index 0000000..6684d12 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Jobs/EPICollectArgs.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Jobs +{ + public class EPICollectArgs + { + } +} diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ar.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ar.json new file mode 100644 index 0000000..778f51d --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ar.json @@ -0,0 +1,7 @@ +{ + "culture": "ar", + "texts": { + "MyAccount": "إدارة ملفى", + "SamplePageMessage": "صفحة نموذجية للوحدة النمطية CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/cs.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/cs.json new file mode 100644 index 0000000..c0c0bff --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/cs.json @@ -0,0 +1,7 @@ +{ + "culture": "cs", + "texts": { + "MyAccount": "Spravovat profil", + "SamplePageMessage": "Ukázková stránka pro modul CollectBus" + } +} diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/de.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/de.json new file mode 100644 index 0000000..33b9f87 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/de.json @@ -0,0 +1,7 @@ +{ + "culture": "de", + "texts": { + "MyAccount": "Mein Konto", + "SamplePageMessage": "Eine Beispielseite für das Modul CollectBusModul" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/en-GB.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/en-GB.json new file mode 100644 index 0000000..e2a7ef5 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/en-GB.json @@ -0,0 +1,7 @@ +{ + "culture": "en-GB", + "texts": { + "MyAccount": "My account", + "SamplePageMessage": "A sample page for the CollectBus module" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/en.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/en.json new file mode 100644 index 0000000..1561b3f --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/en.json @@ -0,0 +1,7 @@ +{ + "culture": "en", + "texts": { + "MyAccount": "My account", + "SamplePageMessage": "A sample page for the CollectBus module" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/es.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/es.json new file mode 100644 index 0000000..eb1d221 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/es.json @@ -0,0 +1,7 @@ +{ + "culture": "es", + "texts": { + "MyAccount": "Mi cuenta", + "SamplePageMessage": "Una página de ejemplo para el módulo CollectBus " + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/fi.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/fi.json new file mode 100644 index 0000000..8436dff --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/fi.json @@ -0,0 +1,7 @@ +{ + "culture": "fi", + "texts": { + "MyAccount": "Tilini", + "SamplePageMessage": "Esimerkkisivu CollectBus-moduulille" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/fr.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/fr.json new file mode 100644 index 0000000..1b92eca --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/fr.json @@ -0,0 +1,7 @@ +{ + "culture": "fr", + "texts": { + "MyAccount": "Mon compte", + "SamplePageMessage": "Exemple de page pour le module CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hi.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hi.json new file mode 100644 index 0000000..3f97c37 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hi.json @@ -0,0 +1,7 @@ +{ + "culture": "hi", + "texts": { + "MyAccount": "मेरा खाता", + "SamplePageMessage": "CollectBus मॉड्यूल के लिए एक नमूना पृष्ठ" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hr.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hr.json new file mode 100644 index 0000000..d200516 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hr.json @@ -0,0 +1,7 @@ +{ + "culture": "hr", + "texts": { + "MyAccount": "Moj račun", + "SamplePageMessage": "Ogledna stranica za modul CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hu.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hu.json new file mode 100644 index 0000000..4fdf4cf --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/hu.json @@ -0,0 +1,7 @@ +{ + "culture": "hu", + "texts": { + "MyAccount": "A fiókom", + "SamplePageMessage": "Mintaoldal a CollectBus modulhoz" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/is.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/is.json new file mode 100644 index 0000000..d66087a --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/is.json @@ -0,0 +1,7 @@ +{ + "culture": "is", + "texts": { + "MyAccount": "Minn aðgangur", + "SamplePageMessage": "Dæmi um síðu fyrir CollectBus eininguna" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/it.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/it.json new file mode 100644 index 0000000..b683efb --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/it.json @@ -0,0 +1,7 @@ +{ + "culture": "it", + "texts": { + "MyAccount": "Il mio conto", + "SamplePageMessage": "Una pagina di esempio per il modulo CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/nl.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/nl.json new file mode 100644 index 0000000..4422030 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/nl.json @@ -0,0 +1,7 @@ +{ + "culture": "nl", + "texts": { + "MyAccount": "Mijn rekening", + "SamplePageMessage": "Een voorbeeldpagina voor de CollectBus module" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/pl-PL.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/pl-PL.json new file mode 100644 index 0000000..62c72d6 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/pl-PL.json @@ -0,0 +1,7 @@ +{ + "culture": "pl-PL", + "texts": { + "MyAccount": "Moje konto", + "SamplePageMessage": "Przykładowa strona modułu CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/pt-BR.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/pt-BR.json new file mode 100644 index 0000000..c9779ea --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/pt-BR.json @@ -0,0 +1,7 @@ +{ + "culture": "pt-BR", + "texts": { + "MyAccount": "Minha conta", + "SamplePageMessage": "Uma página de amostra para o módulo CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ro-RO.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ro-RO.json new file mode 100644 index 0000000..5cfdddd --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ro-RO.json @@ -0,0 +1,7 @@ +{ + "culture": "ro-RO", + "texts": { + "MyAccount": "Contul meu", + "SamplePageMessage": "Un exemplu de pagină pentru modululul CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ru.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ru.json new file mode 100644 index 0000000..87c3b4d --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/ru.json @@ -0,0 +1,7 @@ +{ + "culture": "ru", + "texts": { + "MyAccount": "Мой аккаунт", + "SamplePageMessage": "Пример страницы для модуля CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/sk.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/sk.json new file mode 100644 index 0000000..0118aac --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/sk.json @@ -0,0 +1,7 @@ +{ + "culture": "sk", + "texts": { + "MyAccount": "Môj účet", + "SamplePageMessage": "Ukážka stránky pre modul CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/sl.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/sl.json new file mode 100644 index 0000000..ef0f79e --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/sl.json @@ -0,0 +1,7 @@ +{ + "culture": "sl", + "texts": { + "MyAccount": "Moj račun", + "SamplePageMessage": "Vzorčna stran za modul CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/tr.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/tr.json new file mode 100644 index 0000000..a7a6487 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/tr.json @@ -0,0 +1,7 @@ +{ + "culture": "tr", + "texts": { + "MyAccount": "Hesabım", + "SamplePageMessage": "CollectBus modulünden örnek bir sayfa" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/vi.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/vi.json new file mode 100644 index 0000000..4c2e260 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/vi.json @@ -0,0 +1,7 @@ +{ + "culture": "vi", + "texts": { + "MyAccount": "Tài khoản của tôi", + "SamplePageMessage": "Trang mẫu cho mô-đun CollectBus" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/zh-Hans.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/zh-Hans.json new file mode 100644 index 0000000..e660306 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/zh-Hans.json @@ -0,0 +1,7 @@ +{ + "culture": "zh-Hans", + "texts": { + "MyAccount": "我的账户", + "SamplePageMessage": "CollectBus 模块的示例页面" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/zh-Hant.json b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/zh-Hant.json new file mode 100644 index 0000000..374f374 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBus/zh-Hant.json @@ -0,0 +1,7 @@ +{ + "culture": "zh-Hant", + "texts": { + "MyAccount": "我的賬戶", + "SamplePageMessage": "CollectBus 模塊的示例頁面" + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBusResource.cs b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBusResource.cs new file mode 100644 index 0000000..b4bf534 --- /dev/null +++ b/src/JiShe.CollectBus.Domain.Shared/Localization/CollectBusResource.cs @@ -0,0 +1,9 @@ +using Volo.Abp.Localization; + +namespace JiShe.CollectBus.Localization; + +[LocalizationResourceName("CollectBus")] +public class CollectBusResource +{ + +} diff --git a/src/JiShe.CollectBus.Domain/Ammeters/AmmeterInfo.cs b/src/JiShe.CollectBus.Domain/Ammeters/AmmeterInfo.cs new file mode 100644 index 0000000..e9bc4b5 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/Ammeters/AmmeterInfo.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Ammeters +{ + public class AmmeterInfo + { + public int ID { get; set; } + public string Name { get; set; } + public int FocusID { get; set; } + public string Address { get; set; } + public string AreaCode { get; set; } + /// + /// 电表类别 (1单相、2三相三线、3三相四线), + /// 07协议: 开合闸指令(1A开闸断电,1C单相表合闸,1B多相表合闸) 645 2007 表 + /// 97协议://true(合闸);false(跳闸) 545 1997 没有单相多相 之分 "true" ? "9966" : "3355" + /// + public int TypeName { get; set; } + /// + /// 跳合闸状态字段: 0 合闸,1 跳闸 + /// 电表:TripState (0 合闸-通电, 1 断开、跳闸); + /// + public int TripState { get; set; } + /// + /// 规约 -电表default(30) 1:97协议,30:07协议 + /// + public int? Protocol { get; set; } + /// + /// 一个集中器下的[MeteringCode]必须唯一。 PN + /// + public int MeteringCode { get; set; } + /// + /// 电表通信地址 + /// + public string AmmerterAddress { get; set; } + /// + /// 波特率 default(2400) + /// + public int Baudrate { get; set; } + /// + /// MeteringPort 端口就几个可以枚举。 + /// + public int MeteringPort { get; set; } + /// + /// 电表密码 + /// + public string Password { get; set; } + /// + /// 采集时间间隔(分钟,如15) + /// + public int TimeDensity { get; set; } + /// + /// 该电表方案下采集项,如:0D_80 + /// + public string ItemCodes { get; set; } + /// + /// State表状态: + /// 0新装(未下发),1运行(档案下发成功时设置状态值1), 2暂停, 100销表(销表后是否重新启用) + /// 特定:State -1 已删除 + /// + public int State { get; set; } + /// + /// 是否自动采集(0:主动采集,1:自动采集) + /// + public int AutomaticReport { get; set; } + /// + /// 该电表方案下采集项编号 + /// + public string DataTypes { get; set; } + /// + /// 品牌型号 + /// + public string BrandType { get; set; } + /// + /// 采集器编号 + /// + public string GatherCode { get; set; } + /// + /// 是否特殊表 + /// + public int Special { get; set; } + /// + /// 费率类型,单、多 (SingleRate :单费率(单相表1),多费率(其他0) ,与TypeName字段无关) + /// SingleRate ? "单" : "复" + /// [SingleRate] --0 复费率 false , 1 单费率 true (与PayPlanID保持一致) + ///对应 TB_PayPlan.Type: 1复费率,2单费率 + /// + public bool SingleRate { get; set; } + public int ProjectID { get; set; } + /// + /// 是否异常集中器 0:正常,1异常 + /// + public int AbnormalState { get; set; } + public DateTime LastTime { get; set; } + } +} diff --git a/src/JiShe.CollectBus.Domain/CollectBusConsts.cs b/src/JiShe.CollectBus.Domain/CollectBusConsts.cs new file mode 100644 index 0000000..347e522 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/CollectBusConsts.cs @@ -0,0 +1,7 @@ +namespace JiShe.CollectBus; + +public static class CollectBusConsts +{ + public const string DbTablePrefix = "App"; + public const string? DbSchema = null; +} diff --git a/src/JiShe.CollectBus.Domain/CollectBusDbProperties.cs b/src/JiShe.CollectBus.Domain/CollectBusDbProperties.cs new file mode 100644 index 0000000..c2a18d3 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/CollectBusDbProperties.cs @@ -0,0 +1,10 @@ +namespace JiShe.CollectBus; + +public static class CollectBusDbProperties +{ + public static string DbTablePrefix { get; set; } = "JiSheCollectBus"; + + public static string? DbSchema { get; set; } = null; + + public const string MongoDbConnectionStringName = "Default"; +} diff --git a/src/JiShe.CollectBus.Domain/CollectBusDomainModule.cs b/src/JiShe.CollectBus.Domain/CollectBusDomainModule.cs new file mode 100644 index 0000000..64519c7 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/CollectBusDomainModule.cs @@ -0,0 +1,48 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Volo.Abp.Localization; +using Volo.Abp.Modularity; +using Volo.Abp.Caching; +using Volo.Abp.AuditLogging; +using Volo.Abp.BackgroundJobs; +using Volo.Abp.Emailing; + +namespace JiShe.CollectBus; + +[DependsOn( + typeof(CollectBusDomainSharedModule), + typeof(AbpAuditLoggingDomainModule), + typeof(AbpCachingModule), + typeof(AbpBackgroundJobsDomainModule) + )] +public class CollectBusDomainModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => + { + options.Languages.Add(new LanguageInfo("ar", "ar", "العربية")); + options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština")); + options.Languages.Add(new LanguageInfo("en", "en", "English")); + options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)")); + options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar")); + options.Languages.Add(new LanguageInfo("fi", "fi", "Finnish")); + options.Languages.Add(new LanguageInfo("fr", "fr", "Français")); + options.Languages.Add(new LanguageInfo("hi", "hi", "Hindi")); + options.Languages.Add(new LanguageInfo("it", "it", "Italiano")); + options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português")); + options.Languages.Add(new LanguageInfo("ru", "ru", "Русский")); + options.Languages.Add(new LanguageInfo("sk", "sk", "Slovak")); + options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe")); + options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文")); + options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文")); + options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "Deutsch")); + options.Languages.Add(new LanguageInfo("es", "es", "Español")); + }); + + +#if DEBUG + context.Services.Replace(ServiceDescriptor.Singleton()); +#endif + } +} diff --git a/src/JiShe.CollectBus.Domain/Data/CollectBusDbMigrationService.cs b/src/JiShe.CollectBus.Domain/Data/CollectBusDbMigrationService.cs new file mode 100644 index 0000000..4adb041 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/Data/CollectBusDbMigrationService.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Volo.Abp.Data; +using Volo.Abp.DependencyInjection; + +namespace JiShe.CollectBus.Data; + +public class CollectBusDbMigrationService : ITransientDependency +{ + public ILogger Logger { get; set; } + + private readonly IDataSeeder _dataSeeder; + private readonly IEnumerable _dbSchemaMigrators; + + public CollectBusDbMigrationService( + IDataSeeder dataSeeder, + IEnumerable dbSchemaMigrators) + { + _dataSeeder = dataSeeder; + _dbSchemaMigrators = dbSchemaMigrators; + + Logger = NullLogger.Instance; + } + + public async Task MigrateAsync() + { + + Logger.LogInformation("Started database migrations..."); + + await MigrateDatabaseSchemaAsync(); + await SeedDataAsync(); + + Logger.LogInformation($"Successfully completed host database migrations."); + Logger.LogInformation("Successfully completed all database migrations."); + Logger.LogInformation("You can safely end this process..."); + } + + private async Task MigrateDatabaseSchemaAsync() + { + Logger.LogInformation( + $"Migrating schema for host database..."); + + foreach (var migrator in _dbSchemaMigrators) + { + await migrator.MigrateAsync(); + } + } + + private async Task SeedDataAsync() + { + Logger.LogInformation($"Executing host database seed..."); + } +} diff --git a/src/JiShe.CollectBus.Domain/Data/ICollectBusDbSchemaMigrator.cs b/src/JiShe.CollectBus.Domain/Data/ICollectBusDbSchemaMigrator.cs new file mode 100644 index 0000000..65442ff --- /dev/null +++ b/src/JiShe.CollectBus.Domain/Data/ICollectBusDbSchemaMigrator.cs @@ -0,0 +1,8 @@ +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Data; + +public interface ICollectBusDbSchemaMigrator +{ + Task MigrateAsync(); +} diff --git a/src/JiShe.CollectBus.Domain/Data/NullCollectBusDbSchemaMigrator.cs b/src/JiShe.CollectBus.Domain/Data/NullCollectBusDbSchemaMigrator.cs new file mode 100644 index 0000000..9d911b4 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/Data/NullCollectBusDbSchemaMigrator.cs @@ -0,0 +1,15 @@ +using System.Threading.Tasks; +using Volo.Abp.DependencyInjection; + +namespace JiShe.CollectBus.Data; + +/* This is used if database provider does't define + * ICollectBusDbSchemaMigrator implementation. + */ +public class NullCollectBusDbSchemaMigrator : ICollectBusDbSchemaMigrator, ITransientDependency +{ + public Task MigrateAsync() + { + return Task.CompletedTask; + } +} diff --git a/src/JiShe.CollectBus.Domain/Devices/Device.cs b/src/JiShe.CollectBus.Domain/Devices/Device.cs new file mode 100644 index 0000000..8dcf886 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/Devices/Device.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using JiShe.CollectBus.Enums; +using Volo.Abp.Domain.Entities; + +namespace JiShe.CollectBus.Devices +{ + public class Device : AggregateRoot + { + /// + /// Device + /// + /// + /// + /// + /// + /// + public Device(string number, string clientId, DateTime firstOnlineTime, DateTime lastOnlineTime, DeviceStatus status) + { + Number = number; + FirstOnlineTime = firstOnlineTime; + LastOnlineTime = lastOnlineTime; + ClientId = clientId; + Status = status; + } + + public string Number { get; set; } + + public DateTime FirstOnlineTime { get; set; } + + public DateTime LastOnlineTime { get; set; } + + public string ClientId { get; set; } + + public DateTime? LastOfflineTime { get; set; } + + public DeviceStatus Status { get; set; } + + public void UpdateByLoginAndHeartbeat(string clientId) + { + LastOnlineTime = DateTime.Now; + ClientId = clientId; + Status = DeviceStatus.Online; + } + + public void UpdateByOnClosed() + { + LastOfflineTime = DateTime.Now; + Status = DeviceStatus.Offline; + } + } +} diff --git a/src/JiShe.CollectBus.Domain/FodyWeavers.xml b/src/JiShe.CollectBus.Domain/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain/JiShe - Backup.CollectBus.Domain.csproj b/src/JiShe.CollectBus.Domain/JiShe - Backup.CollectBus.Domain.csproj new file mode 100644 index 0000000..2b48ee7 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/JiShe - Backup.CollectBus.Domain.csproj @@ -0,0 +1,32 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/JiShe.CollectBus.Domain/JiShe.CollectBus.Domain.abppkg b/src/JiShe.CollectBus.Domain/JiShe.CollectBus.Domain.abppkg new file mode 100644 index 0000000..1d574ef --- /dev/null +++ b/src/JiShe.CollectBus.Domain/JiShe.CollectBus.Domain.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.domain" +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Domain/JiShe.CollectBus.Domain.csproj b/src/JiShe.CollectBus.Domain/JiShe.CollectBus.Domain.csproj new file mode 100644 index 0000000..ae1b120 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/JiShe.CollectBus.Domain.csproj @@ -0,0 +1,29 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + + + + + + + + + + + + + + + + + + + + + diff --git a/src/JiShe.CollectBus.Domain/MessageIssueds/MessageIssued.cs b/src/JiShe.CollectBus.Domain/MessageIssueds/MessageIssued.cs new file mode 100644 index 0000000..45f53b1 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/MessageIssueds/MessageIssued.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using JiShe.CollectBus.Common.Enums; + +namespace JiShe.CollectBus.MessageIssueds +{ + public class MessageIssued + { + public string ClientId { get; set; } + public byte[] Message { get; set; } + public string DeviceNo { get; set; } + public IssuedEventType Type { get; set; } + public string MessageId { get; set; } + } +} diff --git a/JiShe.CollectBus.Common/Interfaces/IReceived.cs b/src/JiShe.CollectBus.Domain/MessageReceiveds/IReceived.cs similarity index 64% rename from JiShe.CollectBus.Common/Interfaces/IReceived.cs rename to src/JiShe.CollectBus.Domain/MessageReceiveds/IReceived.cs index 3650fde..40c6a68 100644 --- a/JiShe.CollectBus.Common/Interfaces/IReceived.cs +++ b/src/JiShe.CollectBus.Domain/MessageReceiveds/IReceived.cs @@ -1,4 +1,4 @@ -namespace JiShe.CollectBus.Common.Interfaces +namespace JiShe.CollectBus.MessageReceiveds { public interface IReceived { diff --git a/JiShe.CollectBus.Common/Models/MessageReceivedEvent.cs b/src/JiShe.CollectBus.Domain/MessageReceiveds/MessageReceived.cs similarity index 80% rename from JiShe.CollectBus.Common/Models/MessageReceivedEvent.cs rename to src/JiShe.CollectBus.Domain/MessageReceiveds/MessageReceived.cs index 4cbe5a7..4503873 100644 --- a/JiShe.CollectBus.Common/Models/MessageReceivedEvent.cs +++ b/src/JiShe.CollectBus.Domain/MessageReceiveds/MessageReceived.cs @@ -1,8 +1,9 @@ -using JiShe.CollectBus.Common.Interfaces; +using System; +using Volo.Abp.Domain.Entities; -namespace JiShe.CollectBus.Common.Models +namespace JiShe.CollectBus.MessageReceiveds { - public class MessageReceivedEvent:IReceived + public class MessageReceived: AggregateRoot,IReceived { public string MessageId { get; set; } = string.Empty; /// @@ -36,14 +37,14 @@ namespace JiShe.CollectBus.Common.Models public string ReceivedTime { get; set; } = string.Empty; } - public class MessageReceivedLoginEvent: MessageReceivedEvent + public class MessageReceivedLogin: MessageReceived { public bool IsAck { get; set; } = false; public DateTime? AckTime { get; set; } } - public class MessageReceivedHeartbeatEvent : MessageReceivedEvent + public class MessageReceivedHeartbeat : MessageReceived { public bool IsAck { get; set; } = false; diff --git a/src/JiShe.CollectBus.Domain/PrepayModel/Vi_BaseAmmeterInfo.cs b/src/JiShe.CollectBus.Domain/PrepayModel/Vi_BaseAmmeterInfo.cs new file mode 100644 index 0000000..2990b1e --- /dev/null +++ b/src/JiShe.CollectBus.Domain/PrepayModel/Vi_BaseAmmeterInfo.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.PrepayModel +{ + /// + /// 预付费电表视图模型 + /// + public partial class Vi_BaseAmmeterInfo + { + public int ID { get; set; } + public string BarCode { get; set; } + public string Address { get; set; } + public string BaudRate { get; set; } + public string Password { get; set; } + public string Explan { get; set; } + public System.DateTime AddTime { get; set; } + public bool State { get; set; } + public int TB_EquipmentTypeID { get; set; } + public int BaseID { get; set; } + public string Code { get; set; } + public Nullable MeterCode { get; set; } + public Nullable PortNumber { get; set; } + public int CT { get; set; } + public bool SoftTripsLock { get; set; } + public bool HardwareTripsLock { get; set; } + public bool ValveState { get; set; } + public bool ArchivesState { get; set; } + public Nullable SortNumber { get; set; } + public decimal Balance { get; set; } + public bool IsAlarm { get; set; } + public string sysExplan { get; set; } + public System.DateTime sysAddTime { get; set; } + public bool sysState { get; set; } + public Nullable TB_sysConcentratorID { get; set; } + public Nullable TB_sysChargingSchemeID { get; set; } + public Nullable TB_sysChargingSchemeID1 { get; set; } + public int TB_CustomerID { get; set; } + public Nullable TB_sysAlarmPlanID { get; set; } + public Nullable TB_sysCollectorID { get; set; } + public Nullable TB_sysRoomID { get; set; } + public string SpecialNoCode { get; set; } + public Nullable RatedCurrent { get; set; } + public Nullable TripDelayTime { get; set; } + public Nullable ClosingTime { get; set; } + public Nullable Remainder { get; set; } + public Nullable RatedPower { get; set; } + public Nullable ParentAmmState { get; set; } + public Nullable ParentAmmID { get; set; } + public Nullable LastUpdateTime { get; set; } + public Nullable IsAuthentication { get; set; } + public Nullable IsShowBalance { get; set; } + public string Number { get; set; } + public Nullable LastAuthTime { get; set; } + public Nullable IsAuthenticationFunction { get; set; } + public Nullable IsShowBalanceFunction { get; set; } + public int TB_ProtocolID { get; set; } + public string Operator { get; set; } + public Nullable IsTimingPowerSetting { get; set; } + public string CommSchemeCode { get; set; } + public string RoomAllName { get; set; } + public Nullable IsLadderPrice { get; set; } + public Nullable LadderNum { get; set; } + public Nullable RoomBalance { get; set; } + public Nullable OtherBalance { get; set; } + public Nullable LastValveEventType { get; set; } + public Nullable ReadKwh4 { get; set; } + public Nullable ReadKwh3 { get; set; } + public Nullable ReadKwh2 { get; set; } + public Nullable ReadKwh1 { get; set; } + public Nullable ReadKwh { get; set; } + public Nullable LastEventTime { get; set; } + public Nullable LastReadTime { get; set; } + public string RoomNumber { get; set; } + public string EquipmentName { get; set; } + public Nullable EquipmentId { get; set; } + public Nullable IsMalignantLoad { get; set; } + public string BrandName { get; set; } + public Nullable MalignantPower { get; set; } + public Nullable MalignantPowerState { get; set; } + public Nullable RatedPowerState { get; set; } + public string SolveStatus { get; set; } + public Nullable PowerDownStatus { get; set; } + public Nullable SolveStatusTime { get; set; } + public decimal DisableKwh { get; set; } + public Nullable IsDeliver { get; set; } + public Nullable HandleUser { get; set; } + public string HandleUserName { get; set; } + public string Solutions { get; set; } + public decimal DisableKwh1 { get; set; } + public decimal DisableKwh2 { get; set; } + public decimal DisableKwh3 { get; set; } + public decimal DisableKwh4 { get; set; } + public bool DelaySwitchOff { get; set; } + public string MeterSolveStatus { get; set; } + public Nullable DeliverTime { get; set; } + public bool EnableState { get; set; } + public string DxNbiotDeviceId { get; set; } + public int MeterStatus { get; set; } + public string AllowTripTime { get; set; } + public Nullable LastCostMilliSecond { get; set; } + public string DxNbiotIMEI { get; set; } + public Nullable ReadKwh5 { get; set; } + public Nullable ReadKwh6 { get; set; } + public Nullable ReadKwh7 { get; set; } + public Nullable ReadKwh8 { get; set; } + public Nullable DisableKwh5 { get; set; } + public Nullable DisableKwh6 { get; set; } + public Nullable DisableKwh7 { get; set; } + public Nullable DisableKwh8 { get; set; } + public Nullable IsLadder { get; set; } + public Nullable TimeSpanSetNum { get; set; } + public string ExecutePeriod { get; set; } + public string FreqInterval { get; set; } + public Nullable Tb_sysUseValueAlarmID { get; set; } + public Nullable IsMaxDemandKwh { get; set; } + public Nullable OnLineTime { get; set; } + public Nullable OperatorId { get; set; } + public int PowerCT { get; set; } + public string CommunicationsModule { get; set; } + public Nullable CanBlueTooth { get; set; } + public Nullable CanRemote { get; set; } + public Nullable IsDownPrice { get; set; } + public Nullable BuyCount { get; set; } + } +} diff --git a/src/JiShe.CollectBus.Domain/Properties/AssemblyInfo.cs b/src/JiShe.CollectBus.Domain/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..b923739 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; +[assembly:InternalsVisibleToAttribute("JiShe.CollectBus.Domain.Tests")] +[assembly:InternalsVisibleToAttribute("JiShe.CollectBus.TestBase")] diff --git a/JiShe.CollectBus.Protocol.Contracts/Models/ProtocolInfo.cs b/src/JiShe.CollectBus.Domain/Protocols/ProtocolInfo.cs similarity index 67% rename from JiShe.CollectBus.Protocol.Contracts/Models/ProtocolInfo.cs rename to src/JiShe.CollectBus.Domain/Protocols/ProtocolInfo.cs index ff09e2d..4ae8572 100644 --- a/JiShe.CollectBus.Protocol.Contracts/Models/ProtocolInfo.cs +++ b/src/JiShe.CollectBus.Domain/Protocols/ProtocolInfo.cs @@ -1,9 +1,19 @@ -using JiShe.CollectBus.Protocol.Contracts.Interfaces; +using System; +using JiShe.CollectBus.Interfaces; +using Volo.Abp.Domain.Entities; -namespace JiShe.CollectBus.Protocol.Contracts.Models +namespace JiShe.CollectBus.Protocols { - public class ProtocolInfo : IProtocolInfo + public class ProtocolInfo : AggregateRoot, IProtocolInfo { + /// + /// + /// + /// + /// + /// + /// + /// public ProtocolInfo(string name, string baseProtocol, string type, string description, string regularExpression) { Name = name; diff --git a/src/JiShe.CollectBus.Domain/Settings/CollectBusSettingDefinitionProvider.cs b/src/JiShe.CollectBus.Domain/Settings/CollectBusSettingDefinitionProvider.cs new file mode 100644 index 0000000..ca394f8 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/Settings/CollectBusSettingDefinitionProvider.cs @@ -0,0 +1,12 @@ +using Volo.Abp.Settings; + +namespace JiShe.CollectBus.Settings; + +public class CollectBusSettingDefinitionProvider : SettingDefinitionProvider +{ + public override void Define(ISettingDefinitionContext context) + { + //Define your own settings here. Example: + //context.Add(new SettingDefinition(CollectBusSettings.MySetting1)); + } +} diff --git a/src/JiShe.CollectBus.Domain/Settings/CollectBusSettings.cs b/src/JiShe.CollectBus.Domain/Settings/CollectBusSettings.cs new file mode 100644 index 0000000..c395669 --- /dev/null +++ b/src/JiShe.CollectBus.Domain/Settings/CollectBusSettings.cs @@ -0,0 +1,9 @@ +namespace JiShe.CollectBus.Settings; + +public static class CollectBusSettings +{ + private const string Prefix = "CollectBus"; + + //Add your own setting names here. Example: + //public const string MySetting1 = Prefix + ".MySetting1"; +} diff --git a/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusDbContext.cs b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusDbContext.cs new file mode 100644 index 0000000..bf57b27 --- /dev/null +++ b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusDbContext.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore; +using Volo.Abp.Data; +using Volo.Abp.EntityFrameworkCore; + +namespace JiShe.CollectBus.EntityFrameworkCore; + +[ConnectionStringName("Default")] +public class CollectBusDbContext : + AbpDbContext +{ + /* Add DbSet properties for your Aggregate Roots / Entities here. */ + + + #region Entities from the modules + + /* Notice: We only implemented IIdentityProDbContext and ISaasDbContext + * and replaced them for this DbContext. This allows you to perform JOIN + * queries for the entities of these modules over the repositories easily. You + * typically don't need that for other modules. But, if you need, you can + * implement the DbContext interface of the needed module and use ReplaceDbContext + * attribute just like IIdentityProDbContext and ISaasDbContext. + * + * More info: Replacing a DbContext of a module ensures that the related module + * uses this DbContext on runtime. Otherwise, it will use its own DbContext class. + */ + + #endregion + + public CollectBusDbContext(DbContextOptions options) + : base(options) + { + + } + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + } +} diff --git a/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusDbContextFactory.cs b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusDbContextFactory.cs new file mode 100644 index 0000000..07cc790 --- /dev/null +++ b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusDbContextFactory.cs @@ -0,0 +1,33 @@ +using System; +using System.IO; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.Extensions.Configuration; + +namespace JiShe.CollectBus.EntityFrameworkCore; + +/* This class is needed for EF Core console commands + * (like Add-Migration and Update-Database commands) */ +public class CollectBusDbContextFactory : IDesignTimeDbContextFactory +{ + public CollectBusDbContext CreateDbContext(string[] args) + { + var configuration = BuildConfiguration(); + + CollectBusEfCoreEntityExtensionMappings.Configure(); + + var builder = new DbContextOptionsBuilder() + .UseMySql(configuration.GetConnectionString("Default"), MySqlServerVersion.LatestSupportedServerVersion); + + return new CollectBusDbContext(builder.Options); + } + + private static IConfigurationRoot BuildConfiguration() + { + var builder = new ConfigurationBuilder() + .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../JiShe.CollectBus.DbMigrator/")) + .AddJsonFile("appsettings.json", optional: false); + + return builder.Build(); + } +} diff --git a/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusEfCoreEntityExtensionMappings.cs b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusEfCoreEntityExtensionMappings.cs new file mode 100644 index 0000000..8f002f3 --- /dev/null +++ b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusEfCoreEntityExtensionMappings.cs @@ -0,0 +1,44 @@ +using Microsoft.EntityFrameworkCore; +using Volo.Abp.Identity; +using Volo.Abp.ObjectExtending; +using Volo.Abp.Threading; + +namespace JiShe.CollectBus.EntityFrameworkCore; + +public static class CollectBusEfCoreEntityExtensionMappings +{ + private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + + public static void Configure() + { + CollectBusGlobalFeatureConfigurator.Configure(); + CollectBusModuleExtensionConfigurator.Configure(); + + OneTimeRunner.Run(() => + { + /* You can configure extra properties for the + * entities defined in the modules used by your application. + * + * This class can be used to map these extra properties to table fields in the database. + * + * USE THIS CLASS ONLY TO CONFIGURE EF CORE RELATED MAPPING. + * USE CollectBusModuleExtensionConfigurator CLASS (in the Domain.Shared project) + * FOR A HIGH LEVEL API TO DEFINE EXTRA PROPERTIES TO ENTITIES OF THE USED MODULES + * + * Example: Map a property to a table field: + + ObjectExtensionManager.Instance + .MapEfCoreProperty( + "MyProperty", + (entityBuilder, propertyBuilder) => + { + propertyBuilder.HasMaxLength(128); + } + ); + + * See the documentation for more: + * https://docs.abp.io/en/abp/latest/Customizing-Application-Modules-Extending-Entities + */ + }); + } +} diff --git a/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusEntityFrameworkCoreModule.cs b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusEntityFrameworkCoreModule.cs new file mode 100644 index 0000000..bb34e67 --- /dev/null +++ b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/CollectBusEntityFrameworkCoreModule.cs @@ -0,0 +1,50 @@ +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.AuditLogging.EntityFrameworkCore; +using Volo.Abp.BackgroundJobs.EntityFrameworkCore; +using Volo.Abp.EntityFrameworkCore; +using Volo.Abp.EntityFrameworkCore.MySQL; +using Volo.Abp.FeatureManagement.EntityFrameworkCore; +using Volo.Abp.Identity.EntityFrameworkCore; +using Volo.Abp.Modularity; +using Volo.Abp.PermissionManagement.EntityFrameworkCore; +using Volo.Abp.SettingManagement.EntityFrameworkCore; +using Volo.Abp.BlobStoring.Database.EntityFrameworkCore; + +namespace JiShe.CollectBus.EntityFrameworkCore; + +[DependsOn( + typeof(CollectBusDomainModule), + typeof(AbpPermissionManagementEntityFrameworkCoreModule), + typeof(AbpSettingManagementEntityFrameworkCoreModule), + typeof(AbpEntityFrameworkCoreMySQLModule), + typeof(AbpBackgroundJobsEntityFrameworkCoreModule), + typeof(AbpAuditLoggingEntityFrameworkCoreModule), + typeof(AbpFeatureManagementEntityFrameworkCoreModule), + typeof(AbpIdentityEntityFrameworkCoreModule), + typeof(BlobStoringDatabaseEntityFrameworkCoreModule) + )] +public class CollectBusEntityFrameworkCoreModule : AbpModule +{ + public override void PreConfigureServices(ServiceConfigurationContext context) + { + + CollectBusEfCoreEntityExtensionMappings.Configure(); + } + + public override void ConfigureServices(ServiceConfigurationContext context) + { + context.Services.AddAbpDbContext(options => + { + /* Remove "includeAllEntities: true" to create + * default repositories only for aggregate roots */ + options.AddDefaultRepositories(includeAllEntities: true); + }); + + Configure(options => + { + /* The main point to change your DBMS. + * See also CollectBusDbContextFactory for EF Core tooling. */ + options.UseMySQL(); + }); + } +} diff --git a/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/EntityFrameworkCoreCollectBusDbSchemaMigrator.cs b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/EntityFrameworkCoreCollectBusDbSchemaMigrator.cs new file mode 100644 index 0000000..2b3509a --- /dev/null +++ b/src/JiShe.CollectBus.EntityFrameworkCore/EntityFrameworkCore/EntityFrameworkCoreCollectBusDbSchemaMigrator.cs @@ -0,0 +1,33 @@ +using System; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using JiShe.CollectBus.Data; +using Volo.Abp.DependencyInjection; + +namespace JiShe.CollectBus.EntityFrameworkCore; + +public class EntityFrameworkCoreCollectBusDbSchemaMigrator + : ICollectBusDbSchemaMigrator, ITransientDependency +{ + private readonly IServiceProvider _serviceProvider; + + public EntityFrameworkCoreCollectBusDbSchemaMigrator(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + public async Task MigrateAsync() + { + /* We intentionally resolving the CollectBusDbContext + * from IServiceProvider (instead of directly injecting it) + * to properly get the connection string of the current tenant in the + * current scope. + */ + + await _serviceProvider + .GetRequiredService() + .Database + .MigrateAsync(); + } +} diff --git a/src/JiShe.CollectBus.EntityFrameworkCore/FodyWeavers.xml b/src/JiShe.CollectBus.EntityFrameworkCore/FodyWeavers.xml new file mode 100644 index 0000000..00e1d9a --- /dev/null +++ b/src/JiShe.CollectBus.EntityFrameworkCore/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.abppkg b/src/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.abppkg new file mode 100644 index 0000000..e1c64f0 --- /dev/null +++ b/src/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.ef" +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.csproj b/src/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.csproj new file mode 100644 index 0000000..e6a6338 --- /dev/null +++ b/src/JiShe.CollectBus.EntityFrameworkCore/JiShe.CollectBus.EntityFrameworkCore.csproj @@ -0,0 +1,40 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + + + + + + + + + + + + + + + + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers + compile; contentFiles; build; buildMultitargeting; buildTransitive; analyzers; native + + + + diff --git a/src/JiShe.CollectBus.EntityFrameworkCore/Properties/AssemblyInfo.cs b/src/JiShe.CollectBus.EntityFrameworkCore/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..23df7c8 --- /dev/null +++ b/src/JiShe.CollectBus.EntityFrameworkCore/Properties/AssemblyInfo.cs @@ -0,0 +1,2 @@ +using System.Runtime.CompilerServices; +[assembly:InternalsVisibleToAttribute("JiShe.CollectBus.EntityFrameworkCore.Tests")] diff --git a/src/JiShe.CollectBus.FreeSql/CollectBusFreeSqlModule.cs b/src/JiShe.CollectBus.FreeSql/CollectBusFreeSqlModule.cs new file mode 100644 index 0000000..309e22c --- /dev/null +++ b/src/JiShe.CollectBus.FreeSql/CollectBusFreeSqlModule.cs @@ -0,0 +1,14 @@ +using FreeSql; +using FreeSql.SqlServer; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.Modularity; + +namespace JiShe.CollectBus.FreeSql +{ + public class CollectBusFreeSqlModule : AbpModule + { + public override void ConfigureServices(ServiceConfigurationContext context) + { + } + } +} diff --git a/src/JiShe.CollectBus.FreeSql/DbEnum.cs b/src/JiShe.CollectBus.FreeSql/DbEnum.cs new file mode 100644 index 0000000..81bb094 --- /dev/null +++ b/src/JiShe.CollectBus.FreeSql/DbEnum.cs @@ -0,0 +1,23 @@ +namespace JiShe.CollectBus.FreeSql +{ + /// + /// 数据库枚举 + /// + public enum DbEnum + { + /// + /// 微服务默认数据库,MySQL + /// + Default, + + /// + /// 预付费数据库,SQLSERVER + /// + PrepayDB, + + /// + /// 能耗数据库,SQLSERVER + /// + EnergyDB + } +} diff --git a/src/JiShe.CollectBus.FreeSql/FreeSqlProvider.cs b/src/JiShe.CollectBus.FreeSql/FreeSqlProvider.cs new file mode 100644 index 0000000..e7e7191 --- /dev/null +++ b/src/JiShe.CollectBus.FreeSql/FreeSqlProvider.cs @@ -0,0 +1,37 @@ +using FreeSql; +using Microsoft.Extensions.Configuration; +using Volo.Abp.DependencyInjection; + +namespace JiShe.CollectBus.FreeSql +{ + public class FreeSqlProvider : IFreeSqlProvider, ISingletonDependency + { + /// + /// Initializes a new instance of the class. + /// + /// The configuration. + public FreeSqlProvider(IConfiguration configuration) + { + GetInstance(configuration); + } + + public FreeSqlCloud Instance { get; set; } = new(); + public FreeSqlCloud GetInstance(IConfiguration configuration) + { + Instance = new FreeSqlCloud + { + DistributeTrace = log => Console.WriteLine(log.Split('\n')[0].Trim()) + }; + + Instance.Register(DbEnum.EnergyDB, () => new FreeSqlBuilder() + .UseConnectionString(DataType.SqlServer, configuration.GetConnectionString(DbEnum.EnergyDB.ToString())) + .Build()); + + Instance.Register(DbEnum.PrepayDB, () => new FreeSqlBuilder() + .UseConnectionString(DataType.SqlServer, configuration.GetConnectionString(DbEnum.PrepayDB.ToString())) + .Build()); + return Instance; + } + + } +} diff --git a/src/JiShe.CollectBus.FreeSql/IFreeSqlProvider.cs b/src/JiShe.CollectBus.FreeSql/IFreeSqlProvider.cs new file mode 100644 index 0000000..e4250d6 --- /dev/null +++ b/src/JiShe.CollectBus.FreeSql/IFreeSqlProvider.cs @@ -0,0 +1,12 @@ +using FreeSql; + +namespace JiShe.CollectBus.FreeSql +{ + /// + /// FreeSqlProvider服务 + /// + public interface IFreeSqlProvider + { + FreeSqlCloud Instance { get; set; } + } +} diff --git a/src/JiShe.CollectBus.FreeSql/JiShe.CollectBus.FreeSql.csproj b/src/JiShe.CollectBus.FreeSql/JiShe.CollectBus.FreeSql.csproj new file mode 100644 index 0000000..9b40553 --- /dev/null +++ b/src/JiShe.CollectBus.FreeSql/JiShe.CollectBus.FreeSql.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/src/JiShe.CollectBus.Host/CollectBusHostConst.cs b/src/JiShe.CollectBus.Host/CollectBusHostConst.cs new file mode 100644 index 0000000..4df4b8d --- /dev/null +++ b/src/JiShe.CollectBus.Host/CollectBusHostConst.cs @@ -0,0 +1,16 @@ +namespace JiShe.CollectBus.Host +{ + public static class CollectBusHostConst + { + /// + /// 跨域策略名 + /// + public const string DefaultCorsPolicyName = "Default"; + + /// + /// Cookies名称 + /// + public const string DefaultCookieName = "JiShe.CollectBus.Host"; + + } +} diff --git a/src/JiShe.CollectBus.Host/CollectBusHostModule.Configure.cs b/src/JiShe.CollectBus.Host/CollectBusHostModule.Configure.cs new file mode 100644 index 0000000..1f306f8 --- /dev/null +++ b/src/JiShe.CollectBus.Host/CollectBusHostModule.Configure.cs @@ -0,0 +1,336 @@ +using System.Text; +using Hangfire; +using Hangfire.Redis.StackExchange; +using JiShe.CollectBus.Host.Hangfire; +using JiShe.CollectBus.Host.Swaggers; +using MassTransit; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.IdentityModel.Tokens; +using Microsoft.OpenApi.Models; +using StackExchange.Redis; +using Volo.Abp.AspNetCore.Auditing; +using Volo.Abp.Auditing; +using Volo.Abp.BackgroundJobs; +using Volo.Abp.Caching; +using Volo.Abp.Modularity; +using TouchSocket.Core; +using TouchSocket.Sockets; +using JiShe.CollectBus.Plugins; +using JiShe.CollectBus.Consumers; +using JiShe.CollectBus.MessageReceiveds; +using JiShe.CollectBus.Protocol.Contracts; + + +namespace JiShe.CollectBus.Host +{ + public partial class CollectBusHostModule + { + /// + /// Configures the hangfire. + /// + /// The context. + private void ConfigureHangfire(ServiceConfigurationContext context) + { + var redisStorageOptions = new RedisStorageOptions() + { + Db = context.Services.GetConfiguration().GetValue("Redis:HangfireDB") + }; + + Configure(options => { options.IsJobExecutionEnabled = true; }); + + context.Services.AddHangfire(config => + { + config.UseRedisStorage( + context.Services.GetConfiguration().GetValue("Redis:Configuration"), redisStorageOptions) + .WithJobExpirationTimeout(TimeSpan.FromDays(7)); + var delaysInSeconds = new[] { 10, 60, 60 * 3 }; // 重试时间间隔 + const int Attempts = 3; // 重试次数 + config.UseFilter(new AutomaticRetryAttribute() { Attempts = Attempts, DelaysInSeconds = delaysInSeconds }); + //config.UseFilter(new AutoDeleteAfterSuccessAttribute(TimeSpan.FromDays(7))); + config.UseFilter(new JobRetryLastFilter(Attempts)); + }); + context.Services.AddHangfireServer(); + } + + /// + /// Configures the JWT authentication. + /// + /// The context. + /// The configuration. + private void ConfigureJwtAuthentication(ServiceConfigurationContext context, IConfiguration configuration) + { + context.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(options => + { + options.TokenValidationParameters = + new TokenValidationParameters() + { + // 是否开启签名认证 + ValidateIssuerSigningKey = true, + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero, + ValidIssuer = configuration["Jwt:Issuer"], + ValidAudience = configuration["Jwt:Audience"], + IssuerSigningKey = + new SymmetricSecurityKey( + Encoding.ASCII.GetBytes(configuration["Jwt:SecurityKey"])) + }; + + options.Events = new JwtBearerEvents + { + OnMessageReceived = currentContext => + { + var path = currentContext.HttpContext.Request.Path; + if (path.StartsWithSegments("/login")) + { + return Task.CompletedTask; + } + + var accessToken = string.Empty; + if (currentContext.HttpContext.Request.Headers.ContainsKey("Authorization")) + { + accessToken = currentContext.HttpContext.Request.Headers["Authorization"]; + if (!string.IsNullOrWhiteSpace(accessToken)) + { + accessToken = accessToken.Split(" ").LastOrDefault(); + } + } + + if (string.IsNullOrWhiteSpace(accessToken)) + { + accessToken = currentContext.Request.Query["access_token"].FirstOrDefault(); + } + + if (string.IsNullOrWhiteSpace(accessToken)) + { + accessToken = currentContext.Request.Cookies[@CollectBusHostConst.DefaultCookieName]; + } + + currentContext.Token = accessToken; + currentContext.Request.Headers.Remove("Authorization"); + currentContext.Request.Headers.Add("Authorization", $"Bearer {accessToken}"); + + return Task.CompletedTask; + } + }; + }); + } + + /// + /// Configures the cache. + /// + /// The context. + private void ConfigureCache(ServiceConfigurationContext context) + { + Configure( + options => { options.KeyPrefix = "CollectBus:"; }); + var configuration = context.Services.GetConfiguration(); + var redis = ConnectionMultiplexer.Connect($"{configuration.GetValue("Redis:Configuration")},defaultdatabase={configuration.GetValue("Redis:DefaultDB")}"); + context.Services + .AddDataProtection() + .PersistKeysToStackExchangeRedis(redis, "CollectBus-Protection-Keys"); + } + + /// + /// Configures the swagger services. + /// + /// The context. + /// The configuration. + private void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration) + { + context.Services.AddSwaggerGen( + options => + { + configuration.GetSection("SwaggerConfig").Get>()?.ForEach(group => + { + options.SwaggerDoc(group.GroupName, + new OpenApiInfo { Title = group.Title, Version = group.Version }); + }); + + options.DocInclusionPredicate((docName, apiDes) => + { + if (docName == "Basic" && string.IsNullOrWhiteSpace(apiDes.GroupName)) return true; + return docName == apiDes.GroupName; + }); + + options.EnableAnnotations(); + options.DocumentFilter(); + options.SchemaFilter(); + var xmlPaths = Directory.GetFiles(AppContext.BaseDirectory, "*.xml") + .Where(a => a.EndsWith("Application.xml") || + a.EndsWith("Application.Contracts.xml") || + a.EndsWith("httpApi.xml") || + a.EndsWith("Host.xml")) + .Distinct() + .ToList(); + foreach (var xml in xmlPaths) options.IncludeXmlComments(xml, true); + }); + } + + /// + /// Configures the audit log. + /// + /// The context. + private void ConfigureAuditLog(ServiceConfigurationContext context) + { + Configure + ( + options => + { + options.IsEnabled = true; + options.EntityHistorySelectors.AddAllEntities(); + options.ApplicationName = "JiShe.CollectBus"; + } + ); + + Configure( + options => + { + options.IgnoredUrls.Add("/AuditLogs/page"); + options.IgnoredUrls.Add("/hangfire/stats"); + options.IgnoredUrls.Add("/hangfire/recurring/trigger"); + options.IgnoredUrls.Add("/cap"); + options.IgnoredUrls.Add("/"); + }); + } + + + /// + /// Configures the custom. + /// + /// The context. + /// The configuration. + private void ConfigureCustom(ServiceConfigurationContext context, IConfiguration configuration) + { + context.Services.AddSingleton(); + context.Services.AddHealthChecks(); + } + + /// + /// Configures the network. + /// + /// The context. + /// The configuration. + public void ConfigureNetwork(ServiceConfigurationContext context, IConfiguration configuration) + { + context.Services.AddTcpService(config => + { + config.SetListenIPHosts(int.Parse(configuration["TCP:ClientPort"] ?? "10500")) + //.SetTcpDataHandlingAdapter(()=>new StandardFixedHeaderDataHandlingAdapter()) + .ConfigurePlugins(a => + { + a.Add(); + a.Add(); + a.Add(); + }); + }); + + context.Services.AddUdpSession(config => + { + config.SetBindIPHost(int.Parse(configuration["UDP:ClientPort"] ?? "10500")) + .ConfigurePlugins(a => + { + a.Add(); + a.Add(); + }) + .UseBroadcast() + .SetUdpDataHandlingAdapter(() => new NormalUdpDataHandlingAdapter()); + }); + } + + /// + /// Configures the cap. + /// + /// The context. + /// The configuration. + public void ConfigureCap(ServiceConfigurationContext context, IConfiguration configuration) + { + context.Services.AddCap(x => + { + x.DefaultGroupName = ProtocolConst.SubscriberGroup; + var connectionStr = configuration.GetConnectionString(CollectBusDbProperties.MongoDbConnectionStringName); + x.UseMongoDB(connectionStr); //MongoDB 4.0+ cluster + var kafka = configuration.GetConnectionString("Kafka"); + x.UseKafka(option => + { + option.Servers = kafka; + }); + + x.UseDashboard(); + x.FailedRetryInterval = 10; + x.FailedRetryCount = 5; + }); + + } + + /// + /// Configures the mass transit. + /// + /// The context. + /// The configuration. + public void ConfigureMassTransit(ServiceConfigurationContext context, IConfiguration configuration) + { + context.Services.AddMassTransit(x => + { + x.UsingInMemory(); + + x.AddConfigureEndpointsCallback((c, name, cfg) => + { + cfg.UseDelayedRedelivery(r => r.Intervals(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(30))); + cfg.UseMessageRetry(r => r.Immediate(5)); + cfg.UseInMemoryOutbox(c); + }); + + x.AddRider(rider => + { + rider.AddConsumer(); + rider.AddConsumer(); + rider.AddConsumer(); + rider.AddConsumer(cfg => + { + cfg.Options(options => options + .SetMessageLimit(100) + .SetTimeLimit(s: 1) + .SetTimeLimitStart(BatchTimeLimitStart.FromLast) + .SetConcurrencyLimit(10)); + }); + rider.UsingKafka((c, cfg) => + { + cfg.Host(configuration.GetConnectionString("Kafka")); + + cfg.TopicEndpoint(ProtocolConst.SubscriberReceivedHeartbeatEventName, ProtocolConst.SubscriberGroup, configurator => + { + configurator.ConfigureConsumer(c); + configurator.ConfigureConsumeTopology = false; + }); + + cfg.TopicEndpoint(ProtocolConst.SubscriberReceivedLoginEventName, ProtocolConst.SubscriberGroup, configurator => + { + configurator.ConfigureConsumer(c); + configurator.ConfigureConsumeTopology = false; + }); + + cfg.TopicEndpoint(ProtocolConst.SubscriberReceivedEventName, ProtocolConst.SubscriberGroup, configurator => + { + configurator.ConfigureConsumer(c); + configurator.ConfigureConsumeTopology = false; + }); + + cfg.TopicEndpoint(ProtocolConst.SubscriberIssuedEventName, ProtocolConst.SubscriberGroup, configurator => + { + configurator.ConfigureConsumer(c); + configurator.ConfigureConsumeTopology = false; + }); + }); + }); + }); + } + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.Host/CollectBusHostModule.cs b/src/JiShe.CollectBus.Host/CollectBusHostModule.cs new file mode 100644 index 0000000..4af190f --- /dev/null +++ b/src/JiShe.CollectBus.Host/CollectBusHostModule.cs @@ -0,0 +1,94 @@ +using Hangfire; +using JiShe.CollectBus.Host.HealthChecks; +using JiShe.CollectBus.Host.Swaggers; +using JiShe.CollectBus.MongoDB; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Swashbuckle.AspNetCore.SwaggerUI; +using Volo.Abp; +using Volo.Abp.AspNetCore.Authentication.JwtBearer; +using Volo.Abp.AspNetCore.Serilog; +using Volo.Abp.Autofac; +using Volo.Abp.BackgroundWorkers.Hangfire; +using Volo.Abp.Caching.StackExchangeRedis; +using Volo.Abp.Modularity; +using Volo.Abp.Swashbuckle; + +namespace JiShe.CollectBus.Host +{ + /// + /// + /// + [DependsOn(typeof(CollectBusHttpApiModule), + typeof(AbpAutofacModule), + typeof(AbpAspNetCoreAuthenticationJwtBearerModule), + typeof(AbpAspNetCoreSerilogModule), + typeof(AbpSwashbuckleModule), + typeof(CollectBusApplicationModule), + typeof(CollectBusMongoDbModule), + typeof(AbpCachingStackExchangeRedisModule), + typeof(AbpBackgroundWorkersHangfireModule) + )] + public partial class CollectBusHostModule : AbpModule + { + /// + /// ConfigureServices + /// + /// + public override void ConfigureServices(ServiceConfigurationContext context) + { + var configuration = context.Services.GetConfiguration(); + ConfigureCache(context); + ConfigureSwaggerServices(context, configuration); + ConfigureNetwork(context, configuration); + ConfigureJwtAuthentication(context, configuration); + ConfigureHangfire(context); + ConfigureCap(context, configuration); + //ConfigureMassTransit(context, configuration); + ConfigureAuditLog(context); + ConfigureCustom(context, configuration); + } + + + /// + /// OnApplicationInitialization + /// + /// + public override void OnApplicationInitialization(ApplicationInitializationContext context) + { + var app = context.GetApplicationBuilder(); + var configuration = context.GetConfiguration(); + var env = context.GetEnvironment(); + app.UseCorrelationId(); + app.UseStaticFiles(); + app.UseRouting(); + app.UseCors(CollectBusHostConst.DefaultCorsPolicyName); + app.UseAuthentication(); + app.UseAuthorization(); + if (env.IsDevelopment()) + { + app.UseSwagger(); + app.UseAbpSwaggerUI(options => + { + configuration.GetSection("SwaggerConfig").Get>()?.ForEach(group => + { + options.SwaggerEndpoint($"/swagger/{group.GroupName}/swagger.json", group.Title); //分组显示 + }); + options.DocExpansion(DocExpansion.None); + options.DefaultModelsExpandDepth(-1); + }); + } + app.UseAuditing(); + app.UseAbpSerilogEnrichers(); + app.UseUnitOfWork(); + app.UseConfiguredEndpoints(endpoints => + { + endpoints.MapHealthChecks("/health", new HealthCheckOptions + { + Predicate = _ => true, + ResponseWriter = HealthCheckResponse.Writer + }); + }); + app.UseHangfireDashboard(); + } + } +} diff --git a/src/JiShe.CollectBus.Host/Controllers/WeatherForecastController.cs b/src/JiShe.CollectBus.Host/Controllers/WeatherForecastController.cs new file mode 100644 index 0000000..986c33b --- /dev/null +++ b/src/JiShe.CollectBus.Host/Controllers/WeatherForecastController.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Mvc; + +namespace JiShe.CollectBus.Host.Controllers +{ + [ApiController] + [Route("[controller]")] + public class WeatherForecastController : ControllerBase + { + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet(Name = "GetWeatherForecast")] + public IEnumerable Get() + { + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } + } +} diff --git a/JiShe.CollectBus.Console/Extensions/ServiceCollections/ServiceCollectionExtensions.cs b/src/JiShe.CollectBus.Host/Extensions/ServiceCollections/ServiceCollectionExtensions.cs similarity index 100% rename from JiShe.CollectBus.Console/Extensions/ServiceCollections/ServiceCollectionExtensions.cs rename to src/JiShe.CollectBus.Host/Extensions/ServiceCollections/ServiceCollectionExtensions.cs diff --git a/src/JiShe.CollectBus.Host/Hangfire/JobRetryLastFilter.cs b/src/JiShe.CollectBus.Host/Hangfire/JobRetryLastFilter.cs new file mode 100644 index 0000000..5e5d869 --- /dev/null +++ b/src/JiShe.CollectBus.Host/Hangfire/JobRetryLastFilter.cs @@ -0,0 +1,29 @@ +using Hangfire.Common; +using Hangfire.States; +using Serilog; + +namespace JiShe.CollectBus.Host.Hangfire +{ + /// + /// 重试最后一次 + /// + public class JobRetryLastFilter : JobFilterAttribute, IElectStateFilter + { + private int RetryCount { get; } + + public JobRetryLastFilter(int retryCount) + { + RetryCount = retryCount; + } + + + public void OnStateElection(ElectStateContext context) + { + var retryAttempt = context.GetJobParameter("RetryCount"); + if (RetryCount == retryAttempt) + { + Log.Error("最后一次重试"); + } + } + } +} diff --git a/src/JiShe.CollectBus.Host/HealthChecks/HealthCheckResponse.cs b/src/JiShe.CollectBus.Host/HealthChecks/HealthCheckResponse.cs new file mode 100644 index 0000000..d326ef9 --- /dev/null +++ b/src/JiShe.CollectBus.Host/HealthChecks/HealthCheckResponse.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Newtonsoft.Json; + +namespace JiShe.CollectBus.Host.HealthChecks +{ + public class HealthCheckResponse + { + public static Task Writer(HttpContext context, HealthReport healthReport) + { + context.Response.ContentType = "application/json"; + + var result = JsonConvert.SerializeObject(new + { + status = healthReport.Status.ToString(), + errors = healthReport.Entries.Select(e => new + { + key = e.Key, + value = e.Value.Status.ToString() + }) + }); + return context.Response.WriteAsync(result); + + } + } +} diff --git a/src/JiShe.CollectBus.Host/JiShe.CollectBus.Host.csproj b/src/JiShe.CollectBus.Host/JiShe.CollectBus.Host.csproj new file mode 100644 index 0000000..5a549e5 --- /dev/null +++ b/src/JiShe.CollectBus.Host/JiShe.CollectBus.Host.csproj @@ -0,0 +1,67 @@ + + + + net8.0 + enable + enable + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/JiShe.CollectBus.Console/Plugins/ignore.txt b/src/JiShe.CollectBus.Host/Plugins/ignore.txt similarity index 100% rename from JiShe.CollectBus.Console/Plugins/ignore.txt rename to src/JiShe.CollectBus.Host/Plugins/ignore.txt diff --git a/src/JiShe.CollectBus.Host/Program.cs b/src/JiShe.CollectBus.Host/Program.cs new file mode 100644 index 0000000..40a13cc --- /dev/null +++ b/src/JiShe.CollectBus.Host/Program.cs @@ -0,0 +1,41 @@ +using JiShe.CollectBus.Host; +using Microsoft.AspNetCore.Hosting; +using Serilog; + +public class Program +{ + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + private static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseSerilog((context, loggerConfiguration) => + { + loggerConfiguration.ReadFrom.Configuration(context.Configuration); + }) + .UseAutofac() + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + + + + private static IHostBuilder CreateConsoleHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureServices((hostContext, services) => { ConfigureServices(services, hostContext); }) + .UseAutofac() + .UseSerilog((context, loggerConfiguration) => + { + loggerConfiguration.ReadFrom.Configuration(context.Configuration); + }); + + + private static void ConfigureServices(IServiceCollection services, HostBuilderContext hostContext) + { + services.AddApplication(); + } +} \ No newline at end of file diff --git a/JiShe.CollectBus.Host/Properties/launchSettings.json b/src/JiShe.CollectBus.Host/Properties/launchSettings.json similarity index 82% rename from JiShe.CollectBus.Host/Properties/launchSettings.json rename to src/JiShe.CollectBus.Host/Properties/launchSettings.json index de025ab..cf8c7cb 100644 --- a/JiShe.CollectBus.Host/Properties/launchSettings.json +++ b/src/JiShe.CollectBus.Host/Properties/launchSettings.json @@ -4,25 +4,17 @@ "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { - "applicationUrl": "http://localhost:15225", - "sslPort": 44348 + "applicationUrl": "http://localhost:38293", + "sslPort": 44329 } }, "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, "http": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "swagger", - "applicationUrl": "http://localhost:5000", + "applicationUrl": "http://localhost:5063", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -32,7 +24,15 @@ "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "swagger", - "applicationUrl": "https://localhost:7219;http://localhost:5000", + "applicationUrl": "https://localhost:7232;http://localhost:5063", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/src/JiShe.CollectBus.Host/Startup.cs b/src/JiShe.CollectBus.Host/Startup.cs new file mode 100644 index 0000000..223e6d9 --- /dev/null +++ b/src/JiShe.CollectBus.Host/Startup.cs @@ -0,0 +1,31 @@ +using Volo.Abp.Modularity.PlugIns; + +namespace JiShe.CollectBus.Host +{ + public class Startup + { + private readonly IConfiguration _configuration; + + public Startup(IConfiguration configuration) + { + _configuration = configuration; + } + + + public void ConfigureServices(IServiceCollection services) + { + services.AddApplication(options => + { + // 加载插件,固定模式,可热插拔 + options.PlugInSources.AddFolder(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins")); + }); + + //services.AddApplication(); + } + + public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime) + { + app.InitializeApplication(); + } + } +} diff --git a/src/JiShe.CollectBus.Host/Swaggers/EnumSchemaFilter.cs b/src/JiShe.CollectBus.Host/Swaggers/EnumSchemaFilter.cs new file mode 100644 index 0000000..7b40d74 --- /dev/null +++ b/src/JiShe.CollectBus.Host/Swaggers/EnumSchemaFilter.cs @@ -0,0 +1,24 @@ +using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Interfaces; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace JiShe.CollectBus.Host.Swaggers +{ + /// + /// swagger 枚举映射, + /// 原因:前端代理生成枚举是数字 + /// + public class EnumSchemaFilter : ISchemaFilter + { + public void Apply(OpenApiSchema schema, SchemaFilterContext context) + { + if (!context.Type.IsEnum) + return; + OpenApiArray openApiArray = new OpenApiArray(); + openApiArray.AddRange((IEnumerable)Enum.GetNames(context.Type).Select(n => new OpenApiString(n))); + schema.Extensions.Add("x-enumNames", openApiArray); + schema.Extensions.Add("x-enum-varnames", openApiArray); + } + } +} diff --git a/src/JiShe.CollectBus.Host/Swaggers/HiddenAbpDefaultApiFilter.cs b/src/JiShe.CollectBus.Host/Swaggers/HiddenAbpDefaultApiFilter.cs new file mode 100644 index 0000000..be322a5 --- /dev/null +++ b/src/JiShe.CollectBus.Host/Swaggers/HiddenAbpDefaultApiFilter.cs @@ -0,0 +1,54 @@ +using System.Reflection; +using Microsoft.AspNetCore.Mvc.ApiExplorer; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace JiShe.CollectBus.Host.Swaggers +{ + /// + /// 在使用nswag的时候,原生默认的api导致生产的代理类存在问题 + /// 所有隐藏原生的api,重写路由 + /// + public class HiddenAbpDefaultApiFilter : IDocumentFilter + { + public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) + { + foreach (ApiDescription apiDescription in context.ApiDescriptions) + { + if (apiDescription.TryGetMethodInfo(out MethodInfo _)) + { + string key = "/" + apiDescription.RelativePath; + if (IsHidden(key)) + swaggerDoc.Paths.Remove(key); + } + } + } + + private bool IsHidden(string key) + { + foreach (string hiddenAbpDefaultApi in GetHiddenAbpDefaultApiList()) + { + if (key.Contains(hiddenAbpDefaultApi)) + return true; + } + return false; + } + + private List GetHiddenAbpDefaultApiList() + { + return new List() + { + "/api/abp/multi-tenancy/tenants", + "/api/account", + "/api/feature-management/features", + "/api/permission-management/permissions", + "/api/identity/my-profile", + "/api/identity", + "/api/multi-tenancy/tenants", + "/api/setting-management/emailing", + "/configuration", + "/outputcache" + }; + } + } +} diff --git a/src/JiShe.CollectBus.Host/Swaggers/SwaggerConfig.cs b/src/JiShe.CollectBus.Host/Swaggers/SwaggerConfig.cs new file mode 100644 index 0000000..9a0f695 --- /dev/null +++ b/src/JiShe.CollectBus.Host/Swaggers/SwaggerConfig.cs @@ -0,0 +1,11 @@ +namespace JiShe.CollectBus.Host.Swaggers +{ + public class SwaggerConfig + { + public string GroupName { get; set; } + + public string Title { get; set; } + + public string Version { get; set; } + } +} diff --git a/src/JiShe.CollectBus.Host/WeatherForecast.cs b/src/JiShe.CollectBus.Host/WeatherForecast.cs new file mode 100644 index 0000000..137fed8 --- /dev/null +++ b/src/JiShe.CollectBus.Host/WeatherForecast.cs @@ -0,0 +1,13 @@ +namespace JiShe.CollectBus.Host +{ + public class WeatherForecast + { + public DateOnly Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string? Summary { get; set; } + } +} diff --git a/JiShe.CollectBus.Host/appsettings.Development.json b/src/JiShe.CollectBus.Host/appsettings.Development.json similarity index 100% rename from JiShe.CollectBus.Host/appsettings.Development.json rename to src/JiShe.CollectBus.Host/appsettings.Development.json diff --git a/src/JiShe.CollectBus.Host/appsettings.json b/src/JiShe.CollectBus.Host/appsettings.json new file mode 100644 index 0000000..d39bfa8 --- /dev/null +++ b/src/JiShe.CollectBus.Host/appsettings.json @@ -0,0 +1,84 @@ + { + "Serilog": { + "Using": [ + "Serilog.Sinks.Console", + "Serilog.Sinks.File" + ], + "MinimumLevel": { + "Default": "Information", + "Override": { + "Microsoft": "Information", + "Volo.Abp": "Warning", + "Hangfire": "Information", + "DotNetCore.CAP": "Warning", + "Serilog.AspNetCore": "Information", + "Microsoft.EntityFrameworkCore": "Warning", + "Microsoft.AspNetCore": "Warning" + } + }, + "WriteTo": [ + { + "Name": "Console" + }, + { + "Name": "File", + "Args": { + "path": "logs/logs-.txt", + "rollingInterval": "Day" + } + } + ] + }, + "App": { + "SelfUrl": "http://localhost:44315", + "CorsOrigins": "http://localhost:4200,http://localhost:3100" + }, + "ConnectionStrings": { + "Default": "mongodb://admin:admin02023@118.190.144.92:37117,118.190.144.92:37119,118.190.144.92:3712/JiSheCollectBus?authSource=admin", + "Kafka": "118.190.144.92:29092,118.190.144.92:39092,118.190.144.92:49092", + "PrepayDB": "server=118.190.144.92;database=jishe.sysdb;uid=sa;pwd=admin@2023;Encrypt=False;Trust Server Certificate=False", + "EnergyDB": "server=118.190.144.92;database=db_energy;uid=sa;pwd=admin@2023;Encrypt=False;Trust Server Certificate=False" + }, + "Redis": { + "Configuration": "118.190.144.92:6381,syncTimeout=30000,abortConnect=false,connectTimeout=30000,allowAdmin=true", + "DefaultDB": "4", + "HangfireDB": "5" + }, + "Jwt": { + "Audience": "JiShe.CollectBus", + "SecurityKey": "dzehzRz9a8asdfasfdadfasdfasdfafsdadfasbasdf=", + "Issuer": "JiShe.CollectBus", + "ExpirationTime": 2 + }, + "HealthCheck": { + "IsEnable": true, + "MySql": { + "IsEnable": true + }, + "Pings": { + "IsEnable": true, + "Host": "https://www.baidu.com/", + "TimeOut": 5000 + } + }, + "SwaggerConfig": [ + { + "GroupName": "Basic", + "Title": "【后台管理】基础模块", + "Version": "V1" + }, + { + "GroupName": "Business", + "Title": "【后台管理】业务模块", + "Version": "V1" + } + ], + "Cap": { + "RabbitMq": { + "HostName": "118.190.144.92", + "UserName": "collectbus", + "Password": "123456", + "Port": 5672 + } + } +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.HttpApi/CollectBusController.cs b/src/JiShe.CollectBus.HttpApi/CollectBusController.cs new file mode 100644 index 0000000..0124c24 --- /dev/null +++ b/src/JiShe.CollectBus.HttpApi/CollectBusController.cs @@ -0,0 +1,12 @@ +using JiShe.CollectBus.Localization; +using Volo.Abp.AspNetCore.Mvc; + +namespace JiShe.CollectBus; + +public abstract class CollectBusController : AbpControllerBase +{ + protected CollectBusController() + { + LocalizationResource = typeof(CollectBusResource); + } +} diff --git a/src/JiShe.CollectBus.HttpApi/CollectBusHttpApiModule.cs b/src/JiShe.CollectBus.HttpApi/CollectBusHttpApiModule.cs new file mode 100644 index 0000000..d1a068a --- /dev/null +++ b/src/JiShe.CollectBus.HttpApi/CollectBusHttpApiModule.cs @@ -0,0 +1,40 @@ +using Localization.Resources.AbpUi; +using JiShe.CollectBus.Localization; +using Volo.Abp.AspNetCore.Mvc; +using Volo.Abp.Localization; +using Volo.Abp.Modularity; +using Microsoft.Extensions.DependencyInjection; + +namespace JiShe.CollectBus; + +[DependsOn( + typeof(CollectBusApplicationModule), + typeof(CollectBusApplicationContractsModule), + typeof(AbpAspNetCoreMvcModule) + )] +public class CollectBusHttpApiModule : AbpModule +{ + public override void PreConfigureServices(ServiceConfigurationContext context) + { + PreConfigure(mvcBuilder => + { + mvcBuilder.AddApplicationPartIfNotExists(typeof(CollectBusHttpApiModule).Assembly); + }); + + Configure(options => + { + options.ConventionalControllers + .Create(typeof(CollectBusApplicationModule).Assembly); + }); + } + + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => + { + options.Resources + .Get() + .AddBaseTypes(typeof(AbpUiResource)); + }); + } +} diff --git a/src/JiShe.CollectBus.HttpApi/FodyWeavers.xml b/src/JiShe.CollectBus.HttpApi/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/src/JiShe.CollectBus.HttpApi/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/JiShe.CollectBus.HttpApi/JiShe.CollectBus.HttpApi.abppkg b/src/JiShe.CollectBus.HttpApi/JiShe.CollectBus.HttpApi.abppkg new file mode 100644 index 0000000..515bfe6 --- /dev/null +++ b/src/JiShe.CollectBus.HttpApi/JiShe.CollectBus.HttpApi.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.http-api" +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.HttpApi/JiShe.CollectBus.HttpApi.csproj b/src/JiShe.CollectBus.HttpApi/JiShe.CollectBus.HttpApi.csproj new file mode 100644 index 0000000..d5ecd25 --- /dev/null +++ b/src/JiShe.CollectBus.HttpApi/JiShe.CollectBus.HttpApi.csproj @@ -0,0 +1,23 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + True + + + + + + + + + + + + + + diff --git a/src/JiShe.CollectBus.HttpApi/Samples/SampleController.cs b/src/JiShe.CollectBus.HttpApi/Samples/SampleController.cs new file mode 100644 index 0000000..1e26430 --- /dev/null +++ b/src/JiShe.CollectBus.HttpApi/Samples/SampleController.cs @@ -0,0 +1,33 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Volo.Abp; + +namespace JiShe.CollectBus.Samples; + +[Area(CollectBusRemoteServiceConsts.ModuleName)] +[RemoteService(Name = CollectBusRemoteServiceConsts.RemoteServiceName)] +[Route("api/CollectBus/sample")] +public class SampleController : CollectBusController, ISampleAppService +{ + private readonly ISampleAppService _sampleAppService; + + public SampleController(ISampleAppService sampleAppService) + { + _sampleAppService = sampleAppService; + } + + [HttpGet] + public async Task GetAsync() + { + return await _sampleAppService.GetAsync(); + } + + [HttpGet] + [Route("authorized")] + [Authorize] + public async Task GetAuthorizedAsync() + { + return await _sampleAppService.GetAsync(); + } +} diff --git a/src/JiShe.CollectBus.MongoDB/FodyWeavers.xml b/src/JiShe.CollectBus.MongoDB/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/src/JiShe.CollectBus.MongoDB/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.abppkg b/src/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.abppkg new file mode 100644 index 0000000..8b23fd1 --- /dev/null +++ b/src/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.mongodb" +} \ No newline at end of file diff --git a/src/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.csproj b/src/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.csproj new file mode 100644 index 0000000..fcb97fa --- /dev/null +++ b/src/JiShe.CollectBus.MongoDB/JiShe.CollectBus.MongoDB.csproj @@ -0,0 +1,23 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + + + + + + + + + + + + + + + diff --git a/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusDbSchemaMigrator.cs b/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusDbSchemaMigrator.cs new file mode 100644 index 0000000..28dbd19 --- /dev/null +++ b/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusDbSchemaMigrator.cs @@ -0,0 +1,52 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using JiShe.CollectBus.Data; +using Microsoft.Extensions.DependencyInjection; +using MongoDB.Driver; +using Volo.Abp.Data; +using Volo.Abp.DependencyInjection; +using Volo.Abp.MongoDB; +using Volo.Abp.MultiTenancy; + +namespace JiShe.CollectBus.MongoDB +{ + public class CollectBusDbSchemaMigrator : ICollectBusDbSchemaMigrator, ITransientDependency + { + private readonly IServiceProvider _serviceProvider; + + public CollectBusDbSchemaMigrator(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + public async Task MigrateAsync() + { + var dbContexts = _serviceProvider.GetServices(); + var connectionStringResolver = _serviceProvider.GetRequiredService(); + + if (_serviceProvider.GetRequiredService().IsAvailable) + { + dbContexts = dbContexts.Where(x => !x.GetType().IsDefined(typeof(IgnoreMultiTenancyAttribute))); + } + + foreach (var dbContext in dbContexts) + { + var connectionString = + await connectionStringResolver.ResolveAsync( + ConnectionStringNameAttribute.GetConnStringName(dbContext.GetType())); + var mongoUrl = new MongoUrl(connectionString); + var databaseName = mongoUrl.DatabaseName; + var client = new MongoClient(mongoUrl); + + if (databaseName.IsNullOrWhiteSpace()) + { + databaseName = ConnectionStringNameAttribute.GetConnStringName(dbContext.GetType()); + } + + (dbContext as AbpMongoDbContext)?.InitializeCollections(client.GetDatabase(databaseName)); + } + } + } +} diff --git a/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbContext.cs b/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbContext.cs new file mode 100644 index 0000000..890a29f --- /dev/null +++ b/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbContext.cs @@ -0,0 +1,31 @@ +using JiShe.CollectBus.Devices; +using JiShe.CollectBus.MessageReceiveds; +using JiShe.CollectBus.Protocols; +using MongoDB.Driver; +using Volo.Abp.Data; +using Volo.Abp.MongoDB; +using Volo.Abp.MultiTenancy; + +namespace JiShe.CollectBus.MongoDB; + +[IgnoreMultiTenancy] +[ConnectionStringName(CollectBusDbProperties.MongoDbConnectionStringName)] +public class CollectBusMongoDbContext : AbpMongoDbContext, ICollectBusMongoDbContext +{ + /* Add mongo collections here. Example: + * public IMongoCollection Questions => Collection(); + */ + + public IMongoCollection MessageReceiveds => Collection(); + public IMongoCollection MessageReceivedLogins => Collection(); + public IMongoCollection MessageReceivedHeartbeats => Collection(); + public IMongoCollection Devices => Collection(); + public IMongoCollection ProtocolInfos => Collection(); + + protected override void CreateModel(IMongoModelBuilder modelBuilder) + { + base.CreateModel(modelBuilder); + + modelBuilder.ConfigureCollectBus(); + } +} diff --git a/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbContextExtensions.cs b/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbContextExtensions.cs new file mode 100644 index 0000000..891bfb5 --- /dev/null +++ b/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbContextExtensions.cs @@ -0,0 +1,13 @@ +using Volo.Abp; +using Volo.Abp.MongoDB; + +namespace JiShe.CollectBus.MongoDB; + +public static class CollectBusMongoDbContextExtensions +{ + public static void ConfigureCollectBus( + this IMongoModelBuilder builder) + { + Check.NotNull(builder, nameof(builder)); + } +} diff --git a/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbModule.cs b/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbModule.cs new file mode 100644 index 0000000..37f9377 --- /dev/null +++ b/src/JiShe.CollectBus.MongoDB/MongoDB/CollectBusMongoDbModule.cs @@ -0,0 +1,31 @@ +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.AuditLogging.MongoDB; +using Volo.Abp.BackgroundJobs.MongoDB; +using Volo.Abp.Modularity; +using Volo.Abp.MongoDB; +using Volo.Abp.Uow; + +namespace JiShe.CollectBus.MongoDB; + +[DependsOn( + typeof(CollectBusDomainModule), + typeof(AbpMongoDbModule), + typeof(AbpBackgroundJobsMongoDbModule), + typeof(AbpAuditLoggingMongoDbModule) + )] +public class CollectBusMongoDbModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + context.Services.AddMongoDbContext(options => + { + options.AddDefaultRepositories(); + }); + + context.Services.AddAlwaysDisableUnitOfWorkTransaction(); + Configure(options => + { + options.TransactionBehavior = UnitOfWorkTransactionBehavior.Disabled; + }); + } +} diff --git a/src/JiShe.CollectBus.MongoDB/MongoDB/ICollectBusMongoDbContext.cs b/src/JiShe.CollectBus.MongoDB/MongoDB/ICollectBusMongoDbContext.cs new file mode 100644 index 0000000..2b554be --- /dev/null +++ b/src/JiShe.CollectBus.MongoDB/MongoDB/ICollectBusMongoDbContext.cs @@ -0,0 +1,12 @@ +using Volo.Abp.Data; +using Volo.Abp.MongoDB; + +namespace JiShe.CollectBus.MongoDB; + +[ConnectionStringName(CollectBusDbProperties.MongoDbConnectionStringName)] +public interface ICollectBusMongoDbContext : IAbpMongoDbContext +{ + /* Define mongo collections here. Example: + * IMongoCollection Questions { get; } + */ +} diff --git a/JiShe.CollectBus.Protocol.Contracts/Abstracts/BaseProtocolPlugin.cs b/src/JiShe.CollectBus.Protocol.Contracts/Abstracts/BaseProtocolPlugin.cs similarity index 52% rename from JiShe.CollectBus.Protocol.Contracts/Abstracts/BaseProtocolPlugin.cs rename to src/JiShe.CollectBus.Protocol.Contracts/Abstracts/BaseProtocolPlugin.cs index 6243016..c5d09a8 100644 --- a/JiShe.CollectBus.Protocol.Contracts/Abstracts/BaseProtocolPlugin.cs +++ b/src/JiShe.CollectBus.Protocol.Contracts/Abstracts/BaseProtocolPlugin.cs @@ -1,36 +1,72 @@ -using JiShe.CollectBus.Common.Enums; +using System.Globalization; +using DotNetCore.CAP; +using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Extensions; using JiShe.CollectBus.Common.Models; +using JiShe.CollectBus.MessageReceiveds; using JiShe.CollectBus.Protocol.Contracts.Interfaces; -using JiShe.CollectBus.Protocol.Contracts.Models; +using JiShe.CollectBus.Protocols; using Microsoft.Extensions.Logging; +using System.Linq; +using JiShe.CollectBus.Protocol.Contracts.Models; +using Volo.Abp.Domain.Repositories; +using System; namespace JiShe.CollectBus.Protocol.Contracts.Abstracts { - public abstract class BaseProtocolPlugin(ILogger logger) : IProtocolPlugin + public abstract class BaseProtocolPlugin : IProtocolPlugin { - + private readonly ICapPublisher _capBus; + private readonly ILogger _logger; + private readonly IRepository _protocolInfoRepository; + + //头部字节长度 - public const int hearderLen = 6; + public const int hearderLen = 6; public const int tPLen = 6; public const string errorData = "EE"; + /// + /// BaseProtocolPlugin + /// + /// + /// + /// + protected BaseProtocolPlugin(ILogger logger, IRepository protocolInfoRepository, ICapPublisher capBus) + { + _logger = logger; + _protocolInfoRepository = protocolInfoRepository; + _capBus = capBus; + } - public abstract Task GetAsync(); - public abstract Task AnalyzeAsync(MessageReceivedEvent messageReceivedEvent, Action? sendAction = null); + public abstract ProtocolInfo Info { get; } + + public virtual async Task GetAsync() => await Task.FromResult(Info); + + public virtual async Task AddAsync() + { + if (Info == null) + { + throw new ArgumentNullException(nameof(Info)); + } + + await _protocolInfoRepository.DeleteDirectAsync(a => a.Name == Info.Name); + await _protocolInfoRepository.InsertAsync(Info); + } + + public abstract Task AnalyzeAsync(MessageReceived messageReceived, Action? sendAction = null); /// /// 登录帧解析 /// - /// 报文 - /// 发送委托 + /// 报文 /// - public virtual async Task LoginAsync(MessageReceivedLoginEvent messageReceivedEvent, Action? sendAction = null) + public virtual async Task LoginAsync(MessageReceivedLogin messageReceived) { - var hexStringList = messageReceivedEvent.MessageHexString.StringToPairs(); + var hexStringList = messageReceived.MessageHexString.StringToPairs(); var aTuple = (Tuple)hexStringList.GetAnalyzeValue(CommandChunkEnum.A); var seq = (Seq)hexStringList.GetAnalyzeValue(CommandChunkEnum.SEQ); var reqParam = new ReqParameter2 @@ -51,22 +87,19 @@ namespace JiShe.CollectBus.Protocol.Contracts.Abstracts Fn = 1 }; var bytes = HexStringExtensions.BuildSendCommandBytes(reqParam); - if (sendAction != null) - { - sendAction(bytes); - } + + await _capBus.PublishAsync(ProtocolConst.SubscriberIssuedEventName, new IssuedEventMessage { ClientId = messageReceived.ClientId, DeviceNo = messageReceived.DeviceNo, Message = bytes, Type = IssuedEventType.Login, MessageId = messageReceived.MessageId }); } /// /// 心跳帧解析 /// - /// 报文 - /// 发送委托 + /// 报文 /// - public virtual async Task HeartbeatAsync(MessageReceivedHeartbeatEvent messageReceivedEvent, Action? sendAction = null) + public virtual async Task HeartbeatAsync(MessageReceivedHeartbeat messageReceived) { - var hexStringList = messageReceivedEvent.MessageHexString.StringToPairs(); - var aTuple = (Tuple)hexStringList.GetAnalyzeValue(CommandChunkEnum.A); + var hexStringList = messageReceived.MessageHexString.StringToPairs(); + var aTuple = (Tuple)hexStringList.GetAnalyzeValue(CommandChunkEnum.A); var seq = (Seq)hexStringList.GetAnalyzeValue(CommandChunkEnum.SEQ); if (seq.TpV == TpV.附加信息域中带时间标签) { @@ -93,10 +126,7 @@ namespace JiShe.CollectBus.Protocol.Contracts.Abstracts Fn = 1 }; var bytes = HexStringExtensions.BuildSendCommandBytes(reqParam); - if (sendAction != null) - { - sendAction(bytes); - } + await _capBus.PublishAsync(ProtocolConst.SubscriberIssuedEventName, new IssuedEventMessage { ClientId = messageReceived.ClientId, DeviceNo = messageReceived.DeviceNo, Message = bytes, Type = IssuedEventType.Heartbeat, MessageId = messageReceived.MessageId }); } } @@ -105,9 +135,9 @@ namespace JiShe.CollectBus.Protocol.Contracts.Abstracts /// /// /// - public virtual async Task AnalyzeAnswerDataAsync(MessageReceivedHeartbeatEvent messageReceivedEvent, Action? sendAction = null) + public virtual async Task AnalyzeAnswerDataAsync(MessageReceivedHeartbeat messageReceived, Action? sendAction = null) { - var hexStringList = messageReceivedEvent.MessageHexString.StringToPairs(); + var hexStringList = messageReceived.MessageHexString.StringToPairs(); var fn = hexStringList.GetAnalyzeValue(CommandChunkEnum.FN); //1:全部确认 //2:全部否认 @@ -118,15 +148,15 @@ namespace JiShe.CollectBus.Protocol.Contracts.Abstracts /// /// 解析电表档案读取数据 /// - /// + /// /// /// - public virtual async Task AnalyzeAmmeterParameterReadingDataAsync(MessageReceivedHeartbeatEvent messageReceivedEvent, Action? sendAction = null) + public virtual async Task AnalyzeAmmeterParameterReadingDataAsync(MessageReceivedHeartbeat messageReceived, Action? sendAction = null) { - var hexDatas = GetHexDatas(messageReceivedEvent.MessageHexString); + var hexDatas = GetHexDatas(messageReceived.MessageHexString); var meterList = new List(); - var count = (hexDatas[1] + hexDatas[0]).HexToDec(); + var count = (hexDatas[1] + hexDatas[0]).HexToDec(); //if (2 + count * 27 != hexDatas.Count - pWLen - tPLen - 2) // return; var index = 2;//数量 @@ -192,18 +222,18 @@ namespace JiShe.CollectBus.Protocol.Contracts.Abstracts UserSubclassNumber = userSubClass, }); } - + } /// /// 解析当前正向有功电能示值抄读数据 /// - /// 报文 + /// 报文 /// 发送委托 /// - public virtual async Task AnalyzeActivePowerIndicationReadingDataAsync(MessageReceivedHeartbeatEvent messageReceivedEvent, Action? sendAction = null) + public virtual async Task AnalyzeActivePowerIndicationReadingDataAsync(MessageReceivedHeartbeat messageReceived, Action? sendAction = null) { - var hexDatas = GetHexDatas(messageReceivedEvent.MessageHexString); + var hexDatas = GetHexDatas(messageReceived.MessageHexString); var minutes = Convert.ToInt32(hexDatas[0]); // 获取当前分钟数 var hours = Convert.ToInt32(hexDatas[1]); // 获取当前小时数 @@ -217,7 +247,7 @@ namespace JiShe.CollectBus.Protocol.Contracts.Abstracts var index = 11; for (int i = 0; i < rateNumber; i++) { - var kwhHexList = hexDatas.Skip(11).Take(5).ToList(); + var kwhHexList = hexDatas.Skip(index).Take(5).ToList(); kwhHexList.Reverse(); var integerStr = $"{kwhHexList.Take(0)}{kwhHexList.Take(1)}{kwhHexList.Take(2)}"; var decimalValStr = $"{kwhHexList[3]}{kwhHexList[4]}"; @@ -230,14 +260,14 @@ namespace JiShe.CollectBus.Protocol.Contracts.Abstracts /// /// 解析日冻结正向有功电能示值抄读数据 /// - /// + /// /// /// - public virtual async Task AnalyzeDailyFrozenReadingDataAsync(MessageReceivedHeartbeatEvent messageReceivedEvent, Action? sendAction = null) + public virtual async Task AnalyzeDailyFrozenReadingDataAsync(MessageReceivedHeartbeat messageReceived, Action? sendAction = null) { - var hexDatas = GetHexDatas(messageReceivedEvent.MessageHexString); + var hexDatas = GetHexDatas(messageReceived.MessageHexString); //附录A.20 日月年 - var td_dHex= hexDatas.Take(3).ToList(); + var td_dHex = hexDatas.Take(3).ToList(); //附录A.15 分时日月年 var readingTimeHex = hexDatas.Skip(3).Take(5).ToList(); var rateNumberHex = hexDatas.Skip(8).Take(1).FirstOrDefault().HexToDec(); @@ -294,101 +324,343 @@ namespace JiShe.CollectBus.Protocol.Contracts.Abstracts /// /// 当前三相及总有/无功功率、功率因数、三相电压、电流、零序电流、视在功率 /// + /// + /// + /// + public virtual async Task AnalyzeF25ReadingDataAsync(MessageReceivedHeartbeat messageReceived, Action? sendAction = null) + { + var hexDatas = GetHexDatas(messageReceived.MessageHexString); + //A.15 分时日月年 + var readingTimeHex = hexDatas.Take(5).ToList(); + var readingTime = AnalyzeDataAccordingToA15(readingTimeHex[0], readingTimeHex[1], readingTimeHex[2], readingTimeHex[3], readingTimeHex[4]); + + //A.9 kW + var crntTotalActivePowerHexs = hexDatas.Skip((int)F25DataItemEnum.CrntTotalActivePower).Take(3).ToList(); + var crntTotalActivePower = AnalyzeDataAccordingToA09(crntTotalActivePowerHexs[0], crntTotalActivePowerHexs[1], crntTotalActivePowerHexs[2]); + + var crntActivePowerOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntActivePowerOfA).Take(3).ToList(); + var crntActivePowerOfA = AnalyzeDataAccordingToA09(crntActivePowerOfAHexs[0], crntActivePowerOfAHexs[1], crntActivePowerOfAHexs[2]); + + var crntActivePowerOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntActivePowerOfB).Take(3).ToList(); + var crntActivePowerOfB = AnalyzeDataAccordingToA09(crntActivePowerOfBHexs[0], crntActivePowerOfBHexs[1], crntActivePowerOfBHexs[2]); + + var crntActivePowerOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntActivePowerOfC).Take(3).ToList(); + var crntActivePowerOfC = AnalyzeDataAccordingToA09(crntActivePowerOfCHexs[0], crntActivePowerOfCHexs[1], crntActivePowerOfCHexs[2]); + + var crntTotalReactivePowerHexs = hexDatas.Skip((int)F25DataItemEnum.CrntTotalReactivePower).Take(3).ToList(); + var crntTotalReactivePower = AnalyzeDataAccordingToA09(crntTotalReactivePowerHexs[0], crntTotalReactivePowerHexs[1], crntTotalReactivePowerHexs[2]); + + var crntReactivePowerOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntReactivePowerOfA).Take(3).ToList(); + var crntReactivePowerOfA = AnalyzeDataAccordingToA09(crntReactivePowerOfAHexs[0], crntReactivePowerOfAHexs[1], crntReactivePowerOfAHexs[2]); + + var crntReactivePowerOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntReactivePowerOfB).Take(3).ToList(); + var crntReactivePowerOfB = AnalyzeDataAccordingToA09(crntReactivePowerOfBHexs[0], crntReactivePowerOfBHexs[1], crntReactivePowerOfBHexs[2]); + + var crntReactivePowerOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntReactivePowerOfC).Take(2).ToList(); + var crntReactivePowerOfC = AnalyzeDataAccordingToA09(crntReactivePowerOfCHexs[0], crntReactivePowerOfCHexs[1], crntReactivePowerOfCHexs[2]); + + //A.5 % + var crntTotalPowerFactorHexs = hexDatas.Skip((int)F25DataItemEnum.CrntTotalPowerFactor).Take(2).ToList(); + var crntTotalPowerFactor = AnalyzeDataAccordingToA05(crntTotalPowerFactorHexs[0], crntTotalPowerFactorHexs[1]); + + var crntPowerFactorOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntPowerFactorOfA).Take(2).ToList(); + var crntPowerFactorOfA = AnalyzeDataAccordingToA05(crntPowerFactorOfAHexs[0], crntPowerFactorOfAHexs[1]); + + var crntPowerFactorOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntPowerFactorOfB).Take(2).ToList(); + var crntPowerFactorOfB = AnalyzeDataAccordingToA05(crntPowerFactorOfBHexs[0], crntPowerFactorOfBHexs[1]); + + var crntPowerFactorOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntPowerFactorOfC).Take(2).ToList(); + var crntPowerFactorOfC = AnalyzeDataAccordingToA05(crntPowerFactorOfCHexs[0], crntPowerFactorOfCHexs[1]); + + //A.7 V + var crntVoltageOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntVoltageOfA).Take(2).ToList(); + var crntVoltageOfA = AnalyzeDataAccordingToA07(crntVoltageOfAHexs[0], crntVoltageOfAHexs[1]); + + var crntVoltageOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntVoltageOfB).Take(2).ToList(); + var crntVoltageOfB = AnalyzeDataAccordingToA07(crntVoltageOfBHexs[0], crntVoltageOfBHexs[1]); + + var crntVoltageOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntVoltageOfC).Take(2).ToList(); + var crntVoltageOfC = AnalyzeDataAccordingToA07(crntVoltageOfCHexs[0], crntVoltageOfCHexs[1]); + + //A.25 A + var crntCurrentOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntCurrentOfA).Take(3).ToList(); + var crntCurrentOfA = AnalyzeDataAccordingToA25(crntCurrentOfAHexs[0], crntCurrentOfAHexs[1], crntCurrentOfAHexs[2]); + + var crntCurrentOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntCurrentOfB).Take(3).ToList(); + var crntCurrentOfB = AnalyzeDataAccordingToA25(crntCurrentOfBHexs[0], crntCurrentOfBHexs[1], crntCurrentOfBHexs[2]); + + var crntCurrentOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntCurrentOfC).Take(3).ToList(); + var crntCurrentOfC = AnalyzeDataAccordingToA25(crntCurrentOfCHexs[0], crntCurrentOfCHexs[1], crntCurrentOfCHexs[2]); + + var crntZeroSequenceCurrentHexs = hexDatas.Skip((int)F25DataItemEnum.CrntZeroSequenceCurrent).Take(3).ToList(); + var crntZeroSequenceCurrent = AnalyzeDataAccordingToA25(crntZeroSequenceCurrentHexs[0], crntZeroSequenceCurrentHexs[1], crntZeroSequenceCurrentHexs[2]); + + //A.9 kVA + var crntTotalApparentPowerHexs = hexDatas.Skip((int)F25DataItemEnum.CrntTotalApparentPower).Take(3).ToList(); + var crntTotalApparentPower = AnalyzeDataAccordingToA09(crntTotalApparentPowerHexs[0], crntTotalApparentPowerHexs[1], crntTotalApparentPowerHexs[2]); + + var crntApparentPowerOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntApparentPowerOfA).Take(3).ToList(); + var crntApparentPowerOfA = AnalyzeDataAccordingToA09(crntApparentPowerOfAHexs[0], crntApparentPowerOfAHexs[1], crntApparentPowerOfAHexs[2]); + + var crntApparentPowerOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntApparentPowerOfB).Take(3).ToList(); + var crntApparentPowerOfB = AnalyzeDataAccordingToA09(crntApparentPowerOfBHexs[0], crntApparentPowerOfBHexs[1], crntApparentPowerOfBHexs[2]); + + var crntApparentPowerOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntApparentPowerOfC).Take(3).ToList(); + var crntApparentPowerOfC = AnalyzeDataAccordingToA09(crntApparentPowerOfCHexs[0], crntApparentPowerOfCHexs[1], crntApparentPowerOfCHexs[2]); + + } + + /// + /// 解析相位角 + /// + /// + /// + /// + public virtual async Task AnalyzeATypeOfDataItems49ReadingDataAsync(MessageReceivedHeartbeat messageReceived, Action? sendAction = null) + { + var hexDatas = GetHexDatas(messageReceived.MessageHexString); + + var uabUaList = hexDatas.Take(2).ToList(); + var uabUa = AnalyzeDataAccordingToA05(uabUaList[0], uabUaList[1]); //单位 度 + + var ubList = hexDatas.Skip((int)ATypeOfDataItems49.Ub).Take(2).ToList(); + var ub = AnalyzeDataAccordingToA05(ubList[0], ubList[1]); + + var ucbUcList = hexDatas.Skip((int)ATypeOfDataItems49.UcbUc).Take(2).ToList(); + var ucbUc = AnalyzeDataAccordingToA05(ucbUcList[0], ucbUcList[1]); + + var iaList = hexDatas.Skip((int)ATypeOfDataItems49.Ia).Take(2).ToList(); + var ia = AnalyzeDataAccordingToA05(iaList[0], iaList[1]); + + var ibList = hexDatas.Skip((int)ATypeOfDataItems49.Ib).Take(2).ToList(); + var ib = AnalyzeDataAccordingToA05(ibList[0], ibList[1]); + + var icList = hexDatas.Skip((int)ATypeOfDataItems49.Ic).Take(2).ToList(); + var ic = AnalyzeDataAccordingToA05(icList[0], icList[1]); + } + + /// + /// 通用解析 + /// + /// + /// + /// + public virtual async Task AnalyzeReadingDataAsync(MessageReceivedHeartbeat messageReceived, + Action? sendAction = null) + { + var hexStringList = messageReceived.MessageHexString.StringToPairs(); + var afn = (AFN)hexStringList.GetAnalyzeValue(CommandChunkEnum.AFN); + var fn = (int)hexStringList.GetAnalyzeValue(CommandChunkEnum.FN); + + var tb3761 = QGDW3761Config.CommandList.FirstOrDefault(it => it.Afn == afn); + if (tb3761 == null) return; + + var tb3761Fn = tb3761.FnList.FirstOrDefault(it => it.Fn == fn); + if (tb3761Fn == null) return; + + var hexDatas = (List)hexStringList.GetAnalyzeValue(CommandChunkEnum.Data); + var list = new List(); + + var m = 0; + var rateNumberUpSort = -1; + var rateNumberUp = tb3761Fn.UpList.FirstOrDefault(it => it.Name.Contains("费率数M")); + if (rateNumberUp != null) + { + var rateNumber = hexDatas.Skip(rateNumberUp.DataIndex).Take(rateNumberUp.DataCount).FirstOrDefault(); + m = Convert.ToInt32(rateNumber); + rateNumberUpSort = rateNumberUp.Sort; + } + + foreach (var up in tb3761Fn.UpList) + { + var dataIndex = up.DataIndex; + if (dataIndex == 0 && up.Sort > rateNumberUpSort) + { + var sum1 = tb3761Fn.UpList.Where(it => it.Sort < up.Sort) + .Sum(it => it.DataCount); + var sum2 = tb3761Fn.UpList.Where(it => it.Sort < up.Sort && it.Tb3761UpChildlList.Count > 0) + .Sum(it => it.Tb3761UpChildlList.Sum(c=> m * c.DataCount)); + dataIndex = sum1 + sum2; + } + + var value = AnalyzeDataAccordingDataType(hexDatas, dataIndex, up.DataCount, up.DataType); + if (value != null) + { + list.Add(value); + } + if (up.Tb3761UpChildlList.Count > 0) //复费率根据费率数来解析 + { + var repeatCount = m; + foreach (var upChild in up.Tb3761UpChildlList) + { + for (var j = 0; j < repeatCount; j++) + { + var val = AnalyzeDataAccordingDataType(hexDatas, dataIndex, upChild.DataCount, upChild.DataType); + if (val != null) + { + list.Add(val); + } + dataIndex += upChild.DataCount; + //var name = string.Format(up.Name, i+1); + } + } + + } + } + } + + /// + /// 通用解析 日冻结曲线类 + /// + /// + /// + /// + public virtual async Task AnalyzeReadingTdcDataAsync(MessageReceivedHeartbeat messageReceived, + Action? sendAction = null) + { + + var hexStringList = messageReceived.MessageHexString.StringToPairs(); + var afn = (AFN)hexStringList.GetAnalyzeValue(CommandChunkEnum.AFN); + var fn = (int)hexStringList.GetAnalyzeValue(CommandChunkEnum.FN); + + var tb3761 = QGDW3761Config.CommandList.FirstOrDefault(it => it.Afn == afn); + if (tb3761 == null) return; + + var tb3761Fn = tb3761.FnList.FirstOrDefault(it => it.Fn == fn); + if (tb3761Fn == null) return; + + var hexDatas = (List)hexStringList.GetAnalyzeValue(CommandChunkEnum.Data); + var list = new List(); + + foreach (var up in tb3761Fn.UpList) + { + var value = AnalyzeDataAccordingDataType(hexDatas, up.DataIndex, up.DataCount, up.DataType); + if (value != null) + { + list.Add(value); + + if (up.Tb3761UpChildlList.Count > 0) + { + var dataIndex = up.DataIndex; + var repeatCount = (int)value; + foreach (var upChild in up.Tb3761UpChildlList) + { + for (var j = 0; j < repeatCount; j++) + { + var val = AnalyzeDataAccordingDataType(hexDatas, dataIndex, upChild.DataCount, upChild.DataType); + if (val != null) + { + list.Add(val); + } + dataIndex += upChild.DataCount; + //var name = string.Format(up.Name, i+1); + } + } + } + } + } + //var freezeDensity = (FreezeDensity)Convert.ToInt32(hexDatas.Skip(5).Take(1)); + //var addMinute = 0; + //switch (freezeDensity) + //{ + // case FreezeDensity.No:break; + // case FreezeDensity.Min15: + // addMinute = 15; + // break; + // case FreezeDensity.Min30: + // addMinute = 30; + // break; + // case FreezeDensity.Min60: + // addMinute = 60; + // break; + // case FreezeDensity.Min5: break; + // addMinute = 5; + // case FreezeDensity.Min1: + // addMinute = 1; + // break; + // } + } + + private object? AnalyzeDataAccordingDataType(List hexDatas, int dataIndex,int dataCount,string dataType) + { + var valueList = hexDatas.Skip(dataIndex).Take(dataCount).ToList(); + object? value = null; + switch (dataType) + { + case "BIN": + value = Convert.ToInt32(valueList[0]); + break; + case "A05": + if (valueList.Count == 2) + { + value = AnalyzeDataAccordingToA05(valueList[0], valueList[1]); + } + break; + case "A09": + if (valueList.Count == 3) + { + value = AnalyzeDataAccordingToA09(valueList[0], valueList[1], valueList[2]); + } + break; + case "A14": + if (valueList.Count == 5) + { + value = AnalyzeDataAccordingToA15(valueList[0], valueList[1], valueList[2], valueList[3], valueList[4]); + } + break; + case "A15": + if (valueList.Count == 5) + { + //var minutes = Convert.ToInt32(hexDatas[0]); // 获取当前分钟数 + //var hours = Convert.ToInt32(hexDatas[1]); // 获取当前小时数 + //var day = Convert.ToInt32(hexDatas[2]); // 获取当前日期的日数 + //var month = Convert.ToInt32(hexDatas[3]); // 获取当前月份 + //var year = Convert.ToInt32(hexDatas[4]); // 获取当前日期的年份 + value = AnalyzeDataAccordingToA15(valueList[0], valueList[1], valueList[2], valueList[3], valueList[4]); + } + break; + } + + return value; + } + + + /// + /// 解析透明转发 应答 + /// /// /// /// - public virtual async Task AnalyzeF25ReadingDataAsync(MessageReceivedHeartbeatEvent messageReceivedEvent, Action? sendAction = null) + public virtual async Task AnalyzeTransparentForwardingAnswerAsync(MessageReceivedHeartbeat messageReceivedEvent, Action? sendAction = null) { - var hexDatas = GetHexDatas(messageReceivedEvent.MessageHexString); - //A.15 分时日月年 - var readingTimeHex = hexDatas.Take(5).ToList(); - var readingTime = AnalyzeDataAccordingToA15(readingTimeHex[0], readingTimeHex[1], readingTimeHex[2], readingTimeHex[3], readingTimeHex[4]); + var hexDatas = GetHexDatas(messageReceivedEvent.MessageHexString); - //A.9 kW - var crntTotalActivePowerHexs = hexDatas.Skip((int)F25DataItemEnum.CrntTotalActivePower).Take(3).ToList(); - var crntTotalActivePower = AnalyzeDataAccordingToA09(crntTotalActivePowerHexs[0], crntTotalActivePowerHexs[1], crntTotalActivePowerHexs[2]); + var port = hexDatas[0].HexToDec(); - var crntActivePowerOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntActivePowerOfA).Take(3).ToList(); - var crntActivePowerOfA = AnalyzeDataAccordingToA09(crntActivePowerOfAHexs[0], crntActivePowerOfAHexs[1], crntActivePowerOfAHexs[2]); + var count = hexDatas[1].HexToDec(); - var crntActivePowerOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntActivePowerOfB).Take(3).ToList(); - var crntActivePowerOfB = AnalyzeDataAccordingToA09(crntActivePowerOfBHexs[0], crntActivePowerOfBHexs[1], crntActivePowerOfBHexs[2]); + var dataList = hexDatas.Skip(2).Take(count).ToList(); - var crntActivePowerOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntActivePowerOfC).Take(3).ToList(); - var crntActivePowerOfC = AnalyzeDataAccordingToA09(crntActivePowerOfCHexs[0], crntActivePowerOfCHexs[1], crntActivePowerOfCHexs[2]); - - var crntTotalReactivePowerHexs = hexDatas.Skip((int)F25DataItemEnum.CrntTotalReactivePower).Take(3).ToList(); - var crntTotalReactivePower = AnalyzeDataAccordingToA09(crntTotalReactivePowerHexs[0], crntTotalReactivePowerHexs[1], crntTotalReactivePowerHexs[2]); - - var crntReactivePowerOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntReactivePowerOfA).Take(3).ToList(); - var crntReactivePowerOfA = AnalyzeDataAccordingToA09(crntReactivePowerOfAHexs[0], crntReactivePowerOfAHexs[1], crntReactivePowerOfAHexs[2]); - - var crntReactivePowerOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntReactivePowerOfB).Take(3).ToList(); - var crntReactivePowerOfB = AnalyzeDataAccordingToA09(crntReactivePowerOfBHexs[0], crntReactivePowerOfBHexs[1], crntReactivePowerOfBHexs[2]); - - var crntReactivePowerOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntReactivePowerOfC).Take(2).ToList(); - var crntReactivePowerOfC = AnalyzeDataAccordingToA09(crntReactivePowerOfCHexs[0], crntReactivePowerOfCHexs[1], crntReactivePowerOfCHexs[2]); - - //A.5 % - var crntTotalPowerFactorHexs = hexDatas.Skip((int)F25DataItemEnum.CrntTotalPowerFactor).Take(2).ToList(); - var crntTotalPowerFactor = AnalyzeDataAccordingToA05(crntTotalPowerFactorHexs[0], crntTotalPowerFactorHexs[1]); - - var crntPowerFactorOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntPowerFactorOfA).Take(2).ToList(); - var crntPowerFactorOfA = AnalyzeDataAccordingToA05(crntPowerFactorOfAHexs[0], crntPowerFactorOfAHexs[1]); - - var crntPowerFactorOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntPowerFactorOfB).Take(2).ToList(); - var crntPowerFactorOfB = AnalyzeDataAccordingToA05(crntPowerFactorOfBHexs[0], crntPowerFactorOfBHexs[1]); - - var crntPowerFactorOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntPowerFactorOfC).Take(2).ToList(); - var crntPowerFactorOfC = AnalyzeDataAccordingToA05(crntPowerFactorOfCHexs[0], crntPowerFactorOfCHexs[1]); - - //A.7 V - var crntVoltageOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntVoltageOfA).Take(2).ToList(); - var crntVoltageOfA = AnalyzeDataAccordingToA07(crntVoltageOfAHexs[0], crntVoltageOfAHexs[1]); - - var crntVoltageOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntVoltageOfB).Take(2).ToList(); - var crntVoltageOfB = AnalyzeDataAccordingToA07(crntVoltageOfBHexs[0], crntVoltageOfBHexs[1]); - - var crntVoltageOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntVoltageOfC).Take(2).ToList(); - var crntVoltageOfC = AnalyzeDataAccordingToA07(crntVoltageOfCHexs[0], crntVoltageOfCHexs[1]); - - //A.25 A - var crntCurrentOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntCurrentOfA).Take(3).ToList(); - var crntCurrentOfA = AnalyzeDataAccordingToA25(crntCurrentOfAHexs[0], crntCurrentOfAHexs[1], crntCurrentOfAHexs[2]); - - var crntCurrentOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntCurrentOfB).Take(3).ToList(); - var crntCurrentOfB = AnalyzeDataAccordingToA25(crntCurrentOfBHexs[0], crntCurrentOfBHexs[1], crntCurrentOfBHexs[2]); - - var crntCurrentOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntCurrentOfC).Take(3).ToList(); - var crntCurrentOfC = AnalyzeDataAccordingToA25(crntCurrentOfCHexs[0], crntCurrentOfCHexs[1], crntCurrentOfCHexs[2]); - - var crntZeroSequenceCurrentHexs = hexDatas.Skip((int)F25DataItemEnum.CrntZeroSequenceCurrent).Take(3).ToList(); - var crntZeroSequenceCurrent = AnalyzeDataAccordingToA25(crntZeroSequenceCurrentHexs[0], crntZeroSequenceCurrentHexs[1], crntZeroSequenceCurrentHexs[2]); - - //A.9 kVA - var crntTotalApparentPowerHexs = hexDatas.Skip((int)F25DataItemEnum.CrntTotalApparentPower).Take(3).ToList(); - var crntTotalApparentPower = AnalyzeDataAccordingToA09(crntTotalApparentPowerHexs[0], crntTotalApparentPowerHexs[1], crntTotalApparentPowerHexs[2]); - - var crntApparentPowerOfAHexs = hexDatas.Skip((int)F25DataItemEnum.CrntApparentPowerOfA).Take(3).ToList(); - var crntApparentPowerOfA = AnalyzeDataAccordingToA09(crntApparentPowerOfAHexs[0], crntApparentPowerOfAHexs[1], crntApparentPowerOfAHexs[2]); - - var crntApparentPowerOfBHexs = hexDatas.Skip((int)F25DataItemEnum.CrntApparentPowerOfB).Take(3).ToList(); - var crntApparentPowerOfB = AnalyzeDataAccordingToA09(crntApparentPowerOfBHexs[0], crntApparentPowerOfBHexs[1], crntApparentPowerOfBHexs[2]); - - var crntApparentPowerOfCHexs = hexDatas.Skip((int)F25DataItemEnum.CrntApparentPowerOfC).Take(3).ToList(); - var crntApparentPowerOfC = AnalyzeDataAccordingToA09(crntApparentPowerOfCHexs[0], crntApparentPowerOfCHexs[1], crntApparentPowerOfCHexs[2]); + //645 + if (dataList[0].IsStartStr() && dataList[hearderLen - 1].IsStartStr()) + { + } + else if (dataList[0].IsStartStr())//188 水表只有开头是68 + { + AnalyzeWaterMeterReadData(dataList); + } } /// /// 解析透明转发 应答结果 /// - /// + /// /// /// - public virtual async Task AnalyzeTransparentForwardingAnswerResultAsync(MessageReceivedHeartbeatEvent messageReceivedEvent, Action? sendAction = null) + public virtual async Task AnalyzeTransparentForwardingAnswerResultAsync(MessageReceivedHeartbeat messageReceived, Action? sendAction = null) { - var hexDatas = GetHexDatas(messageReceivedEvent.MessageHexString); + var hexDatas = GetHexDatas(messageReceived.MessageHexString); var port = hexDatas[0].HexToDec(); @@ -629,7 +901,51 @@ namespace JiShe.CollectBus.Protocol.Contracts.Abstracts #endregion - + #region 188 + + public void AnalyzeWaterMeter188Data(List dataList) + { + var waterMeterType = dataList[(int)WaterMeterReadEnum.Type]; + var addressList = dataList.Skip((int)WaterMeterReadEnum.Address).Take(6).ToList(); + addressList.Reverse(); + var address = string.Join("", addressList); + address = address.Substring(address.Length - 12); + var controlCode = dataList[(int)WaterMeterReadEnum.ControlCode]; + switch (controlCode) + { + case "81": + AnalyzeWaterMeterReadData(dataList); + break; + case "84": + AnalyzeWaterMeterValueResult(dataList); + break; + } + + } + + /// + /// 解析水表读数据 + /// + /// + public void AnalyzeWaterMeterReadData(List dataList) + { + var accumulativeWaterflowList = dataList.Skip((int)WaterMeterReadEnum.AccumulativeWaterflow).Take(5).ToList(); + //xxxxxx.xx + var accumulativeWaterflow = decimal.Parse( + $"{accumulativeWaterflowList[3]}{accumulativeWaterflowList[2]}{accumulativeWaterflowList[1]}." + + $"{accumulativeWaterflowList[0]}"); + } + + /// + /// 解析水表阀控结果 + /// + /// + public bool AnalyzeWaterMeterValueResult(List dataList) + { + return true; + } + + #endregion } } diff --git a/JiShe.CollectBus.Protocol.Contracts/Adapters/StandardFixedHeaderDataHandlingAdapter.cs b/src/JiShe.CollectBus.Protocol.Contracts/Adapters/StandardFixedHeaderDataHandlingAdapter.cs similarity index 100% rename from JiShe.CollectBus.Protocol.Contracts/Adapters/StandardFixedHeaderDataHandlingAdapter.cs rename to src/JiShe.CollectBus.Protocol.Contracts/Adapters/StandardFixedHeaderDataHandlingAdapter.cs diff --git a/JiShe.CollectBus.Protocol.Contracts/Attributes/ProtocolNameAttribute.cs b/src/JiShe.CollectBus.Protocol.Contracts/Attributes/ProtocolNameAttribute.cs similarity index 100% rename from JiShe.CollectBus.Protocol.Contracts/Attributes/ProtocolNameAttribute.cs rename to src/JiShe.CollectBus.Protocol.Contracts/Attributes/ProtocolNameAttribute.cs diff --git a/src/JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolPlugin.cs b/src/JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolPlugin.cs new file mode 100644 index 0000000..1ccc45b --- /dev/null +++ b/src/JiShe.CollectBus.Protocol.Contracts/Interfaces/IProtocolPlugin.cs @@ -0,0 +1,23 @@ +using System; +using System.Threading.Tasks; +using JiShe.CollectBus.Common.Models; +using JiShe.CollectBus.MessageReceiveds; +using JiShe.CollectBus.Protocol.Contracts.Models; +using JiShe.CollectBus.Protocols; +using TouchSocket.Sockets; + +namespace JiShe.CollectBus.Protocol.Contracts.Interfaces +{ + public interface IProtocolPlugin + { + Task GetAsync(); + + Task AddAsync(); + + Task AnalyzeAsync(MessageReceived messageReceived, Action? sendAction = null); + + Task LoginAsync(MessageReceivedLogin messageReceived); + + Task HeartbeatAsync(MessageReceivedHeartbeat messageReceived); + } +} diff --git a/JiShe.CollectBus.Protocol.Contracts/JiShe.CollectBus.Protocol.Contracts.csproj b/src/JiShe.CollectBus.Protocol.Contracts/JiShe.CollectBus.Protocol.Contracts.csproj similarity index 78% rename from JiShe.CollectBus.Protocol.Contracts/JiShe.CollectBus.Protocol.Contracts.csproj rename to src/JiShe.CollectBus.Protocol.Contracts/JiShe.CollectBus.Protocol.Contracts.csproj index 13fd7d4..aa5bd73 100644 --- a/JiShe.CollectBus.Protocol.Contracts/JiShe.CollectBus.Protocol.Contracts.csproj +++ b/src/JiShe.CollectBus.Protocol.Contracts/JiShe.CollectBus.Protocol.Contracts.csproj @@ -7,13 +7,16 @@ + + + diff --git a/JiShe.CollectBus.Protocol.Contracts/Models/CustomFixedHeaderRequestInfo.cs b/src/JiShe.CollectBus.Protocol.Contracts/Models/CustomFixedHeaderRequestInfo.cs similarity index 100% rename from JiShe.CollectBus.Protocol.Contracts/Models/CustomFixedHeaderRequestInfo.cs rename to src/JiShe.CollectBus.Protocol.Contracts/Models/CustomFixedHeaderRequestInfo.cs diff --git a/src/JiShe.CollectBus.Protocol.Contracts/Models/TB3761.cs b/src/JiShe.CollectBus.Protocol.Contracts/Models/TB3761.cs new file mode 100644 index 0000000..e5e5252 --- /dev/null +++ b/src/JiShe.CollectBus.Protocol.Contracts/Models/TB3761.cs @@ -0,0 +1,54 @@ +using JiShe.CollectBus.Common.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Protocol.Contracts.Models +{ + public class TB3761 + { + public int Id { get; set; } + + public AFN Afn { get; set; } + + public List FnList { get; set; } + + } + + public class TB3761FN + { + public int Id { get; set; } + + public int Fn { get; set; } + + public string Text { get; set; } + + public List UpList { get; set; } + + } + + public class TB3761UP + { + public int Id { get; set; } + + public string Name { get; set; } + + public string DataType { get; set; } + + public int DataIndex { get; set; } + + //public int DataIndex { get; set; } + + public int DataCount { get; set; } + + + //public int ParentId { get; set; } + + public int Sort { get; set; } + + public List Tb3761UpChildlList { get; set; } + } + +} diff --git a/src/JiShe.CollectBus.Protocol.Contracts/ProtocolConst.cs b/src/JiShe.CollectBus.Protocol.Contracts/ProtocolConst.cs new file mode 100644 index 0000000..25b160c --- /dev/null +++ b/src/JiShe.CollectBus.Protocol.Contracts/ProtocolConst.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JiShe.CollectBus.Protocol.Contracts +{ + public class ProtocolConst + { + public const string SubscriberGroup = "jishe.collectbus"; + public const string SubscriberIssuedEventName = "issued.event"; + public const string SubscriberReceivedEventName = "received.event"; + public const string SubscriberReceivedHeartbeatEventName = "received.heartbeat.event"; + public const string SubscriberReceivedLoginEventName = "received.login.event"; + + } +} diff --git a/src/JiShe.CollectBus.Protocol.Contracts/QGDW3761Config.cs b/src/JiShe.CollectBus.Protocol.Contracts/QGDW3761Config.cs new file mode 100644 index 0000000..88f6bcb --- /dev/null +++ b/src/JiShe.CollectBus.Protocol.Contracts/QGDW3761Config.cs @@ -0,0 +1,70 @@ +using JiShe.CollectBus.Protocol.Contracts.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using JiShe.CollectBus.Common.Extensions; + +namespace JiShe.CollectBus.Protocol.Contracts +{ + public class QGDW3761Config + { + private static List _commandList = null; + public static List CommandList + { + get + { + if (_commandList == null) + { + var filePath = AppDomain.CurrentDomain.BaseDirectory + "cmd3761Matching.txt"; + + try + { + var fileStr = ""; + if (File.Exists(filePath)) + fileStr = File.ReadAllText(filePath, Encoding.UTF8); + + if (!string.IsNullOrWhiteSpace(fileStr)) + { + _commandList = fileStr.FromJson>(); + } + } + catch (Exception) + { + + } + } + return _commandList; + } + } + + private static List _commandTdcList = null; + public static List CommandTdcList + { + get + { + if (_commandTdcList == null) + { + var filePath = AppDomain.CurrentDomain.BaseDirectory + "cmd3761TdcMatching.txt"; + + try + { + var fileStr = ""; + if (File.Exists(filePath)) + fileStr = File.ReadAllText(filePath, Encoding.UTF8); + + if (!string.IsNullOrWhiteSpace(fileStr)) + { + _commandTdcList = fileStr.FromJson>(); + } + } + catch (Exception) + { + + } + } + return _commandTdcList; + } + } + } +} diff --git a/JiShe.CollectBus.Protocol/JiShe.CollectBus.Protocol.csproj b/src/JiShe.CollectBus.Protocol/JiShe.CollectBus.Protocol.csproj similarity index 74% rename from JiShe.CollectBus.Protocol/JiShe.CollectBus.Protocol.csproj rename to src/JiShe.CollectBus.Protocol/JiShe.CollectBus.Protocol.csproj index fd92cd0..0ee8a46 100644 --- a/JiShe.CollectBus.Protocol/JiShe.CollectBus.Protocol.csproj +++ b/src/JiShe.CollectBus.Protocol/JiShe.CollectBus.Protocol.csproj @@ -10,17 +10,19 @@ + + + - - + diff --git a/JiShe.CollectBus.Protocol/JiSheCollectBusProtocolModule.cs b/src/JiShe.CollectBus.Protocol/JiSheCollectBusProtocolModule.cs similarity index 63% rename from JiShe.CollectBus.Protocol/JiSheCollectBusProtocolModule.cs rename to src/JiShe.CollectBus.Protocol/JiSheCollectBusProtocolModule.cs index b3549ba..64661d1 100644 --- a/JiShe.CollectBus.Protocol/JiSheCollectBusProtocolModule.cs +++ b/src/JiShe.CollectBus.Protocol/JiSheCollectBusProtocolModule.cs @@ -1,22 +1,21 @@ -using JiShe.CollectBus.MQ.Sender; -using JiShe.CollectBus.Protocol.Contracts.Interfaces; +using JiShe.CollectBus.Protocol.Contracts.Interfaces; using Microsoft.Extensions.DependencyInjection; using Volo.Abp; using Volo.Abp.Modularity; namespace JiShe.CollectBus.Protocol { - [DependsOn(typeof(JiSheCollectBusMqSenderModule))] public class JiSheCollectBusProtocolModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { - context.Services.AddKeyedSingleton("Standard"); + context.Services.AddKeyedSingleton(nameof(StandardProtocolPlugin)); } public override void OnApplicationInitialization(ApplicationInitializationContext context) { - + var standardProtocol = context.ServiceProvider.GetRequiredKeyedService(nameof(StandardProtocolPlugin)); + standardProtocol.AddAsync(); } } } diff --git a/JiShe.CollectBus.Protocol/StandardProtocolPlugin.cs b/src/JiShe.CollectBus.Protocol/StandardProtocolPlugin.cs similarity index 71% rename from JiShe.CollectBus.Protocol/StandardProtocolPlugin.cs rename to src/JiShe.CollectBus.Protocol/StandardProtocolPlugin.cs index 25633c8..9010924 100644 --- a/JiShe.CollectBus.Protocol/StandardProtocolPlugin.cs +++ b/src/JiShe.CollectBus.Protocol/StandardProtocolPlugin.cs @@ -1,53 +1,43 @@ -using JiShe.CollectBus.Common.Enums; +using DotNetCore.CAP; +using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Extensions; using JiShe.CollectBus.Common.Models; -using JiShe.CollectBus.MQ.Sender; +using JiShe.CollectBus.MessageReceiveds; using JiShe.CollectBus.Protocol.Contracts.Abstracts; -using JiShe.CollectBus.Protocol.Contracts.Attributes; -using JiShe.CollectBus.Protocol.Contracts.Models; +using JiShe.CollectBus.Protocols; using Microsoft.Extensions.Logging; -using Volo.Abp.DependencyInjection; +using Volo.Abp.Domain.Repositories; namespace JiShe.CollectBus.Protocol -{ - public class StandardProtocolPlugin(INSender nSender, ILogger logger) : BaseProtocolPlugin(logger), ISingletonDependency +{ + public class StandardProtocolPlugin: BaseProtocolPlugin { - public override async Task GetAsync() + private readonly ICapPublisher _capBus; + private readonly ILogger _logger; + private readonly IRepository _protocolInfoRepository; + + /// + /// Initializes a new instance of the class. + /// + /// The cap bus. + /// The logger. + /// The protocol information repository. + public StandardProtocolPlugin(ICapPublisher capBus, + ILogger logger, + IRepository protocolInfoRepository) : base(logger, protocolInfoRepository, capBus) { - var info = new ProtocolInfo("Standard", "376.1", "TCP", "376.1协议", "DTS1980"); - return await Task.FromResult(info); - } - public override async Task AnalyzeAsync(MessageReceivedEvent messageReceivedEvent, Action? sendAction = null) - { - var cmdResult = AnalysisCmd(messageReceivedEvent.MessageHexString); - if (cmdResult == null) - { - return; - } - await Task.CompletedTask; + _capBus = capBus; + _logger = logger; + _protocolInfoRepository = protocolInfoRepository; } - public override async Task LoginAsync(MessageReceivedLoginEvent messageReceivedEvent, Action? sendAction = null) + public sealed override ProtocolInfo Info => new(nameof(StandardProtocolPlugin), "376.1", "TCP", "376.1协议", "DTS1980"); + + public override Task AnalyzeAsync(MessageReceived messageReceived, Action? sendAction = null) { - async void SendAction(byte[] bytes) - { - await nSender.SendToIssuedAsync(new MessageIssuedEvent { ClientId = messageReceivedEvent.ClientId, DeviceNo = messageReceivedEvent.DeviceNo, Message = bytes, Type = IssuedEventType.Login,MessageId = messageReceivedEvent.MessageId}); - } - - await base.LoginAsync(messageReceivedEvent, SendAction); + throw new NotImplementedException(); } - public override async Task HeartbeatAsync(MessageReceivedHeartbeatEvent messageReceivedEvent, Action? sendAction = null) - { - async void SendAction(byte[] bytes) - { - await nSender.SendToIssuedAsync(new MessageIssuedEvent { ClientId = messageReceivedEvent.ClientId, DeviceNo = messageReceivedEvent.DeviceNo, Message = bytes, Type = IssuedEventType.Login, MessageId = messageReceivedEvent.MessageId }); - } - await base.HeartbeatAsync(messageReceivedEvent, SendAction); - } - - - #region 上行命令 //68 diff --git a/test/JiShe.CollectBus.Application.Tests/CollectBusApplicationTestBase.cs b/test/JiShe.CollectBus.Application.Tests/CollectBusApplicationTestBase.cs new file mode 100644 index 0000000..f680698 --- /dev/null +++ b/test/JiShe.CollectBus.Application.Tests/CollectBusApplicationTestBase.cs @@ -0,0 +1,12 @@ +using Volo.Abp.Modularity; + +namespace JiShe.CollectBus; + +/* Inherit from this class for your application layer tests. + * See SampleAppService_Tests for example. + */ +public abstract class CollectBusApplicationTestBase : CollectBusTestBase + where TStartupModule : IAbpModule +{ + +} diff --git a/test/JiShe.CollectBus.Application.Tests/CollectBusApplicationTestModule.cs b/test/JiShe.CollectBus.Application.Tests/CollectBusApplicationTestModule.cs new file mode 100644 index 0000000..bc81f70 --- /dev/null +++ b/test/JiShe.CollectBus.Application.Tests/CollectBusApplicationTestModule.cs @@ -0,0 +1,12 @@ +using Volo.Abp.Modularity; + +namespace JiShe.CollectBus; + +[DependsOn( + typeof(CollectBusApplicationModule), + typeof(CollectBusDomainTestModule) + )] +public class CollectBusApplicationTestModule : AbpModule +{ + +} diff --git a/test/JiShe.CollectBus.Application.Tests/FodyWeavers.xml b/test/JiShe.CollectBus.Application.Tests/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/test/JiShe.CollectBus.Application.Tests/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/test/JiShe.CollectBus.Application.Tests/JiShe.CollectBus.Application.Tests.abppkg b/test/JiShe.CollectBus.Application.Tests/JiShe.CollectBus.Application.Tests.abppkg new file mode 100644 index 0000000..a686451 --- /dev/null +++ b/test/JiShe.CollectBus.Application.Tests/JiShe.CollectBus.Application.Tests.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.test" +} \ No newline at end of file diff --git a/test/JiShe.CollectBus.Application.Tests/JiShe.CollectBus.Application.Tests.csproj b/test/JiShe.CollectBus.Application.Tests/JiShe.CollectBus.Application.Tests.csproj new file mode 100644 index 0000000..04959f7 --- /dev/null +++ b/test/JiShe.CollectBus.Application.Tests/JiShe.CollectBus.Application.Tests.csproj @@ -0,0 +1,17 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + + + + + + + + + diff --git a/test/JiShe.CollectBus.Application.Tests/Samples/SampleAppService_Tests.cs b/test/JiShe.CollectBus.Application.Tests/Samples/SampleAppService_Tests.cs new file mode 100644 index 0000000..9b81ebf --- /dev/null +++ b/test/JiShe.CollectBus.Application.Tests/Samples/SampleAppService_Tests.cs @@ -0,0 +1,31 @@ +using System.Threading.Tasks; +using Shouldly; +using Volo.Abp.Modularity; +using Xunit; + +namespace JiShe.CollectBus.Samples; + +public abstract class SampleAppService_Tests : CollectBusApplicationTestBase + where TStartupModule : IAbpModule +{ + private readonly ISampleAppService _sampleAppService; + + protected SampleAppService_Tests() + { + _sampleAppService = GetRequiredService(); + } + + [Fact] + public async Task GetAsync() + { + var result = await _sampleAppService.GetAsync(); + result.Value.ShouldBe(42); + } + + [Fact] + public async Task GetAuthorizedAsync() + { + var result = await _sampleAppService.GetAuthorizedAsync(); + result.Value.ShouldBe(42); + } +} diff --git a/test/JiShe.CollectBus.Domain.Tests/CollectBusDomainTestBase.cs b/test/JiShe.CollectBus.Domain.Tests/CollectBusDomainTestBase.cs new file mode 100644 index 0000000..71a0f76 --- /dev/null +++ b/test/JiShe.CollectBus.Domain.Tests/CollectBusDomainTestBase.cs @@ -0,0 +1,12 @@ +using Volo.Abp.Modularity; + +namespace JiShe.CollectBus; + +/* Inherit from this class for your domain layer tests. + * See SampleManager_Tests for example. + */ +public abstract class CollectBusDomainTestBase : CollectBusTestBase + where TStartupModule : IAbpModule +{ + +} diff --git a/test/JiShe.CollectBus.Domain.Tests/CollectBusDomainTestModule.cs b/test/JiShe.CollectBus.Domain.Tests/CollectBusDomainTestModule.cs new file mode 100644 index 0000000..ff4d85b --- /dev/null +++ b/test/JiShe.CollectBus.Domain.Tests/CollectBusDomainTestModule.cs @@ -0,0 +1,12 @@ +using Volo.Abp.Modularity; + +namespace JiShe.CollectBus; + +[DependsOn( + typeof(CollectBusDomainModule), + typeof(CollectBusTestBaseModule) +)] +public class CollectBusDomainTestModule : AbpModule +{ + +} diff --git a/test/JiShe.CollectBus.Domain.Tests/FodyWeavers.xml b/test/JiShe.CollectBus.Domain.Tests/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/test/JiShe.CollectBus.Domain.Tests/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/test/JiShe.CollectBus.Domain.Tests/JiShe.CollectBus.Domain.Tests.abppkg b/test/JiShe.CollectBus.Domain.Tests/JiShe.CollectBus.Domain.Tests.abppkg new file mode 100644 index 0000000..a686451 --- /dev/null +++ b/test/JiShe.CollectBus.Domain.Tests/JiShe.CollectBus.Domain.Tests.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.test" +} \ No newline at end of file diff --git a/test/JiShe.CollectBus.Domain.Tests/JiShe.CollectBus.Domain.Tests.csproj b/test/JiShe.CollectBus.Domain.Tests/JiShe.CollectBus.Domain.Tests.csproj new file mode 100644 index 0000000..e9b2d08 --- /dev/null +++ b/test/JiShe.CollectBus.Domain.Tests/JiShe.CollectBus.Domain.Tests.csproj @@ -0,0 +1,21 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + + + + + + + + + + + + + diff --git a/test/JiShe.CollectBus.Domain.Tests/Samples/SampleManager_Tests.cs b/test/JiShe.CollectBus.Domain.Tests/Samples/SampleManager_Tests.cs new file mode 100644 index 0000000..431484b --- /dev/null +++ b/test/JiShe.CollectBus.Domain.Tests/Samples/SampleManager_Tests.cs @@ -0,0 +1,22 @@ +using System.Threading.Tasks; +using Volo.Abp.Modularity; +using Xunit; + +namespace JiShe.CollectBus.Samples; + +public abstract class SampleManager_Tests : CollectBusDomainTestBase + where TStartupModule : IAbpModule +{ + //private readonly SampleManager _sampleManager; + + public SampleManager_Tests() + { + //_sampleManager = GetRequiredService(); + } + + [Fact] + public Task Method1Async() + { + return Task.CompletedTask; + } +} diff --git a/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Applications/EfCoreSampleAppService_Tests.cs b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Applications/EfCoreSampleAppService_Tests.cs new file mode 100644 index 0000000..d63e41d --- /dev/null +++ b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Applications/EfCoreSampleAppService_Tests.cs @@ -0,0 +1,9 @@ +using JiShe.CollectBus.Samples; +using Xunit; + +namespace JiShe.CollectBus.EntityFrameworkCore.Applications; + +public class EfCoreSampleAppService_Tests : SampleAppService_Tests +{ + +} diff --git a/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/CollectBusEntityFrameworkCoreTestBase.cs b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/CollectBusEntityFrameworkCoreTestBase.cs new file mode 100644 index 0000000..dbb442b --- /dev/null +++ b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/CollectBusEntityFrameworkCoreTestBase.cs @@ -0,0 +1,9 @@ +namespace JiShe.CollectBus.EntityFrameworkCore; + +/* This class can be used as a base class for EF Core integration tests, + * while SampleRepository_Tests uses a different approach. + */ +public abstract class CollectBusEntityFrameworkCoreTestBase : CollectBusTestBase +{ + +} diff --git a/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/CollectBusEntityFrameworkCoreTestModule.cs b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/CollectBusEntityFrameworkCoreTestModule.cs new file mode 100644 index 0000000..ec59a28 --- /dev/null +++ b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/CollectBusEntityFrameworkCoreTestModule.cs @@ -0,0 +1,45 @@ +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage; +using Volo.Abp.EntityFrameworkCore; +using Volo.Abp.EntityFrameworkCore.Sqlite; +using Volo.Abp.Modularity; +using Volo.Abp.Uow; + +namespace JiShe.CollectBus.EntityFrameworkCore; + +[DependsOn( + typeof(CollectBusApplicationTestModule), + typeof(CollectBusEntityFrameworkCoreModule), + typeof(AbpEntityFrameworkCoreSqliteModule) +)] +public class CollectBusEntityFrameworkCoreTestModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + context.Services.AddAlwaysDisableUnitOfWorkTransaction(); + + var sqliteConnection = CreateDatabaseAndGetConnection(); + + Configure(options => + { + options.Configure(abpDbContextConfigurationContext => + { + abpDbContextConfigurationContext.DbContextOptions.UseSqlite(sqliteConnection); + }); + }); + } + + private static SqliteConnection CreateDatabaseAndGetConnection() + { + var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + + new CollectBusDbContext( + new DbContextOptionsBuilder().UseSqlite(connection).Options + ).GetService().CreateTables(); + + return connection; + } +} diff --git a/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Domains/EfCoreSampleDomain_Tests.cs b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Domains/EfCoreSampleDomain_Tests.cs new file mode 100644 index 0000000..2a115f5 --- /dev/null +++ b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Domains/EfCoreSampleDomain_Tests.cs @@ -0,0 +1,9 @@ +using JiShe.CollectBus.Samples; +using Xunit; + +namespace JiShe.CollectBus.EntityFrameworkCore.Domains; + +public class EfCoreSampleDomain_Tests : SampleManager_Tests +{ + +} diff --git a/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Samples/SampleRepository_Tests.cs b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Samples/SampleRepository_Tests.cs new file mode 100644 index 0000000..01dd9e2 --- /dev/null +++ b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/EntityFrameworkCore/Samples/SampleRepository_Tests.cs @@ -0,0 +1,11 @@ +using JiShe.CollectBus.Samples; + +namespace JiShe.CollectBus.EntityFrameworkCore.Samples; + +public class SampleRepository_Tests : SampleRepository_Tests +{ + /* Don't write custom repository tests here, instead write to + * the base class. + * One exception can be some specific tests related to EF core. + */ +} diff --git a/test/JiShe.CollectBus.EntityFrameworkCore.Tests/FodyWeavers.xml b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/test/JiShe.CollectBus.EntityFrameworkCore.Tests/JiShe.CollectBus.EntityFrameworkCore.Tests.abppkg b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/JiShe.CollectBus.EntityFrameworkCore.Tests.abppkg new file mode 100644 index 0000000..a686451 --- /dev/null +++ b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/JiShe.CollectBus.EntityFrameworkCore.Tests.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.test" +} \ No newline at end of file diff --git a/test/JiShe.CollectBus.EntityFrameworkCore.Tests/JiShe.CollectBus.EntityFrameworkCore.Tests.csproj b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/JiShe.CollectBus.EntityFrameworkCore.Tests.csproj new file mode 100644 index 0000000..63c7e8e --- /dev/null +++ b/test/JiShe.CollectBus.EntityFrameworkCore.Tests/JiShe.CollectBus.EntityFrameworkCore.Tests.csproj @@ -0,0 +1,19 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + + + + + + + + + + + diff --git a/test/JiShe.CollectBus.MongoDB.Tests/FodyWeavers.xml b/test/JiShe.CollectBus.MongoDB.Tests/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/test/JiShe.CollectBus.MongoDB.Tests/JiShe.CollectBus.MongoDB.Tests.abppkg b/test/JiShe.CollectBus.MongoDB.Tests/JiShe.CollectBus.MongoDB.Tests.abppkg new file mode 100644 index 0000000..a686451 --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/JiShe.CollectBus.MongoDB.Tests.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.test" +} \ No newline at end of file diff --git a/test/JiShe.CollectBus.MongoDB.Tests/JiShe.CollectBus.MongoDB.Tests.csproj b/test/JiShe.CollectBus.MongoDB.Tests/JiShe.CollectBus.MongoDB.Tests.csproj new file mode 100644 index 0000000..c17ce34 --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/JiShe.CollectBus.MongoDB.Tests.csproj @@ -0,0 +1,21 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + + + + + + + + + + + + + diff --git a/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Applications/MongoDBSampleAppService_Tests.cs b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Applications/MongoDBSampleAppService_Tests.cs new file mode 100644 index 0000000..f6dd5c7 --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Applications/MongoDBSampleAppService_Tests.cs @@ -0,0 +1,11 @@ +using JiShe.CollectBus.MongoDB; +using JiShe.CollectBus.Samples; +using Xunit; + +namespace JiShe.CollectBus.MongoDb.Applications; + +[Collection(MongoTestCollection.Name)] +public class MongoDBSampleAppService_Tests : SampleAppService_Tests +{ + +} diff --git a/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/CollectBusMongoDbTestBase.cs b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/CollectBusMongoDbTestBase.cs new file mode 100644 index 0000000..242879a --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/CollectBusMongoDbTestBase.cs @@ -0,0 +1,9 @@ +namespace JiShe.CollectBus.MongoDB; + +/* This class can be used as a base class for MongoDB integration tests, + * while SampleRepository_Tests uses a different approach. + */ +public abstract class CollectBusMongoDbTestBase : CollectBusTestBase +{ + +} diff --git a/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/CollectBusMongoDbTestModule.cs b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/CollectBusMongoDbTestModule.cs new file mode 100644 index 0000000..02028e7 --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/CollectBusMongoDbTestModule.cs @@ -0,0 +1,21 @@ +using System; +using Volo.Abp.Data; +using Volo.Abp.Modularity; +using Volo.Abp.Uow; + +namespace JiShe.CollectBus.MongoDB; + +[DependsOn( + typeof(CollectBusApplicationTestModule), + typeof(CollectBusMongoDbModule) +)] +public class CollectBusMongoDbTestModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => + { + options.ConnectionStrings.Default = MongoDbFixture.GetRandomConnectionString(); + }); + } +} diff --git a/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Domains/MongoDBSampleDomain_Tests.cs b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Domains/MongoDBSampleDomain_Tests.cs new file mode 100644 index 0000000..466ae53 --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Domains/MongoDBSampleDomain_Tests.cs @@ -0,0 +1,10 @@ +using JiShe.CollectBus.Samples; +using Xunit; + +namespace JiShe.CollectBus.MongoDB.Domains; + +[Collection(MongoTestCollection.Name)] +public class MongoDBSampleDomain_Tests : SampleManager_Tests +{ + +} diff --git a/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/MongoDbFixture.cs b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/MongoDbFixture.cs new file mode 100644 index 0000000..540bd3c --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/MongoDbFixture.cs @@ -0,0 +1,34 @@ +using System; +using EphemeralMongo; + +namespace JiShe.CollectBus.MongoDB; + +public class MongoDbFixture : IDisposable +{ + public readonly static IMongoRunner MongoDbRunner; + + static MongoDbFixture() + { + MongoDbRunner = MongoRunner.Run(new MongoRunnerOptions + { + UseSingleNodeReplicaSet = true + }); + } + + public static string GetRandomConnectionString() + { + return GetConnectionString("Db_" + Guid.NewGuid().ToString("N")); + } + + public static string GetConnectionString(string databaseName) + { + var stringArray = MongoDbRunner.ConnectionString.Split('?'); + var connectionString = stringArray[0].EnsureEndsWith('/') + databaseName + "/?" + stringArray[1]; + return connectionString; + } + + public void Dispose() + { + MongoDbRunner?.Dispose(); + } +} diff --git a/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/MongoTestCollection.cs b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/MongoTestCollection.cs new file mode 100644 index 0000000..08fc3b9 --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/MongoTestCollection.cs @@ -0,0 +1,9 @@ +using Xunit; + +namespace JiShe.CollectBus.MongoDB; + +[CollectionDefinition(Name)] +public class MongoTestCollection : ICollectionFixture +{ + public const string Name = "MongoDB Collection"; +} diff --git a/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Samples/SampleRepository_Tests.cs b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Samples/SampleRepository_Tests.cs new file mode 100644 index 0000000..2fc8587 --- /dev/null +++ b/test/JiShe.CollectBus.MongoDB.Tests/MongoDB/Samples/SampleRepository_Tests.cs @@ -0,0 +1,13 @@ +using JiShe.CollectBus.Samples; +using Xunit; + +namespace JiShe.CollectBus.MongoDB.Samples; + +[Collection(MongoTestCollection.Name)] +public class SampleRepository_Tests : SampleRepository_Tests +{ + /* Don't write custom repository tests here, instead write to + * the base class. + * One exception can be some specific tests related to MongoDB. + */ +} diff --git a/test/JiShe.CollectBus.TestBase/CollectBusDataSeedContributor.cs b/test/JiShe.CollectBus.TestBase/CollectBusDataSeedContributor.cs new file mode 100644 index 0000000..a72a0d1 --- /dev/null +++ b/test/JiShe.CollectBus.TestBase/CollectBusDataSeedContributor.cs @@ -0,0 +1,32 @@ +using System.Threading.Tasks; +using Volo.Abp.Data; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Guids; +using Volo.Abp.MultiTenancy; + +namespace JiShe.CollectBus; + +public class CollectBusDataSeedContributor : IDataSeedContributor, ITransientDependency +{ + private readonly IGuidGenerator _guidGenerator; + private readonly ICurrentTenant _currentTenant; + + public CollectBusDataSeedContributor( + IGuidGenerator guidGenerator, ICurrentTenant currentTenant) + { + _guidGenerator = guidGenerator; + _currentTenant = currentTenant; + } + + public Task SeedAsync(DataSeedContext context) + { + /* Instead of returning the Task.CompletedTask, you can insert your test data + * at this point! + */ + + using (_currentTenant.Change(context?.TenantId)) + { + return Task.CompletedTask; + } + } +} diff --git a/test/JiShe.CollectBus.TestBase/CollectBusTestBase.cs b/test/JiShe.CollectBus.TestBase/CollectBusTestBase.cs new file mode 100644 index 0000000..7db1dce --- /dev/null +++ b/test/JiShe.CollectBus.TestBase/CollectBusTestBase.cs @@ -0,0 +1,59 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp; +using Volo.Abp.Modularity; +using Volo.Abp.Uow; +using Volo.Abp.Testing; + +namespace JiShe.CollectBus; + +/* All test classes are derived from this class, directly or indirectly. */ +public abstract class CollectBusTestBase : AbpIntegratedTest + where TStartupModule : IAbpModule +{ + protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) + { + options.UseAutofac(); + } + + protected virtual Task WithUnitOfWorkAsync(Func func) + { + return WithUnitOfWorkAsync(new AbpUnitOfWorkOptions(), func); + } + + protected virtual async Task WithUnitOfWorkAsync(AbpUnitOfWorkOptions options, Func action) + { + using (var scope = ServiceProvider.CreateScope()) + { + var uowManager = scope.ServiceProvider.GetRequiredService(); + + using (var uow = uowManager.Begin(options)) + { + await action(); + + await uow.CompleteAsync(); + } + } + } + + protected virtual Task WithUnitOfWorkAsync(Func> func) + { + return WithUnitOfWorkAsync(new AbpUnitOfWorkOptions(), func); + } + + protected virtual async Task WithUnitOfWorkAsync(AbpUnitOfWorkOptions options, Func> func) + { + using (var scope = ServiceProvider.CreateScope()) + { + var uowManager = scope.ServiceProvider.GetRequiredService(); + + using (var uow = uowManager.Begin(options)) + { + var result = await func(); + await uow.CompleteAsync(); + return result; + } + } + } +} diff --git a/test/JiShe.CollectBus.TestBase/CollectBusTestBaseModule.cs b/test/JiShe.CollectBus.TestBase/CollectBusTestBaseModule.cs new file mode 100644 index 0000000..89b154e --- /dev/null +++ b/test/JiShe.CollectBus.TestBase/CollectBusTestBaseModule.cs @@ -0,0 +1,42 @@ +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp; +using Volo.Abp.Authorization; +using Volo.Abp.Autofac; +using Volo.Abp.Data; +using Volo.Abp.Guids; +using Volo.Abp.Modularity; +using Volo.Abp.Threading; + +namespace JiShe.CollectBus; + +[DependsOn( + typeof(AbpAutofacModule), + typeof(AbpTestBaseModule), + typeof(AbpAuthorizationModule), + typeof(AbpGuidsModule) +)] +public class CollectBusTestBaseModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + context.Services.AddAlwaysAllowAuthorization(); + } + + public override void OnApplicationInitialization(ApplicationInitializationContext context) + { + SeedTestData(context); + } + + private static void SeedTestData(ApplicationInitializationContext context) + { + AsyncHelper.RunSync(async () => + { + using (var scope = context.ServiceProvider.CreateScope()) + { + await scope.ServiceProvider + .GetRequiredService() + .SeedAsync(); + } + }); + } +} diff --git a/test/JiShe.CollectBus.TestBase/FodyWeavers.xml b/test/JiShe.CollectBus.TestBase/FodyWeavers.xml new file mode 100644 index 0000000..1715698 --- /dev/null +++ b/test/JiShe.CollectBus.TestBase/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/test/JiShe.CollectBus.TestBase/JiShe.CollectBus.TestBase.abppkg b/test/JiShe.CollectBus.TestBase/JiShe.CollectBus.TestBase.abppkg new file mode 100644 index 0000000..a686451 --- /dev/null +++ b/test/JiShe.CollectBus.TestBase/JiShe.CollectBus.TestBase.abppkg @@ -0,0 +1,3 @@ +{ + "role": "lib.test" +} \ No newline at end of file diff --git a/test/JiShe.CollectBus.TestBase/JiShe.CollectBus.TestBase.csproj b/test/JiShe.CollectBus.TestBase/JiShe.CollectBus.TestBase.csproj new file mode 100644 index 0000000..cda873b --- /dev/null +++ b/test/JiShe.CollectBus.TestBase/JiShe.CollectBus.TestBase.csproj @@ -0,0 +1,28 @@ + + + + + + net8.0 + enable + JiShe.CollectBus + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + + + + + + + + diff --git a/test/JiShe.CollectBus.TestBase/Samples/SampleRepository_Tests.cs b/test/JiShe.CollectBus.TestBase/Samples/SampleRepository_Tests.cs new file mode 100644 index 0000000..06874fd --- /dev/null +++ b/test/JiShe.CollectBus.TestBase/Samples/SampleRepository_Tests.cs @@ -0,0 +1,26 @@ +using System.Threading.Tasks; +using Volo.Abp.Modularity; +using Xunit; + +namespace JiShe.CollectBus.Samples; + +/* Write your custom repository tests like that, in this project, as abstract classes. + * Then inherit these abstract classes from EF Core & MongoDB test projects. + * In this way, both database providers are tests with the same set tests. + */ +public abstract class SampleRepository_Tests : CollectBusTestBase + where TStartupModule : IAbpModule +{ + //private readonly ISampleRepository _sampleRepository; + + protected SampleRepository_Tests() + { + //_sampleRepository = GetRequiredService(); + } + + [Fact] + public Task Method1Async() + { + return Task.CompletedTask; + } +} diff --git a/test/JiShe.CollectBus.TestBase/Security/FakeCurrentPrincipalAccessor.cs b/test/JiShe.CollectBus.TestBase/Security/FakeCurrentPrincipalAccessor.cs new file mode 100644 index 0000000..a976624 --- /dev/null +++ b/test/JiShe.CollectBus.TestBase/Security/FakeCurrentPrincipalAccessor.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using System.Security.Claims; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Security.Claims; + +namespace JiShe.CollectBus.Security; + +[Dependency(ReplaceServices = true)] +public class FakeCurrentPrincipalAccessor : ThreadCurrentPrincipalAccessor +{ + protected override ClaimsPrincipal GetClaimsPrincipal() + { + return GetPrincipal(); + } + + private ClaimsPrincipal GetPrincipal() + { + return new ClaimsPrincipal(new ClaimsIdentity(new List + { + new Claim(AbpClaimTypes.UserId, "2e701e62-0953-4dd3-910b-dc6cc93ccb0d"), + new Claim(AbpClaimTypes.UserName, "admin"), + new Claim(AbpClaimTypes.Email, "admin@abp.io") + } + ) + ); + } +}