未验证 提交 caf7f499 编写于 作者: P Patrick Grawehr 提交者: GitHub

Use common logging provider (#1497)

* Use common logging provider for Arduino binding

* Use common logging for card reader

* Use common logging for Pn532

* Use common logging for Pn5180

* Use common logging for Mfrc522
上级 fa0a4f73
......@@ -13,6 +13,7 @@
<SystemMemoryPackageVersion>4.5.4</SystemMemoryPackageVersion>
<SystemRuntimeInteropServicesWindowsRuntimePackageVersion>4.3.0</SystemRuntimeInteropServicesWindowsRuntimePackageVersion>
<UnitsNetPackageVersion>4.77.0</UnitsNetPackageVersion>
<MicrosoftExtensionsLoggingConsolePackageVersion>5.0.0</MicrosoftExtensionsLoggingConsolePackageVersion>
<MicrosoftExtensionsLoggingPackageVersion>5.0.0</MicrosoftExtensionsLoggingPackageVersion>
<MicrosoftExtensionsLoggingAbstractionsPackageVersion>5.0.0</MicrosoftExtensionsLoggingAbstractionsPackageVersion>
<SixLaborsImageSharpPackageVersion>1.0.2</SixLaborsImageSharpPackageVersion>
......
......@@ -17,6 +17,8 @@ using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Linq;
using Iot.Device.Common;
using Microsoft.Extensions.Logging;
using UnitsNet;
namespace Iot.Device.Arduino
......@@ -44,6 +46,8 @@ namespace Iot.Device.Arduino
private object _initializationLock = new object();
private ILogger _logger;
/// <summary>
/// Creates an instance of an Ardino board connection using the given stream (typically from a serial port)
/// </summary>
......@@ -54,6 +58,7 @@ namespace Iot.Device.Arduino
public ArduinoBoard(Stream serialPortStream)
{
_dataStream = serialPortStream ?? throw new ArgumentNullException(nameof(serialPortStream));
_logger = this.GetCurrentClassLogger();
}
/// <summary>
......@@ -67,12 +72,13 @@ namespace Iot.Device.Arduino
{
_dataStream = null;
_serialPort = new SerialPort(portName, baudRate);
_logger = this.GetCurrentClassLogger();
}
/// <summary>
/// Attach to this event to retrieve log messages. The Exception argument may be null if it is only an informational message.
/// The board logger.
/// </summary>
public event Action<string, Exception?>? LogMessages;
protected ILogger Logger => _logger;
/// <summary>
/// Searches the given list of com ports for a firmata device.
......@@ -202,21 +208,21 @@ namespace Iot.Device.Arduino
throw new NotSupportedException($"Firmata version on board is {_firmataVersion}. Expected {_firmata.QuerySupportedFirmataVersion()}. They must be equal.");
}
Log($"Firmata version on board is {_firmataVersion}.");
Logger.LogInformation($"Firmata version on board is {_firmataVersion}.");
_firmwareVersion = _firmata.QueryFirmwareVersion(out var firmwareName);
_firmwareName = firmwareName;
Log($"Firmware version on board is {_firmwareVersion}");
Logger.LogInformation($"Firmware version on board is {_firmwareVersion}");
_firmata.QueryCapabilities();
_supportedPinConfigurations = _firmata.PinConfigurations.AsReadOnly();
Log("Device capabilities: ");
Logger.LogInformation("Device capabilities: ");
foreach (var pin in _supportedPinConfigurations)
{
Log(pin.ToString());
Logger.LogInformation(pin.ToString());
}
_firmata.EnableDigitalReporting();
......@@ -291,14 +297,16 @@ namespace Iot.Device.Arduino
}
}
internal void Log(string message)
{
LogMessages?.Invoke(message, null);
}
private void FirmataOnError(string message, Exception? innerException)
private void FirmataOnError(string message, Exception? exception)
{
LogMessages?.Invoke(message, innerException);
if (exception != null)
{
Logger.LogError(exception, message);
}
else
{
Logger.LogInformation(message);
}
}
/// <summary>
......
......@@ -7,6 +7,8 @@ using System.Collections.Generic;
using System.Device.Gpio;
using System.Linq;
using System.Threading;
using Iot.Device.Common;
using Microsoft.Extensions.Logging;
namespace Iot.Device.Arduino
{
......@@ -18,6 +20,7 @@ namespace Iot.Device.Arduino
private readonly ConcurrentDictionary<int, PinMode> _pinModes;
private readonly object _callbackContainersLock;
private readonly AutoResetEvent _waitForEventResetEvent;
private readonly ILogger _logger;
internal ArduinoGpioControllerDriver(ArduinoBoard arduinoBoard, IReadOnlyCollection<SupportedPinConfiguration> supportedPinConfigurations)
{
......@@ -27,6 +30,7 @@ namespace Iot.Device.Arduino
_waitForEventResetEvent = new AutoResetEvent(false);
_callbackContainersLock = new object();
_pinModes = new ConcurrentDictionary<int, PinMode>();
_logger = this.GetCurrentClassLogger();
PinCount = _supportedPinConfigurations.Count;
_arduinoBoard.Firmata.DigitalPortValueUpdated += FirmataOnDigitalPortValueUpdated;
......@@ -66,12 +70,14 @@ namespace Iot.Device.Arduino
firmataMode = SupportedMode.DigitalInput;
break;
default:
_logger.LogError($"Mode {mode} is not supported as argument to {nameof(SetPinMode)}");
throw new NotSupportedException($"Mode {mode} is not supported for this operation");
}
var pinConfig = _supportedPinConfigurations.FirstOrDefault(x => x.Pin == pinNumber);
if (pinConfig == null || !pinConfig.PinModes.Contains(firmataMode))
{
_logger.LogError($"Mode {mode} is not supported on Pin {pinNumber}");
throw new NotSupportedException($"Mode {mode} is not supported on Pin {pinNumber}.");
}
......@@ -104,7 +110,7 @@ namespace Iot.Device.Arduino
ret = PinMode.Input;
break;
default:
_arduinoBoard.Log($"Unexpected pin mode found: {mode}. Is the pin not set to GPIO?");
_logger.LogError($"Unexpected pin mode found: {mode}. Is the pin not set to GPIO?");
ret = PinMode.Input;
break;
}
......
......@@ -54,7 +54,6 @@ namespace Arduino.Samples
ArduinoBoard board = new ArduinoBoard(port.BaseStream);
try
{
board.LogMessages += BoardOnLogMessages;
Console.WriteLine($"Firmware version: {board.FirmwareVersion}, Builder: {board.FirmwareName}");
DisplayModes(board);
}
......
......@@ -5,6 +5,7 @@
<TargetFrameworks>net5.0;netcoreapp2.1</TargetFrameworks>
<RootNamespace>Iot.Device.Arduino.Sample</RootNamespace>
<EnableDefaultItems>false</EnableDefaultItems>
<AssemblyName>Arduino.Monitor</AssemblyName>
</PropertyGroup>
<ItemGroup>
......
......@@ -18,6 +18,8 @@ using Iot.Device.Adc;
using Iot.Device.Arduino;
using Iot.Device.Bmxx80;
using Iot.Device.Bmxx80.PowerMode;
using Iot.Device.Common;
using Microsoft.Extensions.Logging;
using UnitsNet;
namespace Arduino.Samples
......@@ -38,6 +40,14 @@ namespace Arduino.Samples
string portName = args[0];
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
});
// Statically register our factory. Note that this must be done before instantiation of any class that wants to use logging.
LogDispatcher.LoggerFactory = loggerFactory;
using (var port = new SerialPort(portName, 115200))
{
Console.WriteLine($"Connecting to Arduino on {portName}");
......@@ -54,7 +64,6 @@ namespace Arduino.Samples
ArduinoBoard board = new ArduinoBoard(port.BaseStream);
try
{
board.LogMessages += BoardOnLogMessages;
// This implicitly connects
Console.WriteLine($"Connecting... Firmware version: {board.FirmwareVersion}, Builder: {board.FirmwareName}");
while (Menu(board))
......
......@@ -5,9 +5,11 @@
<TargetFrameworks>net5.0;netcoreapp2.1</TargetFrameworks>
<RootNamespace>Iot.Device.Arduino.Sample</RootNamespace>
<EnableDefaultItems>false</EnableDefaultItems>
<AssemblyName>Arduino.sample</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(MicrosoftExtensionsLoggingConsolePackageVersion)" />
<PackageReference Include="System.IO.Ports" Version="$(SystemIOPortsPackageVersion)" />
</ItemGroup>
......
......@@ -11,6 +11,8 @@
<ItemGroup>
<ProjectReference Include="../Arduino.csproj" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="5.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.16.0" />
<PackageReference Include="System.IO.Ports" Version="$(SystemIOPortsPackageVersion)" />
......
......@@ -8,6 +8,8 @@ using System.Net;
using System.Net.Sockets;
using System.Text;
using Iot.Device.Arduino;
using Iot.Device.Common;
using Microsoft.Extensions.Logging;
using Xunit;
namespace Arduino.Tests
......@@ -21,6 +23,13 @@ namespace Arduino.Tests
{
try
{
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole().AddProvider(new DebuggerOutputLoggerProvider());
});
// Statically register our factory. Note that this must be done before instantiation of any class that wants to use logging.
LogDispatcher.LoggerFactory = loggerFactory;
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(IPAddress.Loopback, 27016);
_socket.NoDelay = true;
......@@ -32,8 +41,6 @@ namespace Arduino.Tests
throw new NotSupportedException("Very old firmware found");
}
Board.LogMessages += (x, y) => Console.WriteLine(x);
return;
}
catch (SocketException)
......@@ -48,7 +55,6 @@ namespace Arduino.Tests
}
Board = board;
Board.LogMessages += (x, y) => Console.WriteLine(x);
}
public ArduinoBoard? Board
......

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26124.0
# Visual Studio Version 16
VisualStudioVersion = 16.0.31105.61
MinimumVisualStudioVersion = 15.0.26124.0
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CardRfid", "CardRfid.csproj", "{2B97523A-956B-4C88-8931-28C1AF88012C}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CardRfid", "CardRfid.csproj", "{2B97523A-956B-4C88-8931-28C1AF88012C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditCardProcessing", "CreditCard\CreditCardProcessing.csproj", "{A9AC5868-77E7-4742-AF7E-E140F2CFF79B}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CreditCardProcessing", "CreditCard\CreditCardProcessing.csproj", "{A9AC5868-77E7-4742-AF7E-E140F2CFF79B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mifare", "Mifare\Mifare.csproj", "{81A964D2-BA4B-4769-A630-084D8C4BEBDA}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mifare", "Mifare\Mifare.csproj", "{81A964D2-BA4B-4769-A630-084D8C4BEBDA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CommonHelpers", "..\Common\CommonHelpers.csproj", "{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
......@@ -18,9 +20,6 @@ Global
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2B97523A-956B-4C88-8931-28C1AF88012C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2B97523A-956B-4C88-8931-28C1AF88012C}.Debug|Any CPU.Build.0 = Debug|Any CPU
......@@ -58,5 +57,23 @@ Global
{81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Release|x64.Build.0 = Release|Any CPU
{81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Release|x86.ActiveCfg = Release|Any CPU
{81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Release|x86.Build.0 = Release|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Debug|x64.ActiveCfg = Debug|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Debug|x64.Build.0 = Debug|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Debug|x86.ActiveCfg = Debug|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Debug|x86.Build.0 = Debug|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Release|Any CPU.Build.0 = Release|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Release|x64.ActiveCfg = Release|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Release|x64.Build.0 = Release|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Release|x86.ActiveCfg = Release|Any CPU
{03F9B2A3-4B73-4D39-872B-BB0D81F3593E}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D4095E39-2A90-408C-900D-6596AAC77EDA}
EndGlobalSection
EndGlobal
......@@ -8,6 +8,7 @@ using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using Iot.Device.Common;
using Microsoft.Extensions.Logging;
namespace Iot.Device.Card.CreditCardProcessing
{
......@@ -36,6 +37,7 @@ namespace Iot.Device.Card.CreditCardProcessing
private CardTransceiver _nfc;
private bool _alreadyReadSfi = false;
private byte _target;
private ILogger _logger;
/// <summary>
/// The size of the tailer elements. Some readers add an extra byte
......@@ -68,6 +70,7 @@ namespace Iot.Device.Card.CreditCardProcessing
Tags = new List<Tag>();
LogEntries = new List<byte[]>();
TailerSize = tailerSize;
_logger = this.GetCurrentClassLogger();
}
/// <summary>
......@@ -354,7 +357,7 @@ namespace Iot.Device.Card.CreditCardProcessing
List<Tag> appTemplates = Tag.SearchTag(Tags, 0x61);
if (appTemplates.Count > 0)
{
LogInfo.Log($"Number of App Templates: {appTemplates.Count}", LogLevel.Debug);
_logger.LogDebug($"Number of App Templates: {appTemplates.Count}");
foreach (var app in appTemplates)
{
// Find the Application Identifier 0x4F
......@@ -369,7 +372,7 @@ namespace Iot.Device.Card.CreditCardProcessing
}
// do we have a PDOL tag 0x9F38
LogInfo.Log($"APPID: {BitConverter.ToString(appIdentifier.Data)}, Priority: {appPriotity.Data[0]}", LogLevel.Debug);
_logger.LogDebug($"APPID: {BitConverter.ToString(appIdentifier.Data)}, Priority: {appPriotity.Data[0]}");
var ret = Select(appIdentifier.Data);
if (ret == ErrorType.ProcessCompletedNormal)
{
......@@ -504,7 +507,7 @@ namespace Iot.Device.Card.CreditCardProcessing
for (byte record = detail.Start; record < detail.End + 1; record++)
{
ret = ReadRecord(detail.Sfi, record);
LogInfo.Log($"Read record {record}, SFI {detail.Sfi}, status: {ret}", LogLevel.Debug);
_logger.LogDebug($"Read record {record}, SFI {detail.Sfi}, status: {ret}");
}
}
......@@ -522,7 +525,7 @@ namespace Iot.Device.Card.CreditCardProcessing
for (byte sfi = 1; sfi < 11; sfi++)
{
ret = ReadRecord(sfi, record);
LogInfo.Log($"Read record {record}, SFI {sfi}, status: {ret}", LogLevel.Debug);
_logger.LogDebug($"Read record {record}, SFI {sfi}, status: {ret}");
}
}
......@@ -545,11 +548,11 @@ namespace Iot.Device.Card.CreditCardProcessing
var appSfi = Tag.SearchTag(Tags, 0x88).FirstOrDefault();
if (appSfi is object)
{
LogInfo.Log($"AppSFI: {appSfi.Data[0]}", LogLevel.Debug);
_logger.LogDebug($"AppSFI: {appSfi.Data[0]}");
for (byte record = 1; record < 10; record++)
{
var ret = ReadRecord(appSfi.Data[0], record);
LogInfo.Log($"Read record {record}, SFI {appSfi.Data[0]}, status: {ret}", LogLevel.Debug);
_logger.LogDebug($"Read record {record}, SFI {appSfi.Data[0]}, status: {ret}");
}
_alreadyReadSfi = true;
......@@ -567,7 +570,7 @@ namespace Iot.Device.Card.CreditCardProcessing
for (byte record = 1; record < numberOfRecords + 1; record++)
{
var ret = ReadRecord(sfi, record, true);
LogInfo.Log($"Read record {record}, SFI {sfi},status: {ret}", LogLevel.Debug);
_logger.LogDebug($"Read record {record}, SFI {sfi},status: {ret}");
}
}
......@@ -718,11 +721,11 @@ namespace Iot.Device.Card.CreditCardProcessing
}
FillTagList(Tags, received.Slice(0, ret - TailerSize));
LogInfo.Log($"{BitConverter.ToString(received.Slice(0, ret).ToArray())}", LogLevel.Debug);
_logger.LogDebug($"{BitConverter.ToString(received.Slice(0, ret).ToArray())}");
var ber = new BerSplitter(received.Slice(0, ret - TailerSize));
foreach (var b in ber.Tags)
{
LogInfo.Log($"DataType: {dataType}, Tag: {b.TagNumber.ToString("X4")}, Data: {BitConverter.ToString(b.Data)}", LogLevel.Debug);
_logger.LogDebug($"DataType: {dataType}, Tag: {b.TagNumber.ToString("X4")}, Data: {BitConverter.ToString(b.Data)}");
}
return new ProcessError(received.Slice(ret - TailerSize)).ErrorType;
......
......@@ -10,6 +10,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Common\CommonHelpers.csproj" />
<ProjectReference Include="..\CardRfid.csproj" />
</ItemGroup>
......
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
namespace Iot.Device.Card
{
/// <summary>
/// The log level
/// </summary>
public enum LogLevel
{
/// <summary>
/// No log level
/// </summary>
None = 0,
/// <summary>
/// Only information
/// </summary>
Info = 1,
/// <summary>
/// Deep log for debug purpose
/// </summary>
Debug = 2
}
/// <summary>
/// Output where to log the information
/// </summary>
[Flags]
public enum LogTo
{
/// <summary>
/// Log to console
/// </summary>
Console = 0b0000_00001,
/// <summary>
/// Log to debug
/// </summary>
Debug = 0b0000_0010
}
/// <summary>
/// Simple log class to help in debugging the communication
/// between the PN532 and the host
/// </summary>
public class LogInfo
{
/// <summary>
/// Log Level
/// </summary>
public static LogLevel LogLevel { get; set; }
/// <summary>
/// Log to
/// </summary>
public static LogTo LogTo { get; set; } = LogTo.Console;
/// <summary>
/// Log something
/// </summary>
/// <param name="toLog">String to log</param>
/// <param name="logLevel">Log level</param>
public static void Log(string toLog, LogLevel logLevel)
{
if (LogLevel >= logLevel)
{
if ((LogTo & LogTo.Console) == LogTo.Console)
{
Console.WriteLine(toLog);
}
if ((LogTo & LogTo.Debug) == LogTo.Debug)
{
Debug.WriteLine(toLog);
}
}
}
}
}
......@@ -5,6 +5,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Common\CommonHelpers.csproj" />
<ProjectReference Include="..\CardRfid.csproj" />
<ProjectReference Include="..\Ndef\Ndef.csproj" />
</ItemGroup>
......
......@@ -3,7 +3,9 @@
using System;
using System.Linq;
using Iot.Device.Common;
using Iot.Device.Ndef;
using Microsoft.Extensions.Logging;
namespace Iot.Device.Card.Mifare
{
......@@ -27,6 +29,8 @@ namespace Iot.Device.Card.Mifare
// This is the actual RFID reader
private CardTransceiver _rfid;
private ILogger _logger;
/// <summary>
/// Default Key A
/// </summary>
......@@ -98,6 +102,7 @@ namespace Iot.Device.Card.Mifare
{
_rfid = rfid;
Target = target;
_logger = this.GetCurrentClassLogger();
}
/// <summary>
......@@ -113,7 +118,7 @@ namespace Iot.Device.Card.Mifare
}
var ret = _rfid.Transceive(Target, Serialize(), dataOut.AsSpan());
LogInfo.Log($"{nameof(RunMifareCardCommand)}: {Command}, Target: {Target}, Data: {BitConverter.ToString(Serialize())}, Success: {ret}, Dataout: {BitConverter.ToString(dataOut)}", LogLevel.Debug);
_logger.LogDebug($"{nameof(RunMifareCardCommand)}: {Command}, Target: {Target}, Data: {BitConverter.ToString(Serialize())}, Success: {ret}, Dataout: {BitConverter.ToString(dataOut)}");
if ((ret > 0) && (Command == MifareCardCommand.Read16Bytes))
{
Data = dataOut;
......
......@@ -5,6 +5,9 @@
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(MicrosoftExtensionsLoggingConsolePackageVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(MainLibraryPath)System.Device.Gpio.csproj" />
<ProjectReference Include="..\..\Mifare\Mifare.csproj" />
......
......@@ -9,12 +9,14 @@ using System.Text;
using System.Threading;
using Iot.Device.Card;
using Iot.Device.Card.Mifare;
using Iot.Device.Common;
using Iot.Device.Ft4222;
using Iot.Device.Ndef;
using Iot.Device.Pn5180;
using Iot.Device.Pn532;
using Iot.Device.Pn532.ListPassive;
using Iot.Device.Rfid;
using Microsoft.Extensions.Logging;
Pn5180 pn5180;
Pn532 pn532;
......@@ -96,7 +98,15 @@ else
Console.WriteLine("Do you want log level to Debug? Y/N");
var debugLevelConsole = Console.ReadKey();
Console.WriteLine();
LogLevel debugLevel = debugLevelConsole is { KeyChar: 'Y' or 'y' } ? LogLevel.Debug : LogLevel.None;
LogLevel debugLevel = debugLevelConsole is { KeyChar: 'Y' or 'y' } ? LogLevel.Debug : LogLevel.Information;
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddFilter(x => x >= debugLevel);
builder.AddConsole();
});
LogDispatcher.LoggerFactory = loggerFactory;
switch (choiceInterface.KeyChar)
{
......@@ -114,16 +124,16 @@ else
return;
}
pn532 = new Pn532(SpiDevice.Create(new SpiConnectionSettings(0)), pinSelect, logLevel: debugLevel);
pn532 = new Pn532(SpiDevice.Create(new SpiConnectionSettings(0)), pinSelect);
break;
case '2':
pn532 = new Pn532(I2cDevice.Create(new I2cConnectionSettings(1, Pn532.I2cDefaultAddress)), debugLevel);
pn532 = new Pn532(I2cDevice.Create(new I2cConnectionSettings(1, Pn532.I2cDefaultAddress)));
break;
default:
Console.WriteLine("Please enter the serial port to use. ex: COM3 on Windows or /dev/ttyS0 on Linux");
var device = Console.ReadLine();
pn532 = new Pn532(device!, debugLevel);
pn532 = new Pn532(device!);
break;
}
......
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Iot.Device.Common
{
/// <summary>
/// A logger that prints to the debug console
/// </summary>
public class DebuggerOutputLogger : ILogger
{
/// <summary>
/// Creates a new instance of the <see cref="DebuggerOutputLogger"/>
/// </summary>
public DebuggerOutputLogger()
{
MinLogLevel = LogLevel.Debug;
}
/// <summary>
/// Sets the minimum log level
/// </summary>
public LogLevel MinLogLevel
{
get;
set;
}
/// <inheritdoc />
public IDisposable BeginScope<TState>(TState state)
{
return new LogDispatcher.ScopeDisposable();
}
/// <inheritdoc />
public bool IsEnabled(LogLevel logLevel)
{
return logLevel >= MinLogLevel;
}
/// <inheritdoc />
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
string msg = formatter(state, exception);
Debug.WriteLine(msg);
}
}
}
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Iot.Device.Common
{
/// <summary>
/// Creates a debugger logger
/// </summary>
public class DebuggerOutputLoggerProvider : ILoggerProvider
{
/// <inheritdoc />
public ILogger CreateLogger(string categoryName)
{
return new DebuggerOutputLogger();
}
/// <inheritdoc />
public void Dispose()
{
}
}
}
......@@ -7,7 +7,7 @@
<ItemGroup>
<ProjectReference Include="../CommonHelpers.csproj" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(MicrosoftExtensionsLoggingConsolePackageVersion)" />
</ItemGroup>
</Project>
......@@ -13,6 +13,8 @@ using System.Threading;
using Iot.Device.Card;
using Iot.Device.Rfid;
using Iot.Device.Card.Mifare;
using Iot.Device.Common;
using Microsoft.Extensions.Logging;
namespace Iot.Device.Mfrc522
{
......@@ -37,8 +39,9 @@ namespace Iot.Device.Mfrc522
private SerialPort? _serialPort;
private GpioController? _controller;
private bool _shouldDispose;
private ILogger _logger;
#region constructors
#region Constructors
/// <summary>
/// Constructor for MFRC5222 with SPI interface.
......@@ -51,6 +54,7 @@ namespace Iot.Device.Mfrc522
{
_spiDevice = spiDevice;
_pinReset = pinReset;
_logger = this.GetCurrentClassLogger();
HardReset(gpioController, shouldDispose);
SetDefaultValues();
......@@ -67,6 +71,7 @@ namespace Iot.Device.Mfrc522
{
_i2CDevice = i2cDevice;
_pinReset = pinReset;
_logger = this.GetCurrentClassLogger();
HardReset(gpioController, shouldDispose);
SetDefaultValues();
......@@ -93,6 +98,7 @@ namespace Iot.Device.Mfrc522
/// <param name="shouldDispose">True to dispose the GpioController.</param>
public MfRc522(SerialPort serialPort, int pinReset = -1, GpioController? gpioController = null, bool shouldDispose = true)
{
_logger = this.GetCurrentClassLogger();
_serialPort = serialPort;
_serialPort.ReadTimeout = 1000;
_serialPort.WriteTimeout = 1000;
......@@ -929,7 +935,7 @@ namespace Iot.Device.Mfrc522
status = SendAndReceiveData(MfrcCommand.Transceive, toSendFirst.ToArray(), null);
if (status != Status.Ok)
{
LogInfo.Log($"{nameof(TwoStepsIncDecRestore)} - Error {(MfrcCommand)dataToSend[0]}", LogLevel.Debug);
_logger.LogWarning($"{nameof(TwoStepsIncDecRestore)} - Error {(MfrcCommand)dataToSend[0]}");
return -1;
}
......
......@@ -13,7 +13,9 @@ using System.Threading;
using System.Diagnostics.CodeAnalysis;
using Iot.Device.Card;
using Iot.Device.Card.Mifare;
using Iot.Device.Common;
using Iot.Device.Rfid;
using Microsoft.Extensions.Logging;
namespace Iot.Device.Pn5180
{
......@@ -33,6 +35,8 @@ namespace Iot.Device.Pn5180
private int _pinBusy;
private int _pinNss;
private ILogger _logger;
/// <summary>
/// A radio Frequency configuration element size is 5 bytes
/// Byte 1 = Register Address
......@@ -50,24 +54,6 @@ namespace Iot.Device.Pn5180
/// </summary>
public const SpiMode DefaultSpiMode = System.Device.Spi.SpiMode.Mode0;
/// <summary>
/// The Log level
/// </summary>
public LogLevel LogLevel
{
get => LogInfo.LogLevel;
set => LogInfo.LogLevel = value;
}
/// <summary>
/// The location to log the info
/// </summary>
public LogTo LogTo
{
get => LogInfo.LogTo;
set => LogInfo.LogTo = value;
}
/// <summary>
/// Create a PN5180 RFID/NFC reader
/// </summary>
......@@ -76,8 +62,7 @@ namespace Iot.Device.Pn5180
/// <param name="pinNss">The pin for the SPI select line. This has to be handle differently than thru the normal process as PN5180 has a specific way of working</param>
/// <param name="gpioController">A GPIO controller, null will use a default one</param>
/// <param name="shouldDispose">Dispose the SPI and the GPIO controller at the end if true</param>
/// <param name="logLevel">The log level</param>
public Pn5180(SpiDevice spiDevice, int pinBusy, int pinNss, GpioController? gpioController = null, bool shouldDispose = true, LogLevel logLevel = LogLevel.None)
public Pn5180(SpiDevice spiDevice, int pinBusy, int pinNss, GpioController? gpioController = null, bool shouldDispose = true)
{
if (pinBusy < 0)
{
......@@ -89,9 +74,8 @@ namespace Iot.Device.Pn5180
throw new ArgumentException(nameof(pinBusy), "Value must be a legal pin number. cannot be negative.");
}
LogLevel = logLevel;
LogInfo.Log($"Opening PN5180, pin busy: {pinBusy}, pin NSS: {pinNss}", LogLevel.Debug);
_logger = this.GetCurrentClassLogger();
_logger.LogDebug($"Opening PN5180, pin busy: {pinBusy}, pin NSS: {pinNss}");
_spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
_gpioController = gpioController ?? new GpioController(PinNumberingScheme.Logical);
_shouldDispose = shouldDispose || gpioController is null;
......@@ -206,22 +190,16 @@ namespace Iot.Device.Pn5180
dumpEeprom[0] = (byte)Command.READ_EEPROM;
dumpEeprom[1] = (byte)address;
dumpEeprom[2] = (byte)eeprom.Length;
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(ReadEeprom)}, {nameof(dumpEeprom)}: {BitConverter.ToString(dumpEeprom.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(ReadEeprom)}, {nameof(dumpEeprom)}: {BitConverter.ToString(dumpEeprom.ToArray())}");
try
{
SpiWriteRead(dumpEeprom, eeprom);
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(ReadEeprom)}, {nameof(dumpEeprom)}: {BitConverter.ToString(dumpEeprom.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(ReadEeprom)}, {nameof(dumpEeprom)}: {BitConverter.ToString(dumpEeprom.ToArray())}");
}
catch (TimeoutException)
catch (TimeoutException tx)
{
LogInfo.Log($"{nameof(ReadEeprom)}: {nameof(TimeoutException)} during {nameof(SpiWriteRead)}", LogLevel.Debug);
_logger.LogError(tx, $"{nameof(ReadEeprom)}: {nameof(TimeoutException)} during {nameof(SpiWriteRead)}");
return false;
}
......@@ -246,18 +224,12 @@ namespace Iot.Device.Pn5180
dumpEeprom[0] = (byte)Command.WRITE_EEPROM;
dumpEeprom[1] = (byte)address;
eeprom.CopyTo(dumpEeprom.Slice(2));
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(WriteEeprom)}, {nameof(eeprom)}: {BitConverter.ToString(eeprom.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(WriteEeprom)}, {nameof(eeprom)}: {BitConverter.ToString(eeprom.ToArray())}");
try
{
SpiWrite(dumpEeprom);
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(WriteEeprom)}, {nameof(dumpEeprom)}: {BitConverter.ToString(dumpEeprom.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(WriteEeprom)}, {nameof(dumpEeprom)}: {BitConverter.ToString(dumpEeprom.ToArray())}");
Span<byte> irqStatus = stackalloc byte[4];
ret = GetIrqStatus(irqStatus);
......@@ -265,9 +237,9 @@ namespace Iot.Device.Pn5180
// Clear IRQ
SpiWriteRegister(Command.WRITE_REGISTER, Register.IRQ_CLEAR, new byte[] { 0xFF, 0xFF, 0x0F, 0x00 });
}
catch (TimeoutException)
catch (TimeoutException tx)
{
LogInfo.Log($"{nameof(WriteEeprom)}: {nameof(TimeoutException)} during {nameof(SpiWrite)}", LogLevel.Debug);
_logger.LogError(tx, $"{nameof(WriteEeprom)}: {nameof(TimeoutException)} during {nameof(SpiWrite)}");
return false;
}
......@@ -304,18 +276,15 @@ namespace Iot.Device.Pn5180
sendData[0] = (byte)Command.SEND_DATA;
sendData[1] = (byte)(numberValidBitsLastByte == 8 ? 0 : numberValidBitsLastByte);
toSend.CopyTo(sendData.Slice(2));
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(SendDataToCard)}: {nameof(sendData)}, {BitConverter.ToString(sendData.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(SendDataToCard)}: {nameof(sendData)}, {BitConverter.ToString(sendData.ToArray())}");
try
{
SpiWrite(sendData);
}
catch (TimeoutException)
catch (TimeoutException tx)
{
LogInfo.Log($"{nameof(SendDataToCard)}: {nameof(TimeoutException)} in {nameof(SpiWrite)}", LogLevel.Debug);
_logger.LogError(tx, $"{nameof(SendDataToCard)}: {nameof(TimeoutException)} in {nameof(SpiWrite)}");
return false;
}
......@@ -340,22 +309,16 @@ namespace Iot.Device.Pn5180
Span<byte> sendData = stackalloc byte[2];
sendData[0] = (byte)Command.READ_DATA;
sendData[1] = 0x00;
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(ReadDataFromCard)}: {nameof(sendData)}, {BitConverter.ToString(sendData.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(ReadDataFromCard)}: {nameof(sendData)}, {BitConverter.ToString(sendData.ToArray())}");
try
{
SpiWriteRead(sendData, toRead);
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(ReadDataFromCard)}: {nameof(toRead)}, {BitConverter.ToString(toRead.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(ReadDataFromCard)}: {nameof(toRead)}, {BitConverter.ToString(toRead.ToArray())}");
}
catch (TimeoutException)
catch (TimeoutException tx)
{
LogInfo.Log($"{nameof(ReadDataFromCard)}: {nameof(TimeoutException)} in {nameof(SpiWriteRead)}", LogLevel.Debug);
_logger.LogError(tx, $"{nameof(ReadDataFromCard)}: {nameof(TimeoutException)} in {nameof(SpiWriteRead)}");
return false;
}
......@@ -376,19 +339,13 @@ namespace Iot.Device.Pn5180
var (numBytes, _) = GetNumberOfBytesReceivedAndValidBits();
if (numBytes == expectedToRead)
{
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(ReadDataFromCard)}: right number of expected bytes to read", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(ReadDataFromCard)}: right number of expected bytes to read");
return ReadDataFromCard(toRead);
}
else if (numBytes > expectedToRead)
{
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(ReadDataFromCard)}: wrong number of expected bytes, clearing the cache", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(ReadDataFromCard)}: wrong number of expected bytes, clearing the cache");
// Clear all
ReadDataFromCard(new byte[numBytes]);
......@@ -408,7 +365,7 @@ namespace Iot.Device.Pn5180
/// detect a card, select it and then send data</remarks>
public bool ReadDataFromCard(Span<byte> toRead, out int bytesRead)
{
LogInfo.Log($"{nameof(ReadDataFromCard)}: ", LogLevel.Debug);
_logger.LogDebug($"{nameof(ReadDataFromCard)}: ");
var (numBytes, _) = GetNumberOfBytesReceivedAndValidBits();
if (numBytes < 0)
{
......@@ -441,9 +398,9 @@ namespace Iot.Device.Pn5180
// from NXP documentation PN5180AXX-C3.pdf, Page 98
return ((status[0] + ((status[1] & 0x01) << 8)), (status[1] & 0b1110_0000) >> 5);
}
catch (TimeoutException)
catch (TimeoutException tx)
{
LogInfo.Log($"{nameof(SendDataToCard)}: {nameof(TimeoutException)} in {nameof(SpiReadRegister)}", LogLevel.Debug);
_logger.LogError(tx, $"{nameof(SendDataToCard)}: {nameof(TimeoutException)} in {nameof(SpiReadRegister)}");
return (-1, -1);
}
}
......@@ -714,7 +671,7 @@ namespace Iot.Device.Pn5180
/// <returns>True if success</returns>
public bool MifareAuthenticate(ReadOnlySpan<byte> key, MifareCardCommand mifareCommand, byte blockAddress, ReadOnlySpan<byte> cardUid)
{
LogInfo.Log($"{nameof(MifareAuthenticate)}: ", LogLevel.Debug);
_logger.LogDebug($"{nameof(MifareAuthenticate)}: ");
if (key.Length != 6)
{
throw new ArgumentException(nameof(key), "Value must be 6 bytes.");
......@@ -738,22 +695,16 @@ namespace Iot.Device.Pn5180
toAuthenticate[7] = (byte)(mifareCommand == MifareCardCommand.AuthenticationA ? 0x60 : 0x61);
toAuthenticate[8] = blockAddress;
cardUid.CopyTo(toAuthenticate.Slice(9));
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(MifareAuthenticate)}: {nameof(toAuthenticate)}: {BitConverter.ToString(toAuthenticate.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(MifareAuthenticate)}: {nameof(toAuthenticate)}: {BitConverter.ToString(toAuthenticate.ToArray())}");
try
{
SpiWriteRead(toAuthenticate, response);
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(MifareAuthenticate)}: {nameof(response)}: {BitConverter.ToString(response.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(MifareAuthenticate)}: {nameof(response)}: {BitConverter.ToString(response.ToArray())}");
}
catch (TimeoutException)
catch (TimeoutException tx)
{
LogInfo.Log($"{nameof(ReadDataFromCard)}: {nameof(TimeoutException)} in {nameof(SpiWriteRead)}", LogLevel.Debug);
_logger.LogError(tx, $"{nameof(ReadDataFromCard)}: {nameof(TimeoutException)} in {nameof(SpiWriteRead)}");
return false;
}
......@@ -1073,7 +1024,7 @@ namespace Iot.Device.Pn5180
if (numBytes != 5)
{
// This can happen if a card is pulled out of the field
LogInfo.Log($"SAK length not 5", LogLevel.Debug);
_logger.LogWarning($"SAK length not 5");
return false;
}
......@@ -1436,7 +1387,7 @@ namespace Iot.Device.Pn5180
private bool GetRxStatus(Span<byte> rxStatus)
{
LogInfo.Log($"{nameof(GetRxStatus)}", LogLevel.Debug);
_logger.LogDebug($"{nameof(GetRxStatus)}");
if (rxStatus.Length != 4)
{
throw new ArgumentException(nameof(rxStatus), "Value must be 4 bytes.");
......@@ -1445,14 +1396,11 @@ namespace Iot.Device.Pn5180
try
{
SpiReadRegister(Register.RX_STATUS, rxStatus);
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(GetRxStatus)}: {nameof(rxStatus)}: {BitConverter.ToString(rxStatus.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(GetRxStatus)}: {nameof(rxStatus)}: {BitConverter.ToString(rxStatus.ToArray())}");
}
catch (TimeoutException)
catch (TimeoutException tx)
{
LogInfo.Log($"{nameof(GetRxStatus)}: {nameof(TimeoutException)} in {nameof(SpiReadRegister)}", LogLevel.Debug);
_logger.LogError(tx, $"{nameof(GetRxStatus)}: {nameof(TimeoutException)} in {nameof(SpiReadRegister)}");
return false;
}
......@@ -1461,7 +1409,7 @@ namespace Iot.Device.Pn5180
private bool GetIrqStatus(Span<byte> irqStatus)
{
LogInfo.Log($"{nameof(GetIrqStatus)}", LogLevel.Debug);
_logger.LogDebug($"{nameof(GetIrqStatus)}");
if (irqStatus.Length != 4)
{
throw new ArgumentException(nameof(irqStatus), "Value must be 4 bytes.");
......@@ -1470,14 +1418,11 @@ namespace Iot.Device.Pn5180
try
{
SpiReadRegister(Register.IRQ_STATUS, irqStatus);
if (LogLevel >= LogLevel.Debug)
{
LogInfo.Log($"{nameof(GetIrqStatus)}: {nameof(irqStatus)}: {BitConverter.ToString(irqStatus.ToArray())}", LogLevel.Debug);
}
_logger.LogDebug($"{nameof(GetIrqStatus)}: {nameof(irqStatus)}: {BitConverter.ToString(irqStatus.ToArray())}");
}
catch (TimeoutException)
catch (TimeoutException tx)
{
LogInfo.Log($"{nameof(GetIrqStatus)}: {nameof(TimeoutException)} in {nameof(SpiReadRegister)}", LogLevel.Debug);
_logger.LogError(tx, $"{nameof(GetIrqStatus)}: {nameof(TimeoutException)} in {nameof(SpiReadRegister)}");
return false;
}
......
此差异已折叠。
......@@ -17,6 +17,7 @@
<ItemGroup>
<ProjectReference Include="..\Card\CardRfid.csproj" />
<ProjectReference Include="..\Common\CommonHelpers.csproj" />
</ItemGroup>
</Project>
......@@ -7,7 +7,7 @@
<ItemGroup>
<ProjectReference Include="$(MainLibraryPath)System.Device.Gpio.csproj" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(MicrosoftExtensionsLoggingConsolePackageVersion)" />
</ItemGroup>
<ItemGroup>
......
......@@ -12,8 +12,11 @@ using System.Threading.Tasks;
using Iot.Device.Card;
using Iot.Device.Card.CreditCardProcessing;
using Iot.Device.Card.Mifare;
using Iot.Device.Common;
using Iot.Device.Pn532;
using Iot.Device.Pn532.ListPassive;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
Pn532 pn532;
......@@ -33,7 +36,16 @@ if (choiceInterface is not { KeyChar: '1' or '2' or '3' })
Console.WriteLine("Do you want log level to Debug? Y/N");
var debugLevelConsole = Console.ReadKey();
Console.WriteLine();
LogLevel debugLevel = debugLevelConsole is { KeyChar: 'Y' or 'y' } ? LogLevel.Debug : LogLevel.None;
LogLevel debugLevel = debugLevelConsole is { KeyChar: 'Y' or 'y' } ? LogLevel.Debug : LogLevel.Information;
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddFilter(x => x >= debugLevel);
builder.AddConsole();
});
// Statically register our factory. Note that this must be done before instantiation of any class that wants to use logging.
LogDispatcher.LoggerFactory = loggerFactory;
if (choiceInterface is { KeyChar: '3' })
{
......@@ -50,18 +62,18 @@ if (choiceInterface is { KeyChar: '3' })
return;
}
pn532 = new Pn532(SpiDevice.Create(new SpiConnectionSettings(0) { DataFlow = DataFlow.LsbFirst, Mode = SpiMode.Mode0 }), pinSelect, logLevel: debugLevel);
pn532 = new Pn532(SpiDevice.Create(new SpiConnectionSettings(0) { DataFlow = DataFlow.LsbFirst, Mode = SpiMode.Mode0 }), pinSelect);
}
else if (choiceInterface is { KeyChar: '2' })
{
pn532 = new Pn532(I2cDevice.Create(new I2cConnectionSettings(1, Pn532.I2cDefaultAddress)), debugLevel);
pn532 = new Pn532(I2cDevice.Create(new I2cConnectionSettings(1, Pn532.I2cDefaultAddress)));
}
else
{
Console.WriteLine("Please enter the serial port to use. ex: COM3 on Windows or /dev/ttyS0 on Linux");
var device = Console.ReadLine();
pn532 = new Pn532(device!, debugLevel);
pn532 = new Pn532(device!);
}
if (pn532.FirmwareVersion is FirmwareVersion version)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册