-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForm1.cs
2619 lines (2233 loc) · 95.6 KB
/
Form1.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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace pEcount
{
public partial class Form1 : Form
{
int intlastregisternumericversionnumber = 0;
int intlastregisterstate = 0;
byte[] bacomportbuffer = new byte[] { };
//change this to use a COM port other than COM1
int intcurrentcomport = 5;
public Form1()
{
InitializeComponent();
listBox1.Items.Clear();
timer1.Enabled = true;
}
public delegate void DataCOMAcquired(object sender);
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
int bytes = serialPort1.BytesToRead;
byte[] buffer = new byte[bytes];
serialPort1.Read(buffer, 0, bytes);
if (bacomportbuffer.Length > 0)
{
byte[] tempbuffer1 = new byte[bacomportbuffer.Length];
bacomportbuffer.CopyTo(tempbuffer1, 0);
bacomportbuffer = new byte[bytes + bacomportbuffer.Length];
bacomportbuffer = ByteArrayConcatenate(tempbuffer1, buffer);
}
else
{
bacomportbuffer = new byte[bytes];
buffer.CopyTo(bacomportbuffer, 0);
}
if (bacomportbuffer.Length > serialPort1.ReadBufferSize)
{
bacomportbuffer = new byte[] { };
}
}
//catch (Exception e1)
catch
{
//not thread safe ..
//LineOut("serialPort1_DataReceived()::Error Reading Port.InputBuffer", e1);
}
}
public void AddToList(string stringout)
{
if (listBox1.Items.Count>1000)
{
listBox1.Items.Clear();
}
listBox1.Items.Add(stringout);
listBox1.SelectedIndex = listBox1.Items.Count-1;
}
public void LineOut(string stringout)
{
System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " " + stringout);
AddToList(DateTime.Now.ToString() + " " + stringout);
}
public void LineOut(string stringout, Exception e)
{
string stringlocal = "";
if (stringout != null)
{
LineOut(stringout);
}
if (e.Message != null)
{
stringlocal = "ERROR ============================================== ";
LineOut(stringlocal);
stringlocal = "Message: " + e.Message.ToString();
LineOut(stringlocal);
}
if (e.InnerException != null)
{
stringlocal = "InnerException: " + e.InnerException.ToString();
LineOut(stringlocal);
}
if (e.TargetSite != null)
{
stringlocal = "TargetSite: " + e.TargetSite.ToString();
LineOut(stringlocal);
}
if (e.Source != null)
{
stringlocal = "Source: " + e.Source.ToString();
LineOut(stringlocal);
}
}
public void LineOutHexAndASCII(string stringMessage)
{
string sOutA = " ASC: ";
string sOutH = " HEX: ";
string sOutT = " : ";
//string strbinary = stringMessage.Replace("\0", "<NULL>").Replace("\r", "<CR>").Replace("\n", "<LF>");
bool boolbinaryfound = false;
foreach (char c in stringMessage)
{
int val = (int)c;
char chr = '*';
if(val>=32 && val<=127) {
chr = c;
}
int tmp = c;
sOutA += tmp.ToString(" 000") + " ";
sOutH += "0x" + String.Format("{0:x3}", System.Convert.ToUInt32(tmp.ToString())).ToUpper() + " ";
sOutT += chr;
}
LineOut(sOutA);
LineOut(sOutH);
LineOut(sOutT);
//LineOut(" " + strbinary);
}
private bool OpenSerialPort(System.IO.Ports.SerialPort sspport)
{
try
{
if (sspport.IsOpen)
{
sspport.Close();
}
sspport.PortName = "COM" + intcurrentcomport.ToString("0");
sspport.Handshake = System.IO.Ports.Handshake.None;
sspport.BaudRate = 9600;
sspport.Parity = System.IO.Ports.Parity.None;
sspport.DataBits = 8;
sspport.StopBits = System.IO.Ports.StopBits.One;
sspport.ReadBufferSize = 8192;
sspport.WriteBufferSize = 8192;
sspport.DtrEnable = false;
sspport.RtsEnable = false;
sspport.ReceivedBytesThreshold = 1;
if (!sspport.IsOpen)
{
sspport.Open();
sspport.DiscardInBuffer();
}
}
catch (Exception e1)
{
string stringexception = "OpenSerialPort(): Error Opening COM Port " + sspport.PortName.ToString();
LineOut(stringexception, e1);
}
return sspport.IsOpen;
}
private void CloseSerialPort(System.IO.Ports.SerialPort sspport)
{
try
{
if (sspport.IsOpen)
{
sspport.DiscardInBuffer();
sspport.DiscardInBuffer();
if (sspport.BytesToRead > 0)
{
string sdump = sspport.ReadExisting();
}
sspport.Close();
}
}
catch (Exception e1)
{
string stringexception = "CloseSerialPort(): Error Closing COM Port " + sspport.PortName.ToString();
LineOut(stringexception, e1);
}
}
private bool IsCOMPortValid(int intcomport)
{
bool boolfound = false;
foreach (string stringtemplabel in System.IO.Ports.SerialPort.GetPortNames())
{
string stringtest = "COM" + intcomport.ToString();
if (stringtest.CompareTo(stringtemplabel) == 0)
{
boolfound = true;
break;
}
}
return boolfound;
}
public string Chr(int intchar)
{
int intlocal = intchar;
if ((intchar < 0) || (intchar > 255))
{
LineOut("Chr() Invalid (int): intchar = " + intchar.ToString());
LineOut("Chr() Must be between 0 and 255, returning 0.");
intlocal = 0;
throw new ArgumentOutOfRangeException("intchar", "Must be between 0 and 255.");
}
//#if (WINCE)
// //was used until 5/13/2013 in CE5 and Win3264, had problems with X8Pro using it and getting garbage chars
// byte[] bytBuffer = new byte[] { (byte)intlocal };
// return Encoding.GetEncoding(1252).GetString(bytBuffer, 0, 1);
//#elif (WIN3264)
//as it turns out, this is great on pc but bad in CE ..
byte src = Convert.ToByte(intchar);
char chrretrn = (System.Text.Encoding.GetEncoding("iso-8859-1").GetChars(new byte[] { src })[0]);
return Convert.ToString(chrretrn);
//#endif
}
public int Asc(string stringin)
{
return (int)stringin[0];
}
public int Asc(char charin)
{
return (int)charin;
}
public string ToVolume(string stringin) {
return stringin.Substring(0, stringin.Length - 2) + "." + stringin.Substring(stringin.Length - 2);
}
public string ByteArrayToString(byte[] byteArray)
{
string stringreturn = "";
for (int intidx = 0; intidx < byteArray.Length; intidx++)
{
stringreturn += Chr(int.Parse(byteArray[intidx].ToString()));
}
return stringreturn;
}
public byte[] StringToByteArray(string str)
{
byte[] bytearrayreturn = new byte[str.Length];
for (int intidx = 0; intidx < str.Length; intidx++)
{
int intchar = Asc(str.Substring(intidx, 1));
bytearrayreturn[intidx] = byte.Parse(intchar.ToString());
}
return bytearrayreturn;
}
public byte[] ByteArrayConcatenate(byte[] a, byte[] b)
{
byte[] c = new byte[a.Length + b.Length];
Buffer.BlockCopy(a, 0, c, 0, a.Length);
Buffer.BlockCopy(b, 0, c, a.Length, b.Length);
return c;
}
public string ByteArrayToHexStringWithPad(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
}
public string ByteArrayToHexStringNoPad(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 2);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
return sb.ToString().ToUpper();
}
public byte[] ByteArraySubarray(byte[] a, int intstart, int intlength)
{
const string stringfunction = "ByteArraySubarray";
byte[] c = new byte[intlength]; // just one array
try
{
Buffer.BlockCopy(a, intstart, c, 0, intlength);
}
catch (Exception e1)
{
LineOut(stringfunction + "()::Error", e1);
}
return c;
}
public static bool IsNumeric(string stringin)
{
if (stringin.Length <= 0)
return false;
try
{
#pragma warning disable 168
double retNum = Double.Parse(Convert.ToString(stringin), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo);
#pragma warning restore 168
return true;
}
catch
{
return false;
}
}
public static double ReturnValidDouble(string stringin)
{
if (stringin.Length <= 0)
return 0.0;
try
{
double retNum = Double.Parse(Convert.ToString(stringin), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo);
return retNum;
}
catch
{
return 0.0;
}
}
public static int ReturnValidInt(string stringin)
{
if (stringin.Length <= 0)
return 0;
try
{
int retNum = int.Parse(Convert.ToString(stringin), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo);
return retNum;
}
catch
{
return 0;
}
}
private void OutputStatusBits(int intbyte, string stringstatusbinary)
{
for (int i = 7; i >= 0; i--)
{
if (stringstatusbinary[i].CompareTo('1') == 0)
{
LineOut(GetDescriptionForStatusBit(intbyte, 7 - i).ToUpper());
}
}
}
private string GetDescriptionForStatusBit(int intbyte, int intbit)
{
if (intbyte == 1)
{
switch (intbit)
{
case 0:
return " - Bit " + intbit + ": Timeout Elapsed";
case 1:
return " - Bit " + intbit + ": Print Key Pressed";
case 2:
return " - Bit " + intbit + ": Preset Pending";
case 3:
return " - Bit " + intbit + ": Valves Open";
case 4:
return " - Bit " + intbit + ": Product Flowing";
case 5:
return " - Bit " + intbit + ": Delivery Active";
case 6:
return " - Bit " + intbit + ": Ticket Pending";
case 7:
return " - Bit " + intbit + ": Host Mode Active";
}
}
else if (intbyte == 2)
{
switch (intbit)
{
case 0:
return " - Bit " + intbit + ": Power Failure";
case 1:
return "Bit " + intbit + ": Host Mode Cancelled During Delivery";
}
}
return "";
}
public byte GetByteChecksumV1(byte[] sSend)
{
byte bSum = 0;
foreach (byte b in sSend)
{
bSum ^= b;
}
return bSum;
}
public string CurrentVolumeFromHexByteArrayToDecimalString(byte[] sInBytes)
{
const string stringfunction = "CurrentVolumeFromHexByteArrayToDecimalString";
string sReturn = "";
string sVal1 = "";
try
{
sVal1 = ByteArrayToHexStringNoPad(sInBytes);
sReturn = sVal1.Substring(0, 6) + "." + sVal1.Substring(6, 2);
}
catch (Exception e1)
{
LineOut(stringfunction + "()::Error processing hex byte array", e1);
}
return sReturn;
}
public int GetNumericSoftwareVersion(string stringversion)
{
const string stringfunction = "GetNumericSoftwareVersion";
string stringout = "";
int intreturn = 0;
try
{
if (stringversion != null)
{
foreach (char c in stringversion)
{
if (((int)c >= 48) && ((int)c <= 57))
{
stringout += c.ToString();
}
}
if (stringout.Length == 0)
{
stringout = "0";
}
}
else
{
LineOut(stringfunction + "()::stringversion is null, must fix caller..");
}
intreturn = ReturnValidInt(stringout);
}
catch (Exception e1)
{
LineOut(stringfunction + "()::Error", e1);
}
return intreturn;
}
public void DoVersionCommand()
{
//string stringfunction = "DoVersionCommand";
bool boolcomportopen = false;
byte[] bytestosend;
byte[] bytespcmtosend;
int inthundredths = 0;
int intthousandths = 0;
int intpcmcommanddelay = 5; //milliseconds
int intmaxcommandtimeoutTenths = 0; //HUNDREDTHS of seconds
int inttargetresponsecharcount = 0;
int intmaxretries = 0;
int intretrycount = 0;
int intretrytimeoutmilliseconds = 0; //milliseconds
string stringout = "";
try
{
//1. com port
//2. pcm command
//3. send command
//4. get response
//5. parse response
//6. close pcm
LineOut("*** GET E:COUNT VERSION ***");
LineOut("USING SERIAL PORT COM" + intcurrentcomport);
if (!IsCOMPortValid(intcurrentcomport))
{
stringout = "INVALID COM PORT! CHECK DEVICE MANAGER";
LineOut(stringout);
System.Windows.Forms.MessageBox.Show(stringout);
goto End_VersionCommand;
}
//setup com port and open it
if (boolcomportopen)
{
//if the port is open, close it (possibly due to an error)
LineOut("COM PORT ALREADY OPEN, CLOSING");
CloseSerialPort(serialPort1);
boolcomportopen = false;
}
LineOut("INITIALIZING COM PORT");
boolcomportopen = OpenSerialPort(serialPort1);
if (!boolcomportopen)
{
LineOut("ERROR INITIALIZING COM PORT!");
goto End_VersionCommand;
}
//build pcm and command arrays to connect HOST to REGISTER1 (0x1F 0x02) and then send V (0x56)
LineOut("BUILDING COMMAND BYTEARRAYS");
bytespcmtosend = StringToByteArray(Chr(31) + Chr(2)); //chr(31) = HEX 0x1F, chr(2) = HEX 0x02
bytestosend = StringToByteArray(Chr(86)); //chr(86) = ASCII V
//V command response looks like this (from ECount Host Interface docs):
// response: V + data + |
// data = 15 bytes:
//
// Register Firmware Version XXXXXX (may be spaces) 6 bytes
// Firmware Data Block Version (00-99) 2 bytes
// Register Port Number (1/2) 1 byte
// Register Serial Number (000000-999999) 6 bytes
// ==============================================================
// Total 15 bytes
//set parameters for V comamnd
LineOut("INITIALIZING COMMAND CONTROL PARAMETERS");
intmaxcommandtimeoutTenths = 10; //10 hundredths = 1000ms max to wait, this will vary from command to command
inttargetresponsecharcount = 17; //V + 15 data chars + |, this will vary from command to command
intmaxretries = 0; //V cmd should not be re-sent if no response (only J should be resent if no response)
intretrycount = 0;
intretrytimeoutmilliseconds = 0; //delay between retries in ms, J command is only cmd retry that is valid, J requires *min* of 250 ms between retries
Retry_VersionCommand:
//clear RX buffer before sending
LineOut("CLEARING COM PORT BUFFER");
bacomportbuffer = new byte[] { };
//send pcm command bytes
LineOut("SENDING PCM CONNECT HOST-TO-REG1 COMMAND: ");
LineOutHexAndASCII(ByteArrayToString(bytespcmtosend));
serialPort1.Write(bytespcmtosend, 0, bytespcmtosend.GetUpperBound(0) + 1);
//wait X ms for PCM hardware to complete port switching
LineOut("WAITING FOR PCM TO SWITCH PORTS ..");
intthousandths = 0;
while (intthousandths < intpcmcommanddelay)
{
//this is a kludge
intthousandths++;
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(1); //1 = 1ms
}
//send V command bytes
LineOut("SENDING E:COUNT COMMAND: ");
LineOutHexAndASCII(ByteArrayToString(bytestosend));
serialPort1.Write(bytestosend, 0, bytestosend.GetUpperBound(0) + 1);
//wait for response
inthundredths = 0;
while ((inthundredths < intmaxcommandtimeoutTenths) && (bacomportbuffer.Length < inttargetresponsecharcount))
{
inthundredths++;
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(10); //10 = 10ms, 10ms is one-hundredth of a second ..
System.Windows.Forms.Application.DoEvents();
}
if (bacomportbuffer.Length < inttargetresponsecharcount)
{
LineOut("RESPONSE TIMEOUT EXCEEDED " + intmaxcommandtimeoutTenths + " TENTHS OF A SECOND");
if (intretrycount < intmaxretries)
{
intretrycount++;
System.Threading.Thread.Sleep(intretrytimeoutmilliseconds);
LineOut("RETRY # " + intretrycount + " OF " + intmaxretries + ", TOO FEW CHARS: " + bacomportbuffer.Length.ToString());
LineOut("PLEASE WAIT ..");
goto Retry_VersionCommand;
}
else
{
if (intmaxretries == 0)
{
LineOut("INVALID RESPONSE, TOO FEW CHARS: " + bacomportbuffer.Length.ToString());
}
else
{
LineOut("MAX OF " + intmaxretries + " RETRIES REACHED, TOO FEW CHARS: " + bacomportbuffer.Length.ToString());
}
}
}
else
{
string stringresponse = ByteArrayToString(bacomportbuffer);
LineOut("RX FROM E:COUNT: " + stringresponse.Length + " BYTES");
LineOutHexAndASCII(stringresponse);
//NOTE, C# ARRAY INDICES ARE 0-BASED
LineOut("COMMAND ECHO (0,1) ....: " + stringresponse.Substring(0, 1));
LineOut("FIRMWARE VERSION (1,6) ....: " + stringresponse.Substring(1,6));
LineOut("DATABLOCK VERSION (7,2) ....: " + stringresponse.Substring(7,2));
LineOut("REGISTER NUMBER (9,1) ....: " + stringresponse.Substring(9,1));
LineOut("REGISTER SERIAL# (10,6) ....: " + stringresponse.Substring(10,6));
LineOut("TERMINATING PIPE CHARACTER (16,1) ....: " + stringresponse.Substring(16,1));
intlastregisternumericversionnumber = GetNumericSoftwareVersion(stringresponse.Substring(1, 6));
}
//build pcm command arrays to disconnect HOST
bytespcmtosend = StringToByteArray(Chr(255));
//send pcm command bytes
LineOut("SENDING PCM DISCONNECT COMMAND: ");
LineOutHexAndASCII(ByteArrayToString(bytespcmtosend));
serialPort1.Write(bytespcmtosend, 0, bytespcmtosend.GetUpperBound(0) + 1);
}
catch (Exception e1)
{
LineOut("EXCEPTION IN DoVersionCommand()", e1);
}
End_VersionCommand:
LineOut("PROCESSING COMPLETE");
if (boolcomportopen)
{
LineOut("CLOSING COM PORT");
CloseSerialPort(serialPort1);
boolcomportopen = false;
}
LineOut("============================");
}//end- DoVersionCommand()
public void DoPresetCommand()
{
//string stringfunction = "DoPresetCommand";
bool boolcomportopen = false;
byte[] bytestosend;
byte[] bytespcmtosend;
int inthundredths = 0;
int intthousandths = 0;
int intpcmcommanddelay = 5; //milliseconds
int intmaxcommandtimeoutTenths = 0; //HUNDREDTHS of seconds
int inttargetresponsecharcount = 0;
int intmaxretries = 0;
int intretrycount = 0;
int intretrytimeoutmilliseconds = 0; //milliseconds
string stringout = "";
try {
//1. com port
//2. pcm command
//3. send command
//4. get response
//5. parse response
//6. close pcm
LineOut("*** SET E:COUNT PRESET ***");
string strpreset = "A" + "01" + "000000" + "0" + "01";
if (txtPreset.Text.Length > 0) {
decimal dpreset = decimal.Parse(txtPreset.Text) * 10;
if (dpreset > 0.09m && dpreset < 1000000m) {
strpreset = dpreset.ToString("000000");
strpreset = "A" + "01" + strpreset + "1" + "01";
LineOut(" - THIS WILL BE A HOST MODE DELIVERY A PRESET VALUE OF " + txtPreset.Text);
}
else {
LineOut(" - THIS WILL BE A HOST MODE DELIVERY WITH NO PRESET VALUE");
}
}
else {
LineOut("Option 1: To skip the preset and do a Host Mode delivery enter preset of 0.");
LineOut("Option 2: To do a pump + print delivery skip preset and reset the E:Count.");
goto End_PresetCommand;
}
//LineOut(strpreset);
// Note: By sending the "A" or the "E" command prior to the delivery it automatically puts the E:Count in host mode
// which requires the X command be used after the delivery has ended in order to print the delivery ticket
LineOut("USING SERIAL PORT COM" + intcurrentcomport);
if (!IsCOMPortValid(intcurrentcomport)) {
stringout = "INVALID COM PORT! CHECK DEVICE MANAGER";
LineOut(stringout);
System.Windows.Forms.MessageBox.Show(stringout);
goto End_PresetCommand;
}
//setup com port and open it
if (boolcomportopen) {
//if the port is open, close it (possibly due to an error)
LineOut("COM PORT ALREADY OPEN, CLOSING");
CloseSerialPort(serialPort1);
boolcomportopen = false;
}
LineOut("INITIALIZING COM PORT");
boolcomportopen = OpenSerialPort(serialPort1);
if (!boolcomportopen) {
LineOut("ERROR INITIALIZING COM PORT!");
goto End_PresetCommand;
}
//build pcm and command arrays to connect HOST to REGISTER1 (0x1F 0x02) and then send V (0x56)
LineOut("BUILDING COMMAND BYTEARRAYS");
bytespcmtosend = StringToByteArray(Chr(31) + Chr(2)); //chr(31) = HEX 0x1F, chr(2) = HEX 0x02
bytestosend = StringToByteArray(strpreset); // Built above
//A command looks like this (from ECount Host Interface docs):
// response: A + response + | (Response=0:Invalid PC, Response=1:Valid PC)
// command = 11 bytes (10 bytes for E command):
//
// Product Code 2 bytes 01 - 99
// Preset Tenths, Implied Decimal 6 bytes 000000 - 999999
// Preset Enable 1 byte 0 - 1(0 = OFF 1 = ON)
// Byte 10(Ignored) 1 byte 0(Send ASCII 0)
// Byte 11(Ignored) 1 byte 1(Send ASCII 1)
//set parameters for V comamnd
LineOut("INITIALIZING COMMAND CONTROL PARAMETERS");
intmaxcommandtimeoutTenths = 30; //hundredths = N * 100ms max to wait, this will vary from command to command
inttargetresponsecharcount = 3; //E + response + |, this will vary from command to command
intmaxretries = 0; //E cmd should not be re-sent if no response (only J should be resent if no response)
intretrycount = 0;
intretrytimeoutmilliseconds = 0; //delay between retries in ms, J command is only cmd retry that is valid, J requires *min* of 250 ms between retries
//Retry_PresetCommand:
//clear RX buffer before sending
LineOut("CLEARING COM PORT BUFFER");
bacomportbuffer = new byte[] { };
//send pcm command bytes
LineOut("SENDING PCM CONNECT HOST-TO-REG1 COMMAND: ");
LineOutHexAndASCII(ByteArrayToString(bytespcmtosend));
serialPort1.Write(bytespcmtosend, 0, bytespcmtosend.GetUpperBound(0) + 1);
//wait X ms for PCM hardware to complete port switching
LineOut("WAITING FOR PCM TO SWITCH PORTS ..");
intthousandths = 0;
while (intthousandths < intpcmcommanddelay) {
//this is a kludge
intthousandths++;
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(1); //1 = 1ms
}
//send command bytes
LineOut("SENDING E:COUNT COMMAND: ");
LineOutHexAndASCII(ByteArrayToString(bytestosend));
serialPort1.Write(bytestosend, 0, bytestosend.GetUpperBound(0) + 1);
//wait for response
inthundredths = 0;
while ((inthundredths < intmaxcommandtimeoutTenths) && (bacomportbuffer.Length < inttargetresponsecharcount)) {
inthundredths++;
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(10); //10 = 10ms, 10ms is one-hundredth of a second ..
System.Windows.Forms.Application.DoEvents();
}
if (bacomportbuffer.Length < inttargetresponsecharcount) {
LineOut("RESPONSE TIMEOUT EXCEEDED " + intmaxcommandtimeoutTenths + " TENTHS OF A SECOND");
if (intretrycount < intmaxretries) {
intretrycount++;
System.Threading.Thread.Sleep(intretrytimeoutmilliseconds);
LineOut("RETRY # " + intretrycount + " OF " + intmaxretries + ", TOO FEW CHARS: " + bacomportbuffer.Length.ToString());
LineOut("PLEASE WAIT ..");
//goto Retry_PresetCommand;
}
else {
if (intmaxretries == 0) {
LineOut("INVALID RESPONSE, TOO FEW CHARS: " + bacomportbuffer.Length.ToString());
LineOutHexAndASCII(ByteArrayToString(bacomportbuffer));
}
else {
LineOut("MAX OF " + intmaxretries + " RETRIES REACHED, TOO FEW CHARS: " + bacomportbuffer.Length.ToString());
}
}
}
else {
LineOut("TX TO E:COUNT: " + strpreset.Length + " BYTES: " + strpreset);
LineOut("COMMAND (0,1) ....: " + strpreset.Substring(0, 1));
LineOut("PRODUCT CODE (1,2) ....: " + strpreset.Substring(1, 2));
LineOut("PRESET (TENTHS NO DECIMAL) (3,6) ....: " + strpreset.Substring(2, 6));
LineOut("PRESET ENABLE (0,1) (9,1) ....: " + strpreset.Substring(8, 1));
LineOut("REQUIRED CHARS (10,2) ....: " + strpreset.Substring(9, 2));
LineOut("");
string stringresponse = ByteArrayToString(bacomportbuffer);
LineOut("RX FROM E:COUNT: " + stringresponse.Length + " BYTES");
LineOutHexAndASCII(stringresponse);
//NOTE, C# ARRAY INDICES ARE 0-BASED
LineOut("COMMAND ECHO (0,1) ....: " + stringresponse.Substring(0, 1));
LineOut("PRODUCT CODE STATUS (1,1) ....: " + stringresponse.Substring(1, 1));
LineOut("TERMINATING PIPE CHARACTER (2,1) ....: " + stringresponse.Substring(2, 1));
if (stringresponse.Substring(1, 1).CompareTo("1")==0) {
LineOut("*** THE E:COUNT IS IN HOST MOST STATUS AND READY TO BE RESET TO BEGIN A DELVIERY ***");
LineOut("*** NOTE: THE ~DELIVERY~ LEGEND SHOULD BE VISIBLE ON THE E:COUNT ***");
}
}
//build pcm command arrays to disconnect HOST
bytespcmtosend = StringToByteArray(Chr(255));
//send pcm command bytes
LineOut("SENDING PCM DISCONNECT COMMAND: ");
LineOutHexAndASCII(ByteArrayToString(bytespcmtosend));
serialPort1.Write(bytespcmtosend, 0, bytespcmtosend.GetUpperBound(0) + 1);
}
catch (Exception e1)
{
LineOut("EXCEPTION IN DoPresetCommand()", e1);
}
End_PresetCommand:
LineOut("PROCESSING COMPLETE");
if (boolcomportopen)
{
LineOut("CLOSING COM PORT");
CloseSerialPort(serialPort1);
boolcomportopen = false;
}
LineOut("============================");
}//end- DoPresetCommand()
public void DoResetCommand()
{
//string stringfunction = "DoResetCommand";
bool boolcomportopen = false;
byte[] bytestosend;
byte[] bytespcmtosend;
int inthundredths = 0;
int intthousandths = 0;
int intpcmcommanddelay = 5; //milliseconds
int intmaxcommandtimeoutTenths = 0; //HUNDREDTHS of seconds
int inttargetresponsecharcount = 0;
int intmaxretries = 0;
int intretrycount = 0;
int intretrytimeoutmilliseconds = 0; //milliseconds
string stringout = "";
try {
//1. com port
//2. pcm command
//3. send command
//4. get response
//5. parse response
//6. close pcm
LineOut("*** SET E:COUNT RESET ***");
LineOut("USING SERIAL PORT COM" + intcurrentcomport);
if (!IsCOMPortValid(intcurrentcomport)) {
stringout = "INVALID COM PORT! CHECK DEVICE MANAGER";
LineOut(stringout);
System.Windows.Forms.MessageBox.Show(stringout);
goto End_ResetCommand;
}
//setup com port and open it
if (boolcomportopen) {
//if the port is open, close it (possibly due to an error)
LineOut("COM PORT ALREADY OPEN, CLOSING");
CloseSerialPort(serialPort1);
boolcomportopen = false;
}
LineOut("INITIALIZING COM PORT");
boolcomportopen = OpenSerialPort(serialPort1);
if (!boolcomportopen) {
LineOut("ERROR INITIALIZING COM PORT!");
goto End_ResetCommand;
}
//Command Sequence:
//TX: 0x1F 0x02(Connect PCM - Host to PCM - EC1)
//TX: R
//RX: R(Verify R is echoed)
//RX: | (Verify pipe char)
//TX: 0xFF(Disconnect PCM)
//N
string stringtosend = "R";
//build pcm and command arrays to connect HOST to REGISTER1 (0x1F 0x02) and then send V (0x56)
LineOut("BUILDING COMMAND BYTEARRAYS");
bytespcmtosend = StringToByteArray(Chr(31) + Chr(2)); //chr(31) = HEX 0x1F, chr(2) = HEX 0x02
bytestosend = StringToByteArray(stringtosend); // Built above
//set parameters for V comamnd
LineOut("INITIALIZING COMMAND CONTROL PARAMETERS");
intmaxcommandtimeoutTenths = 1000;//10 sec = tenths = N * 100ms max to wait, this will vary from command to command
inttargetresponsecharcount = 2; //E + response + |, this will vary from command to command
intmaxretries = 0; //E cmd should not be re-sent if no response (only J should be resent if no response)
intretrycount = 0;
intretrytimeoutmilliseconds = 0; //delay between retries in ms, J command is only cmd retry that is valid, J requires *min* of 250 ms between retries
//Retry_ResetCommand:
//clear RX buffer before sending
LineOut("CLEARING COM PORT BUFFER");
bacomportbuffer = new byte[] { };
//send pcm command bytes
LineOut("SENDING PCM CONNECT HOST-TO-REG1 COMMAND: ");
LineOutHexAndASCII(ByteArrayToString(bytespcmtosend));
serialPort1.Write(bytespcmtosend, 0, bytespcmtosend.GetUpperBound(0) + 1);
//wait X ms for PCM hardware to complete port switching
LineOut("WAITING FOR PCM TO SWITCH PORTS ..");
intthousandths = 0;
while (intthousandths < intpcmcommanddelay) {
//this is a kludge
intthousandths++;
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(1); //1 = 1ms
}
//send command bytes
LineOut("SENDING E:COUNT COMMAND: ");
LineOutHexAndASCII(ByteArrayToString(bytestosend));
serialPort1.Write(bytestosend, 0, bytestosend.GetUpperBound(0) + 1);
//wait for response
inthundredths = 0;
while ((inthundredths < intmaxcommandtimeoutTenths) && (bacomportbuffer.Length < inttargetresponsecharcount)) {
inthundredths++;
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(10); //10 = 10ms, 10ms is one-hundredth of a second ..
System.Windows.Forms.Application.DoEvents();
}
if (bacomportbuffer.Length < inttargetresponsecharcount) {
LineOut("RESPONSE TIMEOUT EXCEEDED " + intmaxcommandtimeoutTenths + " TENTHS OF A SECOND");
if (intretrycount < intmaxretries) {
intretrycount++;
System.Threading.Thread.Sleep(intretrytimeoutmilliseconds);
LineOut("RETRY # " + intretrycount + " OF " + intmaxretries + ", TOO FEW CHARS: " + bacomportbuffer.Length.ToString());
LineOut("PLEASE WAIT ..");
//goto Retry_ResetCommand;
}
else {
if (intmaxretries == 0) {
LineOut("INVALID RESPONSE, TOO FEW CHARS: " + bacomportbuffer.Length.ToString());
LineOutHexAndASCII(ByteArrayToString(bacomportbuffer));
}
else {
LineOut("MAX OF " + intmaxretries + " RETRIES REACHED, TOO FEW CHARS: " + bacomportbuffer.Length.ToString());
}
}
}
else {
LineOut("TX TO E:COUNT: " + stringtosend.Length + " BYTES: " + stringtosend);
string stringresponse = ByteArrayToString(bacomportbuffer);
LineOut("RX FROM E:COUNT: " + stringresponse.Length + " BYTES");
LineOutHexAndASCII(stringresponse);
//NOTE, C# ARRAY INDICES ARE 0-BASED
LineOut("COMMAND ECHO (0,1) ....: " + stringresponse.Substring(0, 1));
LineOut("TERMINATING PIPE CHARACTER (1,1) ....: " + stringresponse.Substring(1, 1));
}
//build pcm command arrays to disconnect HOST
bytespcmtosend = StringToByteArray(Chr(255));
//send pcm command bytes
LineOut("SENDING PCM DISCONNECT COMMAND: ");
LineOutHexAndASCII(ByteArrayToString(bytespcmtosend));
serialPort1.Write(bytespcmtosend, 0, bytespcmtosend.GetUpperBound(0) + 1);
}
catch (Exception e1) {
LineOut("EXCEPTION IN DoResetCommand()", e1);
}