-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
733 lines (643 loc) · 29.9 KB
/
Program.cs
File metadata and controls
733 lines (643 loc) · 29.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
using AGVSystem;
using AGVSystem.Hubs;
using AGVSystem.Models.Automation;
using AGVSystem.Models.EQDevices;
using AGVSystem.Models.Map;
using AGVSystem.Models.Sys;
using AGVSystem.Models.TaskAllocation.HotRun;
using AGVSystem.Service;
using AGVSystem.Service.Aggregates;
using AGVSystem.Service.ChatBot;
using AGVSystem.Service.LocalAutomationTransfer;
using AGVSystem.Service.MCS;
using AGVSystem.TaskManagers;
using AGVSystemCommonNet6;
using AGVSystemCommonNet6.Alarm;
using AGVSystemCommonNet6.Configuration;
using AGVSystemCommonNet6.DATABASE;
using AGVSystemCommonNet6.DATABASE.BackgroundServices;
using AGVSystemCommonNet6.DATABASE.Services;
using AGVSystemCommonNet6.HttpTools.ApiMiddlewares;
using AGVSystemCommonNet6.Log;
using AGVSystemCommonNet6.Material;
using AGVSystemCommonNet6.Microservices;
using AGVSystemCommonNet6.Microservices.MCS;
using AGVSystemCommonNet6.Microservices.VMS;
using AGVSystemCommonNet6.Notify;
using AGVSystemCommonNet6.Sys;
using AGVSystemCommonNet6.Utilis.DiskMonitor;
using AGVSystemCommonNet6.Vehicle_Control.VCS_ALARM;
using EquipmentManagment.MainEquipment;
using EquipmentManagment.Manager;
using KGSWebAGVSystemAPI.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.AspNetCore.WebSockets;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using NLog;
using NLog.Web;
using System;
using System.Diagnostics;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.Json;
using static AGVSystem.Models.Automation.AutoTransferSettings;
using static AGVSystemCommonNet6.MAP.Map;
using Task = System.Threading.Tasks.Task;
public class Program
{
static bool hotRunEnabled = false;
static string hotRunScriptName = string.Empty;
public static void Main(string[] args)
{
Console.WriteLine(@" 佛祖保佑
_ `-._ `-. `. \ : / .' .-' _.-' _
`--._ `-._ `-. `. `. : .' .' .-' _.-' _.--'
`--._ `-._ `-. `. \ : / .' .-' _.-' _.--'
`--.__ `--._ `-._ `-. `. `. : .' .' .-' _.-' _.--' __.--'
__ `--.__ `--._ `-._ `-. `. \:/ .' .-' _.-' _.--' __.--' __
`--..__ `--.__ `--._ `-._`-.`_=_'.-'_.-' _.--' __.--' __..--'
--..__ `--..__ `--.__ `--._`-q(-_-)p-'_.--' __.--' __..--' __..--
``--..__ `--..__ `--.__ `-'_) (_`-' __.--' __..--' __..--''
...___ ``--..__ `--..__`--/__/ \--'__..--' __..--'' ___...
```---...___ ``--..__`_(<_ _/)_'__..--'' ___...---'''
```-----....._____```---...___(__\_\_|_/__)___...---'''_____.....-----'''
___ __ ________ _______ _ _ _______ ___ __ _______
|| \\ || || ||_____)) \\ // ||_____|| || \\ || ||_____||
|| \\_|| ___||___ || \\ \\___// || || || \\_|| || ||
");
Logger logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
ProcessTools.TryExitAppWhenAlreadRunning(logger).GetAwaiter().GetResult();
foreach (var arg in args)
{
if (arg.Equals("--hotrun", StringComparison.OrdinalIgnoreCase))
{
hotRunEnabled = true;
Console.WriteLine("Auto HotRun enabled");
}
else if (arg.StartsWith("--script=", StringComparison.OrdinalIgnoreCase))
{
hotRunScriptName = arg.Substring("--script=".Length);
Console.WriteLine("hotRunScriptName = " + hotRunScriptName);
}
}
string appVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
Console.Title = $"GPM-AGV系統(AGVs)-v{appVersion}";
EnvironmentVariables.AddUserVariableAsync("AGVSystemInstall", Environment.CurrentDirectory);
try
{
logger.Info($"AGVS Start,Vesion:{appVersion}");
WebApplicationBuilder builder = SystemInitializer.Initialize(args, logger);
WebAppInitializer.ConfigureBuilder(builder);
var app = builder.Build();
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() =>
{
logger.Error($"Ctrl+c triggered 應用程式正在關閉中...");
});
lifetime.ApplicationStopped.Register(() =>
{
logger.Error($"Ctrl+c triggered 應用程式已關閉");
});
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
{
logger.Error($"Close action botton triggered. 應用程式正在關閉中...");
};
WebAppInitializer.ConfigureApp(builder, app);
if (hotRunEnabled)
{
Task.Run(async () =>
{
await Task.Delay(3000);
(bool, string) result = HotRunScriptManager.Run(hotRunScriptName);
logger.Info($"HotRunScriptManager.Run({hotRunScriptName}) result: {result.Item1}, {result.Item2}");
});
}
AGVSSystemStatus? lastSysStatus = SystemInitializer.GetLastSystemState(builder);
SystemInitializer.InitSysStatusDBStoreWithAppVersionAsync(builder, appVersion);
if (AGVSConfigulator.SysConfigs.RestoreRunModeWhenRestartProgram)
AutoSwitchSystemModes(builder, lastSysStatus, logger);
app.Run();
}
catch (Exception ex)
{
logger.Error(ex);
Environment.Exit(ex.GetHashCode());
}
finally
{
LogManager.Shutdown();
}
}
private static void AutoSwitchSystemModes(WebApplicationBuilder builder, AGVSSystemStatus? lastSysStatus, Logger logger)
{
if (lastSysStatus == null)
return;
SystemModesAggregateService service = builder.Services.BuildServiceProvider().GetRequiredService<SystemModesAggregateService>();
Task.Run(async () =>
{
await Task.Delay(3000);
logger?.Info("前次為運轉模式,嘗試自動切換");
(bool success, string message) result = await service.MaintainRunSwitch(lastSysStatus.RunMode, forecing_change: true, 5, 6);
logger?.Info($"前次為運轉模式嘗試自動切換結果: {result}");
});
}
}
public static class SystemInitializer
{
public static WebApplicationBuilder Initialize(string[] args, Logger logger)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
string testAppsettingJsonFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "appsettings.Test.json");
builder.Configuration.AddJsonFile(testAppsettingJsonFilePath, optional: true, true);//嘗試注入測試用
string configRootFolder = builder.Configuration.GetValue<string>("AGVSConfigFolder");
configRootFolder = string.IsNullOrEmpty(configRootFolder) ? @"C:\AGVS" : configRootFolder;
logger.Debug($"派車系統參數檔資料夾路徑={configRootFolder}");
string autoTransferSettingJsonFilePath = Path.Combine(configRootFolder, "DispatchConfigs\\AutoTransferSettings.json");
if (!File.Exists(autoTransferSettingJsonFilePath))
{
Directory.CreateDirectory(Path.GetDirectoryName(autoTransferSettingJsonFilePath));
File.WriteAllText(autoTransferSettingJsonFilePath, new AutoTransferSettings().ToJson());
}
builder.Configuration.AddJsonFile(autoTransferSettingJsonFilePath, optional: true, true);//嘗試注入測試用
builder.Services.Configure<AutoTransferSetting>(builder.Configuration.GetSection("AutoTransfer"));
AGVSConfigulator.Init(configRootFolder);
Task.Run(() =>
{
try
{
var _config = AGVSConfigulator.SysConfigs.AutoSendDailyData;
UncShareManager.RegisterShare(_config.SavePath, _config.userName, _config.password);
}
catch (Exception ex)
{
logger.Error(ex, $"於程式啟動時執行遠端目錄登入過程中發生錯誤 {ex.Message}");
}
});
//#region 在程式啟動時嘗試遠端目錄連接確認
//_ = Task.Run(() =>
//{
// try
// {
// using var networkShareAccesser = new NetworkShareHelper(_config.SavePath, _config.userName, _config.password);
// }
// catch (Exception ex)
// {
// NotifyServiceHelper.ERROR(ex.Message);
// }
//});
//#endregion
InitializeDatabase(logger);
EQTransferTaskManager.Initialize();
AGVSMapManager.Initialize();
HotRunScriptManager.Initialize();
ScheduleMeasureManager.Initialize();
VMSSerivces.OnVMSReconnected += async (sender, e) => await VMSSerivces.RunModeSwitch(SystemModes.RunMode);
VMSSerivces.AliveCheckWorker();
VMSSerivces.RunModeSwitch(AGVSystemCommonNet6.AGVDispatch.RunMode.RUN_MODE.MAINTAIN);
NotifyServiceHelper.OnMessage += NotifyServiceHelper_OnMessage;
void NotifyServiceHelper_OnMessage(object? sender, NotifyServiceHelper.NotifyMessage notifyMessage)
{
Logger _logger = LogManager.GetLogger("NotifierLog");
Task.Run(() =>
{
string msg = notifyMessage.message;
switch (notifyMessage.type)
{
case NotifyServiceHelper.NotifyMessage.NOTIFY_TYPE.info:
_logger.Info(msg);
break;
case NotifyServiceHelper.NotifyMessage.NOTIFY_TYPE.warning:
_logger.Warn(msg);
break;
case NotifyServiceHelper.NotifyMessage.NOTIFY_TYPE.error:
_logger.Error(msg);
break;
case NotifyServiceHelper.NotifyMessage.NOTIFY_TYPE.success:
_logger.Info(msg);
break;
default:
break;
}
//
});
}
return builder;
}
private static void InitializeDatabase(Logger logger)
{
try
{
logger.Info("Database Initialize...");
AGVSDatabase.Initialize().GetAwaiter().GetResult();
logger.Info("Database Initialize...Done");
}
catch (Exception ex)
{
logger.Fatal($"資料庫初始化異常-請確認資料庫! {ex.Message}");
Environment.Exit(4);
}
}
public static async Task InitSysStatusDBStoreWithAppVersionAsync(WebApplicationBuilder build, string appVersion)
{
await build.Services.BuildServiceProvider().GetRequiredService<SystemStatusDbStoreService>().InitSysStatusWithAppVersion(appVersion);
}
internal static AGVSSystemStatus? GetLastSystemState(WebApplicationBuilder builder)
{
SystemStatusDbStoreService dbService = builder.Services.BuildServiceProvider().GetRequiredService<SystemStatusDbStoreService>();
return dbService.GetLastSysState();
}
}
public static class WebAppInitializer
{
public static void ConfigureBuilder(WebApplicationBuilder builder)
{
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.AddServerHeader = false;
});
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
builder.Host.UseNLog();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "GPM 派車系統 RESTFul API",
Version = "V1"
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
options.IncludeXmlComments(xmlPath);
});
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
builder.Services.AddDirectoryBrowser();
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.PropertyNamingPolicy = null;
options.SerializerOptions.PropertyNameCaseInsensitive = false;
options.SerializerOptions.WriteIndented = true;
});
ConfigureAuthentication(builder);
ConfigureDatabase(builder);
ServicesInjection(builder);
ConfigureCors(builder);
ConfigureWebSockets(builder);
ConfigureSignalR(builder);
BuildDiskMonitorService(builder);
BuildDailyReportService(builder);
ConfigurationInject.InjectChargeConfigs(builder);//充電相關參數注入
ConfigurationInject.InjectServiceRunStateMonitorConfigs(builder);//服務狀態監控參數注入
ConfigurationInject.InjectAutomationTransferConfigs(builder);
}
private static void BuildDiskMonitorService(WebApplicationBuilder builder)
{// 設定檔路徑
var configPath = Path.Combine(AGVSConfigulator.SysConfigs.CONFIGS_ROOT_FOLDER, DiskMonitorProvider.CONFIGURATION_FILE_NAME);
// 若檔案不存在,寫入預設內容
if (!File.Exists(configPath))
{
var defaultConfig = new DiskStatusMonitorConfiguration();
var json = JsonSerializer.Serialize(defaultConfig, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(configPath, json);
}
// 建立設定物件
var config = new ConfigurationBuilder()
.AddJsonFile(configPath, optional: true)
.Build();
builder.Services.Configure<DiskStatusMonitorConfiguration>(config);
DiskMonitorProvider.CONFIGURATION_FILE_PATH = configPath;
//Disk監控註冊
builder.Services.AddSingleton<DiskMonitorProvider>();
builder.Services.AddHostedService<DiskMonitorService>();
// 取出注入的參數
var diskMonitorProvider = builder.Services.BuildServiceProvider().GetRequiredService<DiskMonitorProvider>();
//write back to file to ensure all properties are written when the file is created
File.WriteAllText(configPath, JsonSerializer.Serialize(diskMonitorProvider.options, new JsonSerializerOptions { WriteIndented = true }));
}
private static void BuildDailyReportService(WebApplicationBuilder builder)
{
// 設定檔路徑
var configPath = Path.Combine(AGVSConfigulator.SysConfigs.CONFIGS_ROOT_FOLDER, "DailyReportConfig.json");
// 若檔案不存在,寫入預設內容
if (!File.Exists(configPath))
{
var defaultConfig = new DailyReportConfiguration();
var json = JsonSerializer.Serialize(defaultConfig, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(configPath, json);
}
// 建立設定物件
var config = new ConfigurationBuilder()
.AddJsonFile(configPath, optional: true)
.Build();
builder.Services.Configure<DailyReportConfiguration>(config);
builder.Services.AddSingleton<DailyReportService>();
builder.Services.AddHostedService<DailyReportServiceStartup>();
}
private static void ConfigureAuthentication(WebApplicationBuilder builder)
{
builder.Services.AddScoped<UserValidationService>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(
options => options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret_keysecret_keysecret_key11")),
ClockSkew = TimeSpan.Zero //若不設定,預設會容許 5 分鐘寬限時間
}
);
}
private static void ConfigureDatabase(WebApplicationBuilder builder)
{
builder.Services.AddPooledDbContextFactory<AGVSDbContext>(options => options.UseSqlServer(AGVSConfigulator.SysConfigs.DBConnection));
builder.Services.AddDbContext<AGVSDbContext>(options => options.UseSqlServer(AGVSConfigulator.SysConfigs.DBConnection));
if (AGVSConfigulator.SysConfigs.kgsWebAGVSysConfig.BaseOnKGSWebAGVSystem)
{
builder.Services.AddDbContext<WebAGVSystemContext>(options => options.UseSqlServer(AGVSConfigulator.SysConfigs.kgsWebAGVSysConfig.KGSWebAGVSystemDBConnection));
}
EnvironmentVariables.AddUserVariableAsync("AGVSDatabaseConnection", AGVSConfigulator.SysConfigs.DBConnection);
}
private static void ServicesInjection(WebApplicationBuilder builder)
{
SECSConfigsService _secsConfigsService = new SECSConfigsService(Path.Combine(AGVSConfigulator.SysConfigs.CONFIGS_ROOT_FOLDER, "SECSConfigs"));
_secsConfigsService.InitializeAsync();
if (!Debugger.IsAttached)
builder.Services.AddHostedService<ThirdPartyProgramStartService>();
builder.Services.AddMemoryCache();
builder.Services.AddScoped<MeanTimeQueryService>();
builder.Services.AddScoped<LogDownlodService>();
builder.Services.AddScoped<StationSelectService>();
builder.Services.AddScoped<SystemStatusDbStoreService>();
builder.Services.AddScoped<AGVBatteryDataQuerySerivce>();
builder.Services.AddSingleton<RackService>();
builder.Services.AddScoped<MCSService>();
builder.Services.AddScoped<DatabaseMigrateService>();
builder.Services.AddScoped<SECSConfigsService>(service => _secsConfigsService);
builder.Services.AddScoped<TrafficStateDataQueryService>();
builder.Services.AddScoped<SystemModesAggregateService>();
builder.Services.AddScoped<IDatabaseBackupService, DatabaseBackupService>();
builder.Services.AddScoped<CarrierIDInfoService>();
builder.Services.AddChatBotRouterService();
builder.Services.AddHostedService<FetchDBDataAsCachesService>();
builder.Services.AddSingleton<LocalAutomationTransferSettingService>();
builder.Services.AddSingleton<DBDataService>();
builder.Services.AddSingleton<SoundPlayForAlarms>();
builder.Services.AddScoped<EqStatusCheckWhneOrderRunService>();
builder.Services.AddSingleton<AutomationTransferService>();
builder.Services.AddSingleton<FrontendUserConnectionManager>();
builder.Services.AddSingleton<SoundForAlarmsConfigManager>();
//builder.Services.AddSingleton<EQIOStatusMonitorBackgroundService>(provider => qIOStatusMonitorBackgroundService);
builder.Services.AddHostedService<DatabaseDefaultSetupService>();
builder.Services.AddHostedService<VehicleLocationMonitorBackgroundService>();
builder.Services.AddHostedService<FrontEndDataBrocastService>();
builder.Services.AddHostedService(provider => provider.GetRequiredService<SoundPlayForAlarms>());
builder.Services.AddHostedService<PCPerformanceService>();
builder.Services.AddHostedService<EQDeviceEventsHandler.EQDeviceEventHandlerInitService>();
builder.Services.AddHostedService<EquipmentInitStartupService>();
builder.Services.AddHostedService<EquipmentsCollectBackgroundService>();
builder.Services.AddHostedService<RackPortDoubleIDMonitor>();
builder.Services.AddHostedService<TaskManagerInitService>();
//builder.Services.AddSingleton<clsOptimizeAGVDispatcher>(optimizedVehicleDispatcher);
builder.Services.AddHostedService<LocalAutomationTransferService>();
builder.Services.AddHostedService<AlarmManagerCenter.AlarmManagerStarupService>();
builder.Services.AddHostedService<AGVCServiceRunStateMonitorService>();
builder.Services.AddHostedService<SystemModesExtensionServices>();
//builder.Services.AddHostedService<EQIOStatusMonitorBackgroundService>(provider => qIOStatusMonitorBackgroundService);
builder.Services.AddHealthStatusCheck(options =>
{
options.ServiceHosts = new Dictionary<string, string> {
{ HealthCheckConfiguration.SECSPLATFORM_SERVICE_NAME , "http://127.0.0.1:7107/api/AliveCheck" },
};
options.CheckIntervalSeconds = 5; // 可選,預設為5秒
});
}
private static void ConfigureCors(WebApplicationBuilder builder)
{
// 動態獲取本機所有 IP 地址
List<string>? localIPs = Dns.GetHostEntry(Dns.GetHostName())
.AddressList
.Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?
.Select(address => address.ToString())
.ToList();
List<string> allowedOrigins = new List<string> {
"http://127.0.0.1:8080",
"http://127.0.0.1:5216",
"http://127.0.0.1:5036",
"http://localhost:8080",
"http://localhost:5216",
"http://localhost:5036",
};
foreach (var ip in localIPs)
{
allowedOrigins.Add($"http://{ip}:5216");
allowedOrigins.Add($"http://{ip}:5036");
allowedOrigins.Add($"http://{ip}:8080");
allowedOrigins.Add($"http://{ip}:8081");
allowedOrigins.Add($"http://{ip}:8082");
allowedOrigins.Add($"http://{ip}:8083");
allowedOrigins.Add($"http://{ip}:8084");
allowedOrigins.Add($"http://{ip}:7107");
}
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // 允许任何来源
.AllowCredentials(); // 允许凭据
});
});
}
private static void ConfigureWebSockets(WebApplicationBuilder builder)
{
builder.Services.AddWebSockets(options =>
{
options.KeepAliveInterval = TimeSpan.FromSeconds(600);
});
}
private static void ConfigureSignalR(WebApplicationBuilder builder)
{
builder.Services.AddSignalR().AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
}
public static void ConfigureApp(WebApplicationBuilder builder, WebApplication app)
{
// 動態獲取本機所有 IP 地址
string connectSrc = "";
List<string>? localIPs = Dns.GetHostEntry(Dns.GetHostName())
.AddressList
.Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?
.Select(address => address.ToString())
.ToList();
foreach (var ip in localIPs)
{
connectSrc += $"ws://{ip}:5036 http://{ip}:5036 ws://{ip}:5216 http://{ip}:5216 ";
}
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
context.Response.Headers.Add("Content-Security-Policy", $"");
context.Response.Headers.Remove("Server");
await next();
});
app.UseMiddleware<ApiLoggingMiddleware>();
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors("AllowAll");
app.UseWebSockets();
string frontendRootFolder = builder.Configuration.GetValue<string>("FrontendRootFolder");
PhysicalFileProvider frontendFileProvider = new PhysicalFileProvider(Path.Combine(app.Environment.ContentRootPath, frontendRootFolder ?? "wwwroot"));
app.UseDefaultFiles(new DefaultFilesOptions()
{
FileProvider = frontendFileProvider,
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = frontendFileProvider,
});
StaticFileInitializer.Initialize(app);
app.UseVueRouterHistory();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHub<FrontEndDataHub>("/FrontEndDataHub");
app.MapHub<SecsPlatformHub>("/SecsPlatform");
app.MapHub<DiskMonitorHub>("/diskMonitorHub");
}
}
public static class StaticFileInitializer
{
public static void Initialize(WebApplication app)
{
string configRootFolder = app.Configuration.GetValue<string>("AGVSConfigFolder");
configRootFolder = string.IsNullOrEmpty(configRootFolder) ? @"C:\AGVS" : configRootFolder;
try
{
string mapFileFolderRelativePath = app.Configuration.GetValue<string>("StaticFileOptions:MapFile:FolderPath");
string mapFileRequestPath = app.Configuration.GetValue<string>("StaticFileOptions:MapFile:RequestPath");
mapFileRequestPath = mapFileRequestPath ?? "/MapFiles";
string agvImageFileFolderRelativePath = app.Configuration.GetValue<string>("StaticFileOptions:AGVImageStoreFile:FolderPath");
agvImageFileFolderRelativePath = agvImageFileFolderRelativePath ?? "/AGVImages";
string agvImageFileRequestPath = app.Configuration.GetValue<string>("StaticFileOptions:AGVImageStoreFile:RequestPath");
agvImageFileRequestPath = agvImageFileRequestPath ?? "/AGVImages";
string mapFileFolderPath = Path.Combine(configRootFolder, mapFileRequestPath.Trim('/'));
string agvImageFileFolderPath = Path.Combine(configRootFolder, agvImageFileFolderRelativePath.Trim('/'));
Directory.CreateDirectory(mapFileFolderPath);
Directory.CreateDirectory(agvImageFileFolderPath);
var mapFileProvider = new PhysicalFileProvider(mapFileFolderPath);
var agvImageFileProvider = new PhysicalFileProvider(agvImageFileFolderPath);
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = mapFileProvider,
RequestPath = mapFileRequestPath
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = mapFileProvider,
RequestPath = mapFileRequestPath
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = agvImageFileProvider,
RequestPath = agvImageFileRequestPath
});
CreateDefaultAGVImage(agvImageFileFolderPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
}
try
{
Directory.CreateDirectory(AGVSConfigulator.SysConfigs.TrobleShootingFolder);
var trobleshootingFileRequestPath = app.Configuration.GetValue<string>("TrobleShootingFileOptions:TrobleShootingFile:RequestPath");
var trobleshootingFileProvider = new PhysicalFileProvider(AGVSConfigulator.SysConfigs.TrobleShootingFolder);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = trobleshootingFileProvider,
RequestPath = trobleshootingFileRequestPath
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = trobleshootingFileProvider,
RequestPath = trobleshootingFileRequestPath
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
}
try
{
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.GetTempPath()),
RequestPath = "/Download"
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = new PhysicalFileProvider(Path.GetTempPath()),
RequestPath = "/Download"
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
}
try
{
PhysicalFileProvider resourcesFileProvider = new PhysicalFileProvider(Path.Combine(Environment.CurrentDirectory, "Resources"));
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = resourcesFileProvider,
RequestPath = "/Resources"
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = resourcesFileProvider,
RequestPath = "/Resources"
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
}
}
private static void CreateDefaultAGVImage(string agvImageFileFolderPath)
{
try
{
var existFileNames = Directory.GetFiles(agvImageFileFolderPath).Select(file => Path.GetFileName(file)).ToList();
for (int i = 0; i < 10; i++)
{
string agvImageFileName = $"AGV_00{i}-Icon.png";
string defaultImgFullFileName = "./Resources/AGVImages/default.png";
string agvImageFullFileName = Path.Combine(agvImageFileFolderPath, agvImageFileName);
if (!existFileNames.Contains(agvImageFileName))
{
File.Copy(defaultImgFullFileName, agvImageFullFileName, true);
}
}
}
catch (Exception ex)
{
}
}
}