1. MinioService.cs 添加依赖注入

2. 航线上传修改
3. MinioService.cs 添加上传方法
4. MinioService 配置文件重构
feature-flyModify
陈伟 2025-06-16 16:15:02 +08:00
parent 5020a26e70
commit 1d609239af
6 changed files with 156 additions and 80 deletions

View File

@ -1,36 +1,41 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Minio.Exceptions;
using Minio;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Minio.DataModel.Args;
using Minio;
using Minio.DataModel;
using Minio.DataModel.Args;
using Minio.Exceptions;
namespace Infrastructure.CloudSdk.minio;
public class MinioService
{
private IMinioClient _minioClient;
public readonly string _bucketName = null;
private IMinioClient _minioClient;
public string _bucketName;
public MinioService()
{
InitializeMinIOClient();
EnsureBucketExistsAsync(_bucketName).Wait();
//EnsureBucketExistsAsync(_bucketName).Wait();
}
private void InitializeMinIOClient()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("global.json", optional: false, reloadOnChange: true);
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile(
$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json",
optional: true)
.AddEnvironmentVariables();
// 构建配置
var config = builder.Build();
var configuration = builder.Build();
_bucketName = configuration["Minio:BucketName"];
_minioClient = new MinioClient()
.WithEndpoint(config["Minio:Endpoint"])
.WithCredentials(config["Minio:AccessKey"], config["Minio:SecretKey"])
.WithEndpoint(configuration["Minio:Endpoint"])
.WithCredentials(configuration["Minio:AccessKey"], configuration["Minio:SecretKey"])
.Build();
}
/// <summary>
/// 创建存储桶(如果不存在)
/// </summary>
@ -40,12 +45,12 @@ public class MinioService
bool found = await _minioClient.BucketExistsAsync(existsArgs);
if (!found)
{
var makeArgs = new MakeBucketArgs().WithBucket(_bucketName);
await _minioClient.MakeBucketAsync(makeArgs);
Console.WriteLine($"Bucket {_bucketName} created.");
}
}
public async Task EnsureBucketExistsAsync(string bucketName)
{
var existsArgs = new BucketExistsArgs().WithBucket(bucketName);
@ -58,13 +63,13 @@ public class MinioService
await _minioClient.MakeBucketAsync(makeArgs);
}
}
/// <summary>
/// 下载文件
/// </summary>
public async Task DownLoadObject(string bucketName, string objectKey, string localDir, string objectETag,
CancellationToken token = default)
CancellationToken token = default)
{
var index = objectKey.LastIndexOf("/", StringComparison.Ordinal);
if (index > 0)
@ -82,14 +87,13 @@ public class MinioService
.WithObject(objectKey)
.WithFile(localPath);
var stat = await _minioClient.GetObjectAsync(getArgs, token);
}
/// <summary>
/// 列出所有对象
/// </summary>
public async Task<IAsyncEnumerable<Item>> ListAllObject(string bucketName, string prefix, bool recursive,
CancellationToken token = default)
CancellationToken token = default)
{
// Just list of objects
// Check whether 'mybucket' exists or not.
@ -112,6 +116,7 @@ public class MinioService
Console.WriteLine("mybucket does not exist");
throw new Exception("bucket not found");
}
/// <summary>
/// 删除文件
/// </summary>
@ -128,4 +133,43 @@ public class MinioService
Console.WriteLine($"MinIO Exception: {ex.Message}");
}
}
}
public async void UploadFile(IFormFile file, string bucketName)
{
try
{
if (string.IsNullOrEmpty(bucketName))
{
bucketName = _bucketName;
}
//判断桶是否存在
var beArgs = new BucketExistsArgs().WithBucket(bucketName);
bool found = await _minioClient.BucketExistsAsync(beArgs).ConfigureAwait(false);
if (!found)
{
var mbArgs = new MakeBucketArgs()
.WithBucket(bucketName);
await _minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);
}
var objectName = $"{GenerateId.GenerateOrderNumber() }.wpml";
// 使用内存流上传
using var stream = new MemoryStream();
await file.CopyToAsync(stream);
stream.Position = 0;
var putArgs = new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName)
.WithStreamData(stream)
.WithObjectSize(stream.Length)
.WithContentType("application/octet-stream");
//.WithContentType(file.ContentType);
await _minioClient.PutObjectAsync(putArgs);
}
catch (Exception ex)
{
throw new Exception($"上传文件失败: {ex.Message}");
}
}
}

View File

@ -1,6 +1,8 @@
using DocumentFormat.OpenXml.Wordprocessing;
using Infrastructure;
using Infrastructure.CloudSdk.minio;
using Infrastructure.CloudSdk.wayline;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using OpenAuth.App.BaseApp.Base;
@ -18,14 +20,18 @@ namespace OpenAuth.App.ServiceApp
public class ManageApp : SqlSugarBaseApp<LasaDronePort, SugarDbContext>
{
private readonly MqttClientManager _mqttClientManager;
private readonly MinioService _minioService;
public ManageApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<LasaDronePort> repository, IAuth auth,
MqttClientManager mqttClientManager)
MqttClientManager mqttClientManager, MinioService minioService)
: base(unitWork, repository, auth)
{
_mqttClientManager = mqttClientManager;
_minioService = minioService;
}
#region 机场管理
/// <summary>
/// 分页获取所有数据
/// </summary>
@ -69,6 +75,7 @@ namespace OpenAuth.App.ServiceApp
return new Response<bool> { Result = false, Message = "编辑失败" };
}
}
//删除机场信息
public async Task<Response<bool>> DeleteDronePort(string id)
{
@ -84,6 +91,7 @@ namespace OpenAuth.App.ServiceApp
return new Response<bool> { Result = false, Message = "删除失败" };
}
}
#endregion
/// <summary>
@ -107,6 +115,7 @@ namespace OpenAuth.App.ServiceApp
};
}
}
/// <summary>
/// 编辑无人机
/// </summary>
@ -126,6 +135,7 @@ namespace OpenAuth.App.ServiceApp
return new Response<bool> { Result = false, Message = "编辑失败" };
}
}
//删除无人机
public async Task<Response<bool>> DeleteUav(string id)
{
@ -282,17 +292,20 @@ namespace OpenAuth.App.ServiceApp
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<Response<List<dynamic>>> GetWorkspaceList(int isjoin,string key,int state,string order= "\"CreateTime\" desc")
public async Task<Response<List<dynamic>>> GetWorkspaceList(int isjoin, string key, int state,
string order = "\"CreateTime\" desc")
{
RefAsync<int> totalCount = 0;
using (var db = UnitWork.CreateContext())
{
var userid = _auth.GetCurrentUser().User.Id;
List<string> ids=new List<string>();
List<string> ids = new List<string>();
if (isjoin == 1)
{
ids=db.LasaSpaceUser.AsQueryable().Where(r=>r.UserId== userid)?.Select(r => r.WorkSpaceId).ToList();
ids = db.LasaSpaceUser.AsQueryable().Where(r => r.UserId == userid)?.Select(r => r.WorkSpaceId)
.ToList();
}
var list = await db.LasaWorkspace.AsQueryable()
.WhereIF(!string.IsNullOrEmpty(key), a => a.WorkspaceName.Contains(key))
.WhereIF(state != 0, a => a.Sate == state)
@ -309,7 +322,8 @@ namespace OpenAuth.App.ServiceApp
a.CreateId,
u.Account,
u.Name,
UserNames = SqlFunc.Subqueryable<LasaSpaceUser>().Where(r => r.WorkSpaceId == a.Id).LeftJoin<SysUser>((r, s) => r.UserId == s.Id).SelectStringJoin((r, s) => s.Name, ",")
UserNames = SqlFunc.Subqueryable<LasaSpaceUser>().Where(r => r.WorkSpaceId == a.Id)
.LeftJoin<SysUser>((r, s) => r.UserId == s.Id).SelectStringJoin((r, s) => s.Name, ",")
}).MergeTable()
.OrderBy(order)
.ToListAsync();
@ -496,6 +510,7 @@ namespace OpenAuth.App.ServiceApp
return new Response<bool> { Result = false, Message = "归档失败" };
}
}
#endregion
public async Task ExecuteFlyTask(string taskId)
@ -532,7 +547,7 @@ namespace OpenAuth.App.ServiceApp
var configuration = builder.Build();
var wpmlDir = configuration["WpmlDir"];
// 读取连接字符串
var serverIp = configuration["MQTT:Server"];
//var serverIp = configuration["MQTT:Server"];
var data = new
{
flight_id = Guid.NewGuid().ToString(),
@ -566,12 +581,12 @@ namespace OpenAuth.App.ServiceApp
break_point = new
{
index = 1, // 断点序号
state = 1 ,// “0":"在航段上","1":"在航点上
state = 1, // “0":"在航段上","1":"在航点上
progress = 1.0, // {"max":"1.0","min":"0"}
wayline_id = "" // 航线id
},
// 返航高度 {"max":1500,"min":20,"step":"","unit_name":"米 / m"}
rth_altitude = 150, // todo 取自任务
rth_altitude = 150, // todo 取自任务
// 返航高度模式 {"0":"智能高度","1":"设定高度"}
// 智能返航模式下,飞行器将自动规划最佳返航高度。大疆机场当前不支持设置返航高度模式,只能选择'设定高度'模式。当环境,光线不满足视觉系统要求时(譬如傍晚阳光直射、夜间弱光无光),飞行器将使用您设定的返航高度进行直线返航
rth_mode = 1,
@ -603,7 +618,39 @@ namespace OpenAuth.App.ServiceApp
flight_safety_advance_check = 0
};
request.SetData(data);
// 任务下发
await _mqttClientManager.PublishAsync(topic, JsonConvert.SerializeObject(request));
// todo 是否查询就绪任务 执行任务
await _mqttClientManager.PublishAsync(topic, JsonConvert.SerializeObject(request));
//thing/product/{gateway_sn}/services
var flightTaskExecuteTopic = string.Format(GatewayManager.FlightTaskPrepare, serialNo);
// todo
var flightTaskExecuteRequest = new TopicServicesRequest<object>
{
method = "flighttask_execute",
tid = "tid",
bid = "bid",
timestamp = DateTime.Now.Ticks,
data = new
{
flight_id = "" // todo
}
};
await _mqttClientManager.PublishAsync(flightTaskExecuteTopic,
JsonConvert.SerializeObject(flightTaskExecuteRequest));
}
public async Task PendingFlyTask(string taskId)
{
// todo
// todo 查看任务状态(待执行,任务执行,已暂停,已挂起) 1. 待执行,任务执行,需要先取消任务 2. 已暂停,直接挂起任务 3. 已挂起,返回
throw new NotImplementedException();
}
public void UploadFile(IFormFile xmlFile)
{
// todo
_minioService.UploadFile(xmlFile, "");
}
}
}

View File

@ -55,6 +55,7 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
return result;
}
/// <summary>
/// 编辑机场
/// </summary>
@ -64,6 +65,7 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
{
return await _app.EditDronePort(info);
}
/// <summary>
/// 删除机场
/// </summary>
@ -73,6 +75,7 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
{
return await _app.DeleteDronePort(id);
}
#endregion
#region 无人机管理
@ -101,6 +104,7 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
return result;
}
/// <summary>
/// 编辑无人机
/// </summary>
@ -110,6 +114,7 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
{
return await _app.EditUav(info);
}
/// <summary>
/// 删除无人机
/// </summary>
@ -119,6 +124,7 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
{
return await _app.DeleteUav(id);
}
#endregion
#region 任务管理
@ -241,23 +247,14 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
/// <param name="xmlFile"></param>
/// <returns></returns>
[HttpPost("upload")]
[AllowAnonymous]
public async Task<IActionResult> UploadXmlFile(IFormFile xmlFile)
{
if (xmlFile == null || xmlFile.Length == 0)
return BadRequest("文件为空");
var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "Waylines");
if (!Directory.Exists(uploadsFolder))
Directory.CreateDirectory(uploadsFolder);
var fileName = GenerateId.GenerateOrderNumber() + ".wpml";
var filePath = Path.Combine(uploadsFolder, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await xmlFile.CopyToAsync(stream);
}
return Ok(new { message = "上传成功", path = filePath });
_app.UploadFile(xmlFile);
return Ok(new { message = "上传成功" });
}
/*/// <summary>
/// 更新航线文件
@ -300,12 +297,13 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
/// <param name="order">排序</param>
/// <returns></returns>
[HttpGet]
public async Task<Response<List<dynamic>>> GetWorkspaceList(int isjoin, string key, int state, string order = "\"CreateTime\" desc")
public async Task<Response<List<dynamic>>> GetWorkspaceList(int isjoin, string key, int state,
string order = "\"CreateTime\" desc")
{
var result = new Response<List<dynamic>>();
try
{
result = await _app.GetWorkspaceList(isjoin,key,state,order);
result = await _app.GetWorkspaceList(isjoin, key, state, order);
}
catch (Exception ex)
{
@ -355,6 +353,7 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
{
return await _app.CompleteWorkspace(id);
}
/// <summary>
/// 获取机场列表,添加项目使用
/// </summary>
@ -402,9 +401,8 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
#endregion
// 航线任务在云端的 共享查看、下发执行、取消以及进度上报等功能。
/// <summary>
/// 执行任务
/// 解除挂起(执行任务 todo 需不需要加时间限制判断?
/// </summary>
/// <param name="taskId"></param>
[HttpPost]
@ -413,6 +411,16 @@ namespace OpenAuth.WebApi.Controllers.ServiceControllers
await _app.ExecuteFlyTask(taskId);
}
/// <summary>
/// 挂起任务
/// </summary>
/// <param name="taskId"></param>
[HttpPost]
public async Task PendingFlyTask(string taskId)
{
await _app.PendingFlyTask(taskId);
}
/// <summary>
/// 测试
/// </summary>

View File

@ -4,6 +4,7 @@ using Autofac.Extensions.DependencyInjection;
using ce.autofac.extension;
using IdentityServer4.AccessTokenValidation;
using Infrastructure;
using Infrastructure.CloudSdk.minio;
using Infrastructure.Extensions.AutofacManager;
using Infrastructure.Middleware;
using Microsoft.AspNetCore.DataProtection;
@ -45,7 +46,9 @@ namespace OpenAuth.WebApi
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddSingleton<MqttClientManager>(provider => new MqttClientManager());
services.AddSingleton(_ => new MqttClientManager());
// minio client
services.AddSingleton(_ => new MinioService());
#region log4net

View File

@ -73,5 +73,12 @@
"Port": 6011,
"UserName": "sdhc",
"Password": ""
},
"Minio": {
"Endpoint": "175.27.168.120:6013",
"AccessKey": "minioadmin",
"SecretKey": "minioadmin",
"BucketName": "test",
"limitspeed": 1048576
}
}

View File

@ -1,33 +0,0 @@
//{
// "Minio": {
// "Endpoint": "192.168.20.239:9000",
// "AccessKey": "cqlatqb0dgqdBRar7KVF",
// "SecretKey": "FUFzd5VeoBeWhrpql6MBON5tQxNzcIgaK7vkvofX",
// "BucketName": "drone"
// }
//}
{
"Minio": {
"Endpoint": "192.168.10.163:9016",
"AccessKey": "I2c35jD6ayApaneyQZyC",
"SecretKey": "XHlrNeCHK0xf8y2Fo0K5OKyDeaI2ItfEsFbzQPFk",
"BucketName": "demo",
"limitspeed": 1048576
}
//{
// "Minio": {
// "Endpoint": "192.168.20.239:9106",
// "AccessKey": "minioadmin",
// "SecretKey": "hopetry@minio",
// "BucketName": "dev",
// "limitspeed": 1048576
// }
//"Minio": {
// "Endpoint": "nas.continue.fun:10044",
// "AccessKey": "xilonp6jAjBIf0DTaLfY",
// "SecretKey": "DgJF1eUTy61V3s26ofzfpRKUsnr9YVAF5kkwYXZ3",
// "BucketName": "mdimage",
// "limitspeed": 1048576
//}
}