-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
591 lines (443 loc) · 21.6 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ABB.Robotics.Controllers;
using ABB.Robotics.Controllers.Discovery;
using ABB.Robotics.Controllers.FileSystemDomain;
using System.IO.Compression;
using ABB.Robotics.Controllers.MotionDomain;
using Microsoft.Win32;
using System.Reflection.Emit;
using AbbBackup.Backup;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Diagnostics.Eventing.Reader;
using AbbBackup.Params;
using AbbBackup.Logs;
using AbbBackup.Report;
using System.Runtime.InteropServices.WindowsRuntime;
namespace AbbBackup
{
internal class Program
{
static private NetworkScanner scanner;
static private string confFile;
static private RobotParamsList robotsParams;
static private bool onlineOnly;
static string defaultConfFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SIIF", "AbbBackup", "conf.xml");
static string defaultMailsFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SIIF", "AbbBackup", "mail.xml");
static string defaultLogFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SIIF", "AbbBackup\\Logs");
static void Main(string[] args)
{
LogsManager.OnLogAdd += ConsoleWrite;
LogsManager.OnLogAdd += WriteLogFile;
LogsManager.Add(EnumCategory.Info, "Start application", "Start application");
//Pour quitter l'appli
bool Cancel = false;
Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine($"=>Quit");
e.Cancel = true;
Cancel = true;
};
//Gestion des arguments
for (int i = 0; i < args.Length; i++)
{
switch (args[i].ToLower())
{
//Sauvegarde uniquement les robots présent sur le réseau
case "--online":
onlineOnly = true;
LogsManager.Add(EnumCategory.Process, "Parameters", "Save online robot only");
break;
//Spécifie un fichier de configuration
case "--conf":
try
{
if (args.Length > i + 1)
{
confFile = UNCPath(Environment.ExpandEnvironmentVariables(args[i + 1]));
LogsManager.Add(EnumCategory.Info, "Parameters", $"Load config file {confFile}");
robotsParams = RobotParamsList.LoadToXml(confFile);
LogsManager.Add(EnumCategory.Process, "Parameters", $"Config file loaded {confFile}");
}
}
catch (Exception ex)
{
LogsManager.Add(EnumCategory.Error, "Parameters", $"Config file no loaded {confFile}");
}
break;
//Ajout les robots présents sur le réseau au fichier de configuration
case "--addconf":
try
{
if (args.Length > i + 1)
{
confFile = UNCPath(Environment.ExpandEnvironmentVariables(args[i + 1]));
}
else
{
confFile = defaultConfFile;
}
if (File.Exists(confFile))
{
robotsParams = RobotParamsList.LoadToXml(confFile);
}
else
{
robotsParams = new RobotParamsList();
}
CopyrigthMenu();
LogsManager.Add(EnumCategory.Process, "Parameters", $"Search robots for adding to file config.xml");
//Recherche des robots présent sur le réseau
scanner = new NetworkScanner();
Task.Delay(5000).Wait();
while (!ScanReseau(scanner, robotsParams.TimeScan))
{
if (Cancel == true) goto Label;
LogsManager.Add(EnumCategory.Error, "Controller", $"No robot deteted, retry");
Thread.Sleep(1000);
}
foreach (ControllerInfo c in scanner.Controllers)
{
if (c.IsVirtual == false & c.Availability == Availability.Available)
{
if (robotsParams.Add(robotsParams.GetDefaultRobotParams(c)))
{
LogsManager.Add(EnumCategory.Process, "Controller", $"Robot {c.Name} add in file conf.xml");
}
}
}
if (robotsParams.Count > 0) robotsParams.SaveFromXml(confFile);
LogsManager.Add(EnumCategory.Process, "Controller", $"Custom the file conf.xml with user, password, folder backup directory");
Process.Start("explorer.exe", Directory.GetParent(confFile).FullName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return;
//Aide
case "--help":
Console.WriteLine($" Backup Robot - Application for save the robots programs");
Console.WriteLine($" Option : ");
Console.WriteLine($" --All : backup all robot");
Console.WriteLine($" --conf <path> : config.xml");
Console.WriteLine($" --addconf : add robot to default config.xml");
Console.WriteLine($" --addconf <path> : add robot to path config.xml");
Console.ReadLine();
return;
default:
break;
}
}
//Affichage du menu copyrigth
CopyrigthMenu();
//Chargement du fichier de configuration
if (robotsParams == null)
{
//Creation du fichier de configuration par défaut
if (!File.Exists(defaultConfFile))
{
LogsManager.Add(EnumCategory.Info, "Configuration", "no present config file");
Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SIIF", "AbbBackup"));
robotsParams = new RobotParamsList();
robotsParams.Mails.Add(new Mail());
robotsParams.SaveFromXml(defaultConfFile);
LogsManager.Add(EnumCategory.Info, "Configuration", $"Create config file to {defaultConfFile}");
}
//Chargement du fichier de configuration
robotsParams = RobotParamsList.LoadToXml(defaultConfFile);
LogsManager.Add(EnumCategory.Process, "Configuration", $"load config file to {defaultConfFile}");
}
scanner = new NetworkScanner();
ControllerInfo[] ci;
//Sauvegarde uniquement les robots de la listes
if (!onlineOnly)
{
List<ControllerInfo> controllerInfos = new List<ControllerInfo>();
//Recherche des robots présent dans le fichier
foreach (var robot in robotsParams)
{
try
{
LogsManager.Add(EnumCategory.Process, "Ping", $"Ping : {robot.IP}");
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(robot.IP);
if (reply.Status != IPStatus.Success)
{
LogsManager.Add(EnumCategory.Error, "Ping", $"Ping : {robot.IP} -> no response");
continue;
}
else
{
LogsManager.Add(EnumCategory.Process, "Ping", $"Ping : {robot.IP} -> response ok");
}
if (scanner.TryFind(robot.Id, robotsParams.TimeScan, robotsParams.RetryScan, out ControllerInfo cf))
{
LogsManager.Add(EnumCategory.Process, "Identification", $"Robot found : {robot.IP} | {cf.Name} | {cf.VersionName}");
controllerInfos.Add(cf);
}
else
{
LogsManager.Add(EnumCategory.Error, "Identification", $"Robot : {robot.IP} no found");
}
}
catch (Exception ex)
{
LogsManager.Add(EnumCategory.Error, "Exception", $"{ex.Message}");
}
}
ci = controllerInfos.ToArray();
}
//Sauvegarde des robots en ligne
else
{
//Recherche des robots présent sur le réseau
while (!ScanReseau(scanner, robotsParams.TimeScan) & Cancel == false)
{
LogsManager.Add(EnumCategory.Process, "Scan", $"no robot detected, retry");
Thread.Sleep(1000);
}
ci = scanner.GetControllers(NetworkScannerSearchCriterias.Real);
}
//Liste les robot présent sur le réseau et dans le fichier de configuration
var robotsasauvegarder = from controller in ci
join paramController in robotsParams on controller.SystemId equals paramController.Id into gj
from Params in gj.DefaultIfEmpty()
select new
{
controller,
Params
};
//Itération des robots détecté pour affichage des robots présent sur le réseau
Console.WriteLine($"");
Console.WriteLine("-".PadRight(120, '-'));
foreach (var c in robotsasauvegarder)
{
Console.WriteLine(
$"|{(c.controller.Name.PadRight(16))} |" +
$" {c.controller.IPAddress.ToString().PadRight(16)} |" +
$" {c.controller.Id.PadRight(28)} |" +
$" {c.controller.VersionName.PadRight(10)} |" +
$" {c.controller.Availability.ToString().PadRight(12)}|" +
$" {((c.Params != null || onlineOnly) && !c.controller.IsVirtual ? "Backup" : "No Backup").PadRight(12)}|" +
$"");
}
Console.WriteLine("-".PadRight(120, '-'));
Console.WriteLine($"");
List<RobotBackup> listerob = new List<RobotBackup>();
//Itération des robots détecté pour la sauvegarde
BackupCreator backupCreator = new BackupCreator();
foreach (var c in robotsasauvegarder)
{
RobotParams param = c.Params;
var state = (c.Params != null || onlineOnly) && !c.controller.IsVirtual ? "Echec" : "No Backup";
var rb = new RobotBackup(c.controller, c.Params, $"{state}");
listerob.Add(rb);
if (onlineOnly && c.Params == null)
{
param = robotsParams.GetDefaultRobotParams(c.controller);
}
if (param == null || c.controller.IsVirtual)
{
continue;
}
if (!Directory.Exists(param.FolderBackup)) param.FolderBackup = robotsParams.DefaultFolderBackup;
BackupController backupController = backupCreator.Factory(c.controller, param);
backupController.BackupStart += (p) => LogsManager.Add(EnumCategory.Process, "Backup", $"{p.robotparam.NameFileBackup} - Start backup");
backupController.BackupCompleted += (p, e) => LogsManager.Add(EnumCategory.Process, "Backup", $"{p.robotparam.NameFileBackup} - Backup completed -> {p.robotparam.FolderBackup}");
if (backupController.StartBackup())
{
rb.State = "Succes";
}
if (param.DelayDeleteFile != -1)
{
RemoveFilesDirectory(param.FolderBackup, param.DelayDeleteFile);
}
}
//Send report to mail
foreach (var mail in robotsParams.Mails)
{
if (!mail.Actived) continue;
List<Log> logError;
string subjectMail;
if (mail.AllLogs)
{
logError = LogsManager.GetLogs().ToList();
subjectMail = "Backup logs";
}
else
{
logError = LogsManager.GetLogs().Where((l) => l.Category == EnumCategory.Error).ToList();
subjectMail = "Backup Error logs";
}
if (logError.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(FormatHTML(listerob, LogsManager.GetLogs().ToList()));
IReport mr = new MailReport()
{
Mail = mail,
AdressMailFrom = robotsParams.Mails.AdressMailFrom,
NameFrom = robotsParams.Mails.NameFrom,
HostSmtp = robotsParams.Mails.HostSmtp,
PortSmtp = robotsParams.Mails.PortSmtp,
CredentialName = robotsParams.Mails.CredentialName,
Subject = subjectMail,
Content = sb.ToString(),
};
if (mr.Send())
{
LogsManager.Add(EnumCategory.Process, "Report", $"Send report to mail {mail.AdressMailTo}");
}
else
{
LogsManager.Add(EnumCategory.Error, "Report", $"Error Send report to mail {mail.AdressMailTo}");
}
}
}
Label:
//Toutes les sauvegardes sont terminées
Console.WriteLine($"...Exit...");
Thread.Sleep(2000);
}
private static string FormatHTML(List<RobotBackup> rb, List<Log> lm)
{
string htmlTable = $"<div><h1>Rapport de sauvegarde robots du {DateTime.Now.ToString()}</h1>";
// Génération du tableau robot
htmlTable += "<div><h2 style='text-decoration: underline;'>Etat des sauvegardes robots :</h2><p>Liste des robots :</p><table border='1' cellpadding='5' cellspacing='0'><tr><th>ID</th><th>Identifiant</th><th>Version</th><th>Folder directory</th><th>Link</th><th>State</th></tr>";
foreach (var cell in rb)
{
string color = "white";
if (cell.State == "Echec")
{
color = "red";
}
else if (cell.State == "Succes")
{
color = "green";
}
htmlTable += "<tr>";
htmlTable += $"<td>{cell.ControllerInfo.Id}</td>";
htmlTable += $"<td>{cell.ControllerInfo.Name}</td>";
htmlTable += $"<td>{cell.ControllerInfo.VersionName}</td>";
htmlTable += $"<td>{cell.robotParams.FolderBackup}</a></td>";
htmlTable += $"<td><a href=\"{cell.robotParams.FolderBackup}\">💾</a></td>";
htmlTable += $"<td style='background-color:{color};'>{cell.State}</td>";
htmlTable += "</tr>";
}
htmlTable += "</table></div>";
// Génération du tableau robot
htmlTable += "<div><h2 style='text-decoration: underline;'>Rapport des Logs :</h2><p>Liste des logs :</p><table border='1' cellpadding='5' cellspacing='0'><tr><th>Date</th><th>Categorie</th><th>Type</th><th>Description</th></tr>";
foreach (var cell in lm.Where((l)=> l.Category == EnumCategory.Process || l.Category == EnumCategory.Error))
{
string color = "white";
if (cell.Category == EnumCategory.Error)
{
color = "red";
}
htmlTable += "<tr style='background-color:" + color + ";'>";
htmlTable += $"<td>{cell.Date}</td>";
htmlTable += $"<td>{cell.Category}</td>";
htmlTable += $"<td>{cell.Type}</td>";
htmlTable += $"<td>{cell.Description}</td>";
htmlTable += "</tr>";
}
htmlTable += $"</table></div>";
htmlTable += $"<div><p>Détails des logs -><a href=\"{linkLog}\">💾</a></p></div>";
htmlTable += $"<div><p><strong>Rapport édité automatiquement par l'application AbbBackup le {DateTime.Now.ToString()}</strong></p></div>";
return htmlTable;
}
//Affiche des messages dans la console
private static void ConsoleWrite(Log log)
{
if (log.Category == EnumCategory.Process || log.Category == EnumCategory.Error)
{
Console.WriteLine(
$"|{(log.Category.ToString().PadRight(10))} |" +
$" {log.Type.PadRight(16)} |" +
$" {log.Description}");
}
}
static private bool ScanReseau(NetworkScanner scanner, int timeScan)
{
//Scan les robots présents sur le réseau
scanner.Scan();
LogsManager.Add(EnumCategory.Info, "Scan", $"Search robot online");
Thread.Sleep(timeScan);
//Fin du programme si pas de robot détecté
if (scanner.Controllers.Where(p => !p.IsVirtual).ToList().Count() == 0)
{
return false;
}
return true;
}
static string linkLog = "";
private static void WriteLogFile(Log log)
{
Directory.CreateDirectory(defaultLogFile);
linkLog = defaultLogFile + "\\Logs_" + DateTime.Today.ToString("yyyyMMdd") + ".log";
using (StreamWriter fs = new StreamWriter(linkLog, true))
{
fs.WriteLine(log.ToString());
}
}
static public void CopyrigthMenu()
{
//Console.WriteLine($"------Backup------");
Console.WriteLine("-".PadRight(60, '-'));
Console.WriteLine("|ABB BACKUP".PadRight(59) + "|");
Console.WriteLine("|Copyright © SIIF 2025".PadRight(59) + "|");
Console.WriteLine($"|{Assembly.GetExecutingAssembly().GetName().Version.ToString().PadRight(58)}|");
Console.WriteLine("|Application for save the robots programs".PadRight(59) + "|");
Console.WriteLine("-".PadRight(60, '-'));
Console.WriteLine($"Ctrl + c for exit application");
}
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().Location;// .CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
public static string UNCPath(string path)
{
if (!path.StartsWith(@"\\"))
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Network\\" + path[0]))
{
if (key != null)
{
return key.GetValue("RemotePath").ToString() + path.Remove(0, 2).ToString();
}
}
}
return path;
}
public static void RemoveFilesDirectory(string path, int delay)
{
if (Directory.Exists(path))
{
foreach (string dir in Directory.GetDirectories(path))
{
DateTime createdTime = new DirectoryInfo(dir).CreationTime;
if (createdTime < DateTime.Now.AddDays(-delay))
{
Directory.Delete(dir, true);
LogsManager.Add(EnumCategory.Info, "Delete File", $" Remove folder -> {dir}");
}
}
}
}
}
}