Skip to content

Commit

Permalink
Fix cpu version display
Browse files Browse the repository at this point in the history
- fix logger always printing to console if disabled
- add register adding at connected time and clearing
  • Loading branch information
Sandoun committed Aug 25, 2023
1 parent 8bd1ce6 commit 6dd2a16
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 101 deletions.
11 changes: 11 additions & 0 deletions MewtocolNet/IPlc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,17 @@ public interface IPlc : IDisposable, INotifyPropertyChanged {
/// </summary>
IEnumerable<IRegister> GetAllRegisters();

/// <summary>
/// Builds and adds registers to the device
/// </summary>
/// <param name="builder"></param>
void BuildRegisters(Action<RBuildMulti> builder);

/// <summary>
/// Clears all registers atached to the interface
/// </summary>
void ClearAllRegisters();

/// <summary>
/// Explains the register internal layout at this moment in time
/// </summary>
Expand Down
4 changes: 2 additions & 2 deletions MewtocolNet/Logging/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public static class Logger {
/// <summary>
/// Defines the default output logger targets
/// </summary>
public static LoggerTargets DefaultTargets { get; set; } = LoggerTargets.None;
public static LoggerTargets DefaultTargets { get; set; } = LoggerTargets.Console;

internal static Action<DateTime, LogLevel, string> LogInvoked;

Expand All @@ -26,7 +26,7 @@ static Logger () {

OnNewLogMessage((d, l, m) => {
if(isConsoleApplication || DefaultTargets.HasFlag(LoggerTargets.Console)) {
if(isConsoleApplication && DefaultTargets.HasFlag(LoggerTargets.Console)) {
switch (l) {
case LogLevel.Error:
Expand Down
43 changes: 2 additions & 41 deletions MewtocolNet/MewtocolInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ public void StopReconnecting () {
#region Message sending and queuing

//internally used send task
internal async Task<MewtocolFrameResponse> SendCommandInternalAsync(string _msg, Action<double> onReceiveProgress = null) {
internal async Task<MewtocolFrameResponse> SendCommandInternalAsync(string _msg, Action<double> onReceiveProgress = null, int? overrideTimeout = null) {

if (tSourceMessageCancel.Token.IsCancellationRequested) return MewtocolFrameResponse.Canceled;

Expand All @@ -484,7 +484,7 @@ internal async Task<MewtocolFrameResponse> SendCommandInternalAsync(string _msg,
//send request
regularSendTask = SendTwoDirectionalFrameAsync(_msg, onReceiveProgress);

var timeoutAwaiter = await Task.WhenAny(regularSendTask, Task.Delay(sendReceiveTimeoutMs, tSourceMessageCancel.Token));
var timeoutAwaiter = await Task.WhenAny(regularSendTask, Task.Delay(overrideTimeout ?? sendReceiveTimeoutMs, tSourceMessageCancel.Token));

if (timeoutAwaiter != regularSendTask) {

Expand Down Expand Up @@ -530,43 +530,6 @@ internal async Task<MewtocolFrameResponse> SendCommandInternalAsync(string _msg,

}

private protected async Task<MewtocolFrameResponse> SendOneDirectionalFrameAsync (string frame) {

try {

if (stream == null) return MewtocolFrameResponse.NotIntialized;

frame = $"{frame.BCC_Mew()}\r";

SetUpstreamStopWatchStart();

IsSending = true;

if (tSourceMessageCancel.Token.IsCancellationRequested) return MewtocolFrameResponse.Canceled;

//write inital command
byte[] writeBuffer = Encoding.UTF8.GetBytes(frame);
await stream.WriteAsync(writeBuffer, 0, writeBuffer.Length, tSourceMessageCancel.Token);

IsSending = false;

//calc upstream speed
CalcUpstreamSpeed(writeBuffer.Length);

OnOutMsg(frame);
OnEndMsg();

} catch (Exception ex) {

IsSending = false;
return new MewtocolFrameResponse(400, ex.Message.ToString());

}

return MewtocolFrameResponse.EmptySuccess;

}

private protected async Task<MewtocolFrameResponse> SendTwoDirectionalFrameAsync(string frame, Action<double> onReceiveProgress = null) {

try {
Expand Down Expand Up @@ -899,8 +862,6 @@ private protected void OnReconnected () {
ClearRegisterVals();
KillPoller();

//GetAllRegisters().Cast<Register>().ToList().ForEach(x => x.OnPlcDisconnected());

//generate a new cancellation token source
tSourceMessageCancel = new CancellationTokenSource();

Expand Down
56 changes: 10 additions & 46 deletions MewtocolNet/MewtocolInterfaceRegisterHandling.cs
Original file line number Diff line number Diff line change
Expand Up @@ -327,63 +327,27 @@ internal void WithRegisterCollections(List<RegisterCollection> collections) {

#region Register Adding

internal void AddRegisters(params Register[] registers) {

memoryManager.LinkAndMergeRegisters(registers.ToList());

}

private bool CheckDuplicateRegister(Register instance, out Register foundDupe) {

foundDupe = RegistersInternal.FirstOrDefault(x => x.CompareIsDuplicate(instance));

return RegistersInternal.Contains(instance) || foundDupe != null;

}
/// <inheritdoc/>>
public void BuildRegisters (Action<RBuildMulti> builder) {

private bool CheckDuplicateRegister(Register instance) {
var regBuilder = new RBuildMulti(this);

var foundDupe = RegistersInternal.FirstOrDefault(x => x.CompareIsDuplicate(instance));
builder.Invoke(regBuilder);

return RegistersInternal.Contains(instance) || foundDupe != null;
this.AddRegisters(regBuilder.assembler.assembled.ToArray());

}

private bool CheckDuplicateNameRegister(Register instance) {
/// <inheritdoc/>>
public void ClearAllRegisters () {

return RegistersInternal.Any(x => x.CompareIsNameDuplicate(instance));
memoryManager.ClearAllRegisters();

}

private bool CheckOverlappingRegister(Register instance, out Register regB) {

//ignore bool registers, they have their own address spectrum
regB = null;
if (instance is BoolRegister) return false;

uint addressFrom = instance.MemoryAddress;
uint addressTo = addressFrom + instance.GetRegisterAddressLen();

var foundOverlapping = RegistersInternal.FirstOrDefault(x => {
//ignore bool registers, they have their own address spectrum
if (x is BoolRegister) return false;
uint addressF = x.MemoryAddress;
uint addressT = addressF + x.GetRegisterAddressLen();
bool matchingBaseAddress = addressFrom < addressT && addressF < addressTo;
return matchingBaseAddress;
});

if (foundOverlapping != null) {
regB = foundOverlapping;
return true;
}
internal void AddRegisters(params Register[] registers) {

return false;
memoryManager.LinkAndMergeRegisters(registers.ToList());

}

Expand Down
4 changes: 2 additions & 2 deletions MewtocolNet/MewtocolInterfaceRequests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ public abstract partial class MewtocolInterface {
/// <returns>A PLCInfo class</returns>
public async Task<PLCInfo> GetInfoAsync(bool detailed = true) {

MewtocolFrameResponse resRT = await SendCommandInternalAsync("%EE#RT");
MewtocolFrameResponse resRT = await SendCommandInternalAsync($"%{GetStationNumber()}#RT");

if (!resRT.Success || tSourceMessageCancel.Token.IsCancellationRequested) return null;

MewtocolFrameResponse? resEXRT = null;

if (isConnectingStage && detailed) {

resEXRT = await SendCommandInternalAsync("%EE#EX00RT00");
resEXRT = await SendCommandInternalAsync($"%{GetStationNumber()}#EX00RT00");

}

Expand Down
8 changes: 1 addition & 7 deletions MewtocolNet/MewtocolInterfaceTcp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public void ConfigureConnection(IPAddress ip, int port = 9094, int station = 0xE
/// <inheritdoc/>
public override async Task<ConnectResult> ConnectAsync(Func<Task> callBack = null) => await ConnectAsyncPriv(callBack);

private void BuildTcpClient () {
protected internal void BuildTcpClient () {

Check warning on line 75 in MewtocolNet/MewtocolInterfaceTcp.cs

View workflow job for this annotation

GitHub Actions / Run tests and documentation

'MewtocolInterfaceTcp.BuildTcpClient()': new protected member declared in sealed type

if (HostEndpoint != null) {

Expand All @@ -87,9 +87,6 @@ private void BuildTcpClient () {

client = new TcpClient(HostEndpoint) {
ReceiveBufferSize = RecBufferSize,
NoDelay = false,
ReceiveTimeout = sendReceiveTimeoutMs,
SendTimeout = sendReceiveTimeoutMs,
};

var ep = (IPEndPoint)client.Client.LocalEndPoint;
Expand All @@ -99,9 +96,6 @@ private void BuildTcpClient () {

client = new TcpClient() {
ReceiveBufferSize = RecBufferSize,
NoDelay = false,
ReceiveTimeout = sendReceiveTimeoutMs,
SendTimeout = sendReceiveTimeoutMs,
};

}
Expand Down
11 changes: 8 additions & 3 deletions MewtocolNet/PLCInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,11 @@ internal bool TryExtendFromEXRT(string msg) {
this.TypeCode = (PlcType)tempTypeCode;

}


var cpuVerStr = match.Groups["ver"].Value;

//overwrite the other vals that are also contained in EXRT
this.CpuVersion = match.Groups["ver"].Value.Insert(1, ".");
this.CpuVersion = string.Join(".", cpuVerStr.Select(x => byte.Parse($"{x}", NumberStyles.HexNumber).ToString()));
this.HardwareInformation = (HWInformation)byte.Parse(match.Groups["hwif"].Value, NumberStyles.HexNumber);

return true;
Expand Down Expand Up @@ -206,9 +208,12 @@ internal static bool TryFromRT(string msg, MewtocolInterface onInterface, out PL

}

var cpuVerStr = match.Groups["cpuver"].Value;
var cpuVer = string.Join(".", cpuVerStr.Select(x => byte.Parse($"{x}").ToString("X1")));

inf = new PLCInfo (onInterface) {
TypeCode = typeCodeFull,
CpuVersion = match.Groups["cpuver"].Value.Insert(1, "."),
CpuVersion = cpuVer,
ProgramCapacity = definedProgCapacity,
SelfDiagnosticError = match.Groups["sdiag"].Value,
OperationMode = (OPMode)byte.Parse(match.Groups["op"].Value, NumberStyles.HexNumber),
Expand Down

0 comments on commit 6dd2a16

Please sign in to comment.