diff --git a/LICENSE b/LICENSE index 67b52f7..79a535b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2018 SmallChi(Koike) +Copyright (c) 2019 SmallChi(Koike) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index e7bcda4..62abed7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ -# JT808DotNetty +# JT808Gateway -基于DotNetty封装的JT808DotNetty支持TCP/UDP通用消息业务处理 +基于DotNetty封装的JT808DotNetty支持TCP/UDP通用消息业务处理 + +基于Pipeline封装的JT808DotNetty支持TCP/UDP通用消息业务处理 [了解JT808协议进这边](https://github.com/SmallChi/JT808) @@ -14,7 +16,7 @@ [![MIT Licence](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/SmallChi/JT808DotNetty/blob/master/LICENSE)[![Build Status](https://travis-ci.org/SmallChi/JT808DotNetty.svg?branch=master)](https://travis-ci.org/SmallChi/JT808DotNetty) -## 新网关的优势: +## 新网关的优势 1. 跨平台 2. 借助 .NET Core模块化的思想 @@ -55,7 +57,7 @@ |Traffic|流量统计服务 |由于运营商sim卡查询流量滞后,通过流量统计服务可以实时准确的统计设备流量,可以最优配置设备的流量大小,以节省成本 |Transmit| 原包转发服务|该服务可以将设备上报原始数据转发到第三方,支持全部转发,指定终端号转发| -## NuGet安装 +## 基于DotNetty的NuGet安装 | Package Name | Version | Downloads | | --------------------- | -------------------------------------------------- | --------------------------------------------------- | @@ -75,6 +77,13 @@ | Install-Package JT808.DotNetty.Kafka | ![JT808](https://img.shields.io/nuget/v/JT808.DotNetty.Kafka.svg) | ![JT808](https://img.shields.io/nuget/dt/JT808.DotNetty.Kafka.svg) | | Install-Package JT808.DotNetty.RabbitMQ | ![JT808](https://img.shields.io/nuget/v/JT808.DotNetty.RabbitMQ.svg) | ![JT808](https://img.shields.io/nuget/dt/JT808.DotNetty.RabbitMQ.svg) | +## 基于Pipeline的NuGet安装 + +| Package Name | Version | Downloads | +| --------------------- | -------------------------------------------------- | --------------------------------------------------- | +| Install-Package JT808.Gateway | ![JT808.Gateway](https://img.shields.io/nuget/v/JT808.Gateway.svg) | ![JT808.Gateway](https://img.shields.io/nuget/dt/JT808.Gateway.svg) | +| Install-Package JT808.Gateway.Kafka| ![JT808.Gateway.Kafka](https://img.shields.io/nuget/v/JT808.Gateway.Kafka.svg) | ![JT808.Gateway.Kafka](https://img.shields.io/nuget/dt/JT808.Gateway.Kafka.svg) | + ## 举个栗子1 ``` demo1 diff --git a/README_V1.0.0.md b/README_V1.0.0.md deleted file mode 100644 index 1277e7e..0000000 --- a/README_V1.0.0.md +++ /dev/null @@ -1,120 +0,0 @@ -# JT808DotNetty - -基于DotNetty封装的JT808DotNetty支持TCP/UDP通用消息业务处理 - -[了解JT808协议进这边](https://github.com/SmallChi/JT808) - -[了解JT809协议进这边](https://github.com/SmallChi/JT809) - -[了解JT1078协议进这边](https://github.com/SmallChi/JT1078) - -[了解JTNE协议进这边](https://github.com/SmallChi/JTNewEnergy) - -[玩一玩压力测试](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/README.md) - -[V2.2.1老版本](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/README_V2.2.1.md) - -[![MIT Licence](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/SmallChi/JT808DotNetty/blob/master/LICENSE) - -## 新网关的优势 - -1. 跨平台 -2. 借助 .NET Core模块化的思想 -3. 单机同时一万辆车在线不是梦(真有一万辆车那都很吃香了<( ̄3 ̄)> <( ̄3 ̄)> <( ̄3 ̄)> ) -4. 简单易上手 - -## 设计模型 - -![design_model](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/img/design_model.png) - -## 基于Grpc的消息业务处理程序(JT808.Gateway.GrpcService) - -``` 1 -services.AddGrpcClient(o => -{ - o.Address = new Uri("https://localhost:5001"); -}); -``` - -## 集成接口功能(JT808.Gateway.PubSub) - -|接口名称|接口说明|使用场景| -|:------:|:------|:------| -| IJT808SessionProducer| 会话通知(在线/离线)数据生产接口| 有些超长待机的设备,不会实时保持连接,那么通过平台下发的命令是无法到达的,这时候就需要设备一上线,就即时通知服务去处理,然后在即时的下发消息到设备。| -| IJT808SessionConsumer| 会话通知(在线/离线)数据消费接口| -| -| IJT808MsgProducer| 数据生产接口| 网关将接收到的数据发送到队列| -| IJT808MsgConsumer| 数据消费接口| 将数据进行对应的消息业务处理(例:设备流量统计、第三方平台数据转发、消息日志等) | -| IJT808MsgReplyProducer| 应答数据生产接口|将生产的数据解析为对应的消息Id应答发送到队列 | -| IJT808MsgReplyConsumer| 应答数据消费接口| 将接收到的应答数据下发给设备| - -> 使用物联网卡通过udp下发指令时,存储的那个socket地址端口,有效期非常短,不速度快点下发,那个socket地址端口就可能映射到别的对应卡去了,所以此处采用跟随设备消息下发指令。 - -## 基于网关的相关服务(JT808.Gateway.BusinessServices) - -|服务名称|服务说明|使用场景| -|:------:|:------|:------| -|MsgIdHandler| 消息处理服务|从队列中消费设备上报数据,再结合自身的业务场景,将数据进行处理并入库 | -|MsgLogging | 消息日志服务|从队列中消费设备上报和平台应答数据,再将数据存入influxdb等数据库中,便于技术和技术支持排查设备与平台交互的原始数据| -|ReplyMessage| 消息响应服务| 用于响应设备上报消息,以及下发指令信息到设备| -|SessionNotice| 会话管理服务| 通知设备上线下线,对于udp设备来说,可以在设备上线时,将指令跟随消息下发到设备| -|Traffic|流量统计服务 |由于运营商sim卡查询流量滞后,通过流量统计服务可以实时准确的统计设备流量,可以最优配置设备的流量大小,以节省成本 -|Transmit| 原包转发服务|该服务可以将设备上报原始数据转发到第三方,支持全部转发,指定终端号转发| - -## NuGet安装 - -| Package Name | Version | Downloads | -| --------------------- | -------------------------------------------------- | --------------------------------------------------- | -| Install-Package JT808.Gateway | ![JT808.Gateway](https://img.shields.io/nuget/v/JT808.Gateway.svg) | ![JT808.Gateway](https://img.shields.io/nuget/dt/JT808.Gateway.svg) | -| Install-Package JT808.Gateway.Kafka| ![JT808.Gateway.Kafka](https://img.shields.io/nuget/v/JT808.Gateway.Kafka.svg) | ![JT808.Gateway.Kafka](https://img.shields.io/nuget/dt/JT808.Gateway.Kafka.svg) | - -## 举个栗子1 - -1.进入JT808.Gateway.SimpleServer项目下的Debug目录运行服务端 - -2.进入JT808.Gateway.SimpleClient项目下的Debug目录运行客户端 - -``` 1 -static void Main(string[] args) -{ - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - //配置Grpc服务端 - webBuilder - .ConfigureKestrel(options => - { - options.Listen(IPAddress.Any, 5001, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http2; - listenOptions.UseHttps($"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs", "test.cer")}", ""); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseEndpoints(endpoints => - { - //配置Grpc服务节点 - endpoints.MapGrpcService(); - }); - }); - }) - .ConfigureServices((hostContext,services) => - { - //services.Configure(hostContext.Configuration.GetSection("Kestrel")); - //添加Grpc服务 - services.AddGrpc(); - //添加JT808协议 - services.AddJT808Configure() - //添加JT808网关配置 - .AddJT808Gateway(hostContext.Configuration) - //添加基于Tcp的808网关 - .AddJT808GatewayTcpHost() - //添加基于Udp的808网关 - .AddJT808GatewayUdpHost() - .Builder(); - }) - .Build() - .Run(); -} -``` diff --git a/doc/README.md b/doc/README.md index ae791e0..9aaebe3 100644 --- a/doc/README.md +++ b/doc/README.md @@ -1,4 +1,6 @@ -## 压力测试 +# 压力测试 + +## 基于DotNetty [感谢泥水佬提供的压力测试工具](https://www.cnblogs.com/smark/p/4496660.html?utm_source=tuicool) @@ -7,10 +9,25 @@ | win server 2016 | 4c8g | 压力测试客户端 | | centos7 | 4c8g | JT808服务端 | -![performance_1000](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/img/performance_1000.png) +![performance_1000](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/dotnetty/performance_1000.png) + +![performance_2000](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/dotnetty/performance_2000.png) + +![performance_5000](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/dotnetty/performance_5000.png) + +![performance_10000](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/dotnetty/performance_10000.png) + +## 基于pipeline + +| 操作系统 | 配置 | 使用 | +|:-------:|:-------:|:-------:| +| centos7 | 4c8g | JT808服务端 | +| centos7 | 4c8g | JT808客户端 | + +> 计算网络增强型 sn1ne ecs.sn1ne.xlarge 4 vCPU 8 GiB Intel Xeon E5-2682v4 / Intel Xeon(Skylake) Platinum 8163 2.5 GHz 1.5 Gbps 50 万 PPS -![performance_2000](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/img/performance_2000.png) +![server_proccess_10k](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/pipeline/server_proccess_10k.png) -![performance_5000](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/img/performance_5000.png) +![server_network_10k](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/pipeline/server_network_10k.png) -![performance_10000](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/img/performance_10000.png) +![client_10k](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/pipeline/client_10k.png) diff --git a/doc/img/demo1.png b/doc/dotnetty/demo1.png similarity index 100% rename from doc/img/demo1.png rename to doc/dotnetty/demo1.png diff --git a/doc/img/demo2.png b/doc/dotnetty/demo2.png similarity index 100% rename from doc/img/demo2.png rename to doc/dotnetty/demo2.png diff --git a/doc/img/design_model.png b/doc/dotnetty/design_model.png similarity index 100% rename from doc/img/design_model.png rename to doc/dotnetty/design_model.png diff --git a/doc/img/performance_1000.png b/doc/dotnetty/performance_1000.png similarity index 100% rename from doc/img/performance_1000.png rename to doc/dotnetty/performance_1000.png diff --git a/doc/img/performance_10000.png b/doc/dotnetty/performance_10000.png similarity index 100% rename from doc/img/performance_10000.png rename to doc/dotnetty/performance_10000.png diff --git a/doc/img/performance_2000.png b/doc/dotnetty/performance_2000.png similarity index 100% rename from doc/img/performance_2000.png rename to doc/dotnetty/performance_2000.png diff --git a/doc/img/performance_5000.png b/doc/dotnetty/performance_5000.png similarity index 100% rename from doc/img/performance_5000.png rename to doc/dotnetty/performance_5000.png diff --git a/doc/pipeline/client_10k.png b/doc/pipeline/client_10k.png new file mode 100644 index 0000000..85875d6 Binary files /dev/null and b/doc/pipeline/client_10k.png differ diff --git a/doc/pipeline/server_network_10k.png b/doc/pipeline/server_network_10k.png new file mode 100644 index 0000000..4a46990 Binary files /dev/null and b/doc/pipeline/server_network_10k.png differ diff --git a/doc/pipeline/server_proccess_10k.png b/doc/pipeline/server_proccess_10k.png new file mode 100644 index 0000000..c41d69d Binary files /dev/null and b/doc/pipeline/server_proccess_10k.png differ diff --git a/src/JT808.Gateway.CleintBenchmark/Configs/ClientBenchmarkOptions.cs b/src/JT808.Gateway.CleintBenchmark/Configs/ClientBenchmarkOptions.cs deleted file mode 100644 index f8dd628..0000000 --- a/src/JT808.Gateway.CleintBenchmark/Configs/ClientBenchmarkOptions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.CleintBenchmark.Configs -{ - public class ClientBenchmarkOptions : IOptions - { - public string IP { get; set; } - public int Port { get; set; } - public int DeviceCount { get; set; } = 10; - /// - /// 5000ms毫秒 - /// - public int Interval { get; set; } = 5000; - public ClientBenchmarkOptions Value =>this; - } -} diff --git a/src/JT808.Gateway.CleintBenchmark/Configs/NLog.xsd b/src/JT808.Gateway.CleintBenchmark/Configs/NLog.xsd deleted file mode 100644 index 2f57d09..0000000 --- a/src/JT808.Gateway.CleintBenchmark/Configs/NLog.xsd +++ /dev/null @@ -1,3106 +0,0 @@ - - - - - - - - - - - - - - - Watch config file for changes and reload automatically. - - - - - Print internal NLog messages to the console. Default value is: false - - - - - Print internal NLog messages to the console error output. Default value is: false - - - - - Write internal NLog messages to the specified file. - - - - - Log level threshold for internal log messages. Default value is: Info. - - - - - Global log level threshold for application log messages. Messages below this level won't be logged.. - - - - - Throw an exception when there is an internal error. Default value is: false. - - - - - Throw an exception when there is a configuration error. If not set, determined by throwExceptions. - - - - - Gets or sets a value indicating whether Variables should be kept on configuration reload. Default value is: false. - - - - - Write internal NLog messages to the System.Diagnostics.Trace. Default value is: false. - - - - - Write timestamps for internal NLog messages. Default value is: true. - - - - - Use InvariantCulture as default culture instead of CurrentCulture. Default value is: false. - - - - - Perform mesage template parsing and formatting of LogEvent messages (true = Always, false = Never, empty = Auto Detect). Default value is: empty. - - - - - - - - - - - - - - Make all targets within this section asynchronous (creates additional threads but the calling thread isn't blocked by any target writes). - - - - - - - - - - - - - - - - - Prefix for targets/layout renderers/filters/conditions loaded from this assembly. - - - - - Load NLog extensions from the specified file (*.dll) - - - - - Load NLog extensions from the specified assembly. Assembly name should be fully qualified. - - - - - - - - - - Name of the logger. May include '*' character which acts like a wildcard. Allowed forms are: *, Name, *Name, Name* and *Name* - - - - - Comma separated list of levels that this rule matches. - - - - - Minimum level that this rule matches. - - - - - Maximum level that this rule matches. - - - - - Level that this rule matches. - - - - - Comma separated list of target names. - - - - - Ignore further rules if this one matches. - - - - - Enable or disable logging rule. Disabled rules are ignored. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the file to be included. You could use * wildcard. The name is relative to the name of the current config file. - - - - - Ignore any errors in the include file. - - - - - - - Variable name. - - - - - Variable value. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Number of log events that should be processed in a batch by the lazy writer thread. - - - - - Limit of full s to write before yielding into Performance is better when writing many small batches, than writing a single large batch - - - - - Action to be taken when the lazy writer thread request queue count exceeds the set limit. - - - - - Limit on the number of requests in the lazy writer thread request queue. - - - - - Time in milliseconds to sleep between batches. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Delay the flush until the LogEvent has been confirmed as written - - - - - Condition expression. Log events who meet this condition will cause a flush on the wrapped target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Number of log events to be buffered. - - - - - Timeout (in milliseconds) after which the contents of buffer will be flushed if there's no write in the specified period of time. Use -1 to disable timed flushes. - - - - - Indicates whether to use sliding timeout. - - - - - Action to take if the buffer overflows. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Encoding to be used. - - - - - Instance of that is used to format log messages. - - - - - End of line value if a newline is appended at the end of log message . - - - - - Maximum message size in bytes. - - - - - Indicates whether to append newline at the end of log message. - - - - - Action that should be taken if the will be more connections than . - - - - - Action that should be taken if the message is larger than maxMessageSize. - - - - - Maximum current connections. 0 = no maximum. - - - - - Indicates whether to keep connection open whenever possible. - - - - - Size of the connection cache (number of connections which are kept alive). - - - - - Network address. - - - - - Maximum queue size. - - - - - NDC item separator. - - - - - Indicates whether to include source info (file name and line number) in the information sent over the network. - - - - - Indicates whether to include dictionary contents. - - - - - Indicates whether to include contents of the stack. - - - - - Indicates whether to include stack contents. - - - - - Indicates whether to include dictionary contents. - - - - - Indicates whether to include call site (class and method name) in the information sent over the network. - - - - - Option to include all properties from the log events - - - - - AppInfo field. By default it's the friendly name of the current AppDomain. - - - - - Indicates whether to include NLog-specific extensions to log4j schema. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - Layout that should be use to calcuate the value for the parameter. - - - - - Viewer parameter name. - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - Indicates whether to use default row highlighting rules. - - - - - Indicates whether to auto-check if the console is available. - Disables console writing if Environment.UserInteractive = False (Windows Service) - Disables console writing if Console Standard Input is not available (Non-Console-App) - - - - - The encoding for writing messages to the . - - - - - Indicates whether the error stream (stderr) should be used instead of the output stream (stdout). - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Condition that must be met in order to set the specified foreground and background color. - - - - - Background color. - - - - - Foreground color. - - - - - - - - - - - - - - - - Indicates whether to ignore case when comparing texts. - - - - - Regular expression to be matched. You must specify either text or regex. - - - - - Text to be matched. You must specify either text or regex. - - - - - Indicates whether to match whole words only. - - - - - Compile the ? This can improve the performance, but at the costs of more memory usage. If false, the Regex Cache is used. - - - - - Background color. - - - - - Foreground color. - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - Indicates whether to send the log messages to the standard error instead of the standard output. - - - - - Indicates whether to auto-check if the console is available - Disables console writing if Environment.UserInteractive = False (Windows Service) - Disables console writing if Console Standard Input is not available (Non-Console-App) - - - - - The encoding for writing messages to the . - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Obsolete - value will be ignored! The logging code always runs outside of transaction. Gets or sets a value indicating whether to use database transactions. Some data providers require this. - - - - - Database user name. If the ConnectionString is not provided this value will be used to construct the "User ID=" part of the connection string. - - - - - Name of the database provider. - - - - - Database password. If the ConnectionString is not provided this value will be used to construct the "Password=" part of the connection string. - - - - - Indicates whether to keep the database connection open between the log events. - - - - - Database name. If the ConnectionString is not provided this value will be used to construct the "Database=" part of the connection string. - - - - - Name of the connection string (as specified in <connectionStrings> configuration section. - - - - - Connection string. When provided, it overrides the values specified in DBHost, DBUserName, DBPassword, DBDatabase. - - - - - Database host name. If the ConnectionString is not provided this value will be used to construct the "Server=" part of the connection string. - - - - - Connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Text of the SQL command to be run on each log level. - - - - - Type of the SQL command to be run on each log level. - - - - - - - - - - - - - - - - - - - - - - - Type of the command. - - - - - Connection string to run the command against. If not provided, connection string from the target is used. - - - - - Indicates whether to ignore failures. - - - - - Command text. - - - - - - - - - - - - - - Layout that should be use to calcuate the value for the parameter. - - - - - Database parameter name. - - - - - Database parameter precision. - - - - - Database parameter scale. - - - - - Database parameter size. - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Layout that renders event Category. - - - - - Layout that renders event ID. - - - - - Name of the Event Log to write to. This can be System, Application or any user-defined name. - - - - - Name of the machine on which Event Log service is running. - - - - - Value to be used as the event Source. - - - - - Action to take if the message is larger than the option. - - - - - Optional entrytype. When not set, or when not convertable to then determined by - - - - - Maximum Event log size in kilobytes. If null, the value won't be set. Default is 512 Kilobytes as specified by Eventlog API - - - - - Message length limit to write to the Event Log. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Indicates whether to return to the first target after any successful write. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - File encoding. - - - - - Line ending mode. - - - - - Way file archives are numbered. - - - - - Name of the file to be used for an archive. - - - - - Indicates whether to automatically archive log files every time the specified time passes. - - - - - Size in bytes above which log files will be automatically archived. Warning: combining this with isn't supported. We cannot create multiple archive files, if they should have the same name. Choose: - - - - - Indicates whether to compress archive files into the zip archive format. - - - - - Maximum number of archive files that should be kept. - - - - - Gets or set a value indicating whether a managed file stream is forced, instead of using the native implementation. - - - - - Is the an absolute or relative path? - - - - - Cleanup invalid values in a filename, e.g. slashes in a filename. If set to true, this can impact the performance of massive writes. If set to false, nothing gets written when the filename is wrong. - - - - - Whether or not this target should just discard all data that its asked to write. Mostly used for when testing NLog Stack except final write - - - - - Is the an absolute or relative path? - - - - - Value indicationg whether file creation calls should be synchronized by a system global mutex. - - - - - Maximum number of log filenames that should be stored as existing. - - - - - Indicates whether the footer should be written only when the file is archived. - - - - - Name of the file to write to. - - - - - Value specifying the date format to use when archiving files. - - - - - Indicates whether to archive old log file on startup. - - - - - Indicates whether to create directories if they do not exist. - - - - - File attributes (Windows only). - - - - - Indicates whether to delete old log file on startup. - - - - - Indicates whether to replace file contents on each write instead of appending log message at the end. - - - - - Indicates whether to enable log file(s) to be deleted. - - - - - Number of times the write is appended on the file before NLog discards the log message. - - - - - Indicates whether concurrent writes to the log file by multiple processes on the same host. - - - - - Indicates whether to keep log file open instead of opening and closing it on each logging event. - - - - - Indicates whether concurrent writes to the log file by multiple processes on different network hosts. - - - - - Number of files to be kept open. Setting this to a higher value may improve performance in a situation where a single File target is writing to many files (such as splitting by level or by logger). - - - - - Maximum number of seconds that files are kept open. If this number is negative the files are not automatically closed after a period of inactivity. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Log file buffer size in bytes. - - - - - Indicates whether to automatically flush the file buffers after each log message. - - - - - Delay in milliseconds to wait before attempting to write to the file again. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Condition expression. Log events who meet this condition will be forwarded to the wrapped target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Windows domain name to change context to. - - - - - Required impersonation level. - - - - - Type of the logon provider. - - - - - Logon Type. - - - - - User account password. - - - - - Indicates whether to revert to the credentials of the process instead of impersonating another user. - - - - - Username to change context to. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Interval in which messages will be written up to the number of messages. - - - - - Maximum allowed number of messages written per . - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Endpoint address. - - - - - Name of the endpoint configuration in WCF configuration file. - - - - - Indicates whether to use a WCF service contract that is one way (fire and forget) or two way (request-reply) - - - - - Client ID. - - - - - Indicates whether to include per-event properties in the payload sent to the server. - - - - - Indicates whether to use binary message encoding. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - Layout that should be use to calculate the value for the parameter. - - - - - Name of the parameter. - - - - - Type of the parameter. - - - - - Type of the parameter. Obsolete alias for - - - - - Parameter can combine multiple LogEvents into a single parameter value - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - Indicates whether to send message as HTML instead of plain text. - - - - - Encoding to be used for sending e-mail. - - - - - Indicates whether to add new lines between log entries. - - - - - CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). - - - - - Recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). - - - - - BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). - - - - - Mail message body (repeated for each log message send in one mail). - - - - - Mail subject. - - - - - Sender's email address (e.g. joe@domain.com). - - - - - Indicates the SMTP client timeout. - - - - - Priority used for sending mails. - - - - - Indicates whether NewLine characters in the body should be replaced with tags. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - SMTP Server to be used for sending. - - - - - SMTP Authentication mode. - - - - - Username used to connect to SMTP server (used when SmtpAuthentication is set to "basic"). - - - - - Password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic"). - - - - - Indicates whether SSL (secure sockets layer) should be used when communicating with SMTP server. - - - - - Port number that SMTP Server is listening on. - - - - - Indicates whether the default Settings from System.Net.MailSettings should be used. - - - - - Folder where applications save mail messages to be processed by the local SMTP server. - - - - - Specifies how outgoing email messages will be handled. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Class name. - - - - - Method name. The method must be public and static. Use the AssemblyQualifiedName , https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx e.g. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Encoding to be used. - - - - - End of line value if a newline is appended at the end of log message . - - - - - Maximum message size in bytes. - - - - - Indicates whether to append newline at the end of log message. - - - - - Action that should be taken if the will be more connections than . - - - - - Action that should be taken if the message is larger than maxMessageSize. - - - - - Network address. - - - - - Size of the connection cache (number of connections which are kept alive). - - - - - Indicates whether to keep connection open whenever possible. - - - - - Maximum current connections. 0 = no maximum. - - - - - Maximum queue size. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Encoding to be used. - - - - - Instance of that is used to format log messages. - - - - - End of line value if a newline is appended at the end of log message . - - - - - Maximum message size in bytes. - - - - - Indicates whether to append newline at the end of log message. - - - - - Action that should be taken if the will be more connections than . - - - - - Action that should be taken if the message is larger than maxMessageSize. - - - - - Maximum current connections. 0 = no maximum. - - - - - Indicates whether to keep connection open whenever possible. - - - - - Size of the connection cache (number of connections which are kept alive). - - - - - Network address. - - - - - Maximum queue size. - - - - - NDC item separator. - - - - - Indicates whether to include source info (file name and line number) in the information sent over the network. - - - - - Indicates whether to include dictionary contents. - - - - - Indicates whether to include contents of the stack. - - - - - Indicates whether to include stack contents. - - - - - Indicates whether to include dictionary contents. - - - - - Indicates whether to include call site (class and method name) in the information sent over the network. - - - - - Option to include all properties from the log events - - - - - AppInfo field. By default it's the friendly name of the current AppDomain. - - - - - Indicates whether to include NLog-specific extensions to log4j schema. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Indicates whether to perform layout calculation. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Indicates whether performance counter should be automatically created. - - - - - Name of the performance counter category. - - - - - Counter help text. - - - - - Name of the performance counter. - - - - - Performance counter type. - - - - - The value by which to increment the counter. - - - - - Performance counter instance name. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Default filter to be applied when no specific rule matches. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - Condition to be tested. - - - - - Resulting filter to be applied when the condition matches. - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Number of times to repeat each log message. - - - - - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Number of retries that should be attempted on the wrapped target in case of a failure. - - - - - Time to wait between retries in milliseconds. - - - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Always use independent of - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Should we include the BOM (Byte-order-mark) for UTF? Influences the property. This will only work for UTF-8. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Encoding. - - - - - Value whether escaping be done according to the old NLog style (Very non-standard) - - - - - Value whether escaping be done according to Rfc3986 (Supports Internationalized Resource Identifiers - IRIs) - - - - - Web service method name. Only used with Soap. - - - - - Web service namespace. Only used with Soap. - - - - - Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in parameters) - - - - - Protocol to be used when calling web service. - - - - - Web service URL. - - - - - Name of the root XML element, if POST of XML document chosen. If so, this property must not be null. (see and ). - - - - - (optional) root namespace of the XML document, if POST of XML document chosen. (see and ). - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Footer layout. - - - - - Header layout. - - - - - Body layout (can be repeated multiple times). - - - - - Custom column delimiter value (valid when ColumnDelimiter is set to 'Custom'). - - - - - Column delimiter. - - - - - Quote Character. - - - - - Quoting mode. - - - - - Indicates whether CVS should include header. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Layout of the column. - - - - - Name of the column. - - - - - - - - - - - - - - - - - - List of property names to exclude when is true - - - - - Option to include all properties from the log events - - - - - Indicates whether to include contents of the dictionary. - - - - - Indicates whether to include contents of the dictionary. - - - - - Option to render the empty object value {} - - - - - Option to suppress the extra spaces in the output json - - - - - - - - - - - - - - - Determines wether or not this attribute will be Json encoded. - - - - - Indicates whether to escape non-ascii characters - - - - - Layout that will be rendered as the attribute's value. - - - - - Name of the attribute. - - - - - - - - - - - - - - Footer layout. - - - - - Header layout. - - - - - Body layout (can be repeated multiple times). - - - - - - - - - - - - - - - - - - Option to include all properties from the log events - - - - - Indicates whether to include contents of the dictionary. - - - - - Indicates whether to include contents of the dictionary. - - - - - Indicates whether to include contents of the stack. - - - - - Indicates whether to include contents of the stack. - - - - - - - - - - - - - - Layout text. - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - Condition expression. - - - - - - - - - - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - Indicates whether to ignore case when comparing strings. - - - - - Layout to be used to filter log messages. - - - - - Substring to be matched. - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - String to compare the layout to. - - - - - Indicates whether to ignore case when comparing strings. - - - - - Layout to be used to filter log messages. - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - Indicates whether to ignore case when comparing strings. - - - - - Layout to be used to filter log messages. - - - - - Substring to be matched. - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - String to compare the layout to. - - - - - Indicates whether to ignore case when comparing strings. - - - - - Layout to be used to filter log messages. - - - - - - - - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - Layout to be used to filter log messages. - - - - - Default number of unique filter values to expect, will automatically increase if needed - - - - - Append FilterCount to the when an event is no longer filtered - - - - - Insert FilterCount value into when an event is no longer filtered - - - - - Applies the configured action to the initial logevent that starts the timeout period. Used to configure that it should ignore all events until timeout. - - - - - Max number of unique filter values to expect simultaneously - - - - - Max length of filter values, will truncate if above limit - - - - - Default buffer size for the internal buffers - - - - - Reuse internal buffers, and doesn't have to constantly allocate new buffers - - - - - How long before a filter expires, and logging is accepted again - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/JT808.Gateway.CleintBenchmark/Configs/nlog.unix.config b/src/JT808.Gateway.CleintBenchmark/Configs/nlog.unix.config deleted file mode 100644 index 2c8b777..0000000 --- a/src/JT808.Gateway.CleintBenchmark/Configs/nlog.unix.config +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/JT808.Gateway.CleintBenchmark/Configs/nlog.win.config b/src/JT808.Gateway.CleintBenchmark/Configs/nlog.win.config deleted file mode 100644 index 14d4a10..0000000 --- a/src/JT808.Gateway.CleintBenchmark/Configs/nlog.win.config +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/JT808.Gateway.CleintBenchmark/JT808.Gateway.CleintBenchmark.csproj b/src/JT808.Gateway.CleintBenchmark/JT808.Gateway.CleintBenchmark.csproj deleted file mode 100644 index ad20926..0000000 --- a/src/JT808.Gateway.CleintBenchmark/JT808.Gateway.CleintBenchmark.csproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - Exe - netcoreapp3.0 - - - - - - - - - - - - - - - Always - - - Always - - - Always - - - Always - - - - diff --git a/src/JT808.Gateway.CleintBenchmark/Program.cs b/src/JT808.Gateway.CleintBenchmark/Program.cs deleted file mode 100644 index 88451ca..0000000 --- a/src/JT808.Gateway.CleintBenchmark/Program.cs +++ /dev/null @@ -1,51 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; -using System; -using System.Threading.Tasks; -using JT808.Protocol; -using Microsoft.Extensions.Configuration; -using JT808.Gateway.CleintBenchmark.Configs; -using JT808.Gateway.Client; -using JT808.Gateway.CleintBenchmark.Services; - -namespace JT808.Gateway.CleintBenchmark -{ - class Program - { - static async Task Main(string[] args) - { - var serverHostBuilder = new HostBuilder() - .ConfigureAppConfiguration((hostingContext, config) => - { - config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory); - config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); - }) - .ConfigureLogging((context, logging) => - { - if (Environment.OSVersion.Platform == PlatformID.Unix) - { - NLog.LogManager.LoadConfiguration("Configs/nlog.unix.config"); - } - else - { - NLog.LogManager.LoadConfiguration("Configs/nlog.win.config"); - } - logging.AddNLog(); - logging.SetMinimumLevel(LogLevel.Trace); - }) - .ConfigureServices((hostContext, services) => - { - services.Configure(hostContext.Configuration.GetSection("ClientBenchmarkOptions")); - services.AddSingleton(); - services.AddSingleton(typeof(ILogger<>), typeof(Logger<>)); - services.AddJT808Configure() - .AddJT808Client(); - services.AddHostedService(); - services.AddHostedService(); - }); - await serverHostBuilder.RunConsoleAsync(); - } - } -} diff --git a/src/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkHostedService.cs b/src/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkHostedService.cs deleted file mode 100644 index 8cfa879..0000000 --- a/src/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkHostedService.cs +++ /dev/null @@ -1,82 +0,0 @@ -using JT808.Gateway.CleintBenchmark.Configs; -using JT808.Gateway.Client; -using JT808.Protocol.MessageBody; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - - -namespace JT808.Gateway.CleintBenchmark.Services -{ - public class CleintBenchmarkHostedService : IHostedService - { - private readonly ClientBenchmarkOptions clientBenchmarkOptions; - - private readonly ILogger logger; - - private readonly IJT808TcpClientFactory jT808TcpClientFactory; - - private CancellationTokenSource cts=new CancellationTokenSource(); - - private TaskFactory taskFactory; - - public CleintBenchmarkHostedService( - ILoggerFactory loggerFactory, - IJT808TcpClientFactory jT808TcpClientFactory, - IOptions clientBenchmarkOptionsAccessor) - { - this.jT808TcpClientFactory = jT808TcpClientFactory; - clientBenchmarkOptions = clientBenchmarkOptionsAccessor.Value; - logger = loggerFactory.CreateLogger("CleintBenchmarkHostedService"); - taskFactory = new TaskFactory(); - } - public Task StartAsync(CancellationToken cancellationToken) - { - logger.LogInformation("StartAsync..."); - ThreadPool.GetMinThreads(out var minWorkerThreads, out var minCompletionPortThreads); - ThreadPool.GetMaxThreads(out var maxWorkerThreads, out var maxCompletionPortThreads); - logger.LogInformation($"GetMinThreads:{minWorkerThreads}-{minCompletionPortThreads}"); - logger.LogInformation($"GetMaxThreads:{maxWorkerThreads}-{maxCompletionPortThreads}"); - //ThreadPool.SetMaxThreads(20, 20); - //ThreadPool.GetMaxThreads(out var setMaxWorkerThreads, out var setMaxCompletionPortThreads); - //logger.LogInformation($"SetMaxThreads:{setMaxWorkerThreads}-{setMaxCompletionPortThreads}"); - for (int i=0;i< clientBenchmarkOptions.DeviceCount; i++) - { - taskFactory.StartNew((item) => - { - var client = jT808TcpClientFactory.Create(new DeviceConfig(((int)item).ToString(), clientBenchmarkOptions.IP, clientBenchmarkOptions.Port)); - int lat = new Random(1000).Next(100000, 180000); - int Lng = new Random(1000).Next(100000, 180000); - while (!cts.IsCancellationRequested) - { - client.Send(new JT808_0x0200() - { - Lat = lat, - Lng = Lng, - GPSTime = DateTime.Now, - Speed = 50, - Direction = 30, - AlarmFlag = 5, - Altitude = 50, - StatusFlag = 10 - }); - Thread.Sleep(clientBenchmarkOptions.Interval); - } - }, i,cts.Token); - } - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - cts.Cancel(); - logger.LogInformation("StopAsync..."); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkReportHostedService.cs b/src/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkReportHostedService.cs deleted file mode 100644 index 768f475..0000000 --- a/src/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkReportHostedService.cs +++ /dev/null @@ -1,53 +0,0 @@ -using JT808.Gateway.Services; -using JT808.Protocol.MessageBody; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - - -namespace JT808.Gateway.CleintBenchmark.Services -{ - public class CleintBenchmarkReportHostedService : IHostedService - { - private readonly JT808ClientReportService jT808ReportService; - - private CancellationTokenSource cts=new CancellationTokenSource(); - - private readonly ILogger logger; - public CleintBenchmarkReportHostedService( - ILoggerFactory loggerFactory, - JT808ClientReportService jT808ReportService) - { - this.jT808ReportService = jT808ReportService; - logger = loggerFactory.CreateLogger("CleintBenchmarkReportHostedService"); - } - public Task StartAsync(CancellationToken cancellationToken) - { - logger.LogInformation("StartAsync..."); - Task.Run(() => { - while (!cts.IsCancellationRequested) - { - logger.LogInformation(JsonConvert.SerializeObject(jT808ReportService.JT808Reports.LastOrDefault())); - Thread.Sleep(3000); - } - }, cts.Token); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - logger.LogInformation("StopAsync..."); - cts.Cancel(); - logger.LogInformation("正在生成报表..."); - logger.LogInformation(JsonConvert.SerializeObject(jT808ReportService.JT808Reports,Formatting.Indented)); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway.Kafka/Configs/JT808ConsumerConfig.cs b/src/JT808.Gateway.Kafka/Configs/JT808ConsumerConfig.cs deleted file mode 100644 index 9d2aa55..0000000 --- a/src/JT808.Gateway.Kafka/Configs/JT808ConsumerConfig.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Confluent.Kafka; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Configs.Kafka -{ - public class JT808ConsumerConfig: ConsumerConfig, IOptions - { - public string TopicName { get; set; } - - public JT808ConsumerConfig Value => this; - } -} diff --git a/src/JT808.Gateway.Kafka/Configs/JT808MsgConsumerConfig.cs b/src/JT808.Gateway.Kafka/Configs/JT808MsgConsumerConfig.cs deleted file mode 100644 index 53746e2..0000000 --- a/src/JT808.Gateway.Kafka/Configs/JT808MsgConsumerConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Confluent.Kafka; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Configs.Kafka -{ - public class JT808MsgConsumerConfig : JT808ConsumerConfig, IOptions - { - JT808MsgConsumerConfig IOptions.Value => this; - } -} diff --git a/src/JT808.Gateway.Kafka/Configs/JT808MsgProducerConfig.cs b/src/JT808.Gateway.Kafka/Configs/JT808MsgProducerConfig.cs deleted file mode 100644 index d55b2ce..0000000 --- a/src/JT808.Gateway.Kafka/Configs/JT808MsgProducerConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Confluent.Kafka; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Configs.Kafka -{ - public class JT808MsgProducerConfig : JT808ProducerConfig, IOptions - { - JT808MsgProducerConfig IOptions.Value => this; - } -} diff --git a/src/JT808.Gateway.Kafka/Configs/JT808MsgReplyConsumerConfig.cs b/src/JT808.Gateway.Kafka/Configs/JT808MsgReplyConsumerConfig.cs deleted file mode 100644 index 79f4c3c..0000000 --- a/src/JT808.Gateway.Kafka/Configs/JT808MsgReplyConsumerConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Confluent.Kafka; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Configs.Kafka -{ - public class JT808MsgReplyConsumerConfig : JT808ConsumerConfig, IOptions - { - JT808MsgReplyConsumerConfig IOptions.Value => this; - } -} diff --git a/src/JT808.Gateway.Kafka/Configs/JT808MsgReplyProducerConfig.cs b/src/JT808.Gateway.Kafka/Configs/JT808MsgReplyProducerConfig.cs deleted file mode 100644 index 9b62e6e..0000000 --- a/src/JT808.Gateway.Kafka/Configs/JT808MsgReplyProducerConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Confluent.Kafka; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Configs.Kafka -{ - public class JT808MsgReplyProducerConfig : JT808ProducerConfig, IOptions - { - JT808MsgReplyProducerConfig IOptions.Value => this; - } -} diff --git a/src/JT808.Gateway.Kafka/Configs/JT808ProducerConfig.cs b/src/JT808.Gateway.Kafka/Configs/JT808ProducerConfig.cs deleted file mode 100644 index fca47cd..0000000 --- a/src/JT808.Gateway.Kafka/Configs/JT808ProducerConfig.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Confluent.Kafka; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Configs.Kafka -{ - public class JT808ProducerConfig : ProducerConfig,IOptions - { - public string TopicName { get; set; } - - public JT808ProducerConfig Value => this; - } -} diff --git a/src/JT808.Gateway.Kafka/Configs/JT808SessionConsumerConfig.cs b/src/JT808.Gateway.Kafka/Configs/JT808SessionConsumerConfig.cs deleted file mode 100644 index 6b57a0a..0000000 --- a/src/JT808.Gateway.Kafka/Configs/JT808SessionConsumerConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Confluent.Kafka; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Configs.Kafka -{ - public class JT808SessionConsumerConfig : JT808ConsumerConfig, IOptions - { - JT808SessionConsumerConfig IOptions.Value => this; - } -} diff --git a/src/JT808.Gateway.Kafka/Configs/JT808SessionProducerConfig.cs b/src/JT808.Gateway.Kafka/Configs/JT808SessionProducerConfig.cs deleted file mode 100644 index bba6871..0000000 --- a/src/JT808.Gateway.Kafka/Configs/JT808SessionProducerConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Confluent.Kafka; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Configs.Kafka -{ - public class JT808SessionProducerConfig : JT808ProducerConfig, IOptions - { - JT808SessionProducerConfig IOptions.Value => this; - } -} diff --git a/src/JT808.Gateway.Kafka/JT808.Gateway.Kafka.csproj b/src/JT808.Gateway.Kafka/JT808.Gateway.Kafka.csproj deleted file mode 100644 index f68e24b..0000000 --- a/src/JT808.Gateway.Kafka/JT808.Gateway.Kafka.csproj +++ /dev/null @@ -1,39 +0,0 @@ - - - - netstandard2.0 - 8.0 - Copyright 2018. - SmallChi(Koike) - https://github.com/SmallChi/JT808DotNetty - https://github.com/SmallChi/JT808DotNetty - https://github.com/SmallChi/JT808DotNetty/blob/master/LICENSE - https://github.com/SmallChi/JT808DotNetty/blob/master/LICENSE - false - 1.0.0-preview1 - false - LICENSE - true - JT808.Gateway.Kafka - JT808.Gateway.Kafka - 基于Kafka的JT808消息发布与订阅 - 基于Kafka的JT808消息发布与订阅 - - - - - - - - - - - - - - - - - - - diff --git a/src/JT808.Gateway.Kafka/JT808ClientBuilderDefault.cs b/src/JT808.Gateway.Kafka/JT808ClientBuilderDefault.cs deleted file mode 100644 index 3279c64..0000000 --- a/src/JT808.Gateway.Kafka/JT808ClientBuilderDefault.cs +++ /dev/null @@ -1,24 +0,0 @@ -using JT808.Protocol; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Kafka -{ - internal class JT808ClientBuilderDefault : IJT808ClientBuilder - { - public IJT808Builder JT808Builder { get; } - - public JT808ClientBuilderDefault(IJT808Builder builder) - { - JT808Builder = builder; - } - - public IJT808Builder Builder() - { - return JT808Builder; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway.Kafka/JT808ClientKafkaExtensions.cs b/src/JT808.Gateway.Kafka/JT808ClientKafkaExtensions.cs deleted file mode 100644 index b334097..0000000 --- a/src/JT808.Gateway.Kafka/JT808ClientKafkaExtensions.cs +++ /dev/null @@ -1,66 +0,0 @@ -using JJT808.Gateway.Kafka; -using JT808.Gateway.Configs.Kafka; -using JT808.Gateway.PubSub; -using JT808.Protocol; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace JT808.Gateway.Kafka -{ - public static class JT808ClientKafkaExtensions - { - public static IJT808ClientBuilder AddJT808ClientKafka(this IJT808Builder builder) - { - return new JT808ClientBuilderDefault(builder); - } - /// - /// - /// - /// - /// GetSection("JT808MsgConsumerConfig") - /// - public static IJT808ClientBuilder AddMsgConsumer(this IJT808ClientBuilder jT808ClientBuilder, IConfiguration configuration) - { - jT808ClientBuilder.JT808Builder.Services.Configure(configuration.GetSection("JT808MsgConsumerConfig")); - jT808ClientBuilder.JT808Builder.Services.TryAddSingleton(); - return jT808ClientBuilder; - } - /// - /// - /// - /// - /// GetSection("JT808MsgReplyProducerConfig") - /// - public static IJT808ClientBuilder AddMsgReplyProducer(this IJT808ClientBuilder jT808ClientBuilder, IConfiguration configuration) - { - jT808ClientBuilder.JT808Builder.Services.Configure(configuration.GetSection("JT808MsgReplyProducerConfig")); - jT808ClientBuilder.JT808Builder.Services.TryAddSingleton(); - return jT808ClientBuilder; - } - /// - /// - /// - /// - /// GetSection("JT808MsgReplyConsumerConfig") - /// - public static IJT808ClientBuilder AddMsgReplyConsumer(this IJT808ClientBuilder jT808ClientBuilder, IConfiguration configuration) - { - jT808ClientBuilder.JT808Builder.Services.Configure(configuration.GetSection("JT808MsgReplyConsumerConfig")); - jT808ClientBuilder.JT808Builder.Services.Replace(new ServiceDescriptor(typeof(IJT808MsgReplyConsumer), typeof(JT808MsgReplyConsumer), ServiceLifetime.Singleton)); - return jT808ClientBuilder; - } - /// - /// - /// - /// - /// GetSection("JT808SessionConsumerConfig") - /// - public static IJT808ClientBuilder AddSessionConsumer(this IJT808ClientBuilder jT808ClientBuilder, IConfiguration configuration) - { - jT808ClientBuilder.JT808Builder.Services.Configure(configuration.GetSection("JT808SessionConsumerConfig")); - jT808ClientBuilder.JT808Builder.Services.TryAddSingleton(); - return jT808ClientBuilder; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway.Kafka/JT808MsgConsumer.cs b/src/JT808.Gateway.Kafka/JT808MsgConsumer.cs deleted file mode 100644 index 56818f2..0000000 --- a/src/JT808.Gateway.Kafka/JT808MsgConsumer.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Confluent.Kafka; -using JT808.Gateway.Configs.Kafka; -using JT808.Gateway.PubSub; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Kafka -{ - public class JT808MsgConsumer : IJT808MsgConsumer - { - public CancellationTokenSource Cts => new CancellationTokenSource(); - - private readonly IConsumer consumer; - - private readonly ILogger logger; - - public string TopicName { get; } - - public JT808MsgConsumer( - IOptions consumerConfigAccessor, - ILoggerFactory loggerFactory) - { - consumer = new ConsumerBuilder(consumerConfigAccessor.Value).Build(); - TopicName = consumerConfigAccessor.Value.TopicName; - logger = loggerFactory.CreateLogger("JT808MsgConsumer"); - } - - public void OnMessage(Action<(string TerminalNo, byte[] Data)> callback) - { - Task.Run(() => - { - while (!Cts.IsCancellationRequested) - { - try - { - //如果不指定分区,根据kafka的机制会从多个分区中拉取数据 - //如果指定分区,根据kafka的机制会从相应的分区中拉取数据 - var data = consumer.Consume(Cts.Token); - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug($"Topic: {data.Topic} Key: {data.Key} Partition: {data.Partition} Offset: {data.Offset} TopicPartitionOffset:{data.TopicPartitionOffset}"); - } - callback((data.Key, data.Value)); - } - catch (ConsumeException ex) - { - logger.LogError(ex, TopicName); - } - catch (OperationCanceledException ex) - { - logger.LogError(ex, TopicName); - } - catch (Exception ex) - { - logger.LogError(ex, TopicName); - } - } - }, Cts.Token); - } - - public void Subscribe() - { - consumer.Subscribe(TopicName); - } - - public void Unsubscribe() - { - consumer.Unsubscribe(); - } - - public void Dispose() - { - consumer.Close(); - consumer.Dispose(); - } - } -} diff --git a/src/JT808.Gateway.Kafka/JT808MsgProducer.cs b/src/JT808.Gateway.Kafka/JT808MsgProducer.cs deleted file mode 100644 index 67d6d1b..0000000 --- a/src/JT808.Gateway.Kafka/JT808MsgProducer.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Confluent.Kafka; -using JT808.Gateway.Configs.Kafka; -using JT808.Gateway.PubSub; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace JT808.Gateway.Kafka -{ - public class JT808MsgProducer : IJT808MsgProducer - { - public string TopicName { get; } - - private readonly IProducer producer; - public JT808MsgProducer( - IOptions producerConfigAccessor) - { - producer = new ProducerBuilder(producerConfigAccessor.Value).Build(); - TopicName = producerConfigAccessor.Value.TopicName; - } - - public void Dispose() - { - producer.Dispose(); - } - - public async Task ProduceAsync(string terminalNo, byte[] data) - { - await producer.ProduceAsync(TopicName, new Message - { - Key = terminalNo, - Value = data - }); - } - } -} diff --git a/src/JT808.Gateway.Kafka/JT808MsgReplyConsumer.cs b/src/JT808.Gateway.Kafka/JT808MsgReplyConsumer.cs deleted file mode 100644 index 004a391..0000000 --- a/src/JT808.Gateway.Kafka/JT808MsgReplyConsumer.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Confluent.Kafka; -using JT808.Gateway.Configs.Kafka; -using JT808.Gateway.PubSub; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Kafka -{ - public class JT808MsgReplyConsumer : IJT808MsgReplyConsumer - { - public CancellationTokenSource Cts => new CancellationTokenSource(); - - private readonly IConsumer consumer; - - private readonly ILogger logger; - - public string TopicName { get; } - - public JT808MsgReplyConsumer( - IOptions consumerConfigAccessor, - ILoggerFactory loggerFactory) - { - consumer = new ConsumerBuilder(consumerConfigAccessor.Value).Build(); - TopicName = consumerConfigAccessor.Value.TopicName; - logger = loggerFactory.CreateLogger("JT808MsgReplyConsumer"); - } - - public void OnMessage(Action<(string TerminalNo, byte[] Data)> callback) - { - Task.Run(() => - { - while (!Cts.IsCancellationRequested) - { - try - { - //如果不指定分区,根据kafka的机制会从多个分区中拉取数据 - //如果指定分区,根据kafka的机制会从相应的分区中拉取数据 - var data = consumer.Consume(Cts.Token); - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug($"Topic: {data.Topic} Key: {data.Key} Partition: {data.Partition} Offset: {data.Offset} TopicPartitionOffset:{data.TopicPartitionOffset}"); - } - callback((data.Key, data.Value)); - } - catch (ConsumeException ex) - { - logger.LogError(ex, TopicName); - } - catch (OperationCanceledException ex) - { - logger.LogError(ex, TopicName); - } - catch (Exception ex) - { - logger.LogError(ex, TopicName); - } - } - }, Cts.Token); - } - - public void Subscribe() - { - consumer.Subscribe(TopicName); - } - - public void Unsubscribe() - { - consumer.Unsubscribe(); - } - - public void Dispose() - { - consumer.Close(); - consumer.Dispose(); - } - } -} diff --git a/src/JT808.Gateway.Kafka/JT808MsgReplyProducer.cs b/src/JT808.Gateway.Kafka/JT808MsgReplyProducer.cs deleted file mode 100644 index f29e9be..0000000 --- a/src/JT808.Gateway.Kafka/JT808MsgReplyProducer.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Confluent.Kafka; -using JT808.Gateway.Configs.Kafka; -using JT808.Gateway.PubSub; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace JJT808.Gateway.Kafka -{ - public class JT808MsgReplyProducer : IJT808MsgReplyProducer - { - public string TopicName { get;} - - private IProducer producer; - public JT808MsgReplyProducer( - IOptions producerConfigAccessor) - { - producer = new ProducerBuilder(producerConfigAccessor.Value).Build(); - TopicName = producerConfigAccessor.Value.TopicName; - } - - public void Dispose() - { - producer.Dispose(); - } - - public async Task ProduceAsync(string terminalNo, byte[] data) - { - await producer.ProduceAsync(TopicName, new Message - { - Key = terminalNo, - Value = data - }); - } - } -} diff --git a/src/JT808.Gateway.Kafka/JT808ServerKafkaExtensions.cs b/src/JT808.Gateway.Kafka/JT808ServerKafkaExtensions.cs deleted file mode 100644 index e8e1dc1..0000000 --- a/src/JT808.Gateway.Kafka/JT808ServerKafkaExtensions.cs +++ /dev/null @@ -1,48 +0,0 @@ -using JT808.Gateway.Configs.Kafka; -using JT808.Gateway.PubSub; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace JT808.Gateway.Kafka -{ - public static class JT808ServerKafkaExtensions - { - /// - /// - /// - /// - /// GetSection("JT808MsgProducerConfig") - /// - public static IJT808GatewayBuilder AddJT808ServerKafkaMsgProducer(this IJT808GatewayBuilder jT808GatewayBuilder, IConfiguration configuration) - { - jT808GatewayBuilder.JT808Builder.Services.Configure(configuration.GetSection("JT808MsgProducerConfig")); - jT808GatewayBuilder.JT808Builder.Services.Replace(new ServiceDescriptor(typeof(IJT808MsgProducer), typeof(JT808MsgProducer), ServiceLifetime.Singleton)); - return jT808GatewayBuilder; - } - /// - /// - /// - /// - /// GetSection("JT808MsgReplyConsumerConfig") - /// - public static IJT808GatewayBuilder AddJT808ServerKafkaMsgReplyConsumer(this IJT808GatewayBuilder jT808GatewayBuilder, IConfiguration configuration) - { - jT808GatewayBuilder.JT808Builder.Services.Configure(configuration.GetSection("JT808MsgReplyConsumerConfig")); - jT808GatewayBuilder.JT808Builder.Services.Replace(new ServiceDescriptor(typeof(IJT808MsgReplyConsumer), typeof(JT808MsgReplyConsumer), ServiceLifetime.Singleton)); - return jT808GatewayBuilder; - } - /// - /// - /// - /// - /// GetSection("JT808SessionProducerConfig") - /// - public static IJT808GatewayBuilder AddJT808ServerKafkaSessionProducer(this IJT808GatewayBuilder jT808GatewayBuilder, IConfiguration configuration) - { - jT808GatewayBuilder.JT808Builder.Services.Configure(configuration.GetSection("JT808SessionProducerConfig")); - jT808GatewayBuilder.JT808Builder.Services.Replace(new ServiceDescriptor(typeof(IJT808SessionProducer), typeof(JT808SessionProducer), ServiceLifetime.Singleton)); - return jT808GatewayBuilder; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway.Kafka/JT808SessionConsumer.cs b/src/JT808.Gateway.Kafka/JT808SessionConsumer.cs deleted file mode 100644 index 9ccf830..0000000 --- a/src/JT808.Gateway.Kafka/JT808SessionConsumer.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Confluent.Kafka; -using JT808.Gateway.Configs.Kafka; -using JT808.Gateway.PubSub; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Kafka -{ - public class JT808SessionConsumer : IJT808SessionConsumer - { - public CancellationTokenSource Cts => new CancellationTokenSource(); - - private readonly IConsumer consumer; - - private readonly ILogger logger; - - public string TopicName { get; } - - public JT808SessionConsumer( - IOptions consumerConfigAccessor, - ILoggerFactory loggerFactory) - { - consumer = new ConsumerBuilder(consumerConfigAccessor.Value).Build(); - TopicName = consumerConfigAccessor.Value.TopicName; - logger = loggerFactory.CreateLogger("JT808SessionConsumer"); - } - - public void OnMessage(Action<(string Notice, string TerminalNo)> callback) - { - Task.Run(() => - { - while (!Cts.IsCancellationRequested) - { - try - { - //如果不指定分区,根据kafka的机制会从多个分区中拉取数据 - //如果指定分区,根据kafka的机制会从相应的分区中拉取数据 - var data = consumer.Consume(Cts.Token); - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug($"Topic: {data.Topic} Key: {data.Key} Partition: {data.Partition} Offset: {data.Offset} TopicPartitionOffset:{data.TopicPartitionOffset}"); - } - callback((data.Key, data.Value)); - } - catch (ConsumeException ex) - { - logger.LogError(ex, TopicName); - } - catch (OperationCanceledException ex) - { - logger.LogError(ex, TopicName); - } - catch (Exception ex) - { - logger.LogError(ex, TopicName); - } - } - }, Cts.Token); - } - - public void Subscribe() - { - consumer.Subscribe(TopicName); - } - - public void Unsubscribe() - { - consumer.Unsubscribe(); - } - - public void Dispose() - { - consumer.Close(); - consumer.Dispose(); - } - } -} diff --git a/src/JT808.Gateway.Kafka/JT808SessionProducer.cs b/src/JT808.Gateway.Kafka/JT808SessionProducer.cs deleted file mode 100644 index 3b6494f..0000000 --- a/src/JT808.Gateway.Kafka/JT808SessionProducer.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Confluent.Kafka; -using JT808.Gateway.Configs.Kafka; -using JT808.Gateway.PubSub; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace JT808.Gateway.Kafka -{ - public class JT808SessionProducer : IJT808SessionProducer - { - public string TopicName { get; } - - private readonly IProducer producer; - public JT808SessionProducer( - IOptions producerConfigAccessor) - { - producer = new ProducerBuilder(producerConfigAccessor.Value).Build(); - TopicName = producerConfigAccessor.Value.TopicName; - } - - public void Dispose() - { - producer.Dispose(); - } - - public async Task ProduceAsync(string notice,string terminalNo) - { - await producer.ProduceAsync(TopicName, new Message - { - Key = notice, - Value = terminalNo - }); - } - } -} diff --git a/src/JT808.Gateway.SimpleClient/JT808.Gateway.SimpleClient.csproj b/src/JT808.Gateway.SimpleClient/JT808.Gateway.SimpleClient.csproj deleted file mode 100644 index 597fe2f..0000000 --- a/src/JT808.Gateway.SimpleClient/JT808.Gateway.SimpleClient.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - Exe - netcoreapp3.0 - - - - - - - - - - - - - diff --git a/src/JT808.Gateway.SimpleClient/Program.cs b/src/JT808.Gateway.SimpleClient/Program.cs deleted file mode 100644 index e58a3d5..0000000 --- a/src/JT808.Gateway.SimpleClient/Program.cs +++ /dev/null @@ -1,52 +0,0 @@ -using JT808.Gateway.Client; -using JT808.Gateway.SimpleClient.Services; -using JT808.Protocol; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using System; -using System.Threading.Tasks; -using Grpc.Net.Client; -using JT808.Gateway.GrpcService; -using System.Net; - -namespace JT808.Gateway.SimpleClient -{ - class Program - { - static async Task Main(string[] args) - { - //ref https://docs.microsoft.com/zh-cn/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.0#call-insecure-grpc-services-with-net-core-client - //ref https://docs.microsoft.com/zh-cn/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.0 - - //先执行 dotnet dev-certs https --trust 命令生成开发证书 - //使用 certmgr.msc 导出证书在服务端配置对应证书文件 - //Uri "https://localhost:5001" - - var serverHostBuilder = new HostBuilder() - .ConfigureLogging((context, logging) => - { - logging.AddConsole(); - logging.SetMinimumLevel(LogLevel.Trace); - }) - .ConfigureServices((hostContext, services) => - { - services.AddGrpcClient(o => - { - o.Address = new Uri("https://localhost:5001"); - }); - services.AddSingleton(); - services.AddSingleton(typeof(ILogger<>), typeof(Logger<>)); - services.AddLogging(options => { - options.AddConsole(); - options.SetMinimumLevel(LogLevel.Trace); - }); - services.AddJT808Configure() - .AddJT808Client(); - services.AddHostedService(); - //services.AddHostedService(); - }); - await serverHostBuilder.RunConsoleAsync(); - } - } -} diff --git a/src/JT808.Gateway.SimpleClient/Services/GrpcClientService.cs b/src/JT808.Gateway.SimpleClient/Services/GrpcClientService.cs deleted file mode 100644 index e21a3dc..0000000 --- a/src/JT808.Gateway.SimpleClient/Services/GrpcClientService.cs +++ /dev/null @@ -1,68 +0,0 @@ -using JT808.Gateway.Client; -using JT808.Protocol.MessageBody; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using JT808.Gateway.GrpcService; -using static JT808.Gateway.GrpcService.JT808Gateway; -using Google.Protobuf; -using System.Text.Json; -using JT808.Protocol.Extensions; - -namespace JT808.Gateway.SimpleClient.Services -{ - public class GrpcClientService : IHostedService - { - private readonly ILogger logger; - private readonly JT808GatewayClient client; - - public GrpcClientService( - ILoggerFactory loggerFactory, - JT808GatewayClient jT808GatewayClient) - { - this.client = jT808GatewayClient; - logger = loggerFactory.CreateLogger("GrpcClientService"); - } - - public Task StartAsync(CancellationToken cancellationToken) - { - Task.Run(() => { - //while (!cancellationToken.IsCancellationRequested) - //{ - Thread.Sleep(1000 * 10); - var result1 = client.GetTcpAtomicCounter(new Empty()); - var result2 = client.GetUdpAtomicCounter(new Empty()); - var result3 = client.GetTcpSessionAll(new Empty()); - var result4 = client.GetUdpSessionAll(new Empty()); - var result5 = client.UnificationSend(new UnificationSendRequest() - { - TerminalPhoneNo= "12345678910", - Data= ByteString.CopyFrom("7E 02 00 00 26 12 34 56 78 90 12 00 7D 02 00 00 00 01 00 00 00 02 00 BA 7F 0E 07 E4 F1 1C 00 28 00 3C 00 00 18 10 15 10 10 10 01 04 00 00 00 64 02 02 00 7D 01 13 7E".ToHexBytes()) - }); - var result6 = client.RemoveSessionByTerminalPhoneNo(new SessionRemoveRequest() - { - TerminalPhoneNo= "12345678910" - }); - - logger.LogDebug(JsonSerializer.Serialize(result1)); - logger.LogDebug(JsonSerializer.Serialize(result2)); - logger.LogDebug(JsonSerializer.Serialize(result3)); - logger.LogDebug(JsonSerializer.Serialize(result4)); - logger.LogDebug(JsonSerializer.Serialize(result5)); - logger.LogDebug(JsonSerializer.Serialize(result6)); - //} - }, cancellationToken); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway.SimpleClient/Services/UpService.cs b/src/JT808.Gateway.SimpleClient/Services/UpService.cs deleted file mode 100644 index a9a9d83..0000000 --- a/src/JT808.Gateway.SimpleClient/Services/UpService.cs +++ /dev/null @@ -1,68 +0,0 @@ -using JT808.Gateway.Client; -using JT808.Protocol.MessageBody; -using Microsoft.Extensions.Hosting; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.SimpleClient.Services -{ - public class UpService : IHostedService - { - private readonly IJT808TcpClientFactory jT808TcpClientFactory; - - public UpService(IJT808TcpClientFactory jT808TcpClientFactory) - { - this.jT808TcpClientFactory = jT808TcpClientFactory; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - JT808TcpClient client1 = jT808TcpClientFactory.Create(new DeviceConfig("12345678910", "127.0.0.1", 808)); - //1.终端注册 - client1.Send(new JT808_0x0100() - { - PlateNo = "粤A12345", - PlateColor = 2, - AreaID = 0, - CityOrCountyId = 0, - MakerId = "Koike001", - TerminalId = "Koike001", - TerminalModel = "Koike001" - }); - //2.终端鉴权 - client1.Send(new JT808_0x0102() - { - Code = "1234" - }); - Task.Run(() => { - while (true) - { - var i = 0; - //3.每5000秒发一次 - client1.Send(new JT808_0x0200() - { - Lat = 110000 + i, - Lng = 100000 + i, - GPSTime = DateTime.Now, - Speed = 50, - Direction = 30, - AlarmFlag = 5, - Altitude = 50, - StatusFlag = 10 - }); - i++; - Thread.Sleep(5000); - } - }); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway.SimpleServer/Configs/NLog.xsd b/src/JT808.Gateway.SimpleServer/Configs/NLog.xsd deleted file mode 100644 index 2f57d09..0000000 --- a/src/JT808.Gateway.SimpleServer/Configs/NLog.xsd +++ /dev/null @@ -1,3106 +0,0 @@ - - - - - - - - - - - - - - - Watch config file for changes and reload automatically. - - - - - Print internal NLog messages to the console. Default value is: false - - - - - Print internal NLog messages to the console error output. Default value is: false - - - - - Write internal NLog messages to the specified file. - - - - - Log level threshold for internal log messages. Default value is: Info. - - - - - Global log level threshold for application log messages. Messages below this level won't be logged.. - - - - - Throw an exception when there is an internal error. Default value is: false. - - - - - Throw an exception when there is a configuration error. If not set, determined by throwExceptions. - - - - - Gets or sets a value indicating whether Variables should be kept on configuration reload. Default value is: false. - - - - - Write internal NLog messages to the System.Diagnostics.Trace. Default value is: false. - - - - - Write timestamps for internal NLog messages. Default value is: true. - - - - - Use InvariantCulture as default culture instead of CurrentCulture. Default value is: false. - - - - - Perform mesage template parsing and formatting of LogEvent messages (true = Always, false = Never, empty = Auto Detect). Default value is: empty. - - - - - - - - - - - - - - Make all targets within this section asynchronous (creates additional threads but the calling thread isn't blocked by any target writes). - - - - - - - - - - - - - - - - - Prefix for targets/layout renderers/filters/conditions loaded from this assembly. - - - - - Load NLog extensions from the specified file (*.dll) - - - - - Load NLog extensions from the specified assembly. Assembly name should be fully qualified. - - - - - - - - - - Name of the logger. May include '*' character which acts like a wildcard. Allowed forms are: *, Name, *Name, Name* and *Name* - - - - - Comma separated list of levels that this rule matches. - - - - - Minimum level that this rule matches. - - - - - Maximum level that this rule matches. - - - - - Level that this rule matches. - - - - - Comma separated list of target names. - - - - - Ignore further rules if this one matches. - - - - - Enable or disable logging rule. Disabled rules are ignored. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the file to be included. You could use * wildcard. The name is relative to the name of the current config file. - - - - - Ignore any errors in the include file. - - - - - - - Variable name. - - - - - Variable value. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Number of log events that should be processed in a batch by the lazy writer thread. - - - - - Limit of full s to write before yielding into Performance is better when writing many small batches, than writing a single large batch - - - - - Action to be taken when the lazy writer thread request queue count exceeds the set limit. - - - - - Limit on the number of requests in the lazy writer thread request queue. - - - - - Time in milliseconds to sleep between batches. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Delay the flush until the LogEvent has been confirmed as written - - - - - Condition expression. Log events who meet this condition will cause a flush on the wrapped target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Number of log events to be buffered. - - - - - Timeout (in milliseconds) after which the contents of buffer will be flushed if there's no write in the specified period of time. Use -1 to disable timed flushes. - - - - - Indicates whether to use sliding timeout. - - - - - Action to take if the buffer overflows. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Encoding to be used. - - - - - Instance of that is used to format log messages. - - - - - End of line value if a newline is appended at the end of log message . - - - - - Maximum message size in bytes. - - - - - Indicates whether to append newline at the end of log message. - - - - - Action that should be taken if the will be more connections than . - - - - - Action that should be taken if the message is larger than maxMessageSize. - - - - - Maximum current connections. 0 = no maximum. - - - - - Indicates whether to keep connection open whenever possible. - - - - - Size of the connection cache (number of connections which are kept alive). - - - - - Network address. - - - - - Maximum queue size. - - - - - NDC item separator. - - - - - Indicates whether to include source info (file name and line number) in the information sent over the network. - - - - - Indicates whether to include dictionary contents. - - - - - Indicates whether to include contents of the stack. - - - - - Indicates whether to include stack contents. - - - - - Indicates whether to include dictionary contents. - - - - - Indicates whether to include call site (class and method name) in the information sent over the network. - - - - - Option to include all properties from the log events - - - - - AppInfo field. By default it's the friendly name of the current AppDomain. - - - - - Indicates whether to include NLog-specific extensions to log4j schema. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - Layout that should be use to calcuate the value for the parameter. - - - - - Viewer parameter name. - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - Indicates whether to use default row highlighting rules. - - - - - Indicates whether to auto-check if the console is available. - Disables console writing if Environment.UserInteractive = False (Windows Service) - Disables console writing if Console Standard Input is not available (Non-Console-App) - - - - - The encoding for writing messages to the . - - - - - Indicates whether the error stream (stderr) should be used instead of the output stream (stdout). - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Condition that must be met in order to set the specified foreground and background color. - - - - - Background color. - - - - - Foreground color. - - - - - - - - - - - - - - - - Indicates whether to ignore case when comparing texts. - - - - - Regular expression to be matched. You must specify either text or regex. - - - - - Text to be matched. You must specify either text or regex. - - - - - Indicates whether to match whole words only. - - - - - Compile the ? This can improve the performance, but at the costs of more memory usage. If false, the Regex Cache is used. - - - - - Background color. - - - - - Foreground color. - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - Indicates whether to send the log messages to the standard error instead of the standard output. - - - - - Indicates whether to auto-check if the console is available - Disables console writing if Environment.UserInteractive = False (Windows Service) - Disables console writing if Console Standard Input is not available (Non-Console-App) - - - - - The encoding for writing messages to the . - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Obsolete - value will be ignored! The logging code always runs outside of transaction. Gets or sets a value indicating whether to use database transactions. Some data providers require this. - - - - - Database user name. If the ConnectionString is not provided this value will be used to construct the "User ID=" part of the connection string. - - - - - Name of the database provider. - - - - - Database password. If the ConnectionString is not provided this value will be used to construct the "Password=" part of the connection string. - - - - - Indicates whether to keep the database connection open between the log events. - - - - - Database name. If the ConnectionString is not provided this value will be used to construct the "Database=" part of the connection string. - - - - - Name of the connection string (as specified in <connectionStrings> configuration section. - - - - - Connection string. When provided, it overrides the values specified in DBHost, DBUserName, DBPassword, DBDatabase. - - - - - Database host name. If the ConnectionString is not provided this value will be used to construct the "Server=" part of the connection string. - - - - - Connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Text of the SQL command to be run on each log level. - - - - - Type of the SQL command to be run on each log level. - - - - - - - - - - - - - - - - - - - - - - - Type of the command. - - - - - Connection string to run the command against. If not provided, connection string from the target is used. - - - - - Indicates whether to ignore failures. - - - - - Command text. - - - - - - - - - - - - - - Layout that should be use to calcuate the value for the parameter. - - - - - Database parameter name. - - - - - Database parameter precision. - - - - - Database parameter scale. - - - - - Database parameter size. - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Layout that renders event Category. - - - - - Layout that renders event ID. - - - - - Name of the Event Log to write to. This can be System, Application or any user-defined name. - - - - - Name of the machine on which Event Log service is running. - - - - - Value to be used as the event Source. - - - - - Action to take if the message is larger than the option. - - - - - Optional entrytype. When not set, or when not convertable to then determined by - - - - - Maximum Event log size in kilobytes. If null, the value won't be set. Default is 512 Kilobytes as specified by Eventlog API - - - - - Message length limit to write to the Event Log. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Indicates whether to return to the first target after any successful write. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - File encoding. - - - - - Line ending mode. - - - - - Way file archives are numbered. - - - - - Name of the file to be used for an archive. - - - - - Indicates whether to automatically archive log files every time the specified time passes. - - - - - Size in bytes above which log files will be automatically archived. Warning: combining this with isn't supported. We cannot create multiple archive files, if they should have the same name. Choose: - - - - - Indicates whether to compress archive files into the zip archive format. - - - - - Maximum number of archive files that should be kept. - - - - - Gets or set a value indicating whether a managed file stream is forced, instead of using the native implementation. - - - - - Is the an absolute or relative path? - - - - - Cleanup invalid values in a filename, e.g. slashes in a filename. If set to true, this can impact the performance of massive writes. If set to false, nothing gets written when the filename is wrong. - - - - - Whether or not this target should just discard all data that its asked to write. Mostly used for when testing NLog Stack except final write - - - - - Is the an absolute or relative path? - - - - - Value indicationg whether file creation calls should be synchronized by a system global mutex. - - - - - Maximum number of log filenames that should be stored as existing. - - - - - Indicates whether the footer should be written only when the file is archived. - - - - - Name of the file to write to. - - - - - Value specifying the date format to use when archiving files. - - - - - Indicates whether to archive old log file on startup. - - - - - Indicates whether to create directories if they do not exist. - - - - - File attributes (Windows only). - - - - - Indicates whether to delete old log file on startup. - - - - - Indicates whether to replace file contents on each write instead of appending log message at the end. - - - - - Indicates whether to enable log file(s) to be deleted. - - - - - Number of times the write is appended on the file before NLog discards the log message. - - - - - Indicates whether concurrent writes to the log file by multiple processes on the same host. - - - - - Indicates whether to keep log file open instead of opening and closing it on each logging event. - - - - - Indicates whether concurrent writes to the log file by multiple processes on different network hosts. - - - - - Number of files to be kept open. Setting this to a higher value may improve performance in a situation where a single File target is writing to many files (such as splitting by level or by logger). - - - - - Maximum number of seconds that files are kept open. If this number is negative the files are not automatically closed after a period of inactivity. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Log file buffer size in bytes. - - - - - Indicates whether to automatically flush the file buffers after each log message. - - - - - Delay in milliseconds to wait before attempting to write to the file again. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Condition expression. Log events who meet this condition will be forwarded to the wrapped target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Windows domain name to change context to. - - - - - Required impersonation level. - - - - - Type of the logon provider. - - - - - Logon Type. - - - - - User account password. - - - - - Indicates whether to revert to the credentials of the process instead of impersonating another user. - - - - - Username to change context to. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Interval in which messages will be written up to the number of messages. - - - - - Maximum allowed number of messages written per . - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Endpoint address. - - - - - Name of the endpoint configuration in WCF configuration file. - - - - - Indicates whether to use a WCF service contract that is one way (fire and forget) or two way (request-reply) - - - - - Client ID. - - - - - Indicates whether to include per-event properties in the payload sent to the server. - - - - - Indicates whether to use binary message encoding. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - Layout that should be use to calculate the value for the parameter. - - - - - Name of the parameter. - - - - - Type of the parameter. - - - - - Type of the parameter. Obsolete alias for - - - - - Parameter can combine multiple LogEvents into a single parameter value - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Text to be rendered. - - - - - Header. - - - - - Footer. - - - - - Indicates whether to send message as HTML instead of plain text. - - - - - Encoding to be used for sending e-mail. - - - - - Indicates whether to add new lines between log entries. - - - - - CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). - - - - - Recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). - - - - - BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). - - - - - Mail message body (repeated for each log message send in one mail). - - - - - Mail subject. - - - - - Sender's email address (e.g. joe@domain.com). - - - - - Indicates the SMTP client timeout. - - - - - Priority used for sending mails. - - - - - Indicates whether NewLine characters in the body should be replaced with tags. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - SMTP Server to be used for sending. - - - - - SMTP Authentication mode. - - - - - Username used to connect to SMTP server (used when SmtpAuthentication is set to "basic"). - - - - - Password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic"). - - - - - Indicates whether SSL (secure sockets layer) should be used when communicating with SMTP server. - - - - - Port number that SMTP Server is listening on. - - - - - Indicates whether the default Settings from System.Net.MailSettings should be used. - - - - - Folder where applications save mail messages to be processed by the local SMTP server. - - - - - Specifies how outgoing email messages will be handled. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Class name. - - - - - Method name. The method must be public and static. Use the AssemblyQualifiedName , https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx e.g. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Encoding to be used. - - - - - End of line value if a newline is appended at the end of log message . - - - - - Maximum message size in bytes. - - - - - Indicates whether to append newline at the end of log message. - - - - - Action that should be taken if the will be more connections than . - - - - - Action that should be taken if the message is larger than maxMessageSize. - - - - - Network address. - - - - - Size of the connection cache (number of connections which are kept alive). - - - - - Indicates whether to keep connection open whenever possible. - - - - - Maximum current connections. 0 = no maximum. - - - - - Maximum queue size. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Encoding to be used. - - - - - Instance of that is used to format log messages. - - - - - End of line value if a newline is appended at the end of log message . - - - - - Maximum message size in bytes. - - - - - Indicates whether to append newline at the end of log message. - - - - - Action that should be taken if the will be more connections than . - - - - - Action that should be taken if the message is larger than maxMessageSize. - - - - - Maximum current connections. 0 = no maximum. - - - - - Indicates whether to keep connection open whenever possible. - - - - - Size of the connection cache (number of connections which are kept alive). - - - - - Network address. - - - - - Maximum queue size. - - - - - NDC item separator. - - - - - Indicates whether to include source info (file name and line number) in the information sent over the network. - - - - - Indicates whether to include dictionary contents. - - - - - Indicates whether to include contents of the stack. - - - - - Indicates whether to include stack contents. - - - - - Indicates whether to include dictionary contents. - - - - - Indicates whether to include call site (class and method name) in the information sent over the network. - - - - - Option to include all properties from the log events - - - - - AppInfo field. By default it's the friendly name of the current AppDomain. - - - - - Indicates whether to include NLog-specific extensions to log4j schema. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Indicates whether to perform layout calculation. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Indicates whether performance counter should be automatically created. - - - - - Name of the performance counter category. - - - - - Counter help text. - - - - - Name of the performance counter. - - - - - Performance counter type. - - - - - The value by which to increment the counter. - - - - - Performance counter instance name. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Default filter to be applied when no specific rule matches. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - Condition to be tested. - - - - - Resulting filter to be applied when the condition matches. - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Number of times to repeat each log message. - - - - - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Number of retries that should be attempted on the wrapped target in case of a failure. - - - - - Time to wait between retries in milliseconds. - - - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - Name of the target. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - Name of the target. - - - - - Layout used to format log messages. - - - - - Always use independent of - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - - - - - - - - - - - - - - - - - - - - - - - - Name of the target. - - - - - Should we include the BOM (Byte-order-mark) for UTF? Influences the property. This will only work for UTF-8. - - - - - Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit - - - - - Encoding. - - - - - Value whether escaping be done according to the old NLog style (Very non-standard) - - - - - Value whether escaping be done according to Rfc3986 (Supports Internationalized Resource Identifiers - IRIs) - - - - - Web service method name. Only used with Soap. - - - - - Web service namespace. Only used with Soap. - - - - - Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in parameters) - - - - - Protocol to be used when calling web service. - - - - - Web service URL. - - - - - Name of the root XML element, if POST of XML document chosen. If so, this property must not be null. (see and ). - - - - - (optional) root namespace of the XML document, if POST of XML document chosen. (see and ). - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Footer layout. - - - - - Header layout. - - - - - Body layout (can be repeated multiple times). - - - - - Custom column delimiter value (valid when ColumnDelimiter is set to 'Custom'). - - - - - Column delimiter. - - - - - Quote Character. - - - - - Quoting mode. - - - - - Indicates whether CVS should include header. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Layout of the column. - - - - - Name of the column. - - - - - - - - - - - - - - - - - - List of property names to exclude when is true - - - - - Option to include all properties from the log events - - - - - Indicates whether to include contents of the dictionary. - - - - - Indicates whether to include contents of the dictionary. - - - - - Option to render the empty object value {} - - - - - Option to suppress the extra spaces in the output json - - - - - - - - - - - - - - - Determines wether or not this attribute will be Json encoded. - - - - - Indicates whether to escape non-ascii characters - - - - - Layout that will be rendered as the attribute's value. - - - - - Name of the attribute. - - - - - - - - - - - - - - Footer layout. - - - - - Header layout. - - - - - Body layout (can be repeated multiple times). - - - - - - - - - - - - - - - - - - Option to include all properties from the log events - - - - - Indicates whether to include contents of the dictionary. - - - - - Indicates whether to include contents of the dictionary. - - - - - Indicates whether to include contents of the stack. - - - - - Indicates whether to include contents of the stack. - - - - - - - - - - - - - - Layout text. - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - Condition expression. - - - - - - - - - - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - Indicates whether to ignore case when comparing strings. - - - - - Layout to be used to filter log messages. - - - - - Substring to be matched. - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - String to compare the layout to. - - - - - Indicates whether to ignore case when comparing strings. - - - - - Layout to be used to filter log messages. - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - Indicates whether to ignore case when comparing strings. - - - - - Layout to be used to filter log messages. - - - - - Substring to be matched. - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - String to compare the layout to. - - - - - Indicates whether to ignore case when comparing strings. - - - - - Layout to be used to filter log messages. - - - - - - - - - - - - - - - - - - - - - - - - Action to be taken when filter matches. - - - - - Layout to be used to filter log messages. - - - - - Default number of unique filter values to expect, will automatically increase if needed - - - - - Append FilterCount to the when an event is no longer filtered - - - - - Insert FilterCount value into when an event is no longer filtered - - - - - Applies the configured action to the initial logevent that starts the timeout period. Used to configure that it should ignore all events until timeout. - - - - - Max number of unique filter values to expect simultaneously - - - - - Max length of filter values, will truncate if above limit - - - - - Default buffer size for the internal buffers - - - - - Reuse internal buffers, and doesn't have to constantly allocate new buffers - - - - - How long before a filter expires, and logging is accepted again - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/JT808.Gateway.SimpleServer/Configs/nlog.Unix.config b/src/JT808.Gateway.SimpleServer/Configs/nlog.Unix.config deleted file mode 100644 index ee227dd..0000000 --- a/src/JT808.Gateway.SimpleServer/Configs/nlog.Unix.config +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/JT808.Gateway.SimpleServer/Configs/nlog.Win32NT.config b/src/JT808.Gateway.SimpleServer/Configs/nlog.Win32NT.config deleted file mode 100644 index ec26e74..0000000 --- a/src/JT808.Gateway.SimpleServer/Configs/nlog.Win32NT.config +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/JT808.Gateway.SimpleServer/Configs/test.cer b/src/JT808.Gateway.SimpleServer/Configs/test.cer deleted file mode 100644 index 04963c1..0000000 Binary files a/src/JT808.Gateway.SimpleServer/Configs/test.cer and /dev/null differ diff --git a/src/JT808.Gateway.SimpleServer/JT808.Gateway.SimpleServer.csproj b/src/JT808.Gateway.SimpleServer/JT808.Gateway.SimpleServer.csproj deleted file mode 100644 index d8666d6..0000000 --- a/src/JT808.Gateway.SimpleServer/JT808.Gateway.SimpleServer.csproj +++ /dev/null @@ -1,39 +0,0 @@ - - - - Exe - netcoreapp3.0 - - - - - - - - - - - - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - - - diff --git a/src/JT808.Gateway.SimpleServer/Program.cs b/src/JT808.Gateway.SimpleServer/Program.cs deleted file mode 100644 index 2590e7f..0000000 --- a/src/JT808.Gateway.SimpleServer/Program.cs +++ /dev/null @@ -1,71 +0,0 @@ -using JT808.Gateway.Services; -using JT808.Gateway.Tcp; -using JT808.Gateway.Udp; -using JT808.Protocol; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Server.Kestrel.Core; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; -using System; -using System.IO; -using System.Net; - -namespace JT808.Gateway.SimpleServer -{ - class Program - { - static void Main(string[] args) - { - Host.CreateDefaultBuilder(args) - .ConfigureAppConfiguration((hostingContext, config) => - { - config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory); - config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); - }) - .ConfigureLogging((hostContext, configLogging) => { - Console.WriteLine($"Environment.OSVersion.Platform:{Environment.OSVersion.Platform.ToString()}"); - NLog.LogManager.LoadConfiguration($"Configs/nlog.{Environment.OSVersion.Platform.ToString()}.config"); - configLogging.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true }); - configLogging.SetMinimumLevel(LogLevel.Trace); - }) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder - .ConfigureKestrel(options => - { - options.Listen(IPAddress.Any, 5001, listenOptions => - { - listenOptions.Protocols = HttpProtocols.Http2; - listenOptions.UseHttps($"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs", "test.cer")}", ""); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseEndpoints(endpoints => - { - endpoints.MapGrpcService(); - }); - }); - }) - .ConfigureServices((hostContext,services) => - { - //services.Configure(hostContext.Configuration.GetSection("Kestrel")); - services.AddGrpc(); - services.AddSingleton(); - services.AddSingleton(typeof(ILogger<>), typeof(Logger<>)); - services.AddJT808Configure() - .AddJT808Gateway(hostContext.Configuration) - .AddJT808GatewayTcpHost() - .AddJT808GatewayUdpHost() - .Builder(); - }) - .Build() - .Run(); - } - } -} diff --git a/src/JT808.Gateway.sln b/src/JT808.Gateway.sln deleted file mode 100644 index b6b12d5..0000000 --- a/src/JT808.Gateway.sln +++ /dev/null @@ -1,102 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29411.108 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JT808.Gateway", "JT808.Gateway\JT808.Gateway.csproj", "{A42A396F-D32B-4AC2-B554-735AA7E2DBA8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JT808.Gateway.SimpleServer", "JT808.Gateway.SimpleServer\JT808.Gateway.SimpleServer.csproj", "{F9ABFDDB-84A2-44C8-A162-A1FE4EA4D332}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JT808.Gateway.SimpleClient", "JT808.Gateway.SimpleClient\JT808.Gateway.SimpleClient.csproj", "{886D4937-7265-40DC-87CC-85CE35553214}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JT808.Gateway.Kafka", "JT808.Gateway.Kafka\JT808.Gateway.Kafka.csproj", "{790E132C-7D92-4A6A-8CF0-2C181331FB31}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JT808.Gateway.CleintBenchmark", "JT808.Gateway.CleintBenchmark\JT808.Gateway.CleintBenchmark.csproj", "{1A925C08-2590-4E55-84F2-96F01306D34D}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{DC0E0AC1-C4BD-4291-AD16-744080411C3D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JT808.Gateway.Traffic.Test", "JT808.Gateway.Tests\JT808.Gateway.Traffic.Test\JT808.Gateway.Traffic.Test.csproj", "{D4DF5285-612A-417D-BDE4-690BDF0C07C6}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JT808.Gateway.Transmit.Test", "JT808.Gateway.Tests\JT808.Gateway.Transmit.Test\JT808.Gateway.Transmit.Test.csproj", "{5E2C290C-637B-4F8B-AE03-1A4B669F7FFB}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JT808.Gateway.SessionNotice.Test", "JT808.Gateway.Tests\JT808.Gateway.SessionNotice.Test\JT808.Gateway.SessionNotice.Test.csproj", "{562B16BD-1D4C-40FD-86CF-7845DBC9C1EE}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JT808.Gateway.ReplyMessage.Test", "JT808.Gateway.Tests\JT808.Gateway.ReplyMessage.Test\JT808.Gateway.ReplyMessage.Test.csproj", "{CDE064DE-0E8E-4165-8F6A-6C03A8783506}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JT808.Gateway.MsgLogging.Test", "JT808.Gateway.Tests\JT808.Gateway.MsgLogging.Test\JT808.Gateway.MsgLogging.Test.csproj", "{8BD638B1-1F16-4BA8-8506-1B83DA4A884E}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JT808.Gateway.MsgIdHandler.Test", "JT808.Gateway.Tests\JT808.Gateway.MsgIdHandler.Test\JT808.Gateway.MsgIdHandler.Test.csproj", "{CC2ABC8E-CC78-4B68-8670-90C2BCAB434E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JT808.Gateway.Test", "JT808.Gateway.Tests\JT808.Gateway.Test\JT808.Gateway.Test.csproj", "{F1031636-69CF-4C44-AF0B-F8BE8DE03864}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A42A396F-D32B-4AC2-B554-735AA7E2DBA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A42A396F-D32B-4AC2-B554-735AA7E2DBA8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A42A396F-D32B-4AC2-B554-735AA7E2DBA8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A42A396F-D32B-4AC2-B554-735AA7E2DBA8}.Release|Any CPU.Build.0 = Release|Any CPU - {F9ABFDDB-84A2-44C8-A162-A1FE4EA4D332}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F9ABFDDB-84A2-44C8-A162-A1FE4EA4D332}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F9ABFDDB-84A2-44C8-A162-A1FE4EA4D332}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F9ABFDDB-84A2-44C8-A162-A1FE4EA4D332}.Release|Any CPU.Build.0 = Release|Any CPU - {886D4937-7265-40DC-87CC-85CE35553214}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {886D4937-7265-40DC-87CC-85CE35553214}.Debug|Any CPU.Build.0 = Debug|Any CPU - {886D4937-7265-40DC-87CC-85CE35553214}.Release|Any CPU.ActiveCfg = Release|Any CPU - {886D4937-7265-40DC-87CC-85CE35553214}.Release|Any CPU.Build.0 = Release|Any CPU - {790E132C-7D92-4A6A-8CF0-2C181331FB31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {790E132C-7D92-4A6A-8CF0-2C181331FB31}.Debug|Any CPU.Build.0 = Debug|Any CPU - {790E132C-7D92-4A6A-8CF0-2C181331FB31}.Release|Any CPU.ActiveCfg = Release|Any CPU - {790E132C-7D92-4A6A-8CF0-2C181331FB31}.Release|Any CPU.Build.0 = Release|Any CPU - {1A925C08-2590-4E55-84F2-96F01306D34D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1A925C08-2590-4E55-84F2-96F01306D34D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1A925C08-2590-4E55-84F2-96F01306D34D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1A925C08-2590-4E55-84F2-96F01306D34D}.Release|Any CPU.Build.0 = Release|Any CPU - {D4DF5285-612A-417D-BDE4-690BDF0C07C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D4DF5285-612A-417D-BDE4-690BDF0C07C6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D4DF5285-612A-417D-BDE4-690BDF0C07C6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D4DF5285-612A-417D-BDE4-690BDF0C07C6}.Release|Any CPU.Build.0 = Release|Any CPU - {5E2C290C-637B-4F8B-AE03-1A4B669F7FFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5E2C290C-637B-4F8B-AE03-1A4B669F7FFB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5E2C290C-637B-4F8B-AE03-1A4B669F7FFB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5E2C290C-637B-4F8B-AE03-1A4B669F7FFB}.Release|Any CPU.Build.0 = Release|Any CPU - {562B16BD-1D4C-40FD-86CF-7845DBC9C1EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {562B16BD-1D4C-40FD-86CF-7845DBC9C1EE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {562B16BD-1D4C-40FD-86CF-7845DBC9C1EE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {562B16BD-1D4C-40FD-86CF-7845DBC9C1EE}.Release|Any CPU.Build.0 = Release|Any CPU - {CDE064DE-0E8E-4165-8F6A-6C03A8783506}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CDE064DE-0E8E-4165-8F6A-6C03A8783506}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CDE064DE-0E8E-4165-8F6A-6C03A8783506}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CDE064DE-0E8E-4165-8F6A-6C03A8783506}.Release|Any CPU.Build.0 = Release|Any CPU - {8BD638B1-1F16-4BA8-8506-1B83DA4A884E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8BD638B1-1F16-4BA8-8506-1B83DA4A884E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8BD638B1-1F16-4BA8-8506-1B83DA4A884E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8BD638B1-1F16-4BA8-8506-1B83DA4A884E}.Release|Any CPU.Build.0 = Release|Any CPU - {CC2ABC8E-CC78-4B68-8670-90C2BCAB434E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CC2ABC8E-CC78-4B68-8670-90C2BCAB434E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CC2ABC8E-CC78-4B68-8670-90C2BCAB434E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CC2ABC8E-CC78-4B68-8670-90C2BCAB434E}.Release|Any CPU.Build.0 = Release|Any CPU - {F1031636-69CF-4C44-AF0B-F8BE8DE03864}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F1031636-69CF-4C44-AF0B-F8BE8DE03864}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F1031636-69CF-4C44-AF0B-F8BE8DE03864}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F1031636-69CF-4C44-AF0B-F8BE8DE03864}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {D4DF5285-612A-417D-BDE4-690BDF0C07C6} = {DC0E0AC1-C4BD-4291-AD16-744080411C3D} - {5E2C290C-637B-4F8B-AE03-1A4B669F7FFB} = {DC0E0AC1-C4BD-4291-AD16-744080411C3D} - {562B16BD-1D4C-40FD-86CF-7845DBC9C1EE} = {DC0E0AC1-C4BD-4291-AD16-744080411C3D} - {CDE064DE-0E8E-4165-8F6A-6C03A8783506} = {DC0E0AC1-C4BD-4291-AD16-744080411C3D} - {8BD638B1-1F16-4BA8-8506-1B83DA4A884E} = {DC0E0AC1-C4BD-4291-AD16-744080411C3D} - {CC2ABC8E-CC78-4B68-8670-90C2BCAB434E} = {DC0E0AC1-C4BD-4291-AD16-744080411C3D} - {F1031636-69CF-4C44-AF0B-F8BE8DE03864} = {DC0E0AC1-C4BD-4291-AD16-744080411C3D} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {F5671BD2-B44A-4A7C-80EA-E060A512992D} - EndGlobalSection -EndGlobal diff --git a/src/JT808.Gateway/BusinessServices/MsgIdHandler/IJT808MsgIdHandler.cs b/src/JT808.Gateway/BusinessServices/MsgIdHandler/IJT808MsgIdHandler.cs deleted file mode 100644 index 59bf986..0000000 --- a/src/JT808.Gateway/BusinessServices/MsgIdHandler/IJT808MsgIdHandler.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.MsgIdHandler -{ - /// - /// JT808消息Id处理程序 - /// - public interface IJT808MsgIdHandler - { - void Processor((string TerminalNo, byte[] Data) parameter); - } -} diff --git a/src/JT808.Gateway/BusinessServices/MsgIdHandler/JT808MsgIdHandlerExtensions.cs b/src/JT808.Gateway/BusinessServices/MsgIdHandler/JT808MsgIdHandlerExtensions.cs deleted file mode 100644 index 433e065..0000000 --- a/src/JT808.Gateway/BusinessServices/MsgIdHandler/JT808MsgIdHandlerExtensions.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.MsgIdHandler -{ - public static class JT808MsgIdHandlerExtensions - { - public static IJT808ClientBuilder AddJT808MsgIdHandler(this IJT808ClientBuilder jT808ClientBuilder) - where TJT808MsgIdHandler: IJT808MsgIdHandler - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(typeof(IJT808MsgIdHandler),typeof(TJT808MsgIdHandler)); - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - return jT808ClientBuilder; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/MsgIdHandler/JT808MsgIdHandlerHostedService.cs b/src/JT808.Gateway/BusinessServices/MsgIdHandler/JT808MsgIdHandlerHostedService.cs deleted file mode 100644 index d85eb04..0000000 --- a/src/JT808.Gateway/BusinessServices/MsgIdHandler/JT808MsgIdHandlerHostedService.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using System.Threading; -using JT808.Gateway.PubSub; - -namespace JT808.Gateway.BusinessServices.MsgIdHandler -{ - public class JT808MsgIdHandlerHostedService : IHostedService - { - private readonly IJT808MsgConsumer jT808MsgConsumer; - - private readonly IJT808MsgIdHandler jT808MsgIdHandler; - public JT808MsgIdHandlerHostedService( - IJT808MsgIdHandler jT808DotNettyMsgIdHandler, - IJT808MsgConsumer jT808MsgConsumer) - { - this.jT808MsgIdHandler = jT808DotNettyMsgIdHandler; - this.jT808MsgConsumer = jT808MsgConsumer; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Subscribe(); - jT808MsgConsumer.OnMessage(jT808MsgIdHandler.Processor); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Unsubscribe(); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/MsgLogging/IJT808MsgLogging.cs b/src/JT808.Gateway/BusinessServices/MsgLogging/IJT808MsgLogging.cs deleted file mode 100644 index b3daf96..0000000 --- a/src/JT808.Gateway/BusinessServices/MsgLogging/IJT808MsgLogging.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace JT808.Gateway.BusinessServices.MsgLogging -{ - /// - /// 808数据上下行日志接口 - /// - public interface IJT808MsgLogging - { - void Processor((string TerminalNo, byte[] Data) parameter, JT808MsgLoggingType jT808MsgLoggingType); - } -} diff --git a/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgDownLoggingHostedService.cs b/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgDownLoggingHostedService.cs deleted file mode 100644 index 7c52f15..0000000 --- a/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgDownLoggingHostedService.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using System.Threading; -using JT808.Gateway.PubSub; - -namespace JT808.Gateway.BusinessServices.MsgLogging -{ - public class JT808MsgDownLoggingHostedService : IHostedService - { - private readonly IJT808MsgReplyConsumer jT808MsgReplyConsumer; - private readonly IJT808MsgLogging jT808MsgLogging; - public JT808MsgDownLoggingHostedService( - IJT808MsgLogging jT808MsgLogging, - IJT808MsgReplyConsumer jT808MsgReplyConsumer) - { - this.jT808MsgReplyConsumer = jT808MsgReplyConsumer; - this.jT808MsgLogging = jT808MsgLogging; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - jT808MsgReplyConsumer.Subscribe(); - jT808MsgReplyConsumer.OnMessage(item=> - { - jT808MsgLogging.Processor(item, JT808MsgLoggingType.down); - }); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - jT808MsgReplyConsumer.Unsubscribe(); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgLoggingExtensions.cs b/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgLoggingExtensions.cs deleted file mode 100644 index 00f16ac..0000000 --- a/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgLoggingExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.MsgLogging -{ - public static class JT808MsgLoggingExtensions - { - public static IJT808ClientBuilder AddJT808MsgLogging(this IJT808ClientBuilder jT808ClientBuilder) - where TJT808MsgLogging: IJT808MsgLogging - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(typeof(IJT808MsgLogging),typeof(TJT808MsgLogging)); - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - return jT808ClientBuilder; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgLoggingType.cs b/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgLoggingType.cs deleted file mode 100644 index 1c83329..0000000 --- a/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgLoggingType.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.MsgLogging -{ - public enum JT808MsgLoggingType - { - /// - /// 数据上行 - /// - up, - /// - /// 数据下行 - /// - down - } -} diff --git a/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgUpLoggingHostedService.cs b/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgUpLoggingHostedService.cs deleted file mode 100644 index be257b7..0000000 --- a/src/JT808.Gateway/BusinessServices/MsgLogging/JT808MsgUpLoggingHostedService.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using System.Threading; -using JT808.Gateway.PubSub; - -namespace JT808.Gateway.BusinessServices.MsgLogging -{ - public class JT808MsgUpLoggingHostedService : IHostedService - { - private readonly IJT808MsgConsumer jT808MsgConsumer; - private readonly IJT808MsgLogging jT808MsgLogging; - public JT808MsgUpLoggingHostedService( - IJT808MsgLogging jT808MsgLogging, - IJT808MsgConsumer jT808MsgConsumer) - { - this.jT808MsgConsumer = jT808MsgConsumer; - this.jT808MsgLogging = jT808MsgLogging; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Subscribe(); - jT808MsgConsumer.OnMessage(item=> - { - jT808MsgLogging.Processor(item, JT808MsgLoggingType.up); - }); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Unsubscribe(); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/ReplyMessage/JT808ReplyMessageExtensions.cs b/src/JT808.Gateway/BusinessServices/ReplyMessage/JT808ReplyMessageExtensions.cs deleted file mode 100644 index 049f824..0000000 --- a/src/JT808.Gateway/BusinessServices/ReplyMessage/JT808ReplyMessageExtensions.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.ReplyMessage -{ - public static class JT808ReplyMessageExtensions - { - /// - /// 独享消息应答服务(不同的消费者实例) - /// - /// - /// - public static IJT808ClientBuilder AddInprocJT808ReplyMessage(this IJT808ClientBuilder jT808ClientBuilder) - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - return jT808ClientBuilder; - } - /// - /// 独享消息应答服务(不同的消费者实例) - /// - /// 自定义消息回复服务 - /// - /// - public static IJT808ClientBuilder AddInprocJT808ReplyMessage(this IJT808ClientBuilder jT808ClientBuilder) - where TReplyMessageService : JT808ReplyMessageService - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - return jT808ClientBuilder; - } - /// - /// 共享消息应答服务(消费者单实例) - /// - /// 自定义消息回复服务 - /// - /// - public static IJT808ClientBuilder AddShareJT808ReplyMessage(this IJT808ClientBuilder jT808ClientBuilder) - where TReplyMessageService : JT808ReplyMessageService - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - return jT808ClientBuilder; - } - /// - /// 共享消息应答服务(消费者单实例) - /// - /// - /// - public static IJT808ClientBuilder AddShareJT808ReplyMessage(this IJT808ClientBuilder jT808ClientBuilder) - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - return jT808ClientBuilder; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/ReplyMessage/JT808ReplyMessageHostedService.cs b/src/JT808.Gateway/BusinessServices/ReplyMessage/JT808ReplyMessageHostedService.cs deleted file mode 100644 index 1bd7e74..0000000 --- a/src/JT808.Gateway/BusinessServices/ReplyMessage/JT808ReplyMessageHostedService.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using System.Threading; -using JT808.Gateway.PubSub; - -namespace JT808.Gateway.BusinessServices.ReplyMessage -{ - public class JT808ReplyMessageHostedService : IHostedService - { - private readonly IJT808MsgConsumer jT808MsgConsumer; - private readonly JT808ReplyMessageService jT808DotNettyReplyMessageService; - - public JT808ReplyMessageHostedService( - JT808ReplyMessageService jT808DotNettyReplyMessageService, - IJT808MsgConsumer jT808MsgConsumer) - { - this.jT808MsgConsumer = jT808MsgConsumer; - this.jT808DotNettyReplyMessageService = jT808DotNettyReplyMessageService; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Subscribe(); - jT808MsgConsumer.OnMessage(jT808DotNettyReplyMessageService.Processor); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Unsubscribe(); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/ReplyMessage/JT808ReplyMessageService.cs b/src/JT808.Gateway/BusinessServices/ReplyMessage/JT808ReplyMessageService.cs deleted file mode 100644 index 3fc64f6..0000000 --- a/src/JT808.Gateway/BusinessServices/ReplyMessage/JT808ReplyMessageService.cs +++ /dev/null @@ -1,165 +0,0 @@ -using JT808.Gateway.PubSub; -using JT808.Protocol; -using JT808.Protocol.Enums; -using JT808.Protocol.Extensions; -using JT808.Protocol.MessageBody; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.ReplyMessage -{ - public class JT808ReplyMessageService - { - protected Dictionary> HandlerDict { get; } - - protected JT808Serializer JT808Serializer { get; } - protected IJT808MsgReplyProducer JT808MsgReplyProducer { get; } - public JT808ReplyMessageService( - IJT808Config jT808Config, - IJT808MsgReplyProducer jT808MsgReplyProducer) - { - this.JT808Serializer = jT808Config.GetSerializer(); - this.JT808MsgReplyProducer = jT808MsgReplyProducer; - HandlerDict = new Dictionary> { - {JT808MsgId.终端通用应答.ToUInt16Value(), Msg0x0001}, - {JT808MsgId.终端鉴权.ToUInt16Value(), Msg0x0102}, - {JT808MsgId.终端心跳.ToUInt16Value(), Msg0x0002}, - {JT808MsgId.终端注销.ToUInt16Value(), Msg0x0003}, - {JT808MsgId.终端注册.ToUInt16Value(), Msg0x0100}, - {JT808MsgId.位置信息汇报.ToUInt16Value(),Msg0x0200 }, - {JT808MsgId.定位数据批量上传.ToUInt16Value(),Msg0x0704 }, - {JT808MsgId.数据上行透传.ToUInt16Value(),Msg0x0900 } - }; - } - - public virtual void Processor((string TerminalNo, byte[] Data) parameter) - { - try - { - var request = JT808Serializer.HeaderDeserialize(parameter.Data); - if (HandlerDict.TryGetValue(request.Header.MsgId, out var func)) - { - var buffer = func(request); - if (buffer != null) - { - JT808MsgReplyProducer.ProduceAsync(parameter.TerminalNo, buffer); - } - } - } - catch - { - } - } - - /// - /// 终端通用应答 - /// 平台无需回复 - /// 实现自己的业务 - /// - /// - /// - public virtual byte[] Msg0x0001(JT808HeaderPackage request) - { - return null; - } - /// - /// 终端心跳 - /// - /// - /// - public virtual byte[] Msg0x0002(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 终端注销 - /// - /// - /// - public virtual byte[] Msg0x0003(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 终端注册 - /// - /// - /// - public virtual byte[] Msg0x0100(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.终端注册应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8100() - { - Code = "J" + request.Header.TerminalPhoneNo, - JT808TerminalRegisterResult = JT808TerminalRegisterResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 终端鉴权 - /// - /// - /// - public virtual byte[] Msg0x0102(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 位置信息汇报 - /// - /// - /// - public virtual byte[] Msg0x0200(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 定位数据批量上传 - /// - /// - /// - public virtual byte[] Msg0x0704(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 数据上行透传 - /// - /// - /// - public virtual byte[] Msg0x0900(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/SessionNotice/JT808SessionNoticeExtensions.cs b/src/JT808.Gateway/BusinessServices/SessionNotice/JT808SessionNoticeExtensions.cs deleted file mode 100644 index c2c3b9b..0000000 --- a/src/JT808.Gateway/BusinessServices/SessionNotice/JT808SessionNoticeExtensions.cs +++ /dev/null @@ -1,60 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.SessionNotice -{ - public static class JT808SessionNoticeExtensions - { - /// - /// 独享消息会话通知服务(不同的消费者实例) - /// - /// - /// - public static IJT808ClientBuilder AddInprocJT808SessionNotice(this IJT808ClientBuilder jT808ClientBuilder) - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - return jT808ClientBuilder; - } - - /// - /// 独享消息会话通知服务(不同的消费者实例) - /// - /// 自定义会话通知服务 - /// - /// - public static IJT808ClientBuilder AddInprocJT808SessionNotice(this IJT808ClientBuilder jT808ClientBuilder) - where TSessionNoticeService : JT808SessionNoticeService - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - return jT808ClientBuilder; - } - - /// - /// 共享消息会话通知服务(消费者单实例) - /// - /// 自定义会话通知服务 - /// - /// - public static IJT808ClientBuilder AddShareJT808SessionNotice(this IJT808ClientBuilder jT808ClientBuilder) - where TSessionNoticeService : JT808SessionNoticeService - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - return jT808ClientBuilder; - } - - /// - /// 共享消息会话通知服务(消费者单实例) - /// - /// - /// - public static IJT808ClientBuilder AddShareJT808SessionNotice(this IJT808ClientBuilder jT808ClientBuilder) - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - return jT808ClientBuilder; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/SessionNotice/JT808SessionNoticeHostedService.cs b/src/JT808.Gateway/BusinessServices/SessionNotice/JT808SessionNoticeHostedService.cs deleted file mode 100644 index 44c04ae..0000000 --- a/src/JT808.Gateway/BusinessServices/SessionNotice/JT808SessionNoticeHostedService.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Threading.Tasks; -using JT808.Protocol; -using JT808.Protocol.Interfaces; -using Microsoft.Extensions.Hosting; -using System.Threading; -using JT808.Gateway.PubSub; - -namespace JT808.Gateway.BusinessServices.SessionNotice -{ - public class JT808SessionNoticeHostedService : IHostedService - { - private readonly JT808SessionNoticeService jT808DotNettySessionNoticeService; - private readonly IJT808SessionConsumer jT808SessionConsumer; - public JT808SessionNoticeHostedService( - IJT808SessionConsumer jT808SessionConsumer, - JT808SessionNoticeService jT808DotNettySessionNoticeService) - { - this.jT808DotNettySessionNoticeService = jT808DotNettySessionNoticeService; - this.jT808SessionConsumer = jT808SessionConsumer; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - jT808SessionConsumer.Subscribe(); - jT808SessionConsumer.OnMessage(jT808DotNettySessionNoticeService.Processor); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - jT808SessionConsumer.Unsubscribe(); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/SessionNotice/JT808SessionNoticeService.cs b/src/JT808.Gateway/BusinessServices/SessionNotice/JT808SessionNoticeService.cs deleted file mode 100644 index ccf4ace..0000000 --- a/src/JT808.Gateway/BusinessServices/SessionNotice/JT808SessionNoticeService.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.SessionNotice -{ - public class JT808SessionNoticeService - { - protected ILogger logger { get; } - public JT808SessionNoticeService(ILoggerFactory loggerFactory) - { - logger = loggerFactory.CreateLogger("JT808DotNettySessionNoticeService"); - } - public virtual void Processor((string Notice, string TerminalNo) parameter) - { - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug($"{parameter.Notice}-{parameter.TerminalNo}"); - } - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/Traffic/JT808TrafficService.cs b/src/JT808.Gateway/BusinessServices/Traffic/JT808TrafficService.cs deleted file mode 100644 index f028a5d..0000000 --- a/src/JT808.Gateway/BusinessServices/Traffic/JT808TrafficService.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Microsoft.Extensions.Configuration; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.Traffic -{ - public class JT808TrafficService:IDisposable - { - private readonly CSRedis.CSRedisClient redisClien; - public JT808TrafficService(IConfiguration configuration) - { - redisClien = new CSRedis.CSRedisClient(configuration.GetConnectionString("TrafficRedisHost")); - TrafficRedisClient.Initialization(redisClien); - } - - public void Dispose() - { - redisClien.Dispose(); - } - - /// - /// 按设备每天统计sim卡流量 - /// - /// - /// - public void Processor(string terminalNo,int len) - { - TrafficRedisClient.HIncrBy(terminalNo, DateTime.Now.ToString("yyyyMMdd"), len); - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/Traffic/JT808TrafficServiceExtensions.cs b/src/JT808.Gateway/BusinessServices/Traffic/JT808TrafficServiceExtensions.cs deleted file mode 100644 index 4a83b0d..0000000 --- a/src/JT808.Gateway/BusinessServices/Traffic/JT808TrafficServiceExtensions.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.Traffic -{ - public static class JT808TrafficServiceExtensions - { - /// - /// 独享消息流量统计服务(不同的消费者实例) - /// - /// - /// - public static IJT808ClientBuilder AddInprocJT808Traffic(this IJT808ClientBuilder jT808ClientBuilder) - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - return jT808ClientBuilder; - } - /// - /// 共享消息流量统计服务(消费者单实例) - /// - /// - /// - /// - public static IJT808ClientBuilder AddShareJT808Traffic(this IJT808ClientBuilder jT808ClientBuilder) - { - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - return jT808ClientBuilder; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/Traffic/JT808TrafficServiceHostedService.cs b/src/JT808.Gateway/BusinessServices/Traffic/JT808TrafficServiceHostedService.cs deleted file mode 100644 index 84c4299..0000000 --- a/src/JT808.Gateway/BusinessServices/Traffic/JT808TrafficServiceHostedService.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using System.Threading; -using JT808.Protocol.Extensions; -using JT808.Gateway.PubSub; - -namespace JT808.Gateway.BusinessServices.Traffic -{ - public class JT808TrafficServiceHostedService : IHostedService - { - private readonly IJT808MsgConsumer jT808MsgConsumer; - private readonly JT808TrafficService jT808DotNettyTrafficService; - - public JT808TrafficServiceHostedService( - JT808TrafficService jT808DotNettyTrafficService, - IJT808MsgConsumer jT808MsgConsumer) - { - this.jT808MsgConsumer = jT808MsgConsumer; - this.jT808DotNettyTrafficService = jT808DotNettyTrafficService; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Subscribe(); - jT808MsgConsumer.OnMessage((item)=> { - string str = item.Data.ToHexString(); - jT808DotNettyTrafficService.Processor(item.TerminalNo, item.Data.Length); - }); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Unsubscribe(); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/Traffic/TrafficRedisClient.cs b/src/JT808.Gateway/BusinessServices/Traffic/TrafficRedisClient.cs deleted file mode 100644 index eb04aa0..0000000 --- a/src/JT808.Gateway/BusinessServices/Traffic/TrafficRedisClient.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.Traffic -{ - class TrafficRedisClient: RedisHelper - { } -} diff --git a/src/JT808.Gateway/BusinessServices/Transmit/Configs/DataTransferOptions.cs b/src/JT808.Gateway/BusinessServices/Transmit/Configs/DataTransferOptions.cs deleted file mode 100644 index 5a50189..0000000 --- a/src/JT808.Gateway/BusinessServices/Transmit/Configs/DataTransferOptions.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.Transmit.Configs -{ - public class DataTransferOptions - { - public string Host { get; set; } - - public List TerminalNos { get; set; } - } -} diff --git a/src/JT808.Gateway/BusinessServices/Transmit/Configs/RemoteServerOptions.cs b/src/JT808.Gateway/BusinessServices/Transmit/Configs/RemoteServerOptions.cs deleted file mode 100644 index b9872cb..0000000 --- a/src/JT808.Gateway/BusinessServices/Transmit/Configs/RemoteServerOptions.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.BusinessServices.Transmit.Configs -{ - public class RemoteServerOptions - { - public List DataTransfer { get; set; } - } -} diff --git a/src/JT808.Gateway/BusinessServices/Transmit/Handlers/ClientConnectionHandler.cs b/src/JT808.Gateway/BusinessServices/Transmit/Handlers/ClientConnectionHandler.cs deleted file mode 100644 index 397b063..0000000 --- a/src/JT808.Gateway/BusinessServices/Transmit/Handlers/ClientConnectionHandler.cs +++ /dev/null @@ -1,76 +0,0 @@ -using DotNetty.Transport.Bootstrapping; -using DotNetty.Transport.Channels; -using DotNetty.Transport.Channels.Sockets; -using Polly; -using System; -using System.Linq; -using System.Collections.Generic; -using System.Net; -using System.Text; -using Microsoft.Extensions.Logging; - -namespace JT808.Gateway.BusinessServices.Transmit.Handlers -{ - public class ClientConnectionHandler : ChannelHandlerAdapter - { - private readonly Bootstrap bootstrap; - public Dictionary channeldic; - private readonly ILogger logger; - public ClientConnectionHandler(Bootstrap bootstrap, - Dictionary channeldic, - ILoggerFactory loggerFactory) - { - this.bootstrap = bootstrap; - this.channeldic = channeldic; - logger = loggerFactory.CreateLogger(); - } - public override void ChannelInactive(IChannelHandlerContext context) - { - Policy.HandleResult(context.Channel.Open) - .WaitAndRetryForeverAsync(retryAttempt => - { - return retryAttempt > 20 ? TimeSpan.FromSeconds(Math.Pow(2, 50)) : TimeSpan.FromSeconds(Math.Pow(2, retryAttempt));//超过重试20次,之后重试都是接近12个小时重试一次 - }, - (exception, timespan, ctx) => - { - logger.LogError($"服务端断开{context.Channel.RemoteAddress},重试结果{exception.Result},重试次数{timespan},下次重试间隔(s){ctx.TotalSeconds}"); - }) - .ExecuteAsync(async () => - { - try - { - var oldChannel = channeldic.FirstOrDefault(m => m.Value == context.Channel); - if (default(KeyValuePair).Equals(oldChannel)) - { - if(logger.IsEnabled( LogLevel.Debug)) - logger.LogDebug($"服务器已经删除了{oldChannel.Key}远程服务器配置"); - return true; - } - var channel = await bootstrap.ConnectAsync(context.Channel.RemoteAddress); - channeldic.Remove(oldChannel.Key); - channeldic.Add(oldChannel.Key, channel); - return channel.Open; - } - catch (Exception ex) - { - logger.LogError($"服务端断开后{context.Channel.RemoteAddress},重连异常:{ex}"); - return false; - } - }); - } - - public override void ChannelRead(IChannelHandlerContext context, object message) - { - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogError($"服务端返回消息{message}"); - } - } - - public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) - { - logger.LogError($"服务端Exception: {exception}"); - context.CloseAsync(); - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/Transmit/JT808DotNettyTransmitExtensions.cs b/src/JT808.Gateway/BusinessServices/Transmit/JT808DotNettyTransmitExtensions.cs deleted file mode 100644 index 969b2fd..0000000 --- a/src/JT808.Gateway/BusinessServices/Transmit/JT808DotNettyTransmitExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; -using JT808.Protocol; -using Microsoft.Extensions.Configuration; -using JT808.Gateway.BusinessServices.Transmit.Configs; - -namespace JT808.Gateway.BusinessServices.Transmit -{ - public static class JT808DotNettyTransmitExtensions - { - /// - /// 独享转发服务(不同的消费者实例) - /// - /// - /// - /// - public static IJT808ClientBuilder AddInprocJT808Transmit(this IJT808ClientBuilder jT808ClientBuilder,IConfiguration configuration) - { - jT808ClientBuilder.JT808Builder.Services.Configure(configuration.GetSection("RemoteServerOptions")); - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - return jT808ClientBuilder; - } - /// - /// 共享转发服务(消费者单实例) - /// - /// - /// - /// - public static IJT808ClientBuilder AddShareJT808Transmit(this IJT808ClientBuilder jT808ClientBuilder, IConfiguration configuration) - { - jT808ClientBuilder.JT808Builder.Services.Configure(configuration.GetSection("RemoteServerOptions")); - jT808ClientBuilder.JT808Builder.Services.AddSingleton(); - return jT808ClientBuilder; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/Transmit/JT808DotNettyTransmitHostedService.cs b/src/JT808.Gateway/BusinessServices/Transmit/JT808DotNettyTransmitHostedService.cs deleted file mode 100644 index 51504b5..0000000 --- a/src/JT808.Gateway/BusinessServices/Transmit/JT808DotNettyTransmitHostedService.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using System.Threading; -using JT808.Gateway.PubSub; - -namespace JT808.Gateway.BusinessServices.Transmit -{ - public class JT808DotNettyTransmitHostedService:IHostedService - { - private readonly JT808DotNettyTransmitService jT808DotNettyTransmitService; - private readonly IJT808MsgConsumer jT808MsgConsumer; - public JT808DotNettyTransmitHostedService( - IJT808MsgConsumer jT808MsgConsumer, - JT808DotNettyTransmitService jT808DotNettyTransmitService) - { - this.jT808DotNettyTransmitService = jT808DotNettyTransmitService; - this.jT808MsgConsumer = jT808MsgConsumer; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Subscribe(); - jT808MsgConsumer.OnMessage(jT808DotNettyTransmitService.Send); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - jT808MsgConsumer.Unsubscribe(); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/BusinessServices/Transmit/JT808DotNettyTransmitService.cs b/src/JT808.Gateway/BusinessServices/Transmit/JT808DotNettyTransmitService.cs deleted file mode 100644 index 1c2d8c3..0000000 --- a/src/JT808.Gateway/BusinessServices/Transmit/JT808DotNettyTransmitService.cs +++ /dev/null @@ -1,236 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Transport.Bootstrapping; -using DotNetty.Transport.Channels; -using DotNetty.Transport.Channels.Sockets; -using System; -using System.Collections.Generic; -using System.Net; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System.Linq; -using JT808.Gateway.BusinessServices.Transmit.Configs; -using JT808.Gateway.BusinessServices.Transmit.Handlers; - -namespace JT808.Gateway.BusinessServices.Transmit -{ - public class JT808DotNettyTransmitService - { - private readonly ILogger logger; - private readonly ILoggerFactory loggerFactory; - private IOptionsMonitor optionsMonitor; - public Dictionary channeldic = new Dictionary(); - public JT808DotNettyTransmitService(ILoggerFactory loggerFactory, - IOptionsMonitor optionsMonitor) - { - this.loggerFactory = loggerFactory; - logger = loggerFactory.CreateLogger("JT808DotNettyTransmitService"); - this.optionsMonitor = optionsMonitor; - InitialDispatcherClient(); - } - public void Send((string TerminalNo, byte[] Data) parameter) - { - if (optionsMonitor.CurrentValue.DataTransfer != null) - { - foreach (var item in optionsMonitor.CurrentValue.DataTransfer) - { - if (channeldic.TryGetValue($"all_{item.Host}", out var allClientChannel)) - { - try - { - if (allClientChannel.Open) - { - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug($"转发所有数据到该网关{item.Host}"); - } - allClientChannel.WriteAndFlushAsync(Unpooled.WrappedBuffer(parameter.Data)); - } - else - { - logger.LogError($"{item.Host}链接已关闭"); - } - } - catch (Exception ex) - { - logger.LogError($"{item.Host}发送数据出现异常:{ex}"); - } - } - else - { - if (item.TerminalNos.Contains(parameter.TerminalNo) && channeldic.TryGetValue($"{parameter.TerminalNo}_{item.Host}", out var clientChannel)) - { - try - { - if (clientChannel.Open) - { - if (logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) - logger.LogDebug($"转发{parameter.TerminalNo}到该网关{item.Host}"); - clientChannel.WriteAndFlushAsync(Unpooled.WrappedBuffer(parameter.Data)); - } - else - { - logger.LogError($"{item.Host},{parameter.TerminalNo}链接已关闭"); - } - } - catch (Exception ex) - { - logger.LogError($"{item.Host},{parameter.TerminalNo}发送数据出现异常:{ex}"); - } - } - } - } - } - } - - public void InitialDispatcherClient() - { - Task.Run(async () => - { - var group = new MultithreadEventLoopGroup(); - var bootstrap = new Bootstrap(); - bootstrap.Group(group) - .Channel() - .Option(ChannelOption.TcpNodelay, true) - .Handler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - pipeline.AddLast(new ClientConnectionHandler(bootstrap, channeldic, loggerFactory)); - })); - optionsMonitor.OnChange(options => - { - List lastRemoteServers = new List(); - if (options.DataTransfer != null) - { - if (options.DataTransfer.Any()) - { - foreach (var item in options.DataTransfer) - { - if (item.TerminalNos != null) - { - if (item.TerminalNos.Any()) - { - foreach (var terminal in item.TerminalNos) - { - lastRemoteServers.Add($"{terminal}_{item.Host}"); - } - } - else - { - lastRemoteServers.Add($"all_{item.Host}"); - } - } - else - { - lastRemoteServers.Add($"all_{item.Host}"); - } - } - } - } - DelRemoteServsers(lastRemoteServers); - AddRemoteServsers(bootstrap, lastRemoteServers); - }); - await InitRemoteServsers(bootstrap); - }); - } - /// - /// 初始化远程服务器 - /// - /// - /// - /// - private async Task InitRemoteServsers(Bootstrap bootstrap) - { - List remoteServers = new List(); - if (optionsMonitor.CurrentValue.DataTransfer != null) - { - if (optionsMonitor.CurrentValue.DataTransfer.Any()) - { - foreach (var item in optionsMonitor.CurrentValue.DataTransfer) - { - if (item.TerminalNos != null) - { - if (item.TerminalNos.Any()) - { - foreach (var terminal in item.TerminalNos) - { - remoteServers.Add($"{terminal}_{item.Host}"); - } - } - else - { - remoteServers.Add($"all_{item.Host}"); - } - } - else - { - remoteServers.Add($"all_{item.Host}"); - } - } - } - } - foreach (var item in remoteServers) - { - try - { - string ip_port = item.Split('_')[1]; - IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip_port.Split(':')[0]), int.Parse(ip_port.Split(':')[1]))); - channeldic.Add(item, clientChannel); - if (clientChannel.Open) - { - if (logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) - { - logger.LogDebug($"该终端{item.Replace("_", "已连接上该服务器")}"); - } - } - } - catch (Exception ex) - { - logger.LogError($"初始化配置链接远程服务端{item},链接异常:{ex}"); - } - } - await Task.CompletedTask; - } - /// - /// 动态删除远程服务器 - /// - /// - private void DelRemoteServsers(List lastRemoteServers) - { - var delChannels = channeldic.Keys.Except(lastRemoteServers).ToList(); - foreach (var item in delChannels) - { - channeldic[item].CloseAsync(); - channeldic.Remove(item); - } - } - /// - /// 动态添加远程服务器 - /// - /// - /// - private void AddRemoteServsers(Bootstrap bootstrap, List lastRemoteServers) - { - var addChannels = lastRemoteServers.Except(channeldic.Keys).ToList(); - foreach (var item in addChannels) - { - try - { - var ip_port = item.Split('_')[1]; - IChannel clientChannel = bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip_port.Split(':')[0]), int.Parse(ip_port.Split(':')[1]))).Result; - channeldic.Add(item, clientChannel); - if (clientChannel.Open) { - if (logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) - { - logger.LogDebug($"该终端{item.Replace("_", "已连接上该服务器")}"); - } - } - } - catch (Exception ex) - { - logger.LogError($"变更配置后链接远程服务端{item},重连异常:{ex}"); - } - } - } - } -} diff --git a/src/JT808.Gateway/Client/DeviceConfig.cs b/src/JT808.Gateway/Client/DeviceConfig.cs deleted file mode 100644 index 53518ef..0000000 --- a/src/JT808.Gateway/Client/DeviceConfig.cs +++ /dev/null @@ -1,28 +0,0 @@ -using JT808.Protocol; -using JT808.Protocol.Interfaces; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Client -{ - public class DeviceConfig - { - public DeviceConfig(string terminalPhoneNo, string tcpHost,int tcpPort) - { - TerminalPhoneNo = terminalPhoneNo; - TcpHost = tcpHost; - TcpPort = tcpPort; - MsgSNDistributed = new JT808ClientMsgSNDistributedImpl(); - } - public string TerminalPhoneNo { get; private set; } - public string TcpHost { get; private set; } - public int TcpPort { get; private set; } - /// - /// 心跳时间(秒) - /// - public int Heartbeat { get; set; } = 30; - - public IJT808MsgSNDistributed MsgSNDistributed { get; } - } -} diff --git a/src/JT808.Gateway/Client/JT808ClientDotnettyExtensions.cs b/src/JT808.Gateway/Client/JT808ClientDotnettyExtensions.cs deleted file mode 100644 index 05d998f..0000000 --- a/src/JT808.Gateway/Client/JT808ClientDotnettyExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ - -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; -using JT808.Protocol; -using JT808.Gateway.Services; - -namespace JT808.Gateway.Client -{ - public static class JT808ClientDotnettyExtensions - { - public static IJT808Builder AddJT808Client(this IJT808Builder jT808Builder) - { - jT808Builder.Services.AddSingleton(); - jT808Builder.Services.AddSingleton(); - jT808Builder.Services.AddSingleton(); - jT808Builder.Services.AddSingleton(); - jT808Builder.Services.AddHostedService(); - return jT808Builder; - } - } -} diff --git a/src/JT808.Gateway/Client/JT808ClientMsgSNDistributedImpl.cs b/src/JT808.Gateway/Client/JT808ClientMsgSNDistributedImpl.cs deleted file mode 100644 index a7c11b6..0000000 --- a/src/JT808.Gateway/Client/JT808ClientMsgSNDistributedImpl.cs +++ /dev/null @@ -1,16 +0,0 @@ -using JT808.Protocol; -using JT808.Protocol.Interfaces; -using System.Threading; - -namespace JT808.Gateway.Client -{ - internal class JT808ClientMsgSNDistributedImpl : IJT808MsgSNDistributed - { - int _counter = 0; - - public ushort Increment() - { - return (ushort)Interlocked.Increment(ref _counter); - } - } -} diff --git a/src/JT808.Gateway/Client/JT808TcpClient.cs b/src/JT808.Gateway/Client/JT808TcpClient.cs deleted file mode 100644 index 9b6b93c..0000000 --- a/src/JT808.Gateway/Client/JT808TcpClient.cs +++ /dev/null @@ -1,112 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Codecs; -using DotNetty.Handlers.Timeout; -using DotNetty.Transport.Bootstrapping; -using DotNetty.Transport.Channels; -using DotNetty.Transport.Channels.Sockets; -using Microsoft.Extensions.Logging; -using System; -using System.Runtime.InteropServices; -using Microsoft.Extensions.DependencyInjection; -using System.Net; -using JT808.Protocol; -using JT808.Gateway.Services; -using JT808.Gateway.Codecs; -using JT808.Gateway.Handlers; -using JT808.Gateway.Metadata; - -namespace JT808.Gateway.Client -{ - public sealed class JT808TcpClient : IDisposable - { - private MultithreadEventLoopGroup group; - - private IChannel clientChannel; - - private bool disposed = false; - - public DeviceConfig DeviceConfig { get; private set; } - - public ILoggerFactory LoggerFactory { get; private set; } - - public JT808TcpClient(DeviceConfig deviceConfig, IServiceProvider serviceProvider) - { - DeviceConfig = deviceConfig; - LoggerFactory = serviceProvider.GetRequiredService(); - JT808ClientSendAtomicCounterService jT808SendAtomicCounterService = serviceProvider.GetRequiredService(); - JT808ClientReceiveAtomicCounterService jT808ReceiveAtomicCounterService = serviceProvider.GetRequiredService(); - IJT808Config jT808Config = serviceProvider.GetRequiredService(); - group = new MultithreadEventLoopGroup(1); - Bootstrap bootstrap = new Bootstrap(); - bootstrap.Group(group); - bootstrap.Channel(); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - bootstrap.Option(ChannelOption.SoReuseport, true); - } - bootstrap - .Option(ChannelOption.SoBacklog, 8192) - .Handler(new ActionChannelInitializer(channel => - { - channel.Pipeline.AddLast("jt808TcpBuffer", new DelimiterBasedFrameDecoder(int.MaxValue, - Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }), - Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag }))); - channel.Pipeline.AddLast("systemIdleState", new IdleStateHandler(60, deviceConfig.Heartbeat, 3600)); - channel.Pipeline.AddLast("jt808TcpDecode", new JT808ClientTcpDecoder()); - channel.Pipeline.AddLast("jt808TcpEncode", new JT808ClientTcpEncoder(jT808Config,jT808SendAtomicCounterService, LoggerFactory)); - channel.Pipeline.AddLast("jt808TcpClientConnection", new JT808TcpClientConnectionHandler(this)); - channel.Pipeline.AddLast("jt808TcpService", new JT808TcpClientHandler(jT808ReceiveAtomicCounterService,this)); - })); - clientChannel = bootstrap.ConnectAsync(IPAddress.Parse(DeviceConfig.TcpHost), DeviceConfig.TcpPort).Result; - } - - public async void Send(JT808ClientRequest request) - { - if (disposed) return; - if (clientChannel == null) throw new NullReferenceException("Channel is empty."); - if (request == null) throw new ArgumentNullException("JT808ClientRequest Parameter is empty."); - if (clientChannel.Active && clientChannel.Open) - { - await clientChannel.WriteAndFlushAsync(request); - } - } - - public bool IsOpen - { - get - { - if (clientChannel == null) return false; - return clientChannel.Active && clientChannel.Open; - } - } - - private void Dispose(bool disposing) - { - if (disposed) - { - return; - } - if (disposing) - { - // 清理托管资源 - group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); - } - disposed = true; - } - - ~JT808TcpClient() - { - //必须为false - //这表明,隐式清理时,只要处理非托管资源就可以了。 - Dispose(false); - } - - public void Dispose() - { - //必须为true - Dispose(true); - //通知垃圾回收机制不再调用终结器(析构器) - GC.SuppressFinalize(this); - } - } -} diff --git a/src/JT808.Gateway/Client/JT808TcpClientExtensions.cs b/src/JT808.Gateway/Client/JT808TcpClientExtensions.cs deleted file mode 100644 index 919405e..0000000 --- a/src/JT808.Gateway/Client/JT808TcpClientExtensions.cs +++ /dev/null @@ -1,103 +0,0 @@ -using JT808.Protocol; -using JT808.Protocol.MessageBody; -using System; -using System.Collections.Generic; -using System.Text; -using JT808.Protocol.Enums; -using JT808.Protocol.Extensions; -using JT808.Gateway.Metadata; - -namespace JT808.Gateway.Client -{ - public static class JT808TcpClientExtensions - { - public static void Send(this JT808TcpClient client, JT808Header header, JT808Bodies bodies, int minBufferSize = 1024) - { - JT808Package package = new JT808Package(); - package.Header = header; - package.Bodies = bodies; - package.Header.TerminalPhoneNo = client.DeviceConfig.TerminalPhoneNo; - package.Header.MsgNum = client.DeviceConfig.MsgSNDistributed.Increment(); - JT808ClientRequest request = new JT808ClientRequest(package, minBufferSize); - client.Send(request); - } - - /// - /// 终端通用应答 - /// - /// - /// - /// - public static void Send(this JT808TcpClient client, JT808_0x0001 bodies, int minBufferSize = 100) - { - JT808Header header = new JT808Header(); - header.MsgId = JT808MsgId.终端通用应答.ToUInt16Value(); - client.Send(header, bodies, minBufferSize); - } - - /// - /// 终端心跳 - /// - /// - /// - /// - public static void Send(this JT808TcpClient client, JT808_0x0002 bodies, int minBufferSize = 100) - { - JT808Header header = new JT808Header(); - header.MsgId = JT808MsgId.终端心跳.ToUInt16Value(); - client.Send(header, bodies, minBufferSize); - } - - /// - /// 终端注销 - /// - /// - /// - /// - public static void Send(this JT808TcpClient client, JT808_0x0003 bodies, int minBufferSize = 100) - { - JT808Header header = new JT808Header(); - header.MsgId = JT808MsgId.终端注销.ToUInt16Value(); - client.Send(header, bodies, minBufferSize); - } - - /// - /// 终端鉴权 - /// - /// - /// - /// - public static void Send(this JT808TcpClient client, JT808_0x0102 bodies, int minBufferSize = 100) - { - JT808Header header = new JT808Header(); - header.MsgId = JT808MsgId.终端鉴权.ToUInt16Value(); - client.Send(header, bodies, minBufferSize); - } - - /// - /// 终端注册 - /// - /// - /// - /// - public static void Send(this JT808TcpClient client, JT808_0x0100 bodies, int minBufferSize = 100) - { - JT808Header header = new JT808Header(); - header.MsgId = JT808MsgId.终端注册.ToUInt16Value(); - client.Send(header, bodies, minBufferSize); - } - - /// - /// 位置信息汇报 - /// - /// - /// - /// - public static void Send(this JT808TcpClient client, JT808_0x0200 bodies, int minBufferSize = 200) - { - JT808Header header = new JT808Header(); - header.MsgId = JT808MsgId.位置信息汇报.ToUInt16Value(); - client.Send(header, bodies, minBufferSize); - } - } -} diff --git a/src/JT808.Gateway/Client/JT808TcpClientFactory.cs b/src/JT808.Gateway/Client/JT808TcpClientFactory.cs deleted file mode 100644 index 1e78b8a..0000000 --- a/src/JT808.Gateway/Client/JT808TcpClientFactory.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; - -namespace JT808.Gateway.Client -{ - public interface IJT808TcpClientFactory : IDisposable - { - JT808TcpClient Create(DeviceConfig deviceConfig); - - List GetAll(); - } - - public class JT808TcpClientFactory: IJT808TcpClientFactory - { - private readonly ConcurrentDictionary dict; - - private readonly IServiceProvider serviceProvider; - - public JT808TcpClientFactory(IServiceProvider serviceProvider) - { - dict = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - this.serviceProvider = serviceProvider; - } - - public JT808TcpClient Create(DeviceConfig deviceConfig) - { - if(dict.TryGetValue(deviceConfig.TerminalPhoneNo,out var client)) - { - return client; - } - else - { - JT808TcpClient jT808TcpClient = new JT808TcpClient(deviceConfig, serviceProvider); - dict.TryAdd(deviceConfig.TerminalPhoneNo, jT808TcpClient); - return jT808TcpClient; - } - } - - public void Dispose() - { - foreach(var client in dict) - { - try - { - client.Value.Dispose(); - } - catch - { - } - } - } - - public List GetAll() - { - return dict.Values.ToList(); - } - } -} diff --git a/src/JT808.Gateway/Codecs/JT808ClientTcpDecoder.cs b/src/JT808.Gateway/Codecs/JT808ClientTcpDecoder.cs deleted file mode 100644 index c3aa8f1..0000000 --- a/src/JT808.Gateway/Codecs/JT808ClientTcpDecoder.cs +++ /dev/null @@ -1,20 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Codecs; -using System.Collections.Generic; -using JT808.Protocol; -using DotNetty.Transport.Channels; - -namespace JT808.Gateway.Codecs -{ - public class JT808ClientTcpDecoder : ByteToMessageDecoder - { - protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List output) - { - byte[] buffer = new byte[input.Capacity + 2]; - input.ReadBytes(buffer, 1, input.Capacity); - buffer[0] = JT808Package.BeginFlag; - buffer[input.Capacity + 1] = JT808Package.EndFlag; - output.Add(buffer); - } - } -} diff --git a/src/JT808.Gateway/Codecs/JT808ClientTcpEncoder.cs b/src/JT808.Gateway/Codecs/JT808ClientTcpEncoder.cs deleted file mode 100644 index eddc19c..0000000 --- a/src/JT808.Gateway/Codecs/JT808ClientTcpEncoder.cs +++ /dev/null @@ -1,52 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Codecs; -using JT808.Protocol; -using DotNetty.Transport.Channels; -using Microsoft.Extensions.Logging; -using JT808.Gateway.Metadata; -using JT808.Gateway.Services; - -namespace JT808.Gateway.Codecs -{ - public class JT808ClientTcpEncoder : MessageToByteEncoder - { - private readonly ILogger logger; - private readonly JT808ClientSendAtomicCounterService jT808SendAtomicCounterService; - private readonly JT808Serializer JT808Serializer; - - public JT808ClientTcpEncoder( - IJT808Config jT808Config, - JT808ClientSendAtomicCounterService jT808SendAtomicCounterService,ILoggerFactory loggerFactory) - { - logger=loggerFactory.CreateLogger(); - this.jT808SendAtomicCounterService = jT808SendAtomicCounterService; - JT808Serializer = jT808Config.GetSerializer(); - } - - protected override void Encode(IChannelHandlerContext context, JT808ClientRequest message, IByteBuffer output) - { - if (message.Package != null) - { - try - { - var sendData = JT808Serializer.Serialize(message.Package, message.MinBufferSize); - output.WriteBytes(sendData); - jT808SendAtomicCounterService.MsgSuccessIncrement(); - } - catch (JT808.Protocol.Exceptions.JT808Exception ex) - { - logger.LogError(ex, context.Channel.Id.AsShortText()); - } - catch (System.Exception ex) - { - logger.LogError(ex, context.Channel.Id.AsShortText()); - } - } - else if (message.HexData != null) - { - output.WriteBytes(message.HexData); - jT808SendAtomicCounterService.MsgSuccessIncrement(); - } - } - } -} diff --git a/src/JT808.Gateway/Codecs/JT808TcpDecoder.cs b/src/JT808.Gateway/Codecs/JT808TcpDecoder.cs deleted file mode 100644 index 10e3ff1..0000000 --- a/src/JT808.Gateway/Codecs/JT808TcpDecoder.cs +++ /dev/null @@ -1,32 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Codecs; -using System.Collections.Generic; -using JT808.Protocol; -using DotNetty.Transport.Channels; - -namespace JT808.Gateway.Codecs -{ - public class JT808TcpDecoder : ByteToMessageDecoder - { - protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List output) - { - //过滤掉不是808标准包 - //不包括头尾标识 - //(消息 ID )2+(消息体属性)2+(终端手机号)6+(消息流水号)2+(检验码 )1 - if (input.Capacity < 12) - { - byte[] buffer = new byte[input.Capacity]; - input.ReadBytes(buffer, 0, input.Capacity); - return; - } - else - { - byte[] buffer = new byte[input.Capacity + 2]; - input.ReadBytes(buffer, 1, input.Capacity); - buffer[0] = JT808Package.BeginFlag; - buffer[input.Capacity + 1] = JT808Package.EndFlag; - output.Add(buffer); - } - } - } -} diff --git a/src/JT808.Gateway/Codecs/JT808TcpEncoder.cs b/src/JT808.Gateway/Codecs/JT808TcpEncoder.cs deleted file mode 100644 index ca92147..0000000 --- a/src/JT808.Gateway/Codecs/JT808TcpEncoder.cs +++ /dev/null @@ -1,52 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Codecs; -using JT808.Protocol; -using DotNetty.Transport.Channels; -using Microsoft.Extensions.Logging; -using JT808.Protocol.Interfaces; -using JT808.Gateway.Interfaces; - -namespace JT808.Gateway.Codecs -{ - /// - /// tcp统一下发出口 - /// - public class JT808TcpEncoder : MessageToByteEncoder - { - private readonly ILogger logger; - - private readonly JT808Serializer JT808Serializer; - - public JT808TcpEncoder( - IJT808Config jT808Config, - ILoggerFactory loggerFactory) - { - logger = loggerFactory.CreateLogger(); - this.JT808Serializer = jT808Config.GetSerializer(); - } - - protected override void Encode(IChannelHandlerContext context, IJT808Reply message, IByteBuffer output) - { - if (message.Package != null) - { - try - { - var sendData = JT808Serializer.Serialize(message.Package, message.MinBufferSize); - output.WriteBytes(Unpooled.WrappedBuffer(sendData)); - } - catch (JT808.Protocol.Exceptions.JT808Exception ex) - { - logger.LogError(ex, context.Channel.Id.AsShortText()); - } - catch (System.Exception ex) - { - logger.LogError(ex, context.Channel.Id.AsShortText()); - } - } - else if (message.HexData != null) - { - output.WriteBytes(Unpooled.WrappedBuffer(message.HexData)); - } - } - } -} diff --git a/src/JT808.Gateway/Codecs/JT808UdpDecoder.cs b/src/JT808.Gateway/Codecs/JT808UdpDecoder.cs deleted file mode 100644 index d3018f8..0000000 --- a/src/JT808.Gateway/Codecs/JT808UdpDecoder.cs +++ /dev/null @@ -1,33 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Codecs; -using DotNetty.Transport.Channels; -using System.Collections.Generic; -using DotNetty.Transport.Channels.Sockets; -using JT808.Gateway.Metadata; - -namespace JT808.Gateway.Codecs -{ - public class JT808UdpDecoder : MessageToMessageDecoder - { - protected override void Decode(IChannelHandlerContext context, DatagramPacket message, List output) - { - if (!message.Content.IsReadable()) return; - IByteBuffer byteBuffer = message.Content; - //过滤掉非808标准包 - //不包括头尾标识 - //(消息 ID )2+(消息体属性)2+(终端手机号)6+(消息流水号)2+(检验码 )1 - if (byteBuffer.ReadableBytes < 12) - { - byte[] buffer = new byte[byteBuffer.ReadableBytes]; - byteBuffer.ReadBytes(buffer, 0, byteBuffer.ReadableBytes); - return; - } - else - { - byte[] buffer = new byte[byteBuffer.ReadableBytes]; - byteBuffer.ReadBytes(buffer); - output.Add(new JT808UdpPackage(buffer, message.Sender)); - } - } - } -} diff --git a/src/JT808.Gateway/Configurations/JT808Configuration.cs b/src/JT808.Gateway/Configurations/JT808Configuration.cs deleted file mode 100644 index c39ab4e..0000000 --- a/src/JT808.Gateway/Configurations/JT808Configuration.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Configurations -{ - public class JT808Configuration - { - public int TcpPort { get; set; } = 808; - - public int UdpPort { get; set; } = 808; - - public int QuietPeriodSeconds { get; set; } = 1; - - public TimeSpan QuietPeriodTimeSpan => TimeSpan.FromSeconds(QuietPeriodSeconds); - - public int ShutdownTimeoutSeconds { get; set; } = 3; - - public TimeSpan ShutdownTimeoutTimeSpan => TimeSpan.FromSeconds(ShutdownTimeoutSeconds); - - public int SoBacklog { get; set; } = 8192; - - public int EventLoopCount { get; set; } = Environment.ProcessorCount; - - public int ReaderIdleTimeSeconds { get; set; } = 3600; - - public int WriterIdleTimeSeconds { get; set; } = 3600; - - public int AllIdleTimeSeconds { get; set; } = 3600; - - /// - /// 转发远程地址 (可选项)知道转发的地址有利于提升性能 - /// 按照808的消息,有些请求必须要应答,但是转发可以不需要有应答可以节省部分资源包括: - // 1.消息的序列化 - // 2.消息的下发 - // 都有一定的性能损耗,那么不需要判断写超时 IdleState.WriterIdle - // 就跟神兽貔貅一样。。。 - /// - public List ForwardingRemoteIPAddress { get; set; } - } -} diff --git a/src/JT808.Gateway/Dtos/JT808ResultDto.cs b/src/JT808.Gateway/Dtos/JT808ResultDto.cs deleted file mode 100644 index 0b72015..0000000 --- a/src/JT808.Gateway/Dtos/JT808ResultDto.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Dtos -{ - public class JT808ResultDto - { - public JT808ResultDto() - { - Code = JT808ResultCode.Ok; - } - - public string Message { get; set; } - - public int Code { get; set; } - - public T Data { get; set; } - } - - public class JT808ResultCode - { - public const int Ok = 200; - public const int Empty = 201; - public const int NotFound = 404; - public const int Fail = 400; - public const int Error = 500; - } -} diff --git a/src/JT808.Gateway/Dtos/JT808TcpSessionInfoDto.cs b/src/JT808.Gateway/Dtos/JT808TcpSessionInfoDto.cs deleted file mode 100644 index 423381e..0000000 --- a/src/JT808.Gateway/Dtos/JT808TcpSessionInfoDto.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace JT808.Gateway.Dtos -{ - public class JT808TcpSessionInfoDto - { - /// - /// 最后上线时间 - /// - public DateTime LastActiveTime { get; set; } - /// - /// 上线时间 - /// - public DateTime StartTime { get; set; } - /// - /// 终端手机号 - /// - public string TerminalPhoneNo { get; set; } - /// - /// 远程ip地址 - /// - public string RemoteAddressIP { get; set; } - } -} diff --git a/src/JT808.Gateway/Dtos/JT808UdpSessionInfoDto.cs b/src/JT808.Gateway/Dtos/JT808UdpSessionInfoDto.cs deleted file mode 100644 index 9ba9c16..0000000 --- a/src/JT808.Gateway/Dtos/JT808UdpSessionInfoDto.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace JT808.Gateway.Dtos -{ - public class JT808UdpSessionInfoDto - { - /// - /// 最后上线时间 - /// - public DateTime LastActiveTime { get; set; } - /// - /// 上线时间 - /// - public DateTime StartTime { get; set; } - /// - /// 终端手机号 - /// - public string TerminalPhoneNo { get; set; } - /// - /// 远程ip地址 - /// - public string RemoteAddressIP { get; set; } - } -} diff --git a/src/JT808.Gateway/Enums/JT808TransportProtocolType.cs b/src/JT808.Gateway/Enums/JT808TransportProtocolType.cs deleted file mode 100644 index ce9bb9f..0000000 --- a/src/JT808.Gateway/Enums/JT808TransportProtocolType.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Enums -{ - /// - /// 传输协议类型 - /// - public enum JT808TransportProtocolType - { - tcp=1, - udp = 2 - } -} diff --git a/src/JT808.Gateway/Handlers/JT808TcpClientConnectionHandler.cs b/src/JT808.Gateway/Handlers/JT808TcpClientConnectionHandler.cs deleted file mode 100644 index 26ea698..0000000 --- a/src/JT808.Gateway/Handlers/JT808TcpClientConnectionHandler.cs +++ /dev/null @@ -1,96 +0,0 @@ -using DotNetty.Handlers.Timeout; -using DotNetty.Transport.Channels; -using JT808.Gateway.Client; -using JT808.Protocol.MessageBody; -using Microsoft.Extensions.Logging; -using System; -using System.Threading.Tasks; - -namespace JT808.Gateway.Handlers -{ - /// - /// JT808客户端连接通道处理程序 - /// - public class JT808TcpClientConnectionHandler : ChannelHandlerAdapter - { - private readonly ILogger logger; - private readonly JT808TcpClient jT808TcpClient; - - public JT808TcpClientConnectionHandler( - JT808TcpClient jT808TcpClient) - { - logger = jT808TcpClient.LoggerFactory.CreateLogger(); - this.jT808TcpClient = jT808TcpClient; - } - - /// - /// 通道激活 - /// - /// - public override void ChannelActive(IChannelHandlerContext context) - { - string channelId = context.Channel.Id.AsShortText(); - if (logger.IsEnabled(LogLevel.Debug)) - logger.LogDebug($"<<<{ channelId } Successful client connection to server."); - base.ChannelActive(context); - } - - /// - /// 设备主动断开 - /// - /// - public override void ChannelInactive(IChannelHandlerContext context) - { - string channelId = context.Channel.Id.AsShortText(); - if (logger.IsEnabled(LogLevel.Debug)) - logger.LogDebug($">>>{ channelId } The client disconnects from the server."); - - base.ChannelInactive(context); - } - - /// - /// 服务器主动断开 - /// - /// - /// - public override Task CloseAsync(IChannelHandlerContext context) - { - string channelId = context.Channel.Id.AsShortText(); - if (logger.IsEnabled(LogLevel.Debug)) - logger.LogDebug($"<<<{ channelId } The server disconnects from the client."); - - return base.CloseAsync(context); - } - - public override void ChannelReadComplete(IChannelHandlerContext context)=> context.Flush(); - - /// - /// 超时策略 - /// - /// - /// - public override void UserEventTriggered(IChannelHandlerContext context, object evt) - { - IdleStateEvent idleStateEvent = evt as IdleStateEvent; - if (idleStateEvent != null) - { - if(idleStateEvent.State== IdleState.WriterIdle) - { - string channelId = context.Channel.Id.AsShortText(); - logger.LogInformation($"{idleStateEvent.State.ToString()}>>>{channelId}"); - jT808TcpClient.Send(new JT808_0x0002()); - } - } - base.UserEventTriggered(context, evt); - } - - public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) - { - string channelId = context.Channel.Id.AsShortText(); - logger.LogError(exception,$"{channelId} {exception.Message}" ); - - context.CloseAsync(); - } - } -} - diff --git a/src/JT808.Gateway/Handlers/JT808TcpClientHandler.cs b/src/JT808.Gateway/Handlers/JT808TcpClientHandler.cs deleted file mode 100644 index f619a2b..0000000 --- a/src/JT808.Gateway/Handlers/JT808TcpClientHandler.cs +++ /dev/null @@ -1,31 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Transport.Channels; -using System; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; -using JT808.Gateway.Services; -using JT808.Gateway.Client; - -namespace JT808.Gateway.Handlers -{ - /// - /// JT808客户端处理程序 - /// - internal class JT808TcpClientHandler : SimpleChannelInboundHandler - { - private readonly ILogger logger; - private readonly JT808ClientReceiveAtomicCounterService jT808ReceiveAtomicCounterService; - public JT808TcpClientHandler(JT808ClientReceiveAtomicCounterService jT808ReceiveAtomicCounterService,JT808TcpClient jT808TcpClient) - { - logger = jT808TcpClient.LoggerFactory.CreateLogger(); - this.jT808ReceiveAtomicCounterService= jT808ReceiveAtomicCounterService; - } - - protected override void ChannelRead0(IChannelHandlerContext ctx, byte[] msg) - { - if(logger.IsEnabled(LogLevel.Trace)) - logger.LogTrace("accept msg<<<" + ByteBufferUtil.HexDump(msg)); - jT808ReceiveAtomicCounterService.MsgSuccessIncrement(); - } - } -} diff --git a/src/JT808.Gateway/Handlers/JT808TcpConnectionHandler.cs b/src/JT808.Gateway/Handlers/JT808TcpConnectionHandler.cs deleted file mode 100644 index 36f7008..0000000 --- a/src/JT808.Gateway/Handlers/JT808TcpConnectionHandler.cs +++ /dev/null @@ -1,104 +0,0 @@ -using DotNetty.Handlers.Timeout; -using DotNetty.Transport.Channels; -using JT808.Gateway.Session; -using Microsoft.Extensions.Logging; -using System; -using System.Threading.Tasks; - -namespace JT808.Gateway.Handlers -{ - /// - /// JT808服务通道处理程序 - /// - internal class JT808TcpConnectionHandler : ChannelHandlerAdapter - { - private readonly ILogger logger; - - private readonly JT808SessionManager jT808SessionManager; - - public JT808TcpConnectionHandler( - JT808SessionManager jT808SessionManager, - ILoggerFactory loggerFactory) - { - this.jT808SessionManager = jT808SessionManager; - logger = loggerFactory.CreateLogger(); - } - - /// - /// 通道激活 - /// - /// - public override void ChannelActive(IChannelHandlerContext context) - { - string channelId = context.Channel.Id.AsShortText(); - if (logger.IsEnabled(LogLevel.Debug)) - logger.LogDebug($"<<<{ channelId } Successful client connection to server."); - base.ChannelActive(context); - } - - /// - /// 设备主动断开 - /// - /// - public override void ChannelInactive(IChannelHandlerContext context) - { - string channelId = context.Channel.Id.AsShortText(); - if (logger.IsEnabled(LogLevel.Debug)) - logger.LogDebug($">>>{ channelId } The client disconnects from the server."); - jT808SessionManager.RemoveSessionByChannel(context.Channel); - base.ChannelInactive(context); - } - - /// - /// 服务器主动断开 - /// - /// - /// - public override Task CloseAsync(IChannelHandlerContext context) - { - string channelId = context.Channel.Id.AsShortText(); - if (logger.IsEnabled(LogLevel.Debug)) - logger.LogDebug($"<<<{ channelId } The server disconnects from the client."); - jT808SessionManager.RemoveSessionByChannel(context.Channel); - return base.CloseAsync(context); - } - - public override void ChannelReadComplete(IChannelHandlerContext context)=> context.Flush(); - - /// - /// 超时策略 - /// - /// - /// - public override void UserEventTriggered(IChannelHandlerContext context, object evt) - { - IdleStateEvent idleStateEvent = evt as IdleStateEvent; - if (idleStateEvent != null) - { - if(idleStateEvent.State== IdleState.ReaderIdle) - { - string channelId = context.Channel.Id.AsShortText(); - logger.LogInformation($"{idleStateEvent.State.ToString()}>>>{channelId}"); - // 由于808是设备发心跳,如果很久没有上报数据,那么就由服务器主动关闭连接。 - jT808SessionManager.RemoveSessionByChannel(context.Channel); - context.CloseAsync(); - } - // 按照808的消息,有些请求必须要应答,但是转发可以不需要有应答可以节省部分资源包括: - // 1.消息的序列化 - // 2.消息的下发 - // 都有一定的性能损耗,那么不需要判断写超时 IdleState.WriterIdle - // 就跟神兽貔貅一样。。。 - } - base.UserEventTriggered(context, evt); - } - - public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) - { - string channelId = context.Channel.Id.AsShortText(); - logger.LogError(exception,$"{channelId} {exception.Message}" ); - jT808SessionManager.RemoveSessionByChannel(context.Channel); - context.CloseAsync(); - } - } -} - diff --git a/src/JT808.Gateway/Handlers/JT808TcpServerHandler.cs b/src/JT808.Gateway/Handlers/JT808TcpServerHandler.cs deleted file mode 100644 index 35dda80..0000000 --- a/src/JT808.Gateway/Handlers/JT808TcpServerHandler.cs +++ /dev/null @@ -1,77 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Transport.Channels; -using JT808.Protocol; -using System; -using Microsoft.Extensions.Logging; -using JT808.Protocol.Exceptions; -using JT808.Gateway.Session; -using JT808.Gateway.Services; -using JT808.Gateway.PubSub; -using JT808.Gateway.Enums; - -namespace JT808.Gateway.Handlers -{ - /// - /// JT808服务端处理程序 - /// - internal class JT808TcpServerHandler : SimpleChannelInboundHandler - { - private readonly JT808SessionManager jT808SessionManager; - - private readonly JT808AtomicCounterService jT808AtomicCounterService; - - private readonly ILogger logger; - - private readonly JT808Serializer JT808Serializer; - - private readonly IJT808MsgProducer JT808MsgProducer; - - public JT808TcpServerHandler( - IJT808MsgProducer jT808MsgProducer, - IJT808Config jT808Config, - ILoggerFactory loggerFactory, - JT808AtomicCounterServiceFactory jT808AtomicCounterServiceFactory, - JT808SessionManager jT808SessionManager) - { - this.jT808SessionManager = jT808SessionManager; - this.JT808MsgProducer = jT808MsgProducer; - this.jT808AtomicCounterService = jT808AtomicCounterServiceFactory.Create(JT808TransportProtocolType.tcp); - this.JT808Serializer = jT808Config.GetSerializer(); - logger = loggerFactory.CreateLogger(); - } - - protected override void ChannelRead0(IChannelHandlerContext ctx, byte[] msg) - { - try - { - //解析到头部,然后根据具体的消息Id通过队列去进行消费 - //要是一定要解析到数据体可以在JT808MsgIdHandlerBase类中根据具体的消息, - //解析具体的消息体,具体调用JT808Serializer.Deserialize - JT808HeaderPackage jT808HeaderPackage = JT808Serializer.Deserialize(msg); - if (logger.IsEnabled(LogLevel.Trace)) - { - logger.LogTrace($"accept package success count=>{jT808AtomicCounterService.MsgSuccessCount.ToString()},accept msg=>{ByteBufferUtil.HexDump(msg)}"); - } - jT808AtomicCounterService.MsgSuccessIncrement(); - jT808SessionManager.TryAdd(jT808HeaderPackage.Header.TerminalPhoneNo,ctx.Channel); - JT808MsgProducer.ProduceAsync(jT808HeaderPackage.Header.TerminalPhoneNo, msg); - } - catch (JT808Exception ex) - { - jT808AtomicCounterService.MsgFailIncrement(); - if (logger.IsEnabled(LogLevel.Error)) - { - logger.LogError(ex,$"accept package fail count=>{jT808AtomicCounterService.MsgFailCount.ToString()},accept msg=>{ByteBufferUtil.HexDump(msg)}"); - } - } - catch (Exception ex) - { - jT808AtomicCounterService.MsgFailIncrement(); - if (logger.IsEnabled(LogLevel.Error)) - { - logger.LogError(ex, $"accept package fail count=>{jT808AtomicCounterService.MsgFailCount.ToString()},accept msg=>{ByteBufferUtil.HexDump(msg)}"); - } - } - } - } -} diff --git a/src/JT808.Gateway/Handlers/JT808UdpServerHandler.cs b/src/JT808.Gateway/Handlers/JT808UdpServerHandler.cs deleted file mode 100644 index 3ae3972..0000000 --- a/src/JT808.Gateway/Handlers/JT808UdpServerHandler.cs +++ /dev/null @@ -1,79 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Transport.Channels; -using JT808.Protocol; -using System; -using Microsoft.Extensions.Logging; -using JT808.Gateway.Services; -using JT808.Gateway.Session; -using JT808.Gateway.PubSub; -using JT808.Gateway.Metadata; -using JT808.Gateway.Enums; - -namespace JT808.Gateway.Handlers -{ - /// - /// JT808 Udp服务端处理程序 - /// - internal class JT808UdpServerHandler : SimpleChannelInboundHandler - { - private readonly JT808AtomicCounterService jT808AtomicCounterService; - - private readonly ILogger logger; - - private readonly JT808SessionManager jT808UdpSessionManager; - - private readonly JT808Serializer JT808Serializer; - - private readonly IJT808MsgProducer JT808MsgProducer; - - public JT808UdpServerHandler( - IJT808MsgProducer jT808MsgProducer, - IJT808Config jT808Config, - ILoggerFactory loggerFactory, - JT808AtomicCounterServiceFactory jT808AtomicCounterServiceFactory, - JT808SessionManager jT808UdpSessionManager) - { - this.JT808MsgProducer = jT808MsgProducer; - this.jT808AtomicCounterService = jT808AtomicCounterServiceFactory.Create(JT808TransportProtocolType.udp); - this.jT808UdpSessionManager = jT808UdpSessionManager; - logger = loggerFactory.CreateLogger(); - JT808Serializer = jT808Config.GetSerializer(); - } - - protected override void ChannelRead0(IChannelHandlerContext ctx, JT808UdpPackage msg) - { - try - { - //解析到头部,然后根据具体的消息Id通过队列去进行消费 - //要是一定要解析到数据体可以在JT808MsgIdHandlerBase类中根据具体的消息, - //解析具体的消息体,具体调用JT808Serializer.Deserialize - JT808HeaderPackage jT808HeaderPackage = JT808Serializer.Deserialize(msg.Buffer); - if (logger.IsEnabled(LogLevel.Trace)) - { - logger.LogTrace($"accept package success count=>{jT808AtomicCounterService.MsgFailCount.ToString()},accept msg=>{ByteBufferUtil.HexDump(msg.Buffer)}"); - } - jT808AtomicCounterService.MsgSuccessIncrement(); - jT808UdpSessionManager.TryAdd(ctx.Channel, msg.Sender, jT808HeaderPackage.Header.TerminalPhoneNo); - JT808MsgProducer.ProduceAsync(jT808HeaderPackage.Header.TerminalPhoneNo, msg.Buffer); - } - catch (JT808.Protocol.Exceptions.JT808Exception ex) - { - jT808AtomicCounterService.MsgFailIncrement(); - if (logger.IsEnabled(LogLevel.Error)) - { - logger.LogError(ex, $"accept package fail count=>{jT808AtomicCounterService.MsgFailCount.ToString()},accept msg=>{ByteBufferUtil.HexDump(msg.Buffer)}"); - } - } - catch (Exception ex) - { - jT808AtomicCounterService.MsgFailIncrement(); - if (logger.IsEnabled(LogLevel.Error)) - { - logger.LogError(ex, $"accept package fail count=>{jT808AtomicCounterService.MsgFailCount.ToString()},accept msg=>{ByteBufferUtil.HexDump(msg.Buffer)}"); - } - } - } - - public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); - } -} diff --git a/src/JT808.Gateway/IJT808ClientBuilder.cs b/src/JT808.Gateway/IJT808ClientBuilder.cs deleted file mode 100644 index e8681b9..0000000 --- a/src/JT808.Gateway/IJT808ClientBuilder.cs +++ /dev/null @@ -1,14 +0,0 @@ -using JT808.Protocol; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway -{ - public interface IJT808ClientBuilder - { - IJT808Builder JT808Builder { get; } - IJT808Builder Builder(); - } -} diff --git a/src/JT808.Gateway/IJT808GatewayBuilder.cs b/src/JT808.Gateway/IJT808GatewayBuilder.cs deleted file mode 100644 index 6160c23..0000000 --- a/src/JT808.Gateway/IJT808GatewayBuilder.cs +++ /dev/null @@ -1,14 +0,0 @@ -using JT808.Protocol; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway -{ - public interface IJT808GatewayBuilder - { - IJT808Builder JT808Builder { get; } - IJT808Builder Builder(); - } -} diff --git a/src/JT808.Gateway/Impls/JT808DatagramPacketImpl.cs b/src/JT808.Gateway/Impls/JT808DatagramPacketImpl.cs deleted file mode 100644 index 12bf62b..0000000 --- a/src/JT808.Gateway/Impls/JT808DatagramPacketImpl.cs +++ /dev/null @@ -1,18 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Transport.Channels.Sockets; -using JT808.Gateway.Interfaces; -using System; -using System.Collections.Generic; -using System.Net; -using System.Text; - -namespace JT808.Gateway.Impls -{ - class JT808DatagramPacketImpl : IJT808DatagramPacket - { - public DatagramPacket Create(byte[] message, EndPoint recipient) - { - return new DatagramPacket(Unpooled.WrappedBuffer(message), recipient); - } - } -} diff --git a/src/JT808.Gateway/Impls/JT808GatewayBuilderDefault.cs b/src/JT808.Gateway/Impls/JT808GatewayBuilderDefault.cs deleted file mode 100644 index d5e79b5..0000000 --- a/src/JT808.Gateway/Impls/JT808GatewayBuilderDefault.cs +++ /dev/null @@ -1,25 +0,0 @@ -using JT808.Gateway; -using JT808.Protocol; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Impls -{ - internal class JT808GatewayBuilderDefault : IJT808GatewayBuilder - { - public IJT808Builder JT808Builder { get; } - - public JT808GatewayBuilderDefault(IJT808Builder builder) - { - JT808Builder = builder; - } - - public IJT808Builder Builder() - { - return JT808Builder; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway/Impls/JT808MsgProducerDefaultImpl.cs b/src/JT808.Gateway/Impls/JT808MsgProducerDefaultImpl.cs deleted file mode 100644 index 6c68938..0000000 --- a/src/JT808.Gateway/Impls/JT808MsgProducerDefaultImpl.cs +++ /dev/null @@ -1,30 +0,0 @@ -using JT808.Gateway; -using JT808.Gateway.PubSub; -using JT808.Gateway.Services; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace JT808.Gateway.Impls -{ - internal class JT808MsgProducerDefaultImpl : IJT808MsgProducer - { - private readonly JT808MsgService JT808MsgService; - public string TopicName => JT808GatewayConstants.MsgTopic; - public JT808MsgProducerDefaultImpl(JT808MsgService jT808MsgService) - { - JT808MsgService = jT808MsgService; - } - public void Dispose() - { - - } - - public Task ProduceAsync(string terminalNo, byte[] data) - { - JT808MsgService.MsgQueue.Add((terminalNo, data)); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/Impls/JT808MsgReplyConsumerDefaultImpl.cs b/src/JT808.Gateway/Impls/JT808MsgReplyConsumerDefaultImpl.cs deleted file mode 100644 index ed86362..0000000 --- a/src/JT808.Gateway/Impls/JT808MsgReplyConsumerDefaultImpl.cs +++ /dev/null @@ -1,193 +0,0 @@ -using JT808.Gateway; -using JT808.Gateway.PubSub; -using JT808.Gateway.Services; -using JT808.Protocol; -using JT808.Protocol.Enums; -using JT808.Protocol.Extensions; -using JT808.Protocol.MessageBody; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Impls -{ - internal class JT808MsgReplyConsumerDefaultImpl : IJT808MsgReplyConsumer - { - private readonly JT808MsgService JT808MsgService; - private readonly JT808Serializer JT808Serializer; - private Dictionary> HandlerDict; - public JT808MsgReplyConsumerDefaultImpl( - IJT808Config jT808Config, - JT808MsgService jT808MsgService) - { - JT808MsgService = jT808MsgService; - this.JT808Serializer = jT808Config.GetSerializer(); - HandlerDict = new Dictionary> { - {JT808MsgId.终端通用应答.ToUInt16Value(), Msg0x0001}, - {JT808MsgId.终端鉴权.ToUInt16Value(), Msg0x0102}, - {JT808MsgId.终端心跳.ToUInt16Value(), Msg0x0002}, - {JT808MsgId.终端注销.ToUInt16Value(), Msg0x0003}, - {JT808MsgId.终端注册.ToUInt16Value(), Msg0x0100}, - {JT808MsgId.位置信息汇报.ToUInt16Value(),Msg0x0200 }, - {JT808MsgId.定位数据批量上传.ToUInt16Value(),Msg0x0704 }, - {JT808MsgId.数据上行透传.ToUInt16Value(),Msg0x0900 } - }; - } - public CancellationTokenSource Cts =>new CancellationTokenSource(); - - public string TopicName => JT808GatewayConstants.MsgReplyTopic; - - public void Dispose() - { - Cts.Dispose(); - } - - public void OnMessage(Action<(string TerminalNo, byte[] Data)> callback) - { - Task.Run(() => - { - foreach(var item in JT808MsgService.MsgQueue.GetConsumingEnumerable()) - { - try - { - var package = JT808Serializer.HeaderDeserialize(item.Data); - if (HandlerDict.TryGetValue(package.Header.MsgId, out var func)) - { - var buffer = func(package); - if (buffer != null) - { - callback((item.TerminalNo, buffer)); - } - } - } - catch (Exception ex) - { - - } - } - }, Cts.Token); - } - - public void Subscribe() - { - - } - - public void Unsubscribe() - { - Cts.Cancel(); - } - - /// - /// 终端通用应答 - /// 平台无需回复 - /// 实现自己的业务 - /// - /// - /// - public byte[] Msg0x0001(JT808HeaderPackage request) - { - return null; - } - /// - /// 终端心跳 - /// - /// - /// - public byte[] Msg0x0002(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 终端注销 - /// - /// - /// - public byte[] Msg0x0003(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 终端注册 - /// - /// - /// - public byte[] Msg0x0100(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.终端注册应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8100() - { - Code = "J" + request.Header.TerminalPhoneNo, - JT808TerminalRegisterResult = JT808TerminalRegisterResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 终端鉴权 - /// - /// - /// - public byte[] Msg0x0102(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 位置信息汇报 - /// - /// - /// - public byte[] Msg0x0200(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 定位数据批量上传 - /// - /// - /// - public byte[] Msg0x0704(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - /// - /// 数据上行透传 - /// - /// - /// - public byte[] Msg0x0900(JT808HeaderPackage request) - { - return JT808Serializer.Serialize(JT808MsgId.平台通用应答.Create(request.Header.TerminalPhoneNo, new JT808_0x8001() - { - MsgId = request.Header.MsgId, - JT808PlatformResult = JT808PlatformResult.成功, - MsgNum = request.Header.MsgNum - })); - } - } -} diff --git a/src/JT808.Gateway/Impls/JT808SessionProducerDefaultImpl.cs b/src/JT808.Gateway/Impls/JT808SessionProducerDefaultImpl.cs deleted file mode 100644 index 4651d85..0000000 --- a/src/JT808.Gateway/Impls/JT808SessionProducerDefaultImpl.cs +++ /dev/null @@ -1,32 +0,0 @@ -using JT808.Gateway; -using JT808.Gateway.PubSub; -using Microsoft.Extensions.Logging; -using System.Threading.Tasks; - -namespace JT808.Gateway.Impls -{ - internal class JT808SessionProducerDefaultImpl : IJT808SessionProducer - { - private readonly ILogger logger; - public JT808SessionProducerDefaultImpl(ILoggerFactory loggerFactory) - { - logger = loggerFactory.CreateLogger(); - } - - public string TopicName => JT808GatewayConstants.SessionTopic; - - public void Dispose() - { - - } - - public Task ProduceAsync(string terminalNo, string notice) - { - if (logger.IsEnabled(LogLevel.Debug)) - { - logger.LogDebug($"{terminalNo}-{notice}"); - } - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/Interfaces/IJT808DatagramPacket.cs b/src/JT808.Gateway/Interfaces/IJT808DatagramPacket.cs deleted file mode 100644 index dcfd9d0..0000000 --- a/src/JT808.Gateway/Interfaces/IJT808DatagramPacket.cs +++ /dev/null @@ -1,13 +0,0 @@ -using DotNetty.Transport.Channels.Sockets; -using System.Net; - -namespace JT808.Gateway.Interfaces -{ - /// - /// 基于udp的创建发送包 - /// - public interface IJT808DatagramPacket - { - DatagramPacket Create(byte[] message, EndPoint recipient); - } -} diff --git a/src/JT808.Gateway/Interfaces/IJT808Reply.cs b/src/JT808.Gateway/Interfaces/IJT808Reply.cs deleted file mode 100644 index d515cd7..0000000 --- a/src/JT808.Gateway/Interfaces/IJT808Reply.cs +++ /dev/null @@ -1,17 +0,0 @@ -using JT808.Protocol; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Interfaces -{ - public interface IJT808Reply - { - JT808Package Package { get; set; } - byte[] HexData { get; set; } - /// - /// 根据实际情况适当调整包的大小 - /// - int MinBufferSize { get; set; } - } -} diff --git a/src/JT808.Gateway/Interfaces/IJT808Session.cs b/src/JT808.Gateway/Interfaces/IJT808Session.cs deleted file mode 100644 index 80cae87..0000000 --- a/src/JT808.Gateway/Interfaces/IJT808Session.cs +++ /dev/null @@ -1,20 +0,0 @@ -using DotNetty.Transport.Channels; -using JT808.Gateway.Enums; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Interfaces -{ - public interface IJT808Session - { - /// - /// 终端手机号 - /// - string TerminalPhoneNo { get; set; } - IChannel Channel { get; set; } - DateTime LastActiveTime { get; set; } - DateTime StartTime { get; set; } - JT808TransportProtocolType TransportProtocolType { get; set; } - } -} diff --git a/src/JT808.Gateway/Interfaces/IJT808SessionService.cs b/src/JT808.Gateway/Interfaces/IJT808SessionService.cs deleted file mode 100644 index c8e58e5..0000000 --- a/src/JT808.Gateway/Interfaces/IJT808SessionService.cs +++ /dev/null @@ -1,30 +0,0 @@ -using JT808.Gateway.Dtos; -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Interfaces -{ - /// - /// JT808会话服务 - /// - public interface IJT808SessionService - { - /// - /// 获取udp会话集合 - /// - /// - JT808ResultDto> GetUdpAll(); - /// - /// 获取tcp会话集合 - /// - /// - JT808ResultDto> GetTcpAll(); - /// - /// 通过设备终端号移除对应会话 - /// - /// - /// - JT808ResultDto RemoveByTerminalPhoneNo(string terminalPhoneNo); - } -} diff --git a/src/JT808.Gateway/Interfaces/IJT808UnificationSendService.cs b/src/JT808.Gateway/Interfaces/IJT808UnificationSendService.cs deleted file mode 100644 index 227e225..0000000 --- a/src/JT808.Gateway/Interfaces/IJT808UnificationSendService.cs +++ /dev/null @@ -1,12 +0,0 @@ -using JT808.Gateway.Dtos; - -namespace JT808.Gateway.Interfaces -{ - /// - /// JT808统一下发命令服务 - /// - public interface IJT808UnificationSendService - { - JT808ResultDto Send(string terminalPhoneNo, byte[] data); - } -} diff --git a/src/JT808.Gateway/JT808.Gateway.csproj b/src/JT808.Gateway/JT808.Gateway.csproj deleted file mode 100644 index ff7b4aa..0000000 --- a/src/JT808.Gateway/JT808.Gateway.csproj +++ /dev/null @@ -1,45 +0,0 @@ - - - - netstandard2.0 - 8.0 - Copyright 2018. - SmallChi(Koike) - https://github.com/SmallChi/JT808DotNetty - https://github.com/SmallChi/JT808DotNetty - https://github.com/SmallChi/JT808DotNetty/blob/master/LICENSE - https://github.com/SmallChi/JT808DotNetty/blob/master/LICENSE - false - 1.0.0-preview1 - false - LICENSE - true - JT808.Gateway - JT808.Gateway - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - diff --git a/src/JT808.Gateway/JT808GatewayConstants.cs b/src/JT808.Gateway/JT808GatewayConstants.cs deleted file mode 100644 index b09709a..0000000 --- a/src/JT808.Gateway/JT808GatewayConstants.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace JT808.Gateway -{ - public static class JT808GatewayConstants - { - public const string SessionOnline= "JT808SessionOnline"; - - public const string SessionOffline = "JT808SessionOffline"; - public const string SessionTopic = "jt808session"; - public const string MsgTopic = "jt808msgdefault"; - public const string MsgReplyTopic = "jt808msgreplydefault"; - - public static class JT808WebApiRouteTable - { - public const string RouteTablePrefix = "/jt808api"; - - public const string SessionPrefix = "Session"; - - public const string TcpPrefix = "Tcp"; - - public const string UdpPrefix = "Udp"; - - /// - /// 基于Tcp的包计数器 - /// - public static string GetTcpAtomicCounter = $"{RouteTablePrefix}/{TcpPrefix}/GetAtomicCounter"; - /// - /// 基于Tcp的会话服务集合 - /// - public static string SessionTcpGetAll = $"{RouteTablePrefix}/{TcpPrefix}/{SessionPrefix}/GetAll"; - /// - /// 会话服务-通过设备终端号移除对应会话 - /// - public static string SessionRemoveByTerminalPhoneNo = $"{RouteTablePrefix}/{SessionPrefix}/RemoveByTerminalPhoneNo"; - /// - /// 统一下发信息 - /// - public static string UnificationSend = $"{RouteTablePrefix}/UnificationSend"; - /// - /// 获取Udp包计数器 - /// - public static string GetUdpAtomicCounter = $"{RouteTablePrefix}/{UdpPrefix}/GetAtomicCounter"; - /// - /// 基于Udp的会话服务集合 - /// - public static string SessionUdpGetAll = $"{RouteTablePrefix}/{UdpPrefix}/{SessionPrefix}/GetAll"; - } - } -} diff --git a/src/JT808.Gateway/JT808GatewayExtensions.cs b/src/JT808.Gateway/JT808GatewayExtensions.cs deleted file mode 100644 index 17ed1b0..0000000 --- a/src/JT808.Gateway/JT808GatewayExtensions.cs +++ /dev/null @@ -1,54 +0,0 @@ -using JT808.Gateway; -using JT808.Gateway.Configurations; -using JT808.Gateway.Impls; -using JT808.Gateway.Interfaces; -using JT808.Gateway.PubSub; -using JT808.Gateway.Services; -using JT808.Gateway.Session; -using JT808.Protocol; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Options; -using System; -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("JT808.Gateway.Test")] - -namespace JT808.Gateway -{ - public static class JT808GatewayExtensions - { - public static IJT808GatewayBuilder AddJT808Gateway(this IJT808Builder jt808Builder, IConfiguration configuration) - { - IJT808GatewayBuilder nettyBuilder = new JT808GatewayBuilderDefault(jt808Builder); - nettyBuilder.JT808Builder.Services.Configure(configuration.GetSection("JT808Configuration")); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.AddHostedService(); - return nettyBuilder; - } - - public static IJT808GatewayBuilder AddJT808Gateway(this IJT808Builder jt808Builder, Action jt808Options) - { - IJT808GatewayBuilder nettyBuilder = new JT808GatewayBuilderDefault(jt808Builder); - nettyBuilder.JT808Builder.Services.Configure(jt808Options); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.TryAddSingleton(); - nettyBuilder.JT808Builder.Services.AddHostedService(); - return nettyBuilder; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway/Metadata/JT808AtomicCounter.cs b/src/JT808.Gateway/Metadata/JT808AtomicCounter.cs deleted file mode 100644 index 6362905..0000000 --- a/src/JT808.Gateway/Metadata/JT808AtomicCounter.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace JT808.Gateway.Metadata -{ - /// - /// - /// - /// - internal class JT808AtomicCounter - { - long counter = 0; - - public JT808AtomicCounter(long initialCount = 0) - { - this.counter = initialCount; - } - - public void Reset() - { - Interlocked.Exchange(ref counter, 0); - } - - public long Increment() - { - return Interlocked.Increment(ref counter); - } - - public long Add(long len) - { - return Interlocked.Add(ref counter,len); - } - - public long Decrement() - { - return Interlocked.Decrement(ref counter); - } - - public long Count - { - get - { - return Interlocked.Read(ref counter); - } - } - } -} diff --git a/src/JT808.Gateway/Metadata/JT808ClientReport.cs b/src/JT808.Gateway/Metadata/JT808ClientReport.cs deleted file mode 100644 index 6896252..0000000 --- a/src/JT808.Gateway/Metadata/JT808ClientReport.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Metadata -{ - public class JT808ClientReport - { - public long SendTotalCount { get; set; } - public long ReceiveTotalCount { get; set; } - public DateTime CurrentDate { get; set; } - public int Connections { get; set; } - public int OnlineConnections { get; set; } - public int OfflineConnections { get; set; } - } -} diff --git a/src/JT808.Gateway/Metadata/JT808ClientRequest.cs b/src/JT808.Gateway/Metadata/JT808ClientRequest.cs deleted file mode 100644 index 9122dcd..0000000 --- a/src/JT808.Gateway/Metadata/JT808ClientRequest.cs +++ /dev/null @@ -1,30 +0,0 @@ -using JT808.Protocol; -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace JT808.Gateway.Metadata -{ - public class JT808ClientRequest - { - public JT808Package Package { get; } - - public byte[] HexData { get; } - - /// - /// 根据实际情况适当调整包的大小 - /// - public int MinBufferSize { get;} - - public JT808ClientRequest(JT808Package package,int minBufferSize=1024) - { - Package = package; - MinBufferSize = minBufferSize; - } - - public JT808ClientRequest(byte[] hexData) - { - HexData = hexData; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway/Metadata/JT808HttpRequest.cs b/src/JT808.Gateway/Metadata/JT808HttpRequest.cs deleted file mode 100644 index 8c21e94..0000000 --- a/src/JT808.Gateway/Metadata/JT808HttpRequest.cs +++ /dev/null @@ -1,22 +0,0 @@ -using JT808.Protocol; -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace JT808.Gateway.Metadata -{ - public class JT808HttpRequest - { - public string Json { get; set; } - - public JT808HttpRequest() - { - - } - - public JT808HttpRequest(string json) - { - Json = json; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway/Metadata/JT808HttpResponse.cs b/src/JT808.Gateway/Metadata/JT808HttpResponse.cs deleted file mode 100644 index f018dcb..0000000 --- a/src/JT808.Gateway/Metadata/JT808HttpResponse.cs +++ /dev/null @@ -1,22 +0,0 @@ -using JT808.Protocol; -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace JT808.Gateway.Metadata -{ - public class JT808HttpResponse - { - public byte[] Data { get; set; } - - public JT808HttpResponse() - { - - } - - public JT808HttpResponse(byte[] data) - { - this.Data = data; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway/Metadata/JT808Request.cs b/src/JT808.Gateway/Metadata/JT808Request.cs deleted file mode 100644 index 5817ed8..0000000 --- a/src/JT808.Gateway/Metadata/JT808Request.cs +++ /dev/null @@ -1,23 +0,0 @@ -using JT808.Protocol; -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace JT808.Gateway.Metadata -{ - public class JT808Request - { - public JT808HeaderPackage Package { get; } - - /// - /// 用于消息发送 - /// - public byte[] OriginalPackage { get;} - - public JT808Request(JT808HeaderPackage package, byte[] originalPackage) - { - Package = package; - OriginalPackage = originalPackage; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway/Metadata/JT808Response.cs b/src/JT808.Gateway/Metadata/JT808Response.cs deleted file mode 100644 index 5425f73..0000000 --- a/src/JT808.Gateway/Metadata/JT808Response.cs +++ /dev/null @@ -1,31 +0,0 @@ -using JT808.Gateway.Interfaces; -using JT808.Protocol; -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace JT808.Gateway.Metadata -{ - public class JT808Response: IJT808Reply - { - public JT808Package Package { get; set; } - public byte[] HexData { get; set; } - public int MinBufferSize { get; set; } - - public JT808Response() - { - - } - - public JT808Response(JT808Package package, int minBufferSize = 1024) - { - Package = package; - MinBufferSize = minBufferSize; - } - - public JT808Response(byte[] hexData) - { - HexData = hexData; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway/Metadata/JT808TcpSession.cs b/src/JT808.Gateway/Metadata/JT808TcpSession.cs deleted file mode 100644 index dff9d78..0000000 --- a/src/JT808.Gateway/Metadata/JT808TcpSession.cs +++ /dev/null @@ -1,32 +0,0 @@ -using DotNetty.Transport.Channels; -using JT808.Gateway.Enums; -using JT808.Gateway.Interfaces; -using System; - -namespace JT808.Gateway.Metadata -{ - public class JT808TcpSession: IJT808Session - { - public JT808TcpSession(IChannel channel, string terminalPhoneNo) - { - Channel = channel; - TerminalPhoneNo = terminalPhoneNo; - StartTime = DateTime.Now; - LastActiveTime = DateTime.Now; - } - - public JT808TcpSession() { } - - /// - /// 终端手机号 - /// - public string TerminalPhoneNo { get; set; } - - public IChannel Channel { get; set; } - - public DateTime LastActiveTime { get; set; } - - public DateTime StartTime { get; set; } - public JT808TransportProtocolType TransportProtocolType { get; set; } = JT808TransportProtocolType.tcp; - } -} diff --git a/src/JT808.Gateway/Metadata/JT808UdpPackage.cs b/src/JT808.Gateway/Metadata/JT808UdpPackage.cs deleted file mode 100644 index 3f7c4c1..0000000 --- a/src/JT808.Gateway/Metadata/JT808UdpPackage.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Text; - -namespace JT808.Gateway.Metadata -{ - public class JT808UdpPackage - { - public JT808UdpPackage(byte[] buffer, EndPoint sender) - { - Buffer = buffer; - Sender = sender; - } - - public byte[] Buffer { get; } - - public EndPoint Sender { get; } - } -} diff --git a/src/JT808.Gateway/Metadata/JT808UdpSession.cs b/src/JT808.Gateway/Metadata/JT808UdpSession.cs deleted file mode 100644 index b0c60c5..0000000 --- a/src/JT808.Gateway/Metadata/JT808UdpSession.cs +++ /dev/null @@ -1,38 +0,0 @@ -using DotNetty.Transport.Channels; -using JT808.Gateway.Enums; -using JT808.Gateway.Interfaces; -using System; -using System.Net; - -namespace JT808.Gateway.Metadata -{ - public class JT808UdpSession: IJT808Session - { - public JT808UdpSession(IChannel channel, - EndPoint sender, - string terminalPhoneNo) - { - Channel = channel; - TerminalPhoneNo = terminalPhoneNo; - StartTime = DateTime.Now; - LastActiveTime = DateTime.Now; - Sender = sender; - } - - public EndPoint Sender { get; set; } - - public JT808UdpSession() { } - - /// - /// 终端手机号 - /// - public string TerminalPhoneNo { get; set; } - - public IChannel Channel { get; set; } - - public DateTime LastActiveTime { get; set; } - - public DateTime StartTime { get; set; } - public JT808TransportProtocolType TransportProtocolType { get; set; } = JT808TransportProtocolType.udp; - } -} diff --git a/src/JT808.Gateway/Protos/JT808Gateway.proto b/src/JT808.Gateway/Protos/JT808Gateway.proto deleted file mode 100644 index 042fc89..0000000 --- a/src/JT808.Gateway/Protos/JT808Gateway.proto +++ /dev/null @@ -1,63 +0,0 @@ -syntax = "proto3"; - -option csharp_namespace = "JT808.Gateway.GrpcService"; - -package JT808GatewayGrpc; - -service JT808Gateway{ - // 会话服务-获取会话服务集合 - rpc GetTcpSessionAll(Empty) returns (TcpSessionInfoReply); - // 会话服务-通过设备终端号移除对应会话 - rpc RemoveSessionByTerminalPhoneNo(SessionRemoveRequest) returns (SessionRemoveReply); - // 统一下发信息 - rpc UnificationSend(UnificationSendRequest) returns (UnificationSendReply); - // 获取Tcp包计数器 - rpc GetTcpAtomicCounter(Empty) returns (TcpAtomicCounterReply); - // 会话服务-获取会话服务集合 - rpc GetUdpSessionAll(Empty) returns (UdpSessionInfoReply); - // 获取Udp包计数器 - rpc GetUdpAtomicCounter(Empty) returns (UdpAtomicCounterReply); -} - -message Empty{} - -message TcpSessionInfoReply{ - repeated SessionInfo TcpSessions=1; -} -message UdpSessionInfoReply{ - repeated SessionInfo UdpSessions=1; -} - -message SessionInfo{ - string StartTime=1; - string LastActiveTime=2; - string TerminalPhoneNo=3; - string RemoteAddressIP=4; -} - -message SessionRemoveRequest{ - string TerminalPhoneNo=1; -} - -message SessionRemoveReply{ - bool Success = 1; -} - -message UnificationSendRequest{ - string TerminalPhoneNo=1; - bytes Data=2; -} - -message UnificationSendReply{ - bool Success = 1; -} - -message TcpAtomicCounterReply{ - int64 MsgSuccessCount=1; - int64 MsgFailCount=2; -} - -message UdpAtomicCounterReply{ - int64 MsgSuccessCount=1; - int64 MsgFailCount=2; -} \ No newline at end of file diff --git a/src/JT808.Gateway/PubSub/IJT808MsgConsumer.cs b/src/JT808.Gateway/PubSub/IJT808MsgConsumer.cs deleted file mode 100644 index d247c8a..0000000 --- a/src/JT808.Gateway/PubSub/IJT808MsgConsumer.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace JT808.Gateway.PubSub -{ - public interface IJT808MsgConsumer : IJT808PubSub, IDisposable - { - void OnMessage(Action<(string TerminalNo, byte[] Data)> callback); - CancellationTokenSource Cts { get; } - void Subscribe(); - void Unsubscribe(); - } -} diff --git a/src/JT808.Gateway/PubSub/IJT808MsgProducer.cs b/src/JT808.Gateway/PubSub/IJT808MsgProducer.cs deleted file mode 100644 index 33cb252..0000000 --- a/src/JT808.Gateway/PubSub/IJT808MsgProducer.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace JT808.Gateway.PubSub -{ - public interface IJT808MsgProducer : IJT808PubSub, IDisposable - { - /// - /// - /// - /// 设备终端号 - /// 808 hex data - Task ProduceAsync(string terminalNo, byte[] data); - } -} diff --git a/src/JT808.Gateway/PubSub/IJT808MsgReplyConsumer.cs b/src/JT808.Gateway/PubSub/IJT808MsgReplyConsumer.cs deleted file mode 100644 index 3bbe675..0000000 --- a/src/JT808.Gateway/PubSub/IJT808MsgReplyConsumer.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace JT808.Gateway.PubSub -{ - public interface IJT808MsgReplyConsumer : IJT808PubSub, IDisposable - { - void OnMessage(Action<(string TerminalNo, byte[] Data)> callback); - CancellationTokenSource Cts { get; } - void Subscribe(); - void Unsubscribe(); - } -} diff --git a/src/JT808.Gateway/PubSub/IJT808MsgReplyProducer.cs b/src/JT808.Gateway/PubSub/IJT808MsgReplyProducer.cs deleted file mode 100644 index 99b7ae3..0000000 --- a/src/JT808.Gateway/PubSub/IJT808MsgReplyProducer.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace JT808.Gateway.PubSub -{ - public interface IJT808MsgReplyProducer : IJT808PubSub, IDisposable - { - /// - /// - /// - /// 设备终端号 - /// 808 hex data - Task ProduceAsync(string terminalNo, byte[] data); - } -} diff --git a/src/JT808.Gateway/PubSub/IJT808PubSub.cs b/src/JT808.Gateway/PubSub/IJT808PubSub.cs deleted file mode 100644 index 983c205..0000000 --- a/src/JT808.Gateway/PubSub/IJT808PubSub.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.PubSub -{ - public interface IJT808PubSub - { - string TopicName { get; } - } -} diff --git a/src/JT808.Gateway/PubSub/IJT808SessionConsumer.cs b/src/JT808.Gateway/PubSub/IJT808SessionConsumer.cs deleted file mode 100644 index eb3a03e..0000000 --- a/src/JT808.Gateway/PubSub/IJT808SessionConsumer.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace JT808.Gateway.PubSub -{ - /// - /// 会话通知(在线/离线) - /// - public interface IJT808SessionConsumer : IJT808PubSub, IDisposable - { - void OnMessage(Action<(string Notice, string TerminalNo)> callback); - CancellationTokenSource Cts { get; } - void Subscribe(); - void Unsubscribe(); - } -} diff --git a/src/JT808.Gateway/PubSub/IJT808SessionProducer.cs b/src/JT808.Gateway/PubSub/IJT808SessionProducer.cs deleted file mode 100644 index 572cd75..0000000 --- a/src/JT808.Gateway/PubSub/IJT808SessionProducer.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace JT808.Gateway.PubSub -{ - /// - /// 会话通知(在线/离线) - /// - public interface IJT808SessionProducer : IJT808PubSub, IDisposable - { - Task ProduceAsync(string notice,string terminalNo); - } -} diff --git a/src/JT808.Gateway/Services/JT808AtomicCounterService.cs b/src/JT808.Gateway/Services/JT808AtomicCounterService.cs deleted file mode 100644 index cddd31f..0000000 --- a/src/JT808.Gateway/Services/JT808AtomicCounterService.cs +++ /dev/null @@ -1,52 +0,0 @@ -using JT808.Gateway.Metadata; - -namespace JT808.Gateway.Services -{ - /// - /// 计数包服务 - /// - public class JT808AtomicCounterService - { - private readonly JT808AtomicCounter MsgSuccessCounter; - - private readonly JT808AtomicCounter MsgFailCounter; - - public JT808AtomicCounterService() - { - MsgSuccessCounter=new JT808AtomicCounter(); - MsgFailCounter = new JT808AtomicCounter(); - } - - public void Reset() - { - MsgSuccessCounter.Reset(); - MsgFailCounter.Reset(); - } - - public long MsgSuccessIncrement() - { - return MsgSuccessCounter.Increment(); - } - - public long MsgSuccessCount - { - get - { - return MsgSuccessCounter.Count; - } - } - - public long MsgFailIncrement() - { - return MsgFailCounter.Increment(); - } - - public long MsgFailCount - { - get - { - return MsgFailCounter.Count; - } - } - } -} diff --git a/src/JT808.Gateway/Services/JT808AtomicCounterServiceFactory.cs b/src/JT808.Gateway/Services/JT808AtomicCounterServiceFactory.cs deleted file mode 100644 index 087ddcc..0000000 --- a/src/JT808.Gateway/Services/JT808AtomicCounterServiceFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -using JT808.Gateway.Enums; -using System; -using System.Collections.Concurrent; - -namespace JT808.Gateway.Services -{ - public class JT808AtomicCounterServiceFactory - { - private readonly ConcurrentDictionary cache; - - public JT808AtomicCounterServiceFactory() - { - cache = new ConcurrentDictionary(); - } - - public JT808AtomicCounterService Create(JT808TransportProtocolType type) - { - if(cache.TryGetValue(type,out var service)) - { - return service; - } - else - { - var serviceNew = new JT808AtomicCounterService(); - cache.TryAdd(type, serviceNew); - return serviceNew; - } - } - } -} diff --git a/src/JT808.Gateway/Services/JT808ClientReceiveAtomicCounterService.cs b/src/JT808.Gateway/Services/JT808ClientReceiveAtomicCounterService.cs deleted file mode 100644 index 1239084..0000000 --- a/src/JT808.Gateway/Services/JT808ClientReceiveAtomicCounterService.cs +++ /dev/null @@ -1,35 +0,0 @@ -using JT808.Gateway.Metadata; - -namespace JT808.Gateway.Services -{ - /// - /// 接收计数包服务 - /// - public class JT808ClientReceiveAtomicCounterService - { - private readonly JT808AtomicCounter MsgSuccessCounter; - - public JT808ClientReceiveAtomicCounterService() - { - MsgSuccessCounter=new JT808AtomicCounter(); - } - - public void Reset() - { - MsgSuccessCounter.Reset(); - } - - public long MsgSuccessIncrement() - { - return MsgSuccessCounter.Increment(); - } - - public long MsgSuccessCount - { - get - { - return MsgSuccessCounter.Count; - } - } - } -} diff --git a/src/JT808.Gateway/Services/JT808ClientReportHostedService.cs b/src/JT808.Gateway/Services/JT808ClientReportHostedService.cs deleted file mode 100644 index be63e82..0000000 --- a/src/JT808.Gateway/Services/JT808ClientReportHostedService.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Microsoft.Extensions.Hosting; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Services -{ - public class JT808ClientReportHostedService : IHostedService - { - private readonly JT808ClientReportService jT808ReportService; - private CancellationTokenSource cts = new CancellationTokenSource(); - public JT808ClientReportHostedService(JT808ClientReportService jT808ReportService) - { - this.jT808ReportService = jT808ReportService; - } - public Task StartAsync(CancellationToken cancellationToken) - { - Task.Run(() => - { - while (!cts.IsCancellationRequested) - { - jT808ReportService.Create(); - Thread.Sleep(1000); - //Task.Delay(TimeSpan.FromSeconds(1), cts.Token); - } - }, cts.Token); - return Task.CompletedTask; - } - public Task StopAsync(CancellationToken cancellationToken) - { - cts.Cancel(); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/Services/JT808ClientReportService.cs b/src/JT808.Gateway/Services/JT808ClientReportService.cs deleted file mode 100644 index da27f8a..0000000 --- a/src/JT808.Gateway/Services/JT808ClientReportService.cs +++ /dev/null @@ -1,43 +0,0 @@ -using JT808.Gateway.Client; -using JT808.Gateway.Metadata; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace JT808.Gateway.Services -{ - public class JT808ClientReportService - { - private readonly JT808ClientReceiveAtomicCounterService jT808ReceiveAtomicCounterService; - private readonly JT808ClientSendAtomicCounterService jT808SendAtomicCounterService; - private readonly IJT808TcpClientFactory jT808TcpClientFactory; - - public List JT808Reports { get; private set; } - - public JT808ClientReportService( - JT808ClientReceiveAtomicCounterService jT808ReceiveAtomicCounterService, - JT808ClientSendAtomicCounterService jT808SendAtomicCounterService, - IJT808TcpClientFactory jT808TcpClientFactory) - { - this.jT808ReceiveAtomicCounterService = jT808ReceiveAtomicCounterService; - this.jT808SendAtomicCounterService = jT808SendAtomicCounterService; - this.jT808TcpClientFactory = jT808TcpClientFactory; - JT808Reports = new List(); - } - - public void Create() - { - var clients = jT808TcpClientFactory.GetAll(); - JT808Reports.Add(new JT808ClientReport() - { - SendTotalCount= jT808SendAtomicCounterService.MsgSuccessCount, - ReceiveTotalCount= jT808ReceiveAtomicCounterService.MsgSuccessCount, - CurrentDate=DateTime.Now, - Connections= clients.Count, - OnlineConnections= clients.Where(w => w.IsOpen).Count(), - OfflineConnections= clients.Where(w => !w.IsOpen).Count(), - }); - } - } -} diff --git a/src/JT808.Gateway/Services/JT808ClientSendAtomicCounterService.cs b/src/JT808.Gateway/Services/JT808ClientSendAtomicCounterService.cs deleted file mode 100644 index 62b12c4..0000000 --- a/src/JT808.Gateway/Services/JT808ClientSendAtomicCounterService.cs +++ /dev/null @@ -1,35 +0,0 @@ -using JT808.Gateway.Metadata; - -namespace JT808.Gateway.Services -{ - /// - /// 发送计数包服务 - /// - public class JT808ClientSendAtomicCounterService - { - private readonly JT808AtomicCounter MsgSuccessCounter; - - public JT808ClientSendAtomicCounterService() - { - MsgSuccessCounter=new JT808AtomicCounter(); - } - - public void Reset() - { - MsgSuccessCounter.Reset(); - } - - public long MsgSuccessIncrement() - { - return MsgSuccessCounter.Increment(); - } - - public long MsgSuccessCount - { - get - { - return MsgSuccessCounter.Count; - } - } - } -} diff --git a/src/JT808.Gateway/Services/JT808GatewayService.cs b/src/JT808.Gateway/Services/JT808GatewayService.cs deleted file mode 100644 index 9a97d18..0000000 --- a/src/JT808.Gateway/Services/JT808GatewayService.cs +++ /dev/null @@ -1,102 +0,0 @@ -using JT808.Gateway.Interfaces; -using System; -using System.Collections.Generic; -using System.Text; -using JT808.Gateway.Enums; -using JT808.Gateway.GrpcService; -using Grpc.Core; -using System.Threading.Tasks; - -namespace JT808.Gateway.Services -{ - public class JT808GatewayService: JT808Gateway.JT808GatewayBase - { - private readonly JT808AtomicCounterService jT808TcpAtomicCounterService; - - private readonly JT808AtomicCounterService jT808UdpAtomicCounterService; - - private readonly IJT808SessionService jT808SessionService; - - private readonly IJT808UnificationSendService jT808UnificationSendService; - - public JT808GatewayService( - IJT808UnificationSendService jT808UnificationSendService, - IJT808SessionService jT808SessionService, - JT808AtomicCounterServiceFactory jT808AtomicCounterServiceFactory - ) - { - this.jT808UnificationSendService = jT808UnificationSendService; - this.jT808SessionService = jT808SessionService; - this.jT808TcpAtomicCounterService = jT808AtomicCounterServiceFactory.Create(JT808TransportProtocolType.tcp); - this.jT808UdpAtomicCounterService = jT808AtomicCounterServiceFactory.Create(JT808TransportProtocolType.udp); - } - - public override Task GetTcpSessionAll(Empty request, ServerCallContext context) - { - var result = jT808SessionService.GetTcpAll(); - TcpSessionInfoReply reply = new TcpSessionInfoReply(); - if (result.Data != null) - { - foreach (var item in result.Data) - { - reply.TcpSessions.Add(new SessionInfo - { - LastActiveTime = item.LastActiveTime.ToString("yyyy-MM-dd HH:mm:ss"), - StartTime = item.StartTime.ToString("yyyy-MM-dd HH:mm:ss"), - RemoteAddressIP = item.RemoteAddressIP, - TerminalPhoneNo = item.TerminalPhoneNo - }); - } - } - return Task.FromResult(reply); - } - - public override Task RemoveSessionByTerminalPhoneNo(SessionRemoveRequest request, ServerCallContext context) - { - var result = jT808SessionService.RemoveByTerminalPhoneNo(request.TerminalPhoneNo); - return Task.FromResult(new SessionRemoveReply { Success = result.Data }); - } - - public override Task GetUdpSessionAll(Empty request, ServerCallContext context) - { - var result = jT808SessionService.GetUdpAll(); - UdpSessionInfoReply reply = new UdpSessionInfoReply(); - if (result.Data != null) - { - foreach (var item in result.Data) - { - reply.UdpSessions.Add(new SessionInfo - { - LastActiveTime = item.LastActiveTime.ToString("yyyy-MM-dd HH:mm:ss"), - StartTime = item.StartTime.ToString("yyyy-MM-dd HH:mm:ss"), - RemoteAddressIP = item.RemoteAddressIP, - TerminalPhoneNo = item.TerminalPhoneNo - }); - } - } - return Task.FromResult(reply); - } - - public override Task UnificationSend(UnificationSendRequest request, ServerCallContext context) - { - var result = jT808UnificationSendService.Send(request.TerminalPhoneNo, request.Data.ToByteArray()); - return Task.FromResult(new UnificationSendReply { Success = result.Data }); - } - - public override Task GetTcpAtomicCounter(Empty request, ServerCallContext context) - { - TcpAtomicCounterReply reply = new TcpAtomicCounterReply(); - reply.MsgFailCount=jT808TcpAtomicCounterService.MsgFailCount; - reply.MsgSuccessCount=jT808TcpAtomicCounterService.MsgSuccessCount; - return Task.FromResult(reply); - } - - public override Task GetUdpAtomicCounter(Empty request, ServerCallContext context) - { - UdpAtomicCounterReply reply = new UdpAtomicCounterReply(); - reply.MsgFailCount = jT808UdpAtomicCounterService.MsgFailCount; - reply.MsgSuccessCount = jT808UdpAtomicCounterService.MsgSuccessCount; - return Task.FromResult(reply); - } - } -} diff --git a/src/JT808.Gateway/Services/JT808MsgReplyHostedService.cs b/src/JT808.Gateway/Services/JT808MsgReplyHostedService.cs deleted file mode 100644 index ccb3030..0000000 --- a/src/JT808.Gateway/Services/JT808MsgReplyHostedService.cs +++ /dev/null @@ -1,42 +0,0 @@ -using JT808.Gateway.PubSub; -using JT808.Gateway.Session; -using Microsoft.Extensions.Hosting; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Services -{ - internal class JT808MsgReplyHostedService : IHostedService - { - private readonly JT808SessionManager JT808SessionManager; - - private readonly IJT808MsgReplyConsumer JT808MsgReplyConsumer; - - public JT808MsgReplyHostedService( - IJT808MsgReplyConsumer jT808MsgReplyConsumer, - JT808SessionManager jT808SessionManager) - { - JT808MsgReplyConsumer = jT808MsgReplyConsumer; - JT808SessionManager = jT808SessionManager; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - JT808MsgReplyConsumer.OnMessage(item => - { - JT808SessionManager.Send(item.TerminalNo, item.Data); - }); - JT808MsgReplyConsumer.Subscribe(); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - JT808MsgReplyConsumer.Unsubscribe(); - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/Services/JT808MsgService.cs b/src/JT808.Gateway/Services/JT808MsgService.cs deleted file mode 100644 index 68c1b96..0000000 --- a/src/JT808.Gateway/Services/JT808MsgService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace JT808.Gateway.Services -{ - internal class JT808MsgService - { - public System.Collections.Concurrent.BlockingCollection<(string TerminalNo, byte[] Data)> MsgQueue { get; set; } = new System.Collections.Concurrent.BlockingCollection<(string TerminalNo, byte[] Data)>(); - } -} diff --git a/src/JT808.Gateway/Services/JT808SessionService.cs b/src/JT808.Gateway/Services/JT808SessionService.cs deleted file mode 100644 index f2ecb8c..0000000 --- a/src/JT808.Gateway/Services/JT808SessionService.cs +++ /dev/null @@ -1,98 +0,0 @@ -using JT808.Gateway.Dtos; -using JT808.Gateway.Interfaces; -using JT808.Gateway.Session; -using System; -using System.Collections.Generic; -using System.Linq; - - -namespace JT808.Gateway.Services -{ - internal class JT808SessionService : IJT808SessionService - { - private readonly JT808SessionManager jT808SessionManager; - - public JT808SessionService( - JT808SessionManager jT808SessionManager) - { - this.jT808SessionManager = jT808SessionManager; - } - - public JT808ResultDto> GetTcpAll() - { - JT808ResultDto> resultDto = new JT808ResultDto>(); - try - { - resultDto.Data = jT808SessionManager.GetAll().Select(s => new JT808TcpSessionInfoDto - { - LastActiveTime = s.LastActiveTime, - StartTime = s.StartTime, - TerminalPhoneNo = s.TerminalPhoneNo, - RemoteAddressIP = s.Channel.RemoteAddress.ToString(), - }).ToList(); - resultDto.Code = JT808ResultCode.Ok; - } - catch (Exception ex) - { - resultDto.Data = null; - resultDto.Code = JT808ResultCode.Error; - resultDto.Message =ex.Message; - } - return resultDto; - } - - public JT808ResultDto> GetUdpAll() - { - JT808ResultDto> resultDto = new JT808ResultDto>(); - try - { - resultDto.Data = jT808SessionManager.GetUdpAll().Select(s => new JT808UdpSessionInfoDto - { - LastActiveTime = s.LastActiveTime, - StartTime = s.StartTime, - TerminalPhoneNo = s.TerminalPhoneNo, - RemoteAddressIP = s.Sender.ToString() - }).ToList(); - resultDto.Code = JT808ResultCode.Ok; - } - catch (Exception ex) - { - resultDto.Data = null; - resultDto.Code = JT808ResultCode.Error; - resultDto.Message = ex.Message; - } - return resultDto; - } - - public JT808ResultDto RemoveByTerminalPhoneNo(string terminalPhoneNo) - { - JT808ResultDto resultDto = new JT808ResultDto(); - try - { - var session = jT808SessionManager.RemoveSession(terminalPhoneNo); - if (session != null) - { - if(session.Channel.Open) - { - session.Channel.CloseAsync(); - } - } - resultDto.Code = JT808ResultCode.Ok; - resultDto.Data = true; - } - catch (AggregateException ex) - { - resultDto.Data = false; - resultDto.Code = 500; - resultDto.Message = ex.Message; - } - catch (Exception ex) - { - resultDto.Data = false; - resultDto.Code = JT808ResultCode.Error; - resultDto.Message = ex.Message; - } - return resultDto; - } - } -} diff --git a/src/JT808.Gateway/Services/JT808UnificationSendService.cs b/src/JT808.Gateway/Services/JT808UnificationSendService.cs deleted file mode 100644 index d7d54e3..0000000 --- a/src/JT808.Gateway/Services/JT808UnificationSendService.cs +++ /dev/null @@ -1,45 +0,0 @@ -using JT808.Gateway.Dtos; -using JT808.Gateway.Interfaces; -using JT808.Gateway.Session; -using System; - -namespace JT808.Gateway.Services -{ - internal class JT808UnificationSendService : IJT808UnificationSendService - { - private readonly JT808SessionManager jT808SessionManager; - - public JT808UnificationSendService( - JT808SessionManager jT808SessionManager) - { - this.jT808SessionManager = jT808SessionManager; - } - - public JT808ResultDto Send(string terminalPhoneNo, byte[] data) - { - JT808ResultDto resultDto = new JT808ResultDto(); - try - { - if(jT808SessionManager.TrySend(terminalPhoneNo, data, out var message)) - { - resultDto.Code = JT808ResultCode.Ok; - resultDto.Data = true; - resultDto.Message = message; - } - else - { - resultDto.Code = JT808ResultCode.Ok; - resultDto.Data = false; - resultDto.Message = message; - } - } - catch (Exception ex) - { - resultDto.Data = false; - resultDto.Code = JT808ResultCode.Error; - resultDto.Message = ex.Message; - } - return resultDto; - } - } -} diff --git a/src/JT808.Gateway/Session/JT808SessionManager.cs b/src/JT808.Gateway/Session/JT808SessionManager.cs deleted file mode 100644 index d5cf82f..0000000 --- a/src/JT808.Gateway/Session/JT808SessionManager.cs +++ /dev/null @@ -1,304 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Transport.Channels; -using JT808.Gateway.Enums; -using JT808.Gateway.Interfaces; -using JT808.Gateway.Metadata; -using JT808.Gateway.PubSub; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Text; - -namespace JT808.Gateway.Session -{ - public class JT808SessionManager - { - private readonly ILogger logger; - - private readonly IJT808DatagramPacket jT808DatagramPacket; - public IJT808SessionProducer JT808SessionProducer { get; } - - public ConcurrentDictionary Sessions { get; } - - public JT808SessionManager( - IJT808SessionProducer jT808SessionProducer, - ILoggerFactory loggerFactory - ) - { - Sessions = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - JT808SessionProducer = jT808SessionProducer; - logger = loggerFactory.CreateLogger(); - } - - public JT808SessionManager( - IJT808SessionProducer jT808SessionProducer, - ILoggerFactory loggerFactory, - IJT808DatagramPacket jT808DatagramPacket) - { - Sessions = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - JT808SessionProducer = jT808SessionProducer; - logger = loggerFactory.CreateLogger(); - this.jT808DatagramPacket = jT808DatagramPacket; - } - - public int SessionCount - { - get - { - return Sessions.Count; - } - } - public IJT808Session GetSessionByTerminalPhoneNo(string terminalPhoneNo) - { - if (string.IsNullOrEmpty(terminalPhoneNo)) - return default; - if (Sessions.TryGetValue(terminalPhoneNo, out IJT808Session targetSession)) - { - return targetSession; - } - else - { - return default; - } - } - public JT808TcpSession GetTcpSessionByTerminalPhoneNo(string terminalPhoneNo) - { - return (JT808TcpSession)GetSessionByTerminalPhoneNo(terminalPhoneNo); - } - public JT808UdpSession GetUdpSessionByTerminalPhoneNo(string terminalPhoneNo) - { - return (JT808UdpSession)GetSessionByTerminalPhoneNo(terminalPhoneNo); - } - public void Heartbeat(string terminalPhoneNo) - { - if (string.IsNullOrEmpty(terminalPhoneNo)) return; - if (Sessions.TryGetValue(terminalPhoneNo, out IJT808Session oldjT808Session)) - { - oldjT808Session.LastActiveTime = DateTime.Now; - Sessions.TryUpdate(terminalPhoneNo, oldjT808Session, oldjT808Session); - } - } - public bool TrySend(string terminalPhoneNo, byte[] data, out string message) - { - bool isSuccessed; - var session = GetSessionByTerminalPhoneNo(terminalPhoneNo); - if (session != null) - { - //判断转发数据是下发不了消息的 - if (Sessions.Select(s => s.Value).Count(c => c.Channel.Id == session.Channel.Id) > 1) - { - isSuccessed = false; - message = "not support transmit data send."; - } - else - { - if(session.TransportProtocolType== JT808TransportProtocolType.tcp) - { - session.Channel.WriteAndFlushAsync(Unpooled.WrappedBuffer(data)); - isSuccessed = true; - message = "ok"; - } - else if (session.TransportProtocolType == JT808TransportProtocolType.udp) - { - isSuccessed = true; - message = "ok"; - session.Channel.WriteAndFlushAsync(jT808DatagramPacket.Create(data, ((JT808UdpSession)session).Sender)); - } - else - { - isSuccessed = false; - message = "unknow type"; - } - } - } - else - { - isSuccessed = false; - message = "offline"; - } - return isSuccessed; - } - internal void Send(string terminalPhoneNo, byte[] data) - { - var session = GetSessionByTerminalPhoneNo(terminalPhoneNo); - if (session != null) - { - if (session.TransportProtocolType == JT808TransportProtocolType.tcp) - { - session.Channel.WriteAndFlushAsync(Unpooled.WrappedBuffer(data)); - } - else if (session.TransportProtocolType == JT808TransportProtocolType.udp) - { - session.Channel.WriteAndFlushAsync(jT808DatagramPacket.Create(data, ((JT808UdpSession)session).Sender)); - } - } - } - public bool TrySend(string terminalPhoneNo, IJT808Reply reply, out string message) - { - bool isSuccessed; - var session = GetSessionByTerminalPhoneNo(terminalPhoneNo); - if (session != null) - { - //判断转发数据是下发不了消息的 - if (Sessions.Select(s => s.Value).Count(c => c.Channel.Id == session.Channel.Id) > 1) - { - isSuccessed = false; - message = "not support transmit data send."; - } - else - { - if (session.TransportProtocolType == JT808TransportProtocolType.tcp) - { - isSuccessed = true; - message = "ok"; - session.Channel.WriteAndFlushAsync(reply); - } - else if (session.TransportProtocolType == JT808TransportProtocolType.udp) - { - isSuccessed = true; - message = "ok"; - session.Channel.WriteAndFlushAsync(jT808DatagramPacket.Create(reply.HexData, ((JT808UdpSession)session).Sender)); - } - else - { - isSuccessed = false; - message = "unknow type"; - } - } - } - else - { - isSuccessed = false; - message = "offline"; - } - return isSuccessed; - } - public void TryAdd(string terminalPhoneNo, IChannel channel) - { - // 解决了设备号跟通道绑定到一起,不需要用到通道本身的SessionId - // 不管设备下发更改了设备终端号,只要是没有在内存中就当是新的 - // 存在的问题: - // 1.原先老的如何销毁 - // 2.这时候用的通道是相同的,设备终端是不同的 - // 当设备主动或者服务器断开以后,可以释放,这点内存忽略不计,况且更改设备号不是很频繁。 - - //修复第一次通过转发过来的数据,再次通过直连后通道没有改变导致下发不成功,所以每次进行通道的更新操作。 - if (Sessions.TryGetValue(terminalPhoneNo, out IJT808Session oldJT808Session)) - { - oldJT808Session.LastActiveTime = DateTime.Now; - oldJT808Session.Channel = channel; - Sessions.TryUpdate(terminalPhoneNo, oldJT808Session, oldJT808Session); - } - else - { - JT808TcpSession jT808TcpSession = new JT808TcpSession(channel, terminalPhoneNo); - if (Sessions.TryAdd(terminalPhoneNo, jT808TcpSession)) - { - //使用场景: - //部标的超长待机设备,不会像正常的设备一样一直连着,可能10几分钟连上了,然后发完就关闭连接, - //这时候想下发数据需要知道设备什么时候上线,在这边做通知最好不过了。 - //有设备关联上来可以进行通知 例如:使用Redis发布订阅 - JT808SessionProducer.ProduceAsync(JT808GatewayConstants.SessionOnline,jT808TcpSession.TerminalPhoneNo); - } - } - } - public void TryAdd(IChannel channel, EndPoint sender, string terminalPhoneNo) - { - //1.先判断是否在缓存里面 - if (Sessions.TryGetValue(terminalPhoneNo, out IJT808Session jT808UdpSession)) - { - if(jT808UdpSession is JT808UdpSession convertSession) - { - convertSession.LastActiveTime = DateTime.Now; - convertSession.Sender = sender; - convertSession.Channel = channel; - Sessions.TryUpdate(terminalPhoneNo, convertSession, convertSession); - } - } - else - { - //添加缓存 - //使用场景: - //部标的超长待机设备,不会像正常的设备一样一直连着,可能10几分钟连上了,然后发完就关闭连接, - //这时候想下发数据需要知道设备什么时候上线,在这边做通知最好不过了。 - //有设备关联上来可以进行通知 例如:使用Redis发布订阅 - Sessions.TryAdd(terminalPhoneNo, new JT808UdpSession(channel, sender, terminalPhoneNo)); - } - //移动是个大的内网,不跟随下发,根本就发不出来 - //移动很多卡,存储的那个socket地址端口,有效期非常短 - //不速度快点下发,那个socket地址端口就可能映射到别的对应卡去了 - //所以此处采用跟随设备消息下发指令 - JT808SessionProducer.ProduceAsync(JT808GatewayConstants.SessionOnline,terminalPhoneNo); - } - public IJT808Session RemoveSession(string terminalPhoneNo) - { - //设备离线可以进行通知 - //使用Redis 发布订阅 - if (string.IsNullOrEmpty(terminalPhoneNo)) return default; - if (!Sessions.TryGetValue(terminalPhoneNo, out IJT808Session jT808Session)) - { - return default; - } - // 处理转发过来的是数据 这时候通道对设备是1对多关系,需要清理垃圾数据 - //1.用当前会话的通道Id找出通过转发过来的其他设备的终端号 - var terminalPhoneNos = Sessions.Where(w => w.Value.Channel.Id == jT808Session.Channel.Id).Select(s => s.Key).ToList(); - //2.存在则一个个移除 - if (terminalPhoneNos.Count > 1) - { - //3.移除包括当前的设备号 - foreach (var key in terminalPhoneNos) - { - Sessions.TryRemove(key, out IJT808Session jT808SessionRemove); - } - string nos = string.Join(",", terminalPhoneNos); - logger.LogInformation($">>>{terminalPhoneNo}-{nos} 1-n Session Remove."); - JT808SessionProducer.ProduceAsync(JT808GatewayConstants.SessionOffline, nos); - return jT808Session; - } - else - { - if (Sessions.TryRemove(terminalPhoneNo, out IJT808Session jT808SessionRemove)) - { - logger.LogInformation($">>>{terminalPhoneNo} Session Remove."); - JT808SessionProducer.ProduceAsync(JT808GatewayConstants.SessionOffline, terminalPhoneNo); - return jT808SessionRemove; - } - else - { - return default; - } - } - } - public void RemoveSessionByChannel(IChannel channel) - { - //设备离线可以进行通知 - //使用Redis 发布订阅 - var terminalPhoneNos = Sessions.Where(w => w.Value.Channel.Id == channel.Id).Select(s => s.Key).ToList(); - if (terminalPhoneNos.Count > 0) - { - foreach (var key in terminalPhoneNos) - { - Sessions.TryRemove(key, out IJT808Session jT808SessionRemove); - } - string nos = string.Join(",", terminalPhoneNos); - logger.LogInformation($">>>{nos} Channel Remove."); - JT808SessionProducer.ProduceAsync(JT808GatewayConstants.SessionOffline, nos); - } - } - public IEnumerable GetAll() - { - return Sessions.Select(s => s.Value).ToList(); - } - public IEnumerable GetTcpAll() - { - return Sessions.Select(s => (JT808TcpSession)s.Value).Where(w => w.TransportProtocolType == JT808TransportProtocolType.tcp).ToList(); - } - public IEnumerable GetUdpAll() - { - return Sessions.Select(s => (JT808UdpSession)s.Value).Where(w => w.TransportProtocolType == JT808TransportProtocolType.udp).ToList(); - } - } -} diff --git a/src/JT808.Gateway/Simples/JT808SimpleTcpClient.cs b/src/JT808.Gateway/Simples/JT808SimpleTcpClient.cs deleted file mode 100644 index 34102ed..0000000 --- a/src/JT808.Gateway/Simples/JT808SimpleTcpClient.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Diagnostics; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Simples -{ - internal class JT808SimpleTcpClient - { - private TcpClient tcpClient; - - public JT808SimpleTcpClient(IPEndPoint remoteAddress) - { - tcpClient = new TcpClient(); - tcpClient.Connect(remoteAddress); - Task.Run(()=> { - while (true) - { - try - { - byte[] buffer = new byte[100]; - tcpClient.GetStream().Read(buffer, 0, 100); - Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + string.Join(" ", buffer)); - - } - catch - { - - - } - Thread.Sleep(1000); - } - }); - } - - - - public void WriteAsync(byte[] data) - { - tcpClient.GetStream().WriteAsync(data, 0, data.Length); - } - - public void Down() - { - tcpClient.Close(); - } - } -} diff --git a/src/JT808.Gateway/Simples/JT808SimpleUdpClient.cs b/src/JT808.Gateway/Simples/JT808SimpleUdpClient.cs deleted file mode 100644 index 67c3111..0000000 --- a/src/JT808.Gateway/Simples/JT808SimpleUdpClient.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Diagnostics; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Simples -{ - internal class JT808SimpleUdpClient - { - private UdpClient udpClient; - - public JT808SimpleUdpClient(IPEndPoint remoteAddress) - { - udpClient = new UdpClient(); - udpClient.Connect(remoteAddress); - Task.Run(() => - { - while (true) - { - try - { - string tmp = string.Join(" ", udpClient.Receive(ref remoteAddress)); - Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + tmp); - Thread.Sleep(1000); - } - catch - { - - - } - Thread.Sleep(1000); - } - }); - } - - public void WriteAsync(byte[] data) - { - udpClient.SendAsync(data, data.Length); - } - - public void Down() - { - udpClient.Close(); - } - } -} diff --git a/src/JT808.Gateway/Tcp/JT808TcpDotnettyExtensions.cs b/src/JT808.Gateway/Tcp/JT808TcpDotnettyExtensions.cs deleted file mode 100644 index bf513eb..0000000 --- a/src/JT808.Gateway/Tcp/JT808TcpDotnettyExtensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -using JT808.Gateway.Codecs; -using JT808.Gateway.Handlers; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using System.Runtime.CompilerServices; - -namespace JT808.Gateway.Tcp -{ - public static class JT808TcpDotnettyExtensions - { - public static IJT808GatewayBuilder AddJT808GatewayTcpHost(this IJT808GatewayBuilder jT808NettyBuilder) - { - jT808NettyBuilder.JT808Builder.Services.TryAddScoped(); - jT808NettyBuilder.JT808Builder.Services.TryAddScoped(); - jT808NettyBuilder.JT808Builder.Services.TryAddScoped(); - jT808NettyBuilder.JT808Builder.Services.TryAddScoped(); - jT808NettyBuilder.JT808Builder.Services.AddHostedService(); - return jT808NettyBuilder; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway/Tcp/JT808TcpServerHost.cs b/src/JT808.Gateway/Tcp/JT808TcpServerHost.cs deleted file mode 100644 index 3134eaf..0000000 --- a/src/JT808.Gateway/Tcp/JT808TcpServerHost.cs +++ /dev/null @@ -1,95 +0,0 @@ -using DotNetty.Buffers; -using DotNetty.Codecs; -using DotNetty.Handlers.Timeout; -using DotNetty.Transport.Bootstrapping; -using DotNetty.Transport.Channels; -using DotNetty.Transport.Libuv; -using JT808.Gateway.Codecs; -using JT808.Gateway.Configurations; -using JT808.Gateway.Handlers; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System; -using System.Net; -using System.Runtime.InteropServices; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Tcp -{ - /// - /// JT808 Tcp网关服务 - /// - internal class JT808TcpServerHost : IHostedService - { - private readonly IServiceProvider serviceProvider; - private readonly JT808Configuration configuration; - private readonly ILogger logger; - private DispatcherEventLoopGroup bossGroup; - private WorkerEventLoopGroup workerGroup; - private IChannel bootstrapChannel; - private IByteBufferAllocator serverBufferAllocator; - - public JT808TcpServerHost( - IServiceProvider provider, - ILoggerFactory loggerFactory, - IOptions jT808ConfigurationAccessor) - { - serviceProvider = provider; - configuration = jT808ConfigurationAccessor.Value; - logger=loggerFactory.CreateLogger(); - } - - public Task StartAsync(CancellationToken cancellationToken) - { - bossGroup = new DispatcherEventLoopGroup(); - workerGroup = new WorkerEventLoopGroup(bossGroup, configuration.EventLoopCount); - serverBufferAllocator = new PooledByteBufferAllocator(); - ServerBootstrap bootstrap = new ServerBootstrap(); - bootstrap.Group(bossGroup, workerGroup); - bootstrap.Channel(); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) - || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - bootstrap - .Option(ChannelOption.SoReuseport, true) - .ChildOption(ChannelOption.SoReuseaddr, true); - } - bootstrap - .Option(ChannelOption.SoBacklog, configuration.SoBacklog) - .ChildOption(ChannelOption.Allocator, serverBufferAllocator) - .ChildHandler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - using (var scope = serviceProvider.CreateScope()) - { - channel.Pipeline.AddLast("jt808TcpBuffer", new DelimiterBasedFrameDecoder(int.MaxValue, - Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }), - Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag }))); - channel.Pipeline.AddLast("jt808TcpDecode", scope.ServiceProvider.GetRequiredService()); - channel.Pipeline.AddLast("jt808TcpEncode", scope.ServiceProvider.GetRequiredService()); - channel.Pipeline.AddLast("systemIdleState", new IdleStateHandler( - configuration.ReaderIdleTimeSeconds, - configuration.WriterIdleTimeSeconds, - configuration.AllIdleTimeSeconds)); - channel.Pipeline.AddLast("jt808TcpConnection", scope.ServiceProvider.GetRequiredService()); - channel.Pipeline.AddLast("jt808TcpService", scope.ServiceProvider.GetRequiredService()); - } - })); - logger.LogInformation($"JT808 TCP Server start at {IPAddress.Any}:{configuration.TcpPort}."); - return bootstrap.BindAsync(configuration.TcpPort) - .ContinueWith(i => bootstrapChannel = i.Result); - } - - public async Task StopAsync(CancellationToken cancellationToken) - { - await bootstrapChannel.CloseAsync(); - var quietPeriod = configuration.QuietPeriodTimeSpan; - var shutdownTimeout = configuration.ShutdownTimeoutTimeSpan; - await workerGroup.ShutdownGracefullyAsync(quietPeriod, shutdownTimeout); - await bossGroup.ShutdownGracefullyAsync(quietPeriod, shutdownTimeout); - } - } -} diff --git a/src/JT808.Gateway/Udp/JT808UdpDotnettyExtensions.cs b/src/JT808.Gateway/Udp/JT808UdpDotnettyExtensions.cs deleted file mode 100644 index 554eaf4..0000000 --- a/src/JT808.Gateway/Udp/JT808UdpDotnettyExtensions.cs +++ /dev/null @@ -1,22 +0,0 @@ -using JT808.Gateway.Codecs; -using JT808.Gateway.Handlers; -using JT808.Gateway.Impls; -using JT808.Gateway.Interfaces; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using System.Runtime.CompilerServices; - -namespace JT808.Gateway.Udp -{ - public static class JT808UdpDotnettyExtensions - { - public static IJT808GatewayBuilder AddJT808GatewayUdpHost(this IJT808GatewayBuilder jT808NettyBuilder) - { - jT808NettyBuilder.JT808Builder.Services.TryAddSingleton(); - jT808NettyBuilder.JT808Builder.Services.TryAddScoped(); - jT808NettyBuilder.JT808Builder.Services.TryAddScoped(); - jT808NettyBuilder.JT808Builder.Services.AddHostedService(); - return jT808NettyBuilder; - } - } -} \ No newline at end of file diff --git a/src/JT808.Gateway/Udp/JT808UdpServerHost.cs b/src/JT808.Gateway/Udp/JT808UdpServerHost.cs deleted file mode 100644 index 3e1636e..0000000 --- a/src/JT808.Gateway/Udp/JT808UdpServerHost.cs +++ /dev/null @@ -1,76 +0,0 @@ -using DotNetty.Transport.Bootstrapping; -using DotNetty.Transport.Channels; -using DotNetty.Transport.Channels.Sockets; -using JT808.Gateway.Codecs; -using JT808.Gateway.Configurations; -using JT808.Gateway.Handlers; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System; -using System.Net; -using System.Runtime.InteropServices; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Udp -{ - /// - /// JT808 Udp网关服务 - /// - internal class JT808UdpServerHost : IHostedService - { - private readonly IServiceProvider serviceProvider; - private readonly JT808Configuration configuration; - private readonly ILogger logger; - private MultithreadEventLoopGroup group; - private IChannel bootstrapChannel; - - public JT808UdpServerHost( - IServiceProvider provider, - ILoggerFactory loggerFactory, - IOptions jT808ConfigurationAccessor) - { - serviceProvider = provider; - configuration = jT808ConfigurationAccessor.Value; - logger=loggerFactory.CreateLogger(); - } - - public Task StartAsync(CancellationToken cancellationToken) - { - group = new MultithreadEventLoopGroup(); - Bootstrap bootstrap = new Bootstrap(); - bootstrap.Group(group); - bootstrap.Channel(); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) - || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - bootstrap - .Option(ChannelOption.SoReuseport, true); - } - bootstrap - .Option(ChannelOption.SoBroadcast, true) - .Handler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - using (var scope = serviceProvider.CreateScope()) - { - pipeline.AddLast("jt808UdpDecoder", scope.ServiceProvider.GetRequiredService()); - pipeline.AddLast("jt808UdpService", scope.ServiceProvider.GetRequiredService()); - } - })); - logger.LogInformation($"JT808 Udp Server start at {IPAddress.Any}:{configuration.UdpPort}."); - return bootstrap.BindAsync(configuration.UdpPort) - .ContinueWith(i => bootstrapChannel = i.Result); - } - - public async Task StopAsync(CancellationToken cancellationToken) - { - await bootstrapChannel.CloseAsync(); - var quietPeriod = configuration.QuietPeriodTimeSpan; - var shutdownTimeout = configuration.ShutdownTimeoutTimeSpan; - await group.ShutdownGracefullyAsync(quietPeriod, shutdownTimeout); - } - } -}