日常生活的交流与学习

首页 新随笔 联系 管理

secs_learn/Program.cs

using DeviceWorkerService;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Host.CreateDefaultBuilder(args)
    .ConfigureServices((hostContext, services) =>
    {
        services.AddSecs4Net<DeviceLogger>(hostContext.Configuration);
    }).Build().Run();

secs_learn/DeviceWorkerService.cs

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Secs4Net;
using System.Diagnostics.CodeAnalysis;

namespace DeviceWorkerService;

public static class ServiceProvider
{
    public static IServiceCollection AddSecs4Net<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TLogger>(this IServiceCollection services, IConfiguration configuration)
        where TLogger : class, ISecsGemLogger
    {
        var configSection = configuration.GetSection("secs4net");
        services.Configure<SecsGemOptions>(configSection);
        services.AddSingleton<ISecsConnection, HsmsConnection>();
        services.AddSingleton<ISecsGem, SecsGem>();
        services.AddSingleton<ISecsGemLogger, TLogger>();
        return services;
    }
}

secs_learn/DeviceLogger.cs

using Microsoft.Extensions.Logging;
using Secs4Net;
using Secs4Net.Sml;
using System;

namespace DeviceWorkerService;

internal sealed class DeviceLogger(ILogger<DeviceLogger> logger) : ISecsGemLogger
{
    public void MessageIn(SecsMessage msg, int id) => logger.LogTrace($"<-- [0x{id:X8}] {msg.ToSml()}");
    public void MessageOut(SecsMessage msg, int id) => logger.LogTrace($"--> [0x{id:X8}] {msg.ToSml()}");
    public void Debug(string msg) => logger.LogDebug(msg);
    public void Info(string msg) => logger.LogInformation(msg);
    public void Warning(string msg) => logger.LogWarning(msg);
    public void Error(string msg, SecsMessage? message, Exception? ex) => logger.LogError(ex, $"{msg} {message}\n");
}

posted on 2024-01-23 22:26  lazycookie  阅读(251)  评论(0编辑  收藏  举报