-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathClass1.cs
1561 lines (1257 loc) · 58.3 KB
/
Class1.cs
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of VitalSignsCaptureDraegerVent v1.003.
* Copyright (C) 2017-20 John George K., xeonfusion@users.sourceforge.net
VitalSignsCaptureDraegerVent is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
VitalSignsCaptureDraegerVent is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with VitalSignsCaptureDraegerVent. If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace VSCaptureDrgVent
{
public class Crc
{
public byte ComputeChecksum(byte[] bytes)
{
byte sum = 0;
byte crc = 0;
for (int i = 0; i < bytes.Length; ++i)
{
sum += bytes[i];
}
//get 8-bit sum total checksum
crc = (byte)(sum & 0xFF); //For Draeger
return crc;
}
}
public sealed class DSerialPort : SerialPort
{
private int DPortBufSize;
public byte[] DPort_rxbuf;
public List<byte[]> FrameList = new List<byte[]>();
private bool m_storestartResp = false;
private bool m_storestartCom = false;
private bool m_storeend = false;
private List<byte> m_bList = new List<byte>();
private List<byte> m_bRespList = new List<byte>();
private List<byte> m_bComList = new List<byte>();
private bool m_runningCommand = false;
private bool m_readingResponse = false;
public List<NumericValResult> m_NumericValList = new List<NumericValResult>();
public List<string> m_NumValHeaders = new List<string>();
public StringBuilder m_strbuildvalues = new StringBuilder();
public StringBuilder m_strbuildheaders = new StringBuilder();
public string m_strTimestamp;
public bool m_transmissionstart = true;
public bool m_transmissionstart2 = true;
public bool m_transmissionstart3 = true;
public bool m_transmissionstart4 = true;
public List<RealTimeConfigResponse> m_RtConfigRespList = new List<RealTimeConfigResponse>();
public List<byte> m_RealTimeByteList = new List<byte>();
public List<RealTimeData> m_RealTimeDataList = new List<RealTimeData>();
public List<byte> m_RealTimeReqWaveList = new List<byte>();
public List<WaveValResult> m_WaveValResultList = new List<WaveValResult>();
public StringBuilder m_strbuildwavevalues = new StringBuilder();
public long m_RealtiveTimeCounter =0;
public int m_nWaveformSet=0;
public bool m_realtimestart = false;
public bool m_MEDIBUSstart = false;
public class NumericValResult
{
public string Timestamp;
public string PhysioID;
public string Value;
}
public class WaveValResult
{
public string Timestamp;
public string Relativetimestamp;
public string PhysioID;
public string Value;
public string Datastreamindex;
public long Relativetimecounter;
public RealTimeConfigResponse RtConfigData = new RealTimeConfigResponse();
public string RespiratoryCycleState;
}
public class RealTimeConfigResponse
{
public string datacode;
public string interval;
public string minvalue;
public string maxvalue;
public string maxbinvalue;
}
public class RealTimeData
{
public byte syncbyte;
public List<byte[]> synccommand = new List<byte[]>();
public List<byte[]> rtdatavalues = new List<byte[]>();
public List<byte> datastreamlist = new List<byte>();
public string respsyncstate;
}
//Create a singleton serialport subclass
private static volatile DSerialPort DPort = null;
public static DSerialPort getInstance
{
get
{
if (DPort == null)
{
lock (typeof(DSerialPort))
if (DPort == null)
{
DPort = new DSerialPort();
}
}
return DPort;
}
}
public DSerialPort()
{
DPort = this;
DPortBufSize = 4096;
DPort_rxbuf = new byte[DPortBufSize];
if (OSIsUnix())
DPort.PortName = "/dev/ttyUSB0"; //default Unix port
else DPort.PortName = "COM1"; //default Windows port
DPort.BaudRate = 19200;
DPort.Parity = Parity.Even;
DPort.DataBits = 8;
DPort.StopBits = StopBits.One;
DPort.Handshake = Handshake.None;
//DPort.Handshake = Handshake.XOnXOff;
DPort.RtsEnable = true;
DPort.DtrEnable = true;
// Set the read/write timeouts
DPort.ReadTimeout = 600000;
DPort.WriteTimeout = 600000;
//ASCII Encoding in C# is only 7bit so
DPort.Encoding = Encoding.GetEncoding("ISO-8859-1");
}
public void RequestICC()
{
DPort.WriteBuffer(DataConstants.poll_request_icc_msg);
DebugLine("Send: Request ICC");
}
public void RequestDevID()
{
DPort.WriteBuffer(DataConstants.poll_request_deviceid);
DebugLine("Send: Request DevID");
}
public void RequestMeasuredDataCP1()
{
DPort.WriteBuffer(DataConstants.poll_request_config_measured_data_codepage1);
DebugLine("Send: Request Data CP1");
}
public void RequestMeasuredDataCP2()
{
DPort.WriteBuffer(DataConstants.poll_request_config_measured_data_codepage2);
DebugLine("Send: Request Data CP2");
}
public void RequestDeviceSettings()
{
DPort.WriteBuffer(DataConstants.poll_request_device_settings);
DebugLine("Send: Request Data Dev settings");
}
public void RequestTextMessages()
{
DPort.WriteBuffer(DataConstants.poll_request_text_messages);
DebugLine("Send: Request Data TextMsgs");
}
public void RequestStopCommunication()
{
DPort.WriteBuffer(DataConstants.poll_request_stop_com);
DebugLine("Send: Request Stop Communication");
}
public void RequestRealtimeDataConfiguration()
{
DPort.WriteBuffer(DataConstants.poll_request_real_time_data_config);
DebugLine("Send: Request Realtime Config");
}
public void SendNOP()
{
DPort.WriteBuffer(DataConstants.poll_request_no_operation);
DebugLine("Send: NOP");
}
public void SendDeviceID()
{
List<byte> temptxbufflist = new List<byte>();
byte[] deviceidcommandresponse = { 0x52 };
byte[] DevID = Encoding.ASCII.GetBytes("0161");
byte[] DevName = Encoding.ASCII.GetBytes("'VSCaptureDrgVent'");
byte[] DevRevision = Encoding.ASCII.GetBytes("01.03");
byte[] MedibusVer = Encoding.ASCII.GetBytes(":06.00");
temptxbufflist.AddRange(deviceidcommandresponse);
temptxbufflist.AddRange(DevID);
temptxbufflist.AddRange(DevName);
temptxbufflist.AddRange(DevRevision);
temptxbufflist.AddRange(MedibusVer);
CommandEchoResponse(temptxbufflist.ToArray());
DebugLine("Send: Device ID (response)");
}
public void ReadRealtimeConfigResponse(byte[] packetdata)
{
//Store configuration values
MemoryStream memstream = new MemoryStream(packetdata);
BinaryReader binreader = new BinaryReader(memstream);
byte[] packetheader = binreader.ReadBytes(2);
for (int i=2; i<packetdata.Length;i=i+23)
{
byte[] datacode = binreader.ReadBytes(2);
byte[] interval = binreader.ReadBytes(8);
byte[] minvalue = binreader.ReadBytes(5);
byte[] maxvalue = binreader.ReadBytes(5);
byte[] maxbinvalue = binreader.ReadBytes(3);
RealTimeConfigResponse RtConfigResp = new RealTimeConfigResponse();
RtConfigResp.datacode = Regex.Replace(Encoding.ASCII.GetString(datacode), @"\s+", "");
RtConfigResp.interval = Regex.Replace(Encoding.ASCII.GetString(interval), @"\s+", "");
RtConfigResp.minvalue = Regex.Replace(Encoding.ASCII.GetString(minvalue), @"\s+", "");
RtConfigResp.maxvalue = Regex.Replace(Encoding.ASCII.GetString(maxvalue), @"\s+", "");
RtConfigResp.maxbinvalue = Regex.Replace(Encoding.ASCII.GetString(maxbinvalue), @"\s+", "");
m_RtConfigRespList.Add(RtConfigResp);
}
}
public static void CreateWaveformSet(int nWaveSetType, List<byte> WaveTrtype)
{
switch (nWaveSetType)
{
case 0:
break;
case 1:
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Airway_pressure"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Flow_inspiratory_expiratory"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Respiratory_volume_since_start_of_inspiration"));
break;
case 2:
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "O2_saturation_pulse_Pleth"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "O2_concentration_inspiratory_expiratory"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "CO2_concentration_mmHg"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Concentration_of_primary_agent_inspiratory_expiratory_Percent"));
break;
case 3:
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Tracheal_pressure"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Inspiratory_device_flow"));
break;
case 4:
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Airway_pressure"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Flow_inspiratory_expiratory"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Respiratory_volume_since_start_of_inspiration"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "O2_saturation_pulse_Pleth"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "O2_concentration_inspiratory_expiratory"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "CO2_concentration_mmHg"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Concentration_of_primary_agent_inspiratory_expiratory_Percent"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Inspiratory_device_flow"));
WaveTrtype.Add((byte)Enum.Parse(typeof(DataConstants.MedibusXRealTimeData), "Tracheal_pressure"));
break;
}
}
public void ConfigureRealtimeTransmission()
{
if (m_nWaveformSet == 0) return;
List<byte> temptxbufflist = new List<byte>();
List<byte> WaveTrType = new List<byte>();
CreateWaveformSet(m_nWaveformSet, WaveTrType);
byte[] rtdlistarray = WaveTrType.ToArray();
temptxbufflist.AddRange(DataConstants.poll_configure_real_time_transmission);
m_RealTimeReqWaveList.AddRange(rtdlistarray);
for (int i=0; i < rtdlistarray.Count(); i++)
{
byte[] rtdarray = { rtdlistarray.ElementAt(i) };
string rtdtoasciihex1 = BitConverter.ToString(rtdarray);
byte[] rtdasciihexbytes1 = Encoding.ASCII.GetBytes(rtdtoasciihex1);
string multiplier1 = "01";
byte[] multiplierhexbytes1 = Encoding.ASCII.GetBytes(multiplier1);
temptxbufflist.AddRange(rtdasciihexbytes1);
temptxbufflist.AddRange(multiplierhexbytes1);
}
DPort.WriteBuffer(temptxbufflist.ToArray());
DebugLine("Send: Configure realtime transmission (command)");
}
public void EnableDataStreams()
{
EnableDataStream1to4();
if (m_nWaveformSet == 4)
{
EnableDataStream5to8();
EnableDataStream9to12();
}
}
public void DisableDataStreams()
{
DisableDataStream1to4();
if (m_nWaveformSet == 4)
{
DisableDataStream5to8();
DisableDataStream9to12();
}
}
public void EnableDataStream1to4()
{
const byte SyncByte = 0xD0;
const byte SyncCommand = DataConstants.SC_DATASTREAM_1_4; //0xC1
const byte SyncArgument = 0xCF; //number of streams to enable
const byte EndSyncByte = 0xC0;
List<byte> temptxbufflist = new List<byte>();
temptxbufflist.Add(SyncByte);
temptxbufflist.Add(SyncCommand);
temptxbufflist.Add(SyncArgument);
temptxbufflist.Add(EndSyncByte);
temptxbufflist.Add(EndSyncByte);
byte[] finalbuff = temptxbufflist.ToArray();
DPort.Write(finalbuff, 0, finalbuff.Length);
DebugLine("Send: Enable Data Stream 1to4");
}
public void EnableDataStream5to8()
{
const byte SyncByte = 0xD0;
const byte SyncCommand = DataConstants.SC_DATASTREAM_5_8; //0xC2
const byte SyncArgument = 0xCF; //number of streams to enable
const byte EndSyncByte = 0xC0;
List<byte> temptxbufflist = new List<byte>();
temptxbufflist.Add(SyncByte);
temptxbufflist.Add(SyncCommand);
temptxbufflist.Add(SyncArgument);
temptxbufflist.Add(EndSyncByte);
temptxbufflist.Add(EndSyncByte);
byte[] finalbuff = temptxbufflist.ToArray();
DPort.Write(finalbuff, 0, finalbuff.Length);
DebugLine("Send: Enable Data Stream 5to8");
}
public void EnableDataStream9to12()
{
const byte SyncByte = 0xD0;
const byte SyncCommand = DataConstants.SC_DATASTREAM_9_12; //0xC3
const byte SyncArgument = 0xCF; //number of streams to enable
const byte EndSyncByte = 0xC0;
List<byte> temptxbufflist = new List<byte>();
temptxbufflist.Add(SyncByte);
temptxbufflist.Add(SyncCommand);
temptxbufflist.Add(SyncArgument);
temptxbufflist.Add(EndSyncByte);
temptxbufflist.Add(EndSyncByte);
byte[] finalbuff = temptxbufflist.ToArray();
DPort.Write(finalbuff, 0, finalbuff.Length);
DebugLine("Send: Enable Data Stream 9to12");
}
public void DisableDataStream1to4()
{
const byte SyncByte = 0xD0;
const byte SyncCommand = DataConstants.SC_DATASTREAM_1_4; //0xC1
const byte SyncArgument = 0xC0; //number of streams to disable
const byte EndSyncByte = 0xC0;
List<byte> temptxbufflist = new List<byte>();
temptxbufflist.Add(SyncByte);
temptxbufflist.Add(SyncCommand);
temptxbufflist.Add(SyncArgument);
temptxbufflist.Add(EndSyncByte);
temptxbufflist.Add(EndSyncByte);
byte[] finalbuff = temptxbufflist.ToArray();
DPort.Write(finalbuff, 0, finalbuff.Length);
}
public void DisableDataStream5to8()
{
const byte SyncByte = 0xD0;
const byte SyncCommand = DataConstants.SC_DATASTREAM_5_8; //0xC2
const byte SyncArgument = 0xC0; //number of streams to disable
const byte EndSyncByte = 0xC0;
List<byte> temptxbufflist = new List<byte>();
temptxbufflist.Add(SyncByte);
temptxbufflist.Add(SyncCommand);
temptxbufflist.Add(SyncArgument);
temptxbufflist.Add(EndSyncByte);
temptxbufflist.Add(EndSyncByte);
byte[] finalbuff = temptxbufflist.ToArray();
DPort.Write(finalbuff, 0, finalbuff.Length);
}
public void DisableDataStream9to12()
{
const byte SyncByte = 0xD0;
const byte SyncCommand = DataConstants.SC_DATASTREAM_9_12; //0xC3
const byte SyncArgument = 0xC0; //number of streams to disable
const byte EndSyncByte = 0xC0;
List<byte> temptxbufflist = new List<byte>();
temptxbufflist.Add(SyncByte);
temptxbufflist.Add(SyncCommand);
temptxbufflist.Add(SyncArgument);
temptxbufflist.Add(EndSyncByte);
temptxbufflist.Add(EndSyncByte);
byte[] finalbuff = temptxbufflist.ToArray();
DPort.Write(finalbuff, 0, finalbuff.Length);
}
public void RequestRealtimeConfigChanged()
{
DPort.WriteBuffer(DataConstants.poll_request_real_time_config_changed);
}
public void ParseRealtimeDataResponse()
{
if(m_RealTimeByteList.Count()>2 && m_nWaveformSet!=0 && m_realtimestart ==true)
{
byte[] RealTimeByteArray = m_RealTimeByteList.ToArray();
int bytesSuccessfullyRead = 0;
for (int i = 0; i < RealTimeByteArray.Length; i++)
{
byte bvalue = RealTimeByteArray.ElementAt(i);
if ((bvalue & DataConstants.SYNC_BYTE) == DataConstants.SYNC_BYTE)
{
RealTimeData RTdata = new RealTimeData();
RTdata.syncbyte = bvalue;
for (int j = i+1; j < RealTimeByteArray.Length-1; j++)
{
byte bvaluenext = RealTimeByteArray.ElementAt(j);
if ((bvaluenext & DataConstants.SYNC_BYTE) == DataConstants.SYNC_BYTE) break;
if ((bvaluenext & DataConstants.SYNC_CMD_BYTE) == DataConstants.SYNC_CMD_BYTE)
{
byte[] buffer = new byte[2];
Buffer.BlockCopy(RealTimeByteArray, j, buffer, 0, 2);
RTdata.synccommand.Add(buffer);
j = j + 1;
i = j;
}
else
{
byte[] buffer = new byte[2];
Buffer.BlockCopy(RealTimeByteArray, j, buffer, 0, 2);
RTdata.rtdatavalues.Add(buffer);
j = j + 1;
i = j;
}
}
CreateDataStreamList(ref RTdata);
//if (RTdata.rtdatavalues.Count() != 0)
if (RTdata.rtdatavalues.Count() == RTdata.datastreamlist.Count())
{
m_RealTimeDataList.Add(RTdata);
bytesSuccessfullyRead = i + 1;
}
}
}
ReadRealTimeDataList();
m_RealTimeByteList.RemoveRange(0, bytesSuccessfullyRead);
}
}
public void CreateDataStreamList(ref RealTimeData RTdata)
{
//Read enabled Realtime curve numbers from sync byte & sync command byte
//The bit-positions are related to the datastream-number in the same order as specified
//within the "Configure Realtime-Tranmission" command by the data-requesting device before
byte syncbyte = RTdata.syncbyte;
if ((syncbyte & 0x01) != 0) RTdata.datastreamlist.Add(0);
if ((syncbyte & 0x02) != 0) RTdata.datastreamlist.Add(1);
if ((syncbyte & 0x04) != 0) RTdata.datastreamlist.Add(2);
if ((syncbyte & 0x08) != 0) RTdata.datastreamlist.Add(3);
if (RTdata.synccommand.Count() != 0)
{
foreach (byte[] synccommandbytes in RTdata.synccommand)
{
byte synccommand = synccommandbytes[0];
byte syncargument = synccommandbytes[1];
switch (synccommand)
{
case DataConstants.SC_TX_DATASTREAM_5_8:
if ((syncargument & 0x01) != 0) RTdata.datastreamlist.Add(4);
if ((syncargument & 0x02) != 0) RTdata.datastreamlist.Add(5);
if ((syncargument & 0x04) != 0) RTdata.datastreamlist.Add(6);
if ((syncargument & 0x08) != 0) RTdata.datastreamlist.Add(7);
break;
case DataConstants.SC_TX_DATASTREAM_9_12:
if ((syncargument & 0x01) != 0) RTdata.datastreamlist.Add(8);
if ((syncargument & 0x02) != 0) RTdata.datastreamlist.Add(9);
if ((syncargument & 0x04) != 0) RTdata.datastreamlist.Add(10);
if ((syncargument & 0x08) != 0) RTdata.datastreamlist.Add(11);
break;
case DataConstants.SC_START_CYCLE:
if (syncargument == 0xC0) RTdata.respsyncstate = "InspStart";
if (syncargument == 0xC1) RTdata.respsyncstate = "ExpStart";
break;
}
}
}
}
public void ReadRealTimeDataList()
{
int RTdatacount = m_RealTimeDataList.Count();
DateTime dtime = DateTime.Now;
//Get unix timestamp
m_RealtiveTimeCounter = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds * 1000);
for (int i = 0; i < RTdatacount; i++)
{
RealTimeData RTdata = m_RealTimeDataList.ElementAt(i);
for (int j=0;j<RTdata.datastreamlist.Count()&&j<RTdata.rtdatavalues.Count();j++)
{
//Add realtime data values to datastreams
int datastreamindex = RTdata.datastreamlist.ElementAt(j);
WaveValResult WavValResult = new WaveValResult();
WavValResult.Datastreamindex = datastreamindex.ToString();
WavValResult.Timestamp = dtime.ToString("G", DateTimeFormatInfo.InvariantInfo);
if (datastreamindex < m_RealTimeReqWaveList.Count())
{
byte wavecode = m_RealTimeReqWaveList.ElementAt(datastreamindex);
//byte wavecode = (byte)Int32.Parse(m_RtConfigRespList.ElementAt(datastreamindex).datacode);
byte[] wavecodearray = { wavecode };
string wavedatacode = BitConverter.ToString(wavecodearray);
WavValResult.PhysioID = Enum.GetName(typeof(DataConstants.MedibusXRealTimeData), wavecode);
WavValResult.RespiratoryCycleState = RTdata.respsyncstate;
WavValResult.RtConfigData = m_RtConfigRespList.Find(x => x.datacode == wavedatacode);
if (WavValResult.RtConfigData != null)
{
//int interval = Int32.Parse(WavValResult.RtConfigData.interval);
int minvalue = Int32.Parse(WavValResult.RtConfigData.minvalue);
int maxvalue = Int32.Parse(WavValResult.RtConfigData.maxvalue);
int maxbinvalue = Int32.Parse(WavValResult.RtConfigData.maxbinvalue, NumberStyles.HexNumber);
byte[] rtdatabytes = RTdata.rtdatavalues.ElementAt(j);
int firstbinvalue = (rtdatabytes[0] & 0x3F);
int secondbinvalue = (rtdatabytes[1] & 0x3F);
//A realtime value is transmitted at a resolution of 12 bits
int rtbinval = (firstbinvalue & 0x3F) | ((secondbinvalue & 0x3F) << 6);
double rtvalue = (((double)rtbinval / maxbinvalue) * (maxvalue - minvalue)) + minvalue;
double finalrtvalue = Math.Round(rtvalue, 4);
WavValResult.Value = finalrtvalue.ToString(CultureInfo.InvariantCulture);
WavValResult.Relativetimecounter = m_RealtiveTimeCounter;
m_WaveValResultList.Add(WavValResult);
}
}
//byte wavecode = m_RealTimeReqWaveList.ElementAt(datastreamindex);
}
}
m_RealTimeDataList.RemoveRange(0, RTdatacount);
SaveWaveValues();
}
public void SaveWaveValues()
{
int wavevallistcount = m_WaveValResultList.Count;
if (wavevallistcount != 0)
{
//Create list of physio ids available
List<string> PhysioIDList = m_WaveValResultList.Select(x => x.PhysioID).Distinct().ToList();
foreach (string physioid in PhysioIDList)
{
m_strbuildwavevalues = CreateCSVFromWavevalues(physioid);
string WavValID = string.Format("{0}DrgWaveExport.csv", physioid);
string pathcsv = Path.Combine(Directory.GetCurrentDirectory(), WavValID);
ExportNumValListToCSVFile(pathcsv, m_strbuildwavevalues);
m_strbuildwavevalues.Clear();
}
m_WaveValResultList.RemoveRange(0, wavevallistcount);
}
}
public StringBuilder CreateCSVFromWavevalues(string PhysioID)
{
List<WaveValResult> Wavevalues = m_WaveValResultList.FindAll(x => x.PhysioID == PhysioID);
StringBuilder strbuildwavevalues = new StringBuilder();
int i = 0;
foreach (WaveValResult WavValResult in Wavevalues)
{
int interval = Int32.Parse(WavValResult.RtConfigData.interval);
WavValResult.Relativetimestamp = (m_RealtiveTimeCounter+(i++*(interval/1000))).ToString();
strbuildwavevalues.Append(WavValResult.Timestamp);
strbuildwavevalues.Append(',');
strbuildwavevalues.Append(WavValResult.Relativetimestamp);
strbuildwavevalues.Append(',');
strbuildwavevalues.Append(WavValResult.Value);
strbuildwavevalues.Append(',');
strbuildwavevalues.Append(WavValResult.RespiratoryCycleState);
//strbuildwavevalues.Append(',');
strbuildwavevalues.AppendLine();
}
return strbuildwavevalues;
}
public async Task SendCycledICCRequest(int nInterval)
{
int nmillisecond = nInterval * 1000;
if (nmillisecond != 0)
{
do
{
RequestICC();
await Task.Delay(nmillisecond);
}
while (true);
}
RequestICC();
}
public async Task SendCycledRequests(int nInterval)
{
int nmillisecond = nInterval * 1000;
if (nmillisecond != 0)
{
do
{
if (m_MEDIBUSstart == true)
{
RequestMeasuredDataCP1();
}
await Task.Delay(nmillisecond);
}
while (true);
}
if (m_MEDIBUSstart == true) RequestMeasuredDataCP1();
}
public async Task SendCycledPollDataRequestCP1(int nInterval)
{
int nmillisecond = nInterval * 1000;
if (nmillisecond != 0)
{
do
{
if(m_MEDIBUSstart == true)
{
RequestMeasuredDataCP1();
}
await Task.Delay(nmillisecond);
}
while (true);
}
if (m_MEDIBUSstart == true) RequestMeasuredDataCP1();
}
public async Task SendCycledPollDataRequestCP2(int nInterval)
{
int nmillisecond = nInterval * 1000;
if (nmillisecond != 0)
{
do
{
if (m_MEDIBUSstart == true)
{
RequestMeasuredDataCP2();
}
await Task.Delay(nmillisecond);
}
while (true);
}
if (m_MEDIBUSstart == true) RequestMeasuredDataCP2();
}
public async Task SendCycledPollDeviceSettings(int nInterval)
{
int nmillisecond = nInterval * 1000;
if (nmillisecond != 0)
{
do
{
if (m_MEDIBUSstart == true)
{
RequestDeviceSettings();
}
await Task.Delay(nmillisecond);
}
while (true);
}
if (m_MEDIBUSstart == true) RequestDeviceSettings();
}
public async Task SendCycledPollTextMessages(int nInterval)
{
int nmillisecond = nInterval * 1000;
if (nmillisecond != 0)
{
do
{
if (m_MEDIBUSstart == true)
{
RequestTextMessages();
}
await Task.Delay(nmillisecond);
}
while (true);
}
if (m_MEDIBUSstart == true) RequestTextMessages();
}
public async Task KeepConnectionAlive(int nInterval)
{
int nmillisecond = nInterval * 1000;
if (nmillisecond != 0)
{
do
{
if(m_MEDIBUSstart == true && m_readingResponse == false && m_runningCommand == false)
{
SendNOP();
}
await Task.Delay(nmillisecond);
}
while (true);
}
if (m_MEDIBUSstart == true && m_readingResponse == false && m_runningCommand == false) SendNOP();
}
public void WriteBuffer(byte[] txbuf)
{
m_runningCommand = true;
List<byte> temptxbufflist = new List<byte>();
int framelen = txbuf.Length;
if (framelen != 0)
{
//Add first command character 0x1B
temptxbufflist.Add(DataConstants.BOFCOMCHAR);
temptxbufflist.AddRange(txbuf);
byte[] inputbuffer = temptxbufflist.ToArray();
Crc crccheck = new Crc();
byte checksumcomputed = crccheck.ComputeChecksum(inputbuffer);
byte[] checksumarray = { checksumcomputed };
string checksumtoasciihex = BitConverter.ToString(checksumarray);
byte[] checksumasciihexbytes = Encoding.ASCII.GetBytes(checksumtoasciihex);
temptxbufflist.AddRange(checksumasciihexbytes);
temptxbufflist.Add(DataConstants.EOFCHAR);
byte[] finaltxbuff = temptxbufflist.ToArray();
try
{
DPort.Write(finaltxbuff, 0, finaltxbuff.Length);
}
catch (Exception ex)
{
Console.WriteLine("Error opening/writing to serial port :: " + ex.Message, "Error!");
}
}
m_runningCommand = false;
}
public void ClearReadBuffer()
{
//Clear the buffer
for (int i = 0; i < DPortBufSize; i++)
{
DPort_rxbuf[i] = 0;
}
}
public int ReadBuffer()
{
int bytesreadtotal = 0;
try
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "DrgVentRawoutput.raw");
int lenread = 0;
do
{
ClearReadBuffer();
lenread = DPort.Read(DPort_rxbuf, 0, DPortBufSize);
byte[] copyarray = new byte[lenread];
for (int i = 0; i < lenread; i++)
{
copyarray[i] = DPort_rxbuf[i];
CreateFrameListFromByte(copyarray[i]);
}
ByteArrayToFile(path, copyarray, copyarray.GetLength(0));
bytesreadtotal += lenread;
}
while (DPort.BytesToRead != 0);
if (DPort.BytesToRead == 0)
{
ParseRealtimeDataResponse();
if (FrameList.Count > 0)
{
ReadPacketFromFrame();
FrameList.RemoveRange(0, FrameList.Count);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error opening/writing to serial port :: " + ex.Message, "Error!");
}
return bytesreadtotal;
}
public void ReadPacketFromFrame()
{
if (FrameList.Count > 0)
{
foreach (byte[] fArray in FrameList)
{
ProcessPacket(fArray);
}
}
}
public void ProcessPacket(byte[] packetbuffer)
{
string headerdataresponse = Encoding.ASCII.GetString(packetbuffer);
string responsetype = headerdataresponse.Substring(0, 2);
m_strTimestamp = DateTime.Now.ToString();
m_readingResponse = true;
switch (responsetype)
{
case "\x1bQ": //ICC request
DebugLine("Received: ICC request");
byte[] icccommandresponse = {0x51};
CommandEchoResponse(icccommandresponse);
WaitForMilliSeconds(200);
RequestDevID();
break;
case "\x01Q": //ICC response
DebugLine("Received: ICC response");
m_MEDIBUSstart = true;
RequestDevID();
break;
case "\x1bR": //Device ID request
DebugLine("Received: Device ID request");
//Send empty or complete device id response
SendDeviceID();
m_MEDIBUSstart = true;
break;
case "\x01R": //Device id response
DebugLine("Received: Device ID response");
m_MEDIBUSstart = true;
if (m_realtimestart == false)
{
RequestRealtimeDataConfiguration();
}
break;
case "\x01S": //Realtime config respone
DebugLine("Received: Realtime Config Response");
ReadRealtimeConfigResponse(packetbuffer);