117 lines
3.4 KiB
C#
117 lines
3.4 KiB
C#
namespace CommonConsole
|
|
{
|
|
using OmniPlus;
|
|
|
|
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
|
|
public interface ILogger
|
|
{
|
|
|
|
}
|
|
|
|
public partial class Program : ILogger
|
|
{
|
|
private readonly ConcurrentDictionary<string, string> files;
|
|
private readonly ConcurrentQueue<string> states;
|
|
private readonly string directory;
|
|
private readonly string directoryName;
|
|
private readonly string file;
|
|
private readonly string fileName;
|
|
private bool dequeuing;
|
|
|
|
public Program(string directoryName, string fileName)
|
|
{
|
|
this.files = new ConcurrentDictionary<string, string>();
|
|
this.states = new ConcurrentQueue<string>();
|
|
this.directoryName = directoryName;
|
|
this.fileName = fileName;
|
|
|
|
this.AddState += this.AddStateAndDequeue;
|
|
|
|
var currentDirectory = Directory.GetCurrentDirectory();
|
|
var namedDirectory = Path.Combine(currentDirectory, directoryName);
|
|
var namedFile = Path.Combine(namedDirectory, $"{DateTime.Now:yyyyMMdd}_{fileName}.log");
|
|
|
|
Directory.CreateDirectory(namedDirectory);
|
|
File.AppendAllText(namedFile, string.Empty);
|
|
|
|
this.directory = namedDirectory;
|
|
this.file = namedFile;
|
|
|
|
foreach (var file in Directory.GetFiles(this.directory))
|
|
{
|
|
var timestamp = Path
|
|
.GetFileName(file)
|
|
.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries)
|
|
.FirstOrDefault() ?? "n_a";
|
|
this.files[timestamp] = file;
|
|
}
|
|
}
|
|
|
|
protected event Action<object> AddState;
|
|
|
|
public string this[string timestamp]
|
|
{
|
|
get
|
|
{
|
|
var fileName = $"{timestamp}_{this.fileName}.log";
|
|
var filePath = this.files.GetOrAdd(fileName, default(string));
|
|
|
|
if (!string.IsNullOrWhiteSpace(filePath))
|
|
{
|
|
return File.ReadAllText(filePath);
|
|
}
|
|
|
|
return default(string);
|
|
}
|
|
}
|
|
|
|
public IEnumerable<string> Files => this.files.Keys;
|
|
|
|
public ILogger Log(object state)
|
|
{
|
|
this.AddState(state);
|
|
|
|
return this;
|
|
}
|
|
|
|
private void AddStateAndDequeue(object state)
|
|
{
|
|
this.states.Enqueue($"[{DateTime.Now:HH:mm:ss.ffff}] {state}{Environment.NewLine}");
|
|
|
|
if (!this.dequeuing)
|
|
{
|
|
this.dequeuing = true;
|
|
|
|
while (this.states.TryDequeue(out var next))
|
|
{
|
|
File.AppendAllText(this.file, next);
|
|
}
|
|
|
|
this.dequeuing = false;
|
|
}
|
|
}
|
|
|
|
public static void Main()
|
|
{
|
|
var program = new Program("ApplicationNameForExample", "output");
|
|
}
|
|
|
|
|
|
//public static void Main()
|
|
//{
|
|
// //var connection = new OmniUniProConnection("COM16");
|
|
// var connection = new OmniIrdaConnection("COM4");
|
|
// connection.StateChenged += Console.WriteLine;
|
|
|
|
// connection.Open();
|
|
// connection.FactorySeal(true);
|
|
// connection.FactorySeal();
|
|
// connection.Close();
|
|
//}
|
|
}
|
|
} |