-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathZWavePort.cs
More file actions
294 lines (269 loc) · 9.9 KB
/
Copy pathZWavePort.cs
File metadata and controls
294 lines (269 loc) · 9.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/*
* ZSharp - C# Z-Wave Implementation
* HiØ 2011
* H11D13 / iAutomation@Home
* Author: thomrand
*/
using System;
using System.IO.Ports;
using System.Threading;
using System.Collections.Generic;
using iAutomationAtHome.Debugging;
namespace iAutomationAtHome.ZSharp
{
/// <summary>
/// A class that deals with low level serial communications with a Z-Wave USB Controller.
/// </summary>
internal class ZWavePort
{
public class UnsubscribedMessageEventArgs : EventArgs
{
public ZWaveMessage Message;
public UnsubscribedMessageEventArgs(ZWaveMessage message) : base()
{
this.Message = message;
}
}
public event EventHandler UnsubscribedMessageEvent;
public void FireUnsubscribedMessageEvent(ZWaveMessage message)
{
if (this.UnsubscribedMessageEvent != null)
this.UnsubscribedMessageEvent(this, new UnsubscribedMessageEventArgs(message));
}
private SerialPort _sp;
private Thread _runner;
private Object _queueLock = new Object();
private LinkedList<ZWaveJob> _jobQueue;
private LinkedList<ZWaveJob> JobQueue
{
get
{
if(this._jobQueue == null) this._jobQueue = new LinkedList<ZWaveJob>();
return this._jobQueue;
}
}
/// <summary>
/// Create and initialize a new communication port.
/// </summary>
public ZWavePort()
{
this._sp = new SerialPort();
this._sp.Parity = Parity.None;
this._sp.BaudRate = 115200;
this._sp.Handshake = Handshake.None;
this._sp.StopBits = StopBits.One;
this._sp.DtrEnable = true;
this._sp.RtsEnable = true;
this._sp.NewLine = Environment.NewLine;
this._runner = new Thread(new ThreadStart(Run));
}
/// <summary>
/// Open the port.
/// </summary>
public bool Open()
{
Console.WriteLine("Opening port: " + this._sp.PortName);
if (!this._sp.IsOpen)
{
for (int i = 1; i < 5; i++)
{
String port = "COM" + i;
this._sp.PortName = port;
try
{
this._sp.Open();
}
catch (Exception e)
{
DebugLogger.GetLogger.LogMessage(this, "ZWave controller not found at port: " + this._sp.PortName);
}
if (this._sp.IsOpen)
break;
}
if (this._sp.IsOpen)
{
DebugLogger.GetLogger.LogMessage(this, "Found ZWave controller at port: " + this._sp.PortName);
this._runner.Start();
return true;
}
else
{
DebugLogger.GetLogger.LogMessage(this, "ZWave controller not found");
return false;
}
}
else
{
return true;
}
}
public void Close()
{
this._sp.Close();
this._sp.Dispose();
}
/// <summary>
///
/// </summary>
private void Run()
{
byte[] buf = new byte[1024];
while(this._sp.IsOpen)
{
ZWaveJob _currentJob = null;
lock (this._queueLock)
{
if (this.JobQueue.Count > 0)
{
_currentJob = this.JobQueue.First.Value;
if (_currentJob.JobDone)
{
this.JobQueue.RemoveFirst();
_currentJob = null;
if (this.JobQueue.Count > 0)
{
_currentJob = this.JobQueue.First.Value;
}
}
}
}
// Check for incoming messages
int btr = this._sp.BytesToRead;
if (btr > 0)
{
// Read first byte
this._sp.Read(buf, 0, 1);
switch (buf[0])
{
case ZWaveProtocol.SOF:
// Read the length byte
this._sp.Read(buf, 1, 1);
byte len = buf[1];
// Read rest of the frame
this._sp.Read(buf, 2, len);
byte[] message = Utils.ByteSubstring(buf, 0, (len + 2));
Console.WriteLine("Received: " + Utils.ByteArrayToString(message));
// Verify checksum
if (message[(message.Length - 1)] == CalculateChecksum(Utils.ByteSubstring(message, 0, (message.Length - 1))))
{
ZWaveMessage zMessage = new ZWaveMessage(message);
if (_currentJob == null)
{
// Incoming response?
this.FireUnsubscribedMessageEvent(zMessage);
System.Diagnostics.Debug.WriteLine("*** Incoming response");
}
else
{
if (_currentJob.AwaitACK)
{
// We wanted an ACK instead. Resend...
_currentJob.AwaitACK = false;
_currentJob.AwaitResponse = false;
_currentJob.Resend = true;
}
else
{
_currentJob.AddResponse(zMessage);
this.FireUnsubscribedMessageEvent(zMessage);
}
}
// Send ACK - Checksum is correct
this._sp.Write(new byte[] { ZWaveProtocol.ACK }, 0, 1);
Console.WriteLine("Sent: ACK");
}
else
{
// Send NAK
this._sp.Write(new byte[] { ZWaveProtocol.NAK }, 0, 1);
Console.WriteLine("Sent: NAK");
}
break;
case ZWaveProtocol.CAN:
Console.WriteLine("Received: CAN");
break;
case ZWaveProtocol.NAK:
Console.WriteLine("Received: NAK");
_currentJob.AwaitACK = false;
_currentJob.JobStarted = false;
break;
case ZWaveProtocol.ACK:
Console.WriteLine("Received: ACK");
if (_currentJob != null)
{
if (_currentJob.AwaitACK && !_currentJob.AwaitResponse)
{
_currentJob.AwaitResponse = true;
_currentJob.AwaitACK = false;
}
}
break;
default:
Console.WriteLine("Critical error. Out of frame flow.");
break;
}
}
else
{
if (_currentJob == null)
{
lock (this._queueLock)
{
if (this.JobQueue.Count > 0)
{
_currentJob = this.JobQueue.First.Value;
}
}
}
if (_currentJob != null)
{
if (_currentJob.SendCount >= 3)
{
_currentJob.CancelJob();
}
if ((!_currentJob.JobStarted && !_currentJob.JobDone) || _currentJob.Resend)
{
ZWaveMessage msg = _currentJob.Request;
if (msg != null)
{
this._sp.Write(msg.Message, 0, msg.Message.Length);
_currentJob.Start();
_currentJob.Resend = false;
_currentJob.AwaitACK = true;
_currentJob.SendCount++;
Console.WriteLine("Sent: " + Utils.ByteArrayToString(msg.Message));
}
}
}
}
Thread.Sleep(100);
}
}
/// <summary>
///
/// </summary>
public void EnqueueJob(ZWaveJob job)
{
lock (this._queueLock)
{
this.JobQueue.AddLast(job);
}
}
public void InjectJob(ZWaveJob job)
{
lock (this._queueLock)
{
this.JobQueue.AddFirst(job);
}
}
public static byte CalculateChecksum(byte[] message)
{
byte chksum = 0xff;
for(int i = 1; i < message.Length; i++)
{
chksum ^= (byte)message[i];
}
return chksum;
}
}
}