Skip to content

Commit

Permalink
Configuration layer is being added
Browse files Browse the repository at this point in the history
  • Loading branch information
rtaum committed Dec 2, 2018
1 parent d866cf6 commit 1cf645d
Show file tree
Hide file tree
Showing 10 changed files with 96 additions and 109 deletions.
9 changes: 9 additions & 0 deletions ZWaveCore/ZWave.Configuration/INodeConfiguration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System;

namespace ZWave.Configuration
{
public interface INodeConfiguration
{

}
}
7 changes: 7 additions & 0 deletions ZWaveCore/ZWave.Configuration/ZWave.Configuration.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

</Project>
27 changes: 20 additions & 7 deletions ZWaveCore/ZWaveConsole/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using NLog;
using System;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -11,6 +13,8 @@ namespace ZWaveConsole
{
class Program
{
private static ILogger Logger = LogManager.GetCurrentClassLogger();

static void Main(string[] args)
{
Task.Run(async () => await CreateControllerAsync());
Expand All @@ -19,7 +23,7 @@ static void Main(string[] args)

private static async Task CreateControllerAsync()
{
var ports = System.IO.Ports.SerialPort.GetPortNames();
var ports = SerialPort.GetPortNames();
var portName = ports.First();

var channel = new ZWaveChannel(portName);
Expand All @@ -28,11 +32,19 @@ private static async Task CreateControllerAsync()
{
using (var controller = new ZWaveController(portName))
{
controller.Open();
await ExploreNodes(controller);
Console.WriteLine($"Started at {DateTime.Now.ToShortTimeString()}");
Console.ReadLine();
Console.WriteLine("Waiting is over");
try
{
controller.Open();
await ExploreNodes(controller);
Console.WriteLine($"Started at {DateTime.Now.ToShortTimeString()}");
Console.ReadLine();
Console.WriteLine("Waiting is over");
}
catch (Exception ecc)
{

throw;
}
}
}
catch (Exception ex)
Expand All @@ -47,6 +59,7 @@ private static async Task ExploreNodes(ZWaveController controller)
var nodes = allNodes.Skip(1).Take(1);
foreach (var node in nodes)
{
var neighbours = await node.GetNeighbours();
var protocolInfo = await node.GetProtocolInfo();
var supportedClasses = await node.GetSupportedCommandClasses();
var command = node.GetCommandClass<SensorMultiLevel>();
Expand Down
5 changes: 5 additions & 0 deletions ZWaveCore/ZWaveConsole/ZWaveConsole.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
<LangVersion>7.3</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NLog" Version="4.5.11" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.3.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\ZWaveCore\ZWaveCore.csproj" />
</ItemGroup>
Expand Down
10 changes: 8 additions & 2 deletions ZWaveCore/ZWaveCore.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ VisualStudioVersion = 15.0.28010.2041
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZWaveCore", "ZWaveCore\ZWaveCore.csproj", "{91BAA3C2-7AA7-4158-B005-160ADB1D9573}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZWaveConsole", "ZWaveConsole\ZWaveConsole.csproj", "{27F8A0F1-FABD-4E0D-BA56-5F7C7EAF0525}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZWaveConsole", "ZWaveConsole\ZWaveConsole.csproj", "{27F8A0F1-FABD-4E0D-BA56-5F7C7EAF0525}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZWaveTest", "ZWaveTest\ZWaveTest.csproj", "{88384F43-8228-44DE-98EC-C9F3C7A14C1D}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZWaveTest", "ZWaveTest\ZWaveTest.csproj", "{88384F43-8228-44DE-98EC-C9F3C7A14C1D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZWave.Configuration", "ZWave.Configuration\ZWave.Configuration.csproj", "{89710B95-FF30-442E-9437-24D6E1CB93FC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -27,6 +29,10 @@ Global
{88384F43-8228-44DE-98EC-C9F3C7A14C1D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{88384F43-8228-44DE-98EC-C9F3C7A14C1D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{88384F43-8228-44DE-98EC-C9F3C7A14C1D}.Release|Any CPU.Build.0 = Release|Any CPU
{89710B95-FF30-442E-9437-24D6E1CB93FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{89710B95-FF30-442E-9437-24D6E1CB93FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{89710B95-FF30-442E-9437-24D6E1CB93FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{89710B95-FF30-442E-9437-24D6E1CB93FC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

namespace ZWaveCore.Core.EventArguments
{
public class ErrorEventArgs : EventArgs
public class ErrorEventArguments : EventArgs
{
public readonly Exception Error;

public ErrorEventArgs(Exception error)
public ErrorEventArguments(Exception error)
{
Error = error;
}
Expand Down
111 changes: 26 additions & 85 deletions ZWaveCore/ZWaveCore/Core/ZWaveChannel.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using NLog;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using ZWaveCore.Core.EventArguments;
Expand All @@ -10,29 +12,32 @@
using ZWaveCore.Enums;
using ZWaveCore.Messages;

using ErrorEventArgs = ZWaveCore.Core.EventArguments.ErrorEventArgs;

namespace ZWaveCore.Core
{
public class ZWaveChannel : IDisposable
{
private readonly ILogger _logger = null; // LogManager.GetCurrentClassLogger();

private readonly SemaphoreSlim _semaphore;

private Task _portReadTask;
private Task _processEventsTask;
private Task _processUpdatesTask;
private Task _transmitTask;

private BlockingCollection<NodeEvent> _eventQueue;
private BlockingCollection<NodeUpdate> _updateQueue;
private BlockingCollection<Message> _transmitQueue;
private BlockingCollection<Message> _responseQueue;

public readonly ISerialPort Port;
public TextWriter Log { get; set; }

public TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(2);
public TimeSpan ResponseTimeout = TimeSpan.FromSeconds(5);

public event EventHandler<NodeEventArgs> NodeEventReceived;
public event EventHandler<NodeUpdateEventArgs> NodeUpdateReceived;
public event EventHandler<ErrorEventArgs> Error;
public event EventHandler<ErrorEventArguments> Error;
public event EventHandler Closed;

public int MaxRetryCount { get; set; } = 3;
Expand All @@ -43,78 +48,8 @@ public ZWaveChannel(ISerialPort port)
throw new ArgumentNullException(nameof(port));

_semaphore = new SemaphoreSlim(1, 1);
//port.OnDataReceivedHandler += PortDataReceived;
}

//private async void PortDataReceived(object sender, DataReceivedEventArgs e)
//{
// var port = sender as ISerialPort;
// if (port == null)
// {
// throw new ArgumentException(nameof(sender));
// }

// try
// {
// // wait for message received (blocking)
// var message = await Message.Read(port.InputStream).ConfigureAwait(false);
// LogMessage($"Received: {message}");

// // ignore ACK, no processing of ACK needed
// if (message == Message.Acknowledge)
// return;

// // is it a eventmessage from a node?
// if (message is NodeEvent)
// {
// // yes, so add to eventqueue
// _eventQueue.Add(message);
// // send ACK to controller
// _transmitQueue.Add(Message.Acknowledge);
// // we're done
// return;
// }

// // is it a updatemessage from a node?
// if (message is NodeUpdate)
// {
// // yes, so add to eventqueue
// _eventQueue.Add(message);
// // send ACK to controller
// _transmitQueue.Add(Message.Acknowledge);
// // we're done
// return;
// }

// // not a event, so it's a response to a request
// _responseQueue.Add(message);
// // send ACK to controller
// _transmitQueue.Add(Message.Acknowledge);
// }
// catch (ChecksumException ex)
// {
// LogMessage($"Exception: {ex}");
// _transmitQueue.Add(Message.NegativeAcknowledge);
// }
// catch (UnknownFrameException ex)
// {
// // probably out of sync on the serial port
// // ToDo: handle gracefully
// OnError(new ErrorEventArgs(ex));
// }
// catch (IOException)
// {
// // port closed, we're done so return
// OnClosed(EventArgs.Empty);
// return;
// }
// catch (Exception ex)
// {
// // just raise error event. don't break reading of serial port
// OnError(new ErrorEventArgs(ex));
// }
//}

public ZWaveChannel(string portName)
: this(new ZWaveSerialPort(portName))
{
Expand Down Expand Up @@ -142,6 +77,7 @@ public void Open()
// start tasks
_portReadTask.Start();
_processEventsTask.Start();
_processUpdatesTask.Start();
_transmitTask.Start();
}

Expand Down Expand Up @@ -326,7 +262,7 @@ private Task<byte[]> Send(Function function, byte[] payload, Func<ControllerFunc
cancellationToken).ConfigureAwait(false);
return ((ControllerFunctionMessage)response).Payload;
}, $"{function} {(payload != null ? BitConverter.ToString(payload) : string.Empty)}", cancellationToken);
}, $"{function} {BitConverter.ToString(payload ?? new byte[0])}", cancellationToken);
}

private async Task<Message> WaitForResponse(Func<Message, bool> predicate, CancellationToken cancellationToken)
Expand All @@ -349,7 +285,7 @@ private async Task<Message> WaitForResponse(Func<Message, bool> predicate, Cance
throw new NegativeAcknowledgeException();
if (result == Message.Cancel)
throw new CancelledResponseException();

var commandResult = result as NodeCommandCompleted;
if (commandResult != null &&
commandResult.TransmissionState != TransmissionState.CompleteOk)
Expand Down Expand Up @@ -477,7 +413,7 @@ private async void ReadPort(ISerialPort port)
{
// probably out of sync on the serial port
// ToDo: handle gracefully
OnError(new ErrorEventArgs(ex));
OnError(new ErrorEventArguments(ex));
}
catch (IOException)
{
Expand All @@ -488,7 +424,7 @@ private async void ReadPort(ISerialPort port)
catch (Exception ex)
{
// just raise error event. don't break reading of serial port
OnError(new ErrorEventArgs(ex));
OnError(new ErrorEventArguments(ex));
}
}
}
Expand Down Expand Up @@ -518,12 +454,16 @@ private async void ReadPort(ISerialPort port)
}
}

private void LogMessage(string message)
private void LogMessage(string message,
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string caller = null)
{
if (message != null)
{
Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd H:mm:ss.fff")} {message}");
}
_logger?.Log(LogLevel.Debug, message);

//if (message != null)
//{
// Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd H:mm:ss.fff")} {caller} line {lineNumber} {message}");
//}
}

private void HandleException(Exception ex)
Expand All @@ -536,6 +476,7 @@ private void HandleException(Exception ex)
}
return;
}

LogMessage(ex.ToString());
}

Expand Down Expand Up @@ -592,7 +533,7 @@ private void OnTransmit(Message message)
LogMessage($"Transmitted: {message}");
}

protected virtual void OnError(ErrorEventArgs e)
protected virtual void OnError(ErrorEventArguments e)
{
LogMessage($"Exception: {e.Error}");
Error?.Invoke(this, e);
Expand Down
13 changes: 7 additions & 6 deletions ZWaveCore/ZWaveCore/Core/ZWaveController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using NLog;
using System;
using System.Collections;
using System.Linq;
using System.Text;
Expand All @@ -17,7 +18,7 @@ public class ZWaveController : IDisposable
private uint? _homeID;
private byte? _nodeID;
public readonly ZWaveChannel Channel;
public event EventHandler<ErrorEventArgs> Error;
public event EventHandler<ErrorEventArguments> Error;
public event EventHandler ChannelClosed;

private ZWaveController(ZWaveChannel channel)
Expand All @@ -35,7 +36,7 @@ public ZWaveController(string portName)
{
}

protected virtual void OnError(ErrorEventArgs e)
protected virtual void OnError(ErrorEventArguments e)
{
Error?.Invoke(this, e);
}
Expand Down Expand Up @@ -141,7 +142,7 @@ public void Dispose()
Close();
}

private void Channel_Error(object sender, ErrorEventArgs e)
private void Channel_Error(object sender, ErrorEventArguments e)
{
OnError(e);
}
Expand All @@ -164,7 +165,7 @@ private async void Channel_NodeEventReceived(object sender, NodeEventArgs e)
}
catch (Exception ex)
{
OnError(new ErrorEventArgs(ex));
OnError(new ErrorEventArguments(ex));
}
}

Expand All @@ -181,7 +182,7 @@ private async void Channel_NodeUpdateReceived(object sender, NodeUpdateEventArgs
}
catch (Exception ex)
{
OnError(new ErrorEventArgs(ex));
OnError(new ErrorEventArguments(ex));
}
}

Expand Down

0 comments on commit 1cf645d

Please sign in to comment.