devin.zhu@doverfs.com 9 місяців тому
коміт
1ea8ec3f13
29 змінених файлів з 1909 додано та 0 видалено
  1. 63 0
      .gitattributes
  2. 402 0
      .gitignore
  3. 20 0
      Ai.AgentServer/Ai.AgentServer.csproj
  4. 6 0
      Ai.AgentServer/Ai.AgentServer.http
  5. 37 0
      Ai.AgentServer/Ai.AgentServer.sln
  6. 123 0
      Ai.AgentServer/Controllers/FccController.cs
  7. 33 0
      Ai.AgentServer/Controllers/WeatherForecastController.cs
  8. 74 0
      Ai.AgentServer/MQTTSetup.cs
  9. 48 0
      Ai.AgentServer/Program.cs
  10. 41 0
      Ai.AgentServer/Properties/launchSettings.json
  11. 82 0
      Ai.AgentServer/Server/CommonMessageHandle.cs
  12. BIN
      Ai.AgentServer/Server/FuelDto.rar
  13. 34 0
      Ai.AgentServer/Server/FuelDto/FuelCommRequest.cs
  14. 89 0
      Ai.AgentServer/Server/FuelDto/FuelReponse.cs
  15. 111 0
      Ai.AgentServer/Server/FuelDto/FuelSendRequest.cs
  16. 118 0
      Ai.AgentServer/Server/FuelDto/HttpThirdRequest.cs
  17. 36 0
      Ai.AgentServer/Server/FuelDto/MqttMessageDto.cs
  18. 29 0
      Ai.AgentServer/Server/FuelDto/MqttRequestDto.cs
  19. 47 0
      Ai.AgentServer/Server/HttpServer.cs
  20. 9 0
      Ai.AgentServer/Server/IHttpServer.cs
  21. 9 0
      Ai.AgentServer/Server/IMqttServer.cs
  22. 58 0
      Ai.AgentServer/Server/MqttServer.cs
  23. 36 0
      Ai.AgentServer/Server/Mqtt_Ext/IMqttClientManager.cs
  24. 75 0
      Ai.AgentServer/Server/Mqtt_Ext/MqttClientConfig.cs
  25. 157 0
      Ai.AgentServer/Server/Mqtt_Ext/MqttClientManager.cs
  26. 131 0
      Ai.AgentServer/Server/Mqtt_Ext/MqttClientService.cs
  27. 13 0
      Ai.AgentServer/WeatherForecast.cs
  28. 8 0
      Ai.AgentServer/appsettings.Development.json
  29. 20 0
      Ai.AgentServer/appsettings.json

+ 63 - 0
.gitattributes

@@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs     diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following 
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln       merge=binary
+#*.csproj    merge=binary
+#*.vbproj    merge=binary
+#*.vcxproj   merge=binary
+#*.vcproj    merge=binary
+#*.dbproj    merge=binary
+#*.fsproj    merge=binary
+#*.lsproj    merge=binary
+#*.wixproj   merge=binary
+#*.modelproj merge=binary
+#*.sqlproj   merge=binary
+#*.wwaproj   merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg   binary
+#*.png   binary
+#*.gif   binary
+
+###############################################################################
+# diff behavior for common document formats
+# 
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the 
+# entries below.
+###############################################################################
+#*.doc   diff=astextplain
+#*.DOC   diff=astextplain
+#*.docx  diff=astextplain
+#*.DOCX  diff=astextplain
+#*.dot   diff=astextplain
+#*.DOT   diff=astextplain
+#*.pdf   diff=astextplain
+#*.PDF   diff=astextplain
+#*.rtf   diff=astextplain
+#*.RTF   diff=astextplain

+ 402 - 0
.gitignore

@@ -0,0 +1,402 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Ww][Ii][Nn]32/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# ASP.NET Scaffolding
+ScaffoldingReadMe.txt
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.tlog
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Coverlet is a free, cross platform Code Coverage Tool
+coverage*.json
+coverage*.xml
+coverage*.info
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio 6 auto-generated project file (contains which files were open etc.)
+*.vbp
+
+# Visual Studio 6 workspace and project file (working project files containing files to include in project)
+*.dsw
+*.dsp
+
+# Visual Studio 6 technical files
+*.ncb
+*.aps
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# Visual Studio History (VSHistory) files
+.vshistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+# Fody - auto-generated XML schema
+FodyWeavers.xsd
+
+# VS Code files for those working on multiple tools
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+*.code-workspace
+
+# Local History for Visual Studio Code
+.history/
+
+# Windows Installer files from build outputs
+*.cab
+*.msi
+*.msix
+*.msm
+*.msp
+
+# JetBrains Rider
+*.sln.iml
+
+**/wwwroot/upload
+/Dfs.IMes.sln
+/PcClient/protools/SerialPort

+ 20 - 0
Ai.AgentServer/Ai.AgentServer.csproj

@@ -0,0 +1,20 @@
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+  <PropertyGroup>
+    <TargetFramework>net8.0</TargetFramework>
+    <Nullable>enable</Nullable>
+    <ImplicitUsings>enable</ImplicitUsings>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="AutoMapper" Version="13.0.1" />
+    <PackageReference Include="MQTTnet" Version="4.3.6.1152" />
+    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
+    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <Folder Include="Server\Impl\" />
+  </ItemGroup>
+
+</Project>

+ 6 - 0
Ai.AgentServer/Ai.AgentServer.http

@@ -0,0 +1,6 @@
+@Ai.AgentServer_HostAddress = http://localhost:5169
+
+GET {{Ai.AgentServer_HostAddress}}/weatherforecast/
+Accept: application/json
+
+###

+ 37 - 0
Ai.AgentServer/Ai.AgentServer.sln

@@ -0,0 +1,37 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.8.34601.278
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ai.AgentServer", "Ai.AgentServer.csproj", "{6AEF0967-D649-41FA-BA7A-88FB5539CB45}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleMQTT", "C:\Users\11047158\Downloads\SimpleMQTT-master\SimpleMQTT-master\SimpleMQTT\SimpleMQTT.csproj", "{67B8C5EE-FC91-4683-B474-274B5FCE703F}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTClient", "..\MQTTClient\MQTTClient.csproj", "{5F0DCC50-9CD6-45DB-A6C6-E944B0EBED42}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{6AEF0967-D649-41FA-BA7A-88FB5539CB45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{6AEF0967-D649-41FA-BA7A-88FB5539CB45}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{6AEF0967-D649-41FA-BA7A-88FB5539CB45}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{6AEF0967-D649-41FA-BA7A-88FB5539CB45}.Release|Any CPU.Build.0 = Release|Any CPU
+		{67B8C5EE-FC91-4683-B474-274B5FCE703F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{67B8C5EE-FC91-4683-B474-274B5FCE703F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{67B8C5EE-FC91-4683-B474-274B5FCE703F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{67B8C5EE-FC91-4683-B474-274B5FCE703F}.Release|Any CPU.Build.0 = Release|Any CPU
+		{5F0DCC50-9CD6-45DB-A6C6-E944B0EBED42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{5F0DCC50-9CD6-45DB-A6C6-E944B0EBED42}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{5F0DCC50-9CD6-45DB-A6C6-E944B0EBED42}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{5F0DCC50-9CD6-45DB-A6C6-E944B0EBED42}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {1ED44320-B53A-445C-8AFB-3600766D8AC6}
+	EndGlobalSection
+EndGlobal

+ 123 - 0
Ai.AgentServer/Controllers/FccController.cs

@@ -0,0 +1,123 @@
+using Ai.AgentServer.Server;
+using Ai.AgentServer.Server.Fuel;
+using Microsoft.AspNetCore.Mvc;
+using MQTTnet.Client;
+using Newtonsoft.Json;
+
+namespace Ai.AgentServer.Controllers
+{
+    [ApiController]
+    [Route("[controller]")]
+    public class FCCController : ControllerBase
+    {
+        private static readonly string[] Summaries = new[]
+        {
+            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
+        };
+
+        private readonly ILogger<WeatherForecastController> _logger;
+
+        private readonly IHttpServer _server;
+
+        private readonly IMqttServer _mqttServer;
+
+        public FCCController(ILogger<WeatherForecastController> logger, IHttpServer httpServer, IMqttServer mqttServer)
+        {
+            _logger = logger;
+            _server = httpServer;
+            _mqttServer = mqttServer;
+        }
+
+        /// <summary>
+        /// 油机命令传输
+        /// </summary>
+        /// <returns></returns>
+        [HttpPost(Name = "FuelCommon")]
+        public async Task<FuelReponse> SendCommon(FuelSendRequest body,bool test=false)
+        {
+            if (string.IsNullOrWhiteSpace(body.Type))
+            {
+                return new FuelReponse(5001, "Type不能为空", body);
+            }
+            //讯飞调用
+            var reponse=await _server.SendCommon(body);
+
+            //格灵调用
+            await _mqttServer.PublicMessage(body.AIId,body.Type, body.BuildDto());
+
+            return reponse;
+        }
+
+        /// <summary>
+        /// 油机命令传输
+        /// </summary>
+        /// <returns></returns>
+        [HttpGet(Name = "Init")]
+        public Task Init()
+        {
+            var client = new MqttClientService();
+            client.MqttClientStart();
+            return Task.CompletedTask;
+        }
+
+
+
+
+
+        /// <summary>
+        /// mqtt test public
+        /// </summary>
+        /// <param name="message"></param>
+        /// <param name="topic"></param>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        [HttpPost("testMqttpub")]
+        public Task<string> MqttPublic(string message, string topic, string key)
+        {
+            if (string.IsNullOrEmpty(key) || key != "tktest")
+            {
+                return Task.FromResult("key is error");
+            }
+            try
+            {
+                MqttClientService._mqttClient.PublishStringAsync(topic, message).Wait();
+            }
+            catch (Exception ex)
+            {
+                return Task.FromResult($"message is error : {ex.Message}"); ;
+            }
+            return Task.FromResult("message is success public"); ;
+        }
+
+
+        /// <summary>
+        /// mqtt test Sub
+        /// </summary>
+        /// <
+        /// <param name="topic"></param>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        [HttpPost("testtSub")]
+        public Task<string> MqttSub(string topic, string key)
+        {
+            if (string.IsNullOrEmpty(key) || key != "tksubtest")
+            {
+                return Task.FromResult("key is error");
+            }
+            try
+            {
+                MqttClientService._mqttClient.SubscribeAsync(topic).Wait();
+            }
+            catch (Exception ex)
+            {
+                return Task.FromResult($"topic is error : {ex.Message}"); ;
+            }
+            return Task.FromResult("topic is success MqttSub"); ;
+        }
+
+
+
+
+
+    }
+}

+ 33 - 0
Ai.AgentServer/Controllers/WeatherForecastController.cs

@@ -0,0 +1,33 @@
+using Microsoft.AspNetCore.Mvc;
+
+namespace Ai.AgentServer.Controllers
+{
+    [ApiController]
+    [Route("[controller]")]
+    public class WeatherForecastController : ControllerBase
+    {
+        private static readonly string[] Summaries = new[]
+        {
+            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
+        };
+
+        private readonly ILogger<WeatherForecastController> _logger;
+
+        public WeatherForecastController(ILogger<WeatherForecastController> logger)
+        {
+            _logger = logger;
+        }
+
+        [HttpGet(Name = "GetWeatherForecast")]
+        public IEnumerable<WeatherForecast> Get()
+        {
+            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
+            {
+                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
+                TemperatureC = Random.Shared.Next(-20, 55),
+                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
+            })
+            .ToArray();
+        }
+    }
+}

+ 74 - 0
Ai.AgentServer/MQTTSetup.cs

@@ -0,0 +1,74 @@
+//using Ai.AgentServer.Server.Mqtt_Ext;
+
+//namespace Ai.AgentServer
+//{
+//    /// <summary>
+//    /// Mqtt客户端扩展类
+//    /// </summary>
+//    public static class MQTTSetup
+//    {
+//        /// <summary>
+//        /// 添加Mqtt客户端服务
+//        /// </summary>
+//        /// <param name="services"></param>
+//        /// <exception cref="ArgumentNullException"></exception>
+//        public static void AddMqttClientManager(this IServiceCollection services)
+//        {
+//            if (services == null) throw new ArgumentNullException(nameof(services));
+//            //services.AddSingleton<IMqttClientManager, MqttClientManager>();
+//        }
+
+//        /// <summary>
+//        /// 添加Mqtt客户端服务
+//        /// </summary>
+//        /// <param name="services"></param>
+//        /// <param name="configuration">IConfiguration</param>
+//        /// <param name="section">配置文件节点</param>
+//        /// <param name="start">立即启动</param>
+//        /// <exception cref="ArgumentNullException"></exception>
+//        public static void AddMqttClientManager(this IServiceCollection services, IConfiguration configuration, string section = "MqttSettings", bool start = true)
+//        {
+//            if (services == null) throw new ArgumentNullException(nameof(services));
+//            MqttClientConfig config = configuration.GetSection(section).Get<MqttClientConfig>();//获取配置配置
+//            if (config != null && !string.IsNullOrEmpty(config.Host))
+//            {
+//                services.AddSingleton<IMqttClientManager, MqttClientManager>(x => new MqttClientManager(config, start));
+//            }
+//            else
+//            {
+//                List<MqttClientConfig> configs = configuration.GetSection(section).Get<List<MqttClientConfig>>();//获取配置配置
+//                if (configs == null) throw new ArgumentException("mqtt配置未找到,请配置mqtt链接信息", nameof(configuration));
+//                services.AddSingleton<IMqttClientManager, MqttClientManager>(x => new MqttClientManager(configs, start));
+//            }
+
+//        }
+
+//        /// <summary>
+//        /// 添加Mqtt客户端服务
+//        /// </summary>
+//        /// <param name="services"></param>
+//        /// <param name="config">mqtt配置</param>
+//        /// <param name="start">立即启动</param>
+//        /// <exception cref="ArgumentNullException"></exception>
+//        public static void AddMqttClientManager(this IServiceCollection services, MqttClientConfig config, bool start = true)
+//        {
+
+//            if (services == null) throw new ArgumentNullException(nameof(services));
+//            services.AddSingleton<IMqttClientManager, MqttClientManager>(x => new MqttClientManager(config, start));
+//        }
+
+//        /// <summary>
+//        /// 添加Mqtt客户端服务
+//        /// </summary>
+//        /// <param name="services"></param>
+//        /// <param name="configs">mqtt配置</param>
+//        /// <param name="start">立即启动</param>
+//        /// <exception cref="ArgumentNullException"></exception>
+//        public static void AddMqttClientManager(this IServiceCollection services, List<MqttClientConfig> configs, bool start = true)
+//        {
+//            if (services == null) throw new ArgumentNullException(nameof(services));
+//            services.AddSingleton<IMqttClientManager, MqttClientManager>(x => new MqttClientManager(configs, start));
+//        }
+
+//    }
+//}

+ 48 - 0
Ai.AgentServer/Program.cs

@@ -0,0 +1,48 @@
+using Ai.AgentServer;
+using Ai.AgentServer.Server;
+using Ai.AgentServer.Server.Mqtt_Ext;
+
+var builder = WebApplication.CreateBuilder(args);
+
+// Add services to the container.
+
+builder.Services.AddControllers();
+// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
+builder.Services.AddEndpointsApiExplorer();
+builder.Services.AddSwaggerGen();
+
+var config= builder.Configuration.GetSection("MqttSettings").Get<MqttClientConfig>();
+builder.Services.AddHttpClient();
+//Ìí¼ÓMQTTÅäÖÃ
+//builder.Services.AddMqttClientManager();
+//new MqttClientManager(builder.Configuration);
+builder.Services.AddTransient<IHttpServer,HttpServer>();
+builder.Services.AddTransient<IMqttServer, MqttServer>();
+var app = builder.Build();
+
+// Configure the HTTP request pipeline.
+if (app.Environment.IsDevelopment())
+{
+    app.UseSwagger();
+    app.UseSwaggerUI();
+}
+
+app.UseHttpsRedirection();
+
+app.UseAuthorization();
+
+app.MapControllers();
+
+
+
+//var mqttClientManager = builder.Services.BuildServiceProvider().GetService<IMqttClientManager>();
+//var mqttClient = mqttClientManager.GetClient();
+//var rt = await mqttClient.SubscribeAsync("/ToServer/34322113", (e) =>
+//{
+//    Console.WriteLine("sub:" + "/ToServer/34322113 =>" + e.Topic + ":" + e.Payload.ToStr());
+//});
+var client = new MqttClientService();
+client.MqttClientStart(config);
+CommonMessageHandle.init(builder.Configuration.GetSection("Sysurl").ToString());
+
+app.Run();

+ 41 - 0
Ai.AgentServer/Properties/launchSettings.json

@@ -0,0 +1,41 @@
+{
+  "$schema": "http://json.schemastore.org/launchsettings.json",
+  "iisSettings": {
+    "windowsAuthentication": false,
+    "anonymousAuthentication": true,
+    "iisExpress": {
+      "applicationUrl": "http://localhost:34962",
+      "sslPort": 44352
+    }
+  },
+  "profiles": {
+    "http": {
+      "commandName": "Project",
+      "dotnetRunMessages": true,
+      "launchBrowser": true,
+      "launchUrl": "swagger",
+      "applicationUrl": "http://localhost:5169",
+      "environmentVariables": {
+        "ASPNETCORE_ENVIRONMENT": "Development"
+      }
+    },
+    "https": {
+      "commandName": "Project",
+      "dotnetRunMessages": true,
+      "launchBrowser": true,
+      "launchUrl": "swagger",
+      "applicationUrl": "https://localhost:7171;http://localhost:5169",
+      "environmentVariables": {
+        "ASPNETCORE_ENVIRONMENT": "Development"
+      }
+    },
+    "IIS Express": {
+      "commandName": "IISExpress",
+      "launchBrowser": true,
+      "launchUrl": "swagger",
+      "environmentVariables": {
+        "ASPNETCORE_ENVIRONMENT": "Development"
+      }
+    }
+  }
+}

+ 82 - 0
Ai.AgentServer/Server/CommonMessageHandle.cs

@@ -0,0 +1,82 @@
+using Ai.AgentServer.Server.Fuel;
+using Ai.AgentServer.Server.FuelDto;
+using AutoMapper;
+using Newtonsoft.Json;
+using System.Text;
+
+namespace Ai.AgentServer.Server
+{
+    /// <summary>
+    /// 订阅的消息处理
+    /// </summary>
+    public class CommonMessageHandle
+    {
+        public static string Sysurl;
+
+        public static void init(string url)
+        {
+            Sysurl = url;
+        }
+
+
+
+        /// <summary>
+        /// 处理消息
+        /// </summary>
+        /// <param name="topic"></param>
+        /// <param name="message"></param>
+        public static void Handle(string topic, string message)
+        {
+            try
+            {
+                //获取对应的设备id,加油机id
+                string deviceId = topic.Split('/').LastOrDefault();
+                var messageDto = JsonConvert.DeserializeObject<MqttReceveMessageDto>(message);
+                Console.WriteLine($"handlie message: {message}");
+                if (messageDto != null && messageDto.msgID > 0)
+                {
+                    switch (messageDto.msgID)
+                    {
+                        case 10000:
+                            LockNozzle(deviceId, messageDto);
+                            break;
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine(ex.Message);
+            }
+
+        }
+
+        /// <summary>
+        /// 调用油机锁枪
+        /// </summary>
+        /// <param name="deviceId"></param>
+        /// <param name="mqttMessageDto"></param>
+        /// <returns></returns>
+        public static bool LockNozzle(string deviceId, MqttReceveMessageDto mqttMessageDto)
+        {
+            using (var httpclient = new HttpClient())
+            {
+                httpclient.BaseAddress = new Uri(Sysurl);
+                var request = new FuelCommRequest();
+                request.GLid = deviceId;
+                request.NozzleNo = mqttMessageDto.data.nozzleNum;
+                try
+                {
+                    Console.WriteLine($"LockNozzle HttpClient: {Sysurl}");
+                    httpclient.PostAsync($"/nozzles/lock", new StringContent(JsonConvert.SerializeObject(mqttMessageDto), Encoding.UTF8, "application/json")).Wait();
+                
+                }
+                catch (Exception ex)
+                {
+                    Console.WriteLine($"LockNozzle error:{ex.Message}");
+                    return false;
+                }
+                return true;
+            }
+        }
+    }
+}

BIN
Ai.AgentServer/Server/FuelDto.rar


+ 34 - 0
Ai.AgentServer/Server/FuelDto/FuelCommRequest.cs

@@ -0,0 +1,34 @@
+namespace Ai.AgentServer.Server.Fuel
+{
+    /// <summary>
+    /// 油机执行命令参数
+    /// </summary>
+    public class FuelCommRequest
+    {
+        /// <summary>
+        /// 
+        /// </summary>
+        public string AIid { get; set; }
+
+        /// <summary>
+        /// 
+        /// </summary>
+        public string GLid { get; set; }
+
+        /// <summary>
+        /// 命令类型
+        /// NozzleNo_stop,
+        /// </summary>
+        public string Type { get; set; } = "NozzleNo_Stop";
+
+        /// <summary>
+        /// 枪号
+        /// </summary>
+        public int NozzleNo { get; set; }
+
+        public FuelCommRequest()
+        {
+           
+        }
+    }
+}

+ 89 - 0
Ai.AgentServer/Server/FuelDto/FuelReponse.cs

@@ -0,0 +1,89 @@
+namespace Ai.AgentServer.Server.Fuel
+{
+
+    /// <summary>
+    /// 响应结构
+    /// </summary>
+    public class FuelReponse
+    {
+        public int Code { get; set; }
+        public string Message { get; set; }
+        public Data Data { get; set; }
+        public string Type { get; set; }
+
+        /// <summary>
+        /// 讯飞AIID
+        /// </summary>
+        public string AiId { get; set; }
+
+        /// <summary>
+        /// 格灵深瞳ID
+        /// </summary>
+        public string GLId { get; set; }
+
+        public bool MQTT_Public { get; set; }
+
+        /// <summary>
+        /// 给响应结构赋值应用id 和 命令类型
+        /// </summary>
+        /// <param name="request"></param>
+        public FuelReponse SetID(FuelSendRequest request)
+        {
+            AiId = request.AIId;
+            GLId = request.GLId;
+            Type = request.Type;
+            return this;
+        }
+
+
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <param name="code"></param>
+        /// <param name="request"></param>
+        public FuelReponse(int code, FuelSendRequest request)
+        {
+            AiId = request.AIId;
+            GLId = request.GLId;
+            Type = request.Type;
+            Code = code;
+        }
+
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <param name="code"></param>
+        /// <param name="request"></param>
+        public FuelReponse(int code,string message, FuelSendRequest request)
+        {
+            AiId = request.AIId;
+            GLId = request.GLId;
+            Type = request.Type;
+            Code = code;
+            message = message;
+        }
+    }
+
+    /// <summary>
+    /// 
+    /// </summary>
+    public class Data
+    {
+        /// <summary>
+        ///   //定量加油金额 如是0 标识不定量
+        /// </summary>
+        public string OilAmount { get; set; }
+
+        /// <summary>
+        ///  //定量加油升数,如是0 标识不定量
+        /// </summary>
+        public string OilLiters { get; set; }
+
+        /// <summary>
+        /// 车牌号
+        /// </summary>
+        public string LicensePlate { get; set; }
+    }
+}
+
+

+ 111 - 0
Ai.AgentServer/Server/FuelDto/FuelSendRequest.cs

@@ -0,0 +1,111 @@
+using Ai.AgentServer.Server.FuelDto;
+
+namespace Ai.AgentServer.Server.Fuel
+{
+    public class FuelSendRequest
+    {
+        /// <summary>
+        /// 指令
+        /// </summary>
+        public string Type { get; set; }
+
+        /// <summary>
+        /// 加油机id
+        /// </summary>
+        public string ClientId { get; set; }
+
+        /// <summary>
+        /// Aiid
+        /// </summary>
+        public string AIId { get; set; }
+
+        /// <summary>
+        /// 格林id
+        /// </summary>
+        public string GLId { get; set; }
+
+        /// <summary>
+        /// 油枪
+        /// </summary>
+        public int NozzleNo { get; set; }
+
+        /// <summary>
+        /// 油品编码
+        /// </summary>
+        public string OilCode { get; set; }
+
+        /// <summary>
+        /// 卡余额
+        /// </summary>
+        public decimal Balance { get; set; }
+
+        /// <summary>
+        /// 最大的可加金额
+        /// </summary>
+        public decimal MaxRefuelingAmount { get; set; }
+
+        /// <summary>
+        ///  // 0 验证码加油方式或卡类型无效;   1 司机卡; //4 员工卡;// 5  验泵卡;6 维修卡    
+        /// </summary>
+        public int CardType { get; set; }
+
+        /// <summary>
+        /// 金额
+        /// </summary>
+        public decimal Amount { get; set; }
+
+        /// <summary>
+        /// 加油体积
+        /// </summary>
+        public decimal Vol { get; set; }
+
+        /// <summary>
+        ///  "1"   // 车牌匹配标记 "1" 匹配  "0"不匹配   "2"不是限车号卡
+        /// </summary>
+        public int LicensePlateMatching { get; set; }
+
+
+
+        /// <summary>
+        /// 转成讯飞的文档实体对象   or 格灵深瞳的实体对象
+        /// </summary>
+        /// <param name="idType">应用id 赋值,1是讯飞,</param>
+        /// <returns></returns>
+        public HttpThirdRequest BuildDto(int idType=1) {
+            var dto= new HttpThirdRequest {
+                userId = idType ==1?AIId:GLId,
+                textInput=new  Textinput()
+            };
+            dto.textInput.type = Type;
+            switch (Type) {
+                case "refuel_card_refund":
+                    dto.textInput.payload = new Refuel_card_refund() { 
+                        CardType = CardType,
+                        OilCode = OilCode,
+                        Balance=Balance,
+                        MaxRefuelingAmount=MaxRefuelingAmount,
+                        NozzleNo= NozzleNo
+                    };
+                    break;
+                case "refuel_card_send_license_plate_match":
+                   
+                        dto.textInput.payload = new Refuel_card_send_license_plate_match()
+                        {
+                            CardType = CardType,
+                            OilCode = OilCode,
+                            LicensePlateMatching = LicensePlateMatching,
+                            NozzleNo = NozzleNo
+                        };
+           
+                    break;
+                case "fuelSend":
+                    dto.textInput.payload = new CardPayload(cardType: CardType, oilCode: OilCode, nozzleNo: NozzleNo);
+                    break;
+                default:
+                    dto.textInput.payload = new CardPayload(cardType: CardType, oilCode: OilCode, nozzleNo: NozzleNo);
+                    break;
+            }
+            return dto;
+        }
+    }
+}

+ 118 - 0
Ai.AgentServer/Server/FuelDto/HttpThirdRequest.cs

@@ -0,0 +1,118 @@
+namespace Ai.AgentServer.Server.FuelDto
+{
+
+    /// <summary>
+    /// http请求
+    /// </summary>
+    public class HttpThirdRequest
+    {
+        public string callId { get; set; } = new Guid().ToString();
+        public int inType { get; set; } = 2;
+        public Textinput textInput { get; set; }
+        public string useType { get; set; } = "virtual";
+
+        /// <summary>
+        /// 通讯id
+        /// </summary>
+        public string userId { get; set; }
+    }
+
+    public class Textinput
+    {
+        public Object payload { get; set; }
+        public string type { get; set; }
+    }
+
+
+    /// <summary>
+    /// 卡片的
+    /// </summary>
+    public class CardPayload
+    {
+        /// <summary>
+        ///   // 0 验证码加油方式或卡类型无效; 1 司机卡; 4 员工卡; 5 验泵卡;6 维修卡
+        /// </summary>
+        public int CardType { get; set; }
+
+        /// <summary>
+        ///油品信息 
+        /// </summary>
+        public string OilCode { get; set; }
+
+        /// <summary>
+        ///   //卡余额
+        /// </summary>
+        public int NozzleNo { get; set; }
+
+        public CardPayload(int cardType, string oilCode, int nozzleNo)
+        {
+            CardType = cardType;
+            OilCode = oilCode;
+            NozzleNo = nozzleNo;
+        }
+        public CardPayload()
+        {
+
+        }
+    }
+
+
+    /// <summary>
+    /// 油枪归位
+    /// </summary>
+    public class Refuel_out_process : CardPayload
+    {
+        /// <summary>
+        /// 金额
+        /// </summary>
+        public decimal Amount { get; set; }
+
+        /// <summary>
+        /// 升数
+        /// </summary>
+        public decimal Vol { get; set; }
+        /// <summary>
+        ///   卡余额
+        /// </summary>
+        public decimal Balance { get; set; }
+    }
+
+    /// <summary>
+    /// 卡退出
+    /// </summary>
+    public class Refuel_card_refund : CardPayload
+    {
+
+        /// <summary>
+        ///   卡余额
+        /// </summary>
+        public decimal Balance { get; set; }
+
+        /// <summary>
+        ///   最大的可加金额
+        /// </summary>
+        public decimal MaxRefuelingAmount { get; set; }
+    }
+
+    /// <summary>
+    /// 限车号卡车牌匹配结果
+    /// </summary>
+    public class Refuel_card_send_license_plate_match : CardPayload
+    {
+        /// <summary>
+        /// // 车牌匹配标记 "1" 匹配  "0"不匹配   "2"不是限车号卡
+        /// </summary>
+        public int LicensePlateMatching { get; set; }
+    }
+
+    ///// <summary>
+    ///// 一键加油授权
+    ///// </summary>
+    //public class OnePayload
+    //{
+    //    public int CardType { get; set; }
+    //    public string OilCode { get; set; }
+    //    public int nozzleNo { get; set; }
+    //}
+
+}

+ 36 - 0
Ai.AgentServer/Server/FuelDto/MqttMessageDto.cs

@@ -0,0 +1,36 @@
+namespace Ai.AgentServer.Server.FuelDto
+{
+
+
+    /// <summary>
+    /// 发布消息结构体
+    /// </summary>
+    public class MqttMessageDto
+    {
+        public int msgID { get; set; }
+        public string time { get; set; }
+        public object data { get; set; }
+    }
+
+
+
+
+    /// <summary>
+    /// 订阅消息结构体
+    /// </summary>
+    public class MqttReceveMessageDto
+    {
+        public int msgID { get; set; }
+        public string time { get; set; }
+        public MqttData data { get; set; }
+    }
+
+
+    //锁枪
+    public class MqttData
+    {
+        public int nozzleNum { get; set; }
+    }
+    
+
+}

+ 29 - 0
Ai.AgentServer/Server/FuelDto/MqttRequestDto.cs

@@ -0,0 +1,29 @@
+namespace Ai.AgentServer.Server.FuelDto
+{
+    public class MqttRequestDto
+    {
+        /// <summary>
+        /// 消息id   4个整形数字
+        /// 
+        /// </summary>
+        public int MsgId { get; set; }
+
+        /// <summary>
+        /// 时间
+        /// </summary>
+        public string Time { get; set; } = DateTime.Now.ToString("YYYY-MM-DD HH:mm:SS");
+
+        public Object Data { get; set; }
+
+        public MqttRequestDto(int msgId, Object data)
+        {
+            MsgId = msgId;
+            Data = data;
+        }
+
+        public MqttRequestDto()
+        {
+            
+        }
+    }
+}

+ 47 - 0
Ai.AgentServer/Server/HttpServer.cs

@@ -0,0 +1,47 @@
+using Ai.AgentServer.Server.Fuel;
+using Newtonsoft.Json;
+using System.Text;
+
+namespace Ai.AgentServer.Server
+{
+    public class HttpServer: IHttpServer
+    {
+        public IHttpClientFactory _httpClientFactory;
+        public HttpServer(IHttpClientFactory httpClientFactory)
+        {
+            _httpClientFactory=httpClientFactory;
+        }
+
+
+        /// <summary>
+        ///  讯飞通讯
+        /// </summary>
+        /// <param name="url"></param>
+        /// <returns></returns>
+        public async Task<FuelReponse> SendCommon(FuelSendRequest request)
+        {
+            if (request == null||string.IsNullOrWhiteSpace(request.Type)) return new FuelReponse(5001, request);
+            var client = _httpClientFactory.CreateClient("FuelClient");
+            //配置文件读取
+            client.BaseAddress =new Uri("http://211.91.71.15:8899");
+            var requesStr = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
+            try
+            {
+                var response = await _httpClientFactory.CreateClient("FuelClient").PostAsync("/app-control-center/app/manualDrive", requesStr);
+                if (response != null && response.IsSuccessStatusCode)
+                {
+                    Console.WriteLine("Success");
+                    var fuelreponse = JsonConvert.DeserializeObject<FuelReponse>(await response.Content.ReadAsStringAsync());
+                    return fuelreponse.SetID(request);
+                }
+              
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine(ex.Message);
+                return new FuelReponse(5001, request);
+            }
+            return new FuelReponse(5000, request);
+        }
+    }
+}

+ 9 - 0
Ai.AgentServer/Server/IHttpServer.cs

@@ -0,0 +1,9 @@
+using Ai.AgentServer.Server.Fuel;
+
+namespace Ai.AgentServer.Server
+{
+    public interface IHttpServer
+    {
+        Task<FuelReponse> SendCommon(FuelSendRequest request);
+    }
+}

+ 9 - 0
Ai.AgentServer/Server/IMqttServer.cs

@@ -0,0 +1,9 @@
+using Ai.AgentServer.Server.FuelDto;
+
+namespace Ai.AgentServer.Server
+{
+    public interface IMqttServer
+    {
+        Task<bool> PublicMessage(string topic, string type, HttpThirdRequest request);
+    }
+}

+ 58 - 0
Ai.AgentServer/Server/MqttServer.cs

@@ -0,0 +1,58 @@
+using Ai.AgentServer.Server.Fuel;
+using Ai.AgentServer.Server.FuelDto;
+using MQTTnet.Client;
+using Newtonsoft.Json;
+
+namespace Ai.AgentServer.Server
+{
+    /// <summary>
+    /// 格灵mq
+    /// </summary>
+    public class MqttServer: IMqttServer
+    {
+     
+        public MqttServer( )
+        {
+            
+        }
+
+
+        public Task<bool> PublicMessage(string topic,string type, HttpThirdRequest request)
+        {
+            //暂时指传递交易上传的类型数据  && type!= "refuel_out_process"
+            if (string.IsNullOrEmpty(type)) {
+                Console.WriteLine($"type{type}命令不能为空 {DateTime.Now}");
+                return Task.FromResult(false);
+            }
+
+            var requestDto= new MqttRequestDto();
+            requestDto.MsgId = 10001;
+            //switch (type)
+            //{
+            //    //交易数据上传
+            //    case "refuel_out_process":
+            //        requestDto.MsgId = 10001;
+            //        break;
+            //    ////交易数据上传
+            //    //case "refuel_out_process":
+            //    //    requestDto.MsgId = 10001;
+            //    //    break;
+            //    default:
+            //        Console.WriteLine($"type命令匹配不到");
+            //        return Task.FromResult(false);
+            //        break;
+            //}
+            try
+            {
+                requestDto.Data = request;
+                MqttClientService._mqttClient.PublishStringAsync($"/ToServer/{topic}", JsonConvert.SerializeObject(requestDto));
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine(ex.Message);
+                return Task.FromResult(false);
+            }
+            return Task.FromResult(true);
+        }
+    }
+}

+ 36 - 0
Ai.AgentServer/Server/Mqtt_Ext/IMqttClientManager.cs

@@ -0,0 +1,36 @@
+//using NewLife.MQTT;
+
+//namespace Ai.AgentServer.Server.Mqtt_Ext
+//{
+//    /// <summary>
+//    /// MQTT客户端服务
+//    /// </summary>
+//    public interface IMqttClientManager
+//    {
+//        /// <summary>
+//        /// 添加mqtt客户端
+//        /// </summary>
+//        /// <param name="config">配置信息</param>
+//        void AddClient(MqttClientConfig config);
+
+//        /// <summary>
+//        /// 获取mqtt客户端
+//        /// </summary>
+//        /// <param name="name">客户端名称</param>
+//        /// <returns></returns>
+//        MqttClient GetClient(string name = "Mqtt");
+
+//        /// <summary>
+//        /// 获取所有客户端
+//        /// </summary>
+//        /// <returns></returns>
+//        List<MqttClient> GetClients();
+
+//        /// <summary>
+//        /// 启动Mqtt客户端
+//        /// </summary>
+//        /// <param name="name">客户端名称</param>
+//        /// <returns></returns>
+//        bool StartClient(string name = "Mqtt");
+//    }
+//}

+ 75 - 0
Ai.AgentServer/Server/Mqtt_Ext/MqttClientConfig.cs

@@ -0,0 +1,75 @@
+namespace Ai.AgentServer.Server.Mqtt_Ext
+{
+    /// <summary>
+    /// mqtt客户端配置
+    /// </summary>
+    public class MqttClientConfig
+    {
+        public MqttClientConfig()
+        {
+
+        }
+
+        /// <summary>
+        /// 客户端名称
+        /// </summary>
+        public string Name { get; set; } = "Mqtt";
+
+        /// <summary>
+        /// 主机地址
+        /// </summary>
+        public string Host { get; set; }
+
+        /// <summary>
+        /// 端口
+        /// </summary>
+        public int Port { get; set; }
+
+
+        /// <summary>
+        /// 订阅的设备号用 ,逗号分隔
+        /// </summary>
+        public string SubClients { get; set; }
+
+
+        /// <summary>
+        /// 用户名
+        /// </summary>
+        public string UserName { get; set; }
+
+        /// <summary>
+        /// 秘钥
+        ///// </summary>
+        public string SecretKey { get; set; }
+
+        /// <summary>
+        /// 客户端ID
+        /// </summary>
+        public string ClientId { get; set; }
+
+        /// <summary>
+        /// 心跳
+        /// </summary>
+        public int KeepAlive { get; set; } = 60;
+
+        /// <summary>
+        /// 是否自动重连,默认True
+        /// </summary>
+        public bool Reconnect { get; set; } = true;
+
+        /// <summary>
+        /// 是否清除会话,默认True
+        /// </summary>
+        public bool CleanSession { get; set; } = true;
+
+        /// <summary>
+        /// 超时。默认15000ms
+        /// </summary>
+        public int Timeout { get; set; } = 15000;
+
+        /// <summary>
+        /// 是否进行SSL连接
+        /// </summary>
+        public bool UseSSL { get; set; } = false;
+    }
+}

+ 157 - 0
Ai.AgentServer/Server/Mqtt_Ext/MqttClientManager.cs

@@ -0,0 +1,157 @@
+//using NewLife.MQTT;
+//using System.Security.Authentication;
+
+//namespace Ai.AgentServer.Server.Mqtt_Ext
+//{
+//    /// <summary>
+//    /// <inheritdoc cref="IMqttClientManager"/>
+//    /// </summary>
+//    public class MqttClientManager : IMqttClientManager
+//    {
+//        /// <summary>
+//        /// mqtt对象列表
+//        /// </summary>
+//        private List<MqttClient> MqttClients = new List<MqttClient>();
+
+//        public MqttClientManager(IConfiguration configuration)
+//        {
+//            MqttClientConfig config = configuration.GetSection("MqttSettings").Get<MqttClientConfig>();//获取配置配置
+//            if (config != null && !string.IsNullOrEmpty(config.Host))
+//            {
+//                //如果配置不是空则创建连接
+//                AddClient(config);
+//                StartClient(config.Name);
+//            }
+//            else
+//            {
+//                //配置是空,试试是不是多个客户端配置
+//                List<MqttClientConfig> configs = configuration.GetSection("MqttSettings").Get<List<MqttClientConfig>>();//获取配置配置
+//                if (configs != null)
+//                {
+//                    //如果不为空,创建连接
+//                    configs.ForEach(it =>
+//                    {
+//                        AddClient(it);
+//                        StartClient(it.Name);
+//                    });
+//                }
+//                else
+//                {
+//                    throw new ArgumentException("mqtt配置未找到,请配置mqtt链接信息", nameof(config));
+//                }
+//            }
+//        }
+
+//        public MqttClientManager(MqttClientConfig config, bool start = false)
+//        {
+//            //如果配置不是空则创建连接
+//            AddClient(config);
+//            if (start)
+//                StartClient(config.Name);
+//        }
+
+//        public MqttClientManager(List<MqttClientConfig> configs, bool start = false)
+//        {
+//            //如果不为空,创建连接
+//            configs.ForEach(it =>
+//            {
+//                AddClient(it);
+//                if (start)
+//                    StartClient(it.Name);
+//            });
+//        }
+
+
+//        /// <inheritdoc/>
+//        public void AddClient(MqttClientConfig config)
+//        {
+//            if (!string.IsNullOrEmpty(config.Host))
+//            {
+//                if (MqttClients.Any(it => it.Name == config.Name))
+//                    throw new ArgumentException("mqtt配置错误,Name属性唯一", nameof(config));
+//                var client = new MqttClient
+//                {
+//                    Server = $"tcp://{config.Host}:{config.Port}",
+//                    Name = config.Name,
+//                    UserName = config.UserName,
+//                    Password = config.SecretKey,
+//                    ClientId = config.ClientId,
+//                    KeepAlive = config.KeepAlive,
+//                    Reconnect = config.Reconnect,
+//                    CleanSession = config.CleanSession,
+//                    Timeout = config.Timeout,
+//                    SslProtocol = config.UseSSL ? SslProtocols.Tls13 : SslProtocols.None,
+
+//                };
+//                client.Connected += MqttClient_Connected;
+//                client.Disconnected += MqttClient_Disconnected;
+//                MqttClients.Add(client);
+//            }
+//            else
+//            {
+//                throw new ArgumentException("mqtt配置错误,请配置mqtt链接信息", nameof(config));
+//            }
+
+
+//        }
+
+
+//        /// <inheritdoc/>
+//        public bool StartClient(string name = "Mqtt")
+//        {
+//            //获取mqtt连接
+//            var client = MqttClients.Where(it => it.Name == name).FirstOrDefault();
+//            if (client != null)//获取不为空
+//            {
+//                try
+//                {
+//                    client.ConnectAsync().Wait();//连接服务器
+//                }
+//                catch (Exception ex)
+//                {
+//                    throw ex;
+//                }
+
+//                return client.IsConnected;//返回连接状态
+//            }
+//            else { return false; }
+//        }
+
+
+//        /// <inheritdoc/>
+//        public MqttClient GetClient(string name = "Mqtt")
+//        {
+//            var client = MqttClients.Where(it => it.Name == name).FirstOrDefault();
+//            if (client != null) return client;
+//            else return null;
+//        }
+
+//        /// <inheritdoc/>
+//        public List<MqttClient> GetClients()
+//        {
+//            return MqttClients;
+//        }
+
+//        /// <summary>
+//        /// 断开事件
+//        /// </summary>
+//        /// <param name="sender"></param>
+//        /// <param name="e"></param>
+//        private void MqttClient_Disconnected(object sender, EventArgs e)
+//        {
+//            var client = ((MqttClient)sender);
+//            Console.WriteLine($"已断开{client.Name}服务端!:" + DateTime.Now);
+//        }
+
+//        /// <summary>
+//        /// 连接事件
+//        /// </summary>
+//        /// <param name="sender"></param>
+//        /// <param name="e"></param>
+//        private void MqttClient_Connected(object sender, EventArgs e)
+//        {
+//            var client = ((MqttClient)sender);
+//            Console.WriteLine($"已连接{client.Name}的服务端!:" + DateTime.Now);
+//        }
+//    }
+//}

+ 131 - 0
Ai.AgentServer/Server/Mqtt_Ext/MqttClientService.cs

@@ -0,0 +1,131 @@
+using MQTTnet.Client;
+using MQTTnet.Protocol;
+using MQTTnet;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Ai.AgentServer.Server.Mqtt_Ext;
+using Microsoft.AspNetCore.SignalR;
+using MQTTnet.Server;
+using Ai.AgentServer.Server;
+
+namespace Ai.AgentServer
+{
+    /// <summary>
+    /// MQTT 客户端
+    /// 
+    /// 生成 的对象必须,开启 satrt 如需自动订阅主题需,配置 SubClients
+    /// </summary>
+    public class MqttClientService
+    {
+        public static IMqttClient _mqttClient;
+
+        public static string _subClients=string.Empty;
+
+        /// <summary>
+        /// 启用
+        /// </summary>
+        /// <param name="config"></param>
+ 
+        public void MqttClientStart(MqttClientConfig config)
+        {
+            var optionsBuilder = new MqttClientOptionsBuilder()
+                .WithTcpServer(config.Host, config.Port) // 要访问的mqtt服务端的 ip 和 端口号
+               // 要访问的mqtt服务端的用户名和密码
+                .WithClientId(config.ClientId) // 设置客户端id
+                .WithCleanSession()
+                .WithTlsOptions(new MqttClientTlsOptions
+                {
+                    UseTls = false  // 是否使用 tls加密
+                });
+
+            var clientOptions = optionsBuilder.Build();
+            _mqttClient = new MqttFactory().CreateMqttClient();
+
+            _mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync; // 客户端连接成功事件
+            _mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync; // 客户端连接关闭事件
+            _mqttClient.ApplicationMessageReceivedAsync += _mqttClient_ApplicationMessageReceivedAsync; // 收到消息事件
+
+            //添加配置订阅的ID
+            _subClients=config.SubClients;
+     
+            _mqttClient.ConnectAsync(clientOptions);
+
+
+        }
+
+        /// <summary>
+        /// 客户端连接关闭事件
+        /// </summary>
+        /// <param name="arg"></param>
+        /// <returns></returns>
+        private Task _mqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
+        {
+            Console.WriteLine($"客户端已断开与服务端的连接……");
+            return Task.CompletedTask;
+        }
+
+        /// <summary>
+        /// 客户端连接成功事件
+        /// </summary>
+        /// <param name="arg"></param>
+        /// <returns></returns>
+        private Task _mqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
+        {
+            Console.WriteLine($"客户端已连接服务端……");
+
+            // 订阅消息主题
+            // MqttQualityOfServiceLevel: (QoS):  0 最多一次,接收者不确认收到消息,并且消息不被发送者存储和重新发送提供与底层 TCP 协议相同的保证。
+            // 1: 保证一条消息至少有一次会传递给接收方。发送方存储消息,直到它从接收方收到确认收到消息的数据包。一条消息可以多次发送或传递。
+            // 2: 保证每条消息仅由预期的收件人接收一次。级别2是最安全和最慢的服务质量级别,保证由发送方和接收方之间的至少两个请求/响应(四次握手)。
+
+            if ( !string.IsNullOrEmpty(_subClients) )
+            {
+                foreach (var subClient in _subClients.Split(","))
+                {
+                    _mqttClient.SubscribeAsync($"/ToDispenser/{subClient}", MqttQualityOfServiceLevel.AtLeastOnce);
+                }
+            }
+            return Task.CompletedTask;
+        }
+
+        /// <summary>
+        /// 收到消息事件
+        /// </summary>
+        /// <param name="arg"></param>
+        /// <returns></returns>
+        private Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
+        {
+            Console.WriteLine($"ApplicationMessageReceivedAsync:客户端ID=【{arg.ClientId}】接收到消息。 Topic主题=【{arg.ApplicationMessage.Topic}】 消息=【{Encoding.UTF8.GetString(arg.ApplicationMessage.Payload)}】 qos等级=【{arg.ApplicationMessage.QualityOfServiceLevel}】");
+
+            return Task.CompletedTask;
+        }
+
+        public void Publish(string data)
+        {
+            var message = new MqttApplicationMessage
+            {
+                Topic = "topic_02",
+                Payload = Encoding.Default.GetBytes(data),
+                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
+                Retain = true  // 服务端是否保留消息。true为保留,如果有新的订阅者连接,就会立马收到该消息。
+            };
+            _mqttClient.PublishAsync(message);
+        }
+
+
+        public void PublishToTopic(string topic,string data)
+        {
+            var message = new MqttApplicationMessage
+            {
+                Topic = topic,
+                Payload = Encoding.Default.GetBytes(data),
+                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
+                Retain = true  // 服务端是否保留消息。true为保留,如果有新的订阅者连接,就会立马收到该消息。
+            };
+            _mqttClient.PublishAsync(message);
+        }
+    }
+}

+ 13 - 0
Ai.AgentServer/WeatherForecast.cs

@@ -0,0 +1,13 @@
+namespace Ai.AgentServer
+{
+    public class WeatherForecast
+    {
+        public DateOnly Date { get; set; }
+
+        public int TemperatureC { get; set; }
+
+        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
+
+        public string? Summary { get; set; }
+    }
+}

+ 8 - 0
Ai.AgentServer/appsettings.Development.json

@@ -0,0 +1,8 @@
+{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft.AspNetCore": "Warning"
+    }
+  }
+}

+ 20 - 0
Ai.AgentServer/appsettings.json

@@ -0,0 +1,20 @@
+{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft.AspNetCore": "Warning"
+    }
+  },
+  "AllowedHosts": "*",
+  "XunFei": "",
+  "GeLin": "",
+  "MqttSettings": {
+    "Name": "Mqtt",
+    "Host": "0.0.0.0",
+    "Port": "1883",
+    "UserName": "ss",
+    "SecretKey": "aa",
+    "ClientId": "12121"
+ 
+  }
+}