Form1.cs
62.6 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
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;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Data.SqlClient;
using System.Xml;
using MyClassLib;
using MyControlLib;
namespace HaierExe04
{
public partial class Form1 : MyFrmReg
{
#region 定义要用到的类
private IPEndPoint ServerInfo;//存放服务器的IP和端口信息
private Socket ServerSocket;//服务端运行的SOCKET
private Thread ServerThread;//服务端运行的线程
private Socket[] ClientSocket;//为客户端建立的SOCKET连接
private int ClientNumb;//存放客户端数量
private byte[] MsgBuffer;//存放消息数据
private int LocalPort = 51237;//定义端口号
private DgvDisplayUtil dgv;//设备IP表格
private DgvDisplayUtil DgvPLC;//PLC 信息处理表格
private DgvDisplayUtil DgvBarcode;// 条码厂商信息处理表格
/// <summary>
/// 校验首工位标志
/// </summary>
bool checkFirstFlag = false;
/// <summary>
/// 校验顺序工位标志
/// </summary>
bool checkSequenceFlag = false;
/// <summary>
/// 校验条码的来源库
/// </summary>
bool checkBarcodeSource = false;
/// <summary>
/// 发送的方式 (先进先出)
/// </summary>
bool checkSendWay = false;
/// <summary>
/// 写入PLC的方式(先进先出)
/// </summary>
bool checkWritePLC = false;
#endregion
public Form1()
{
InitializeComponent();
#region 显示的datagridview 初始化
dgv = new DgvDisplayUtil(dataGridView1);
//string strSql = "select top(10) [stationInfoID] ,[IP] ,[OrderID] , a.[barcode] ,a.[InputTime] FROM [T_BarCodeScan] a left join T_BarcodeInfo b on a.barcode=b.BarCode where IsUse=1";
dgv.AddDgvTitle("stationInfoID", "工位", 60);
dgv.AddDgvTitle("IP", "IP地址", 80);
dgv.AddDgvTitle("OrderID", "订单号", 120);
dgv.AddDgvTitle("OrderCode", "虚拟单号", 90);
dgv.AddDgvTitle("SerialNo", "序列", 60);
dgv.AddDgvTitle("barcode", "条码值", 140);
dgv.AddDateTimeDgvTitle("scheduleTime", "计划时间", 130);
dgv.AddDateTimeDgvTitle("StartTime", "上线时间", 145);
dgv.AddDateTimeDgvTitle("InputTime", "更新时间", 145);
DgvPLC = new DgvDisplayUtil(dataGridView2);
DgvPLC.AddDgvTitle("C_ID", "编号", 80);
DgvPLC.AddDgvTitle("IP", "条码设备", 120);
DgvPLC.AddDgvTitle("Barcode", "条码值", 130);
DgvPLC.AddDgvTitle("WriteFlag", "写入标志", 120);
DgvPLC.AddDgvTitle("WriteCount", "写入次数", 120);
DgvPLC.AddDateTimeDgvTitle("InputTime", "更新时间", 150);
DgvBarcode = new DgvDisplayUtil(dataGridView3);
DgvBarcode.AddDgvTitle("C_ID", "编号", 80);
DgvBarcode.AddDgvTitle("IP", "设备IP", 120);
DgvBarcode.AddDgvTitle("Barcode", "条码值", 130);
DgvBarcode.AddDgvTitle("SendFlag", "发送标志", 100);
DgvBarcode.AddDgvTitle("SendCount", "发送次数", 100);
DgvBarcode.AddDateTimeDgvTitle("ReceiveTime", "接收时间", 120);
DgvBarcode.AddDateTimeDgvTitle("PrintTime", "打印时间", 120);
DgvBarcode.AddDateTimeDgvTitle("InputTime", "记录时间", 120);
#endregion
LocalPort = Properties.Settings.Default.Port;
timerScan.Interval = Properties.Settings.Default.Interval;
timerScan.Enabled = false;
//滚动条 初始化
ucErrorDisplay1.MoveEnable = true;
ucErrorDisplay1.Interval = 400;
ucErrorDisplay1.SpeedMove = 25;
//服务端初始化
IPAddress[] addresslist = Dns.GetHostByName(Dns.GetHostName()).AddressList;
int i = 0;
for (i = 0; i < addresslist.Length; i++)
{
if (!addresslist[i].IsIPv6LinkLocal)
{
toolStripComboBoxIP.Items.Add( addresslist[i].ToString());
}
}
toolStripComboBoxIP.Text = toolStripComboBoxIP.Items[0].ToString();
toolStripTextBoxPort.Text = LocalPort.ToString();
//这里采用连接数据库的方式 可以通过更改数据库配置 另:XML文件的方式 ReadXmlConfig();
ReadSqlConfig();
RefreshData();
}
#region //配置方面
/// <summary>
/// 扫描条码设备相关信息
/// </summary>
public struct ScanConfigInfo
{
/// <summary>
/// 设备工位ID
/// </summary>
public int StationInfoID;
/// <summary>
/// 是否为首工位 默认第一个扫描枪
/// </summary>
public bool IsFirst;
/// <summary>
/// 条码设备的IP
/// </summary>
public string Ip;
/// <summary>
/// 连接PLC的IP
/// </summary>
public string HostAddress;
/// <summary>
/// 连接PLC的端口号
/// </summary>
public int Port;
/// <summary>
/// 需要写入的地址列表
/// </summary>
public string Address;
/// <summary>
/// 序号
/// </summary>
public int Index;
}
/// <summary>
/// 打印和贴标条码设备信息
/// </summary>
public struct BarcodeEquipmentInfo
{
/// <summary>
/// 设备名称
/// </summary>
public string strName;
/// <summary>
/// 设备IP
/// </summary>
public string strIp;
/// <summary>
/// 条码IP
/// </summary>
public string ScanIP;
/// <summary>
/// 标示
/// </summary>
public int Num;
/// <summary>
/// 设备ID
/// </summary>
public int AddressID;
}
/// <summary>
/// 定义一个扫条码设备信息数组
/// </summary>
private ScanConfigInfo[] ScanInfo;
/// <summary>
/// 定义一个贴码设备信息数组
/// </summary>
private BarcodeEquipmentInfo[] BarcodeEquipInfo;
/// <summary>
/// 读取配置文件
/// </summary>
private void ReadXmlConfig()
{
try
{
//step1: 获取XML文件的根节点
XmlDocument doc = new XmlDocument();
string pathName = Application.StartupPath + "\\config\\config.xml";
doc.Load(pathName);
XmlNode root = doc.SelectSingleNode("root");
#region// 条码设备的配置
int t = root.FirstChild.ChildNodes.Count;
ScanInfo = new ScanConfigInfo[t];
//默认设置 第一个扫描设备为首工位
ScanInfo[0].IsFirst = true;
int i = 0;
foreach (XmlNode xn in root.FirstChild.ChildNodes)
{
XmlElement xe = (XmlElement)xn;
foreach (XmlNode xl in xe.ChildNodes)
{
if (xl.Name == "IP")
{
ScanInfo[i].Ip = xl.Value;
}
else if (xl.Name == "ActHostAddress")
{
ScanInfo[i].HostAddress = xl.Value;
}
else if (xl.Name == "Port")
{
ScanInfo[i].Port = int.Parse(xl.Value);
}
else if (xl.Name == "Address")
{
ScanInfo[i].Address = xl.Value;
}
}
i++;
}
#endregion
#region//贴码设备的配置
int t2 = root.LastChild.ChildNodes.Count;
BarcodeEquipInfo = new BarcodeEquipmentInfo[t2];
i = 0;
foreach (XmlNode xn2 in root.LastChild.ChildNodes)
{
XmlElement xe = (XmlElement)xn2;
foreach (XmlNode xl in xe.ChildNodes)
{
if (xl.Name == "IP")
{
BarcodeEquipInfo[i].strIp = xl.Value;
}
else if (xl.Name == "ScanIP")
{
BarcodeEquipInfo[i].ScanIP= xl.Value;
}
else if (xl.Name == "strName")
{
BarcodeEquipInfo[i].strName= xl.Value;
}
else if (xl.Name == "Num")
{
BarcodeEquipInfo[i].Num = int.Parse(xl.Value);
}
else if(xl.Name=="AddressID")
{
BarcodeEquipInfo[i].AddressID=int.Parse(xl.Value);
}
}
i++;
}
#endregion
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("ReadXmlConfig",ex);
}
}
/// <summary>
/// 读取数据库配置
/// </summary>
private void ReadSqlConfig()
{
try
{
#region//step1: 获取扫描设备的配置信息
string str = "select * from T_BarcodeScan where IsUse>=1 order by stationInfoID";
DataTable dt = CSqlHelper.ExecuteDataset(str).Tables[0];
int count = dt.Rows.Count;
ScanInfo = new ScanConfigInfo[count];
//默认 第一个扫描设备 首工位
ScanInfo[0].IsFirst = true;
for (int i = 0; i < count; i++)
{
ScanInfo[i].Ip = dt.Rows[i]["IP"].ToString();
ScanInfo[i].HostAddress = dt.Rows[i]["ActHostAddress"].ToString();
ScanInfo[i].Port = int.Parse(dt.Rows[i]["PortNumber"].ToString());
ScanInfo[i].Address = dt.Rows[i]["AddressList"].ToString();
ScanInfo[i].StationInfoID = int.Parse(dt.Rows[i]["stationInfoID"].ToString());
ScanInfo[i].Index = i;
if (i == 0)
{
ScanInfo[i].IsFirst = true;
}
else
{
ScanInfo[i].IsFirst = false;
}
}
#endregion
#region
string str2 = "select * from T_SocketBarcode ";
DataTable dt2 = CSqlHelper.ExecuteDataset(str2).Tables[0];
int count2 = dt2.Rows.Count;
BarcodeEquipInfo = new BarcodeEquipmentInfo[count2];
for (int j = 0; j < count2; j++)
{
BarcodeEquipInfo[j].strIp = dt2.Rows[j]["SelfIP"].ToString();
BarcodeEquipInfo[j].Num = int.Parse(dt2.Rows[j]["C_ID"].ToString());
BarcodeEquipInfo[j].strName = dt2.Rows[j]["EquipmentName"].ToString();
BarcodeEquipInfo[j].ScanIP = dt2.Rows[j]["BandingScanIP"].ToString();
BarcodeEquipInfo[j].AddressID=int.Parse(dt2.Rows[j]["AddressID"].ToString());
}
#endregion
#region
string str3 = "select * from T_BarcodeCheckConfig";
DataTable dt3 = CSqlHelper.ExecuteDataset(str3).Tables[0];
if (dt3.Rows.Count > 0)
{
if (dt3.Rows[0]["IsAllow"].ToString() == "1")
{
groupBox1.Enabled = true;
groupBox2.Enabled = true;
groupBox3.Enabled = true;
}
else
{
groupBox1.Enabled = false;
groupBox2.Enabled = false;
groupBox3.Enabled = false;
}
if (dt3.Rows[0]["CheckFirst"].ToString() == "1")
{
checkBox1.Checked = true;
}
else
{
checkBox1.Checked = false;
}
if (dt3.Rows[0]["CheckSequenc"].ToString() == "1")
{
checkBox2.Checked = true;
}
else
{
checkBox2.Checked = false;
}
if (dt3.Rows[0]["CheckSource"].ToString() == "1")
{
checkBox3.Checked = true;
}
else
{
checkBox3.Checked = false;
}
}
#endregion
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("ReadSqlConfig", ex);
}
}
#endregion
#region Socket相关的函数
private string GetLocalIPAddress()
{
//string hostName = Dns.GetHostName();//本机名
//System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期,我运行时且只返回了一个IPv4的地址
//System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//会返回所有地址,包括IPv4和IPv6
IPAddress[] addresslist = Dns.GetHostByName(Dns.GetHostName()).AddressList;
//IPAddress[] addresslist=Dns.GetHostAddresses(Dns.GetHostName());
int i = 0;
for (i = 0; i < addresslist.Length; i++)
{
if (!addresslist[i].IsIPv6LinkLocal)
{
return addresslist[i].ToString();
}
}
return addresslist[0].ToString();
}
/// <summary>
/// //开启服务器 侦听客户端的连接请求
/// </summary>
private bool SocketListen()
{
bool flag = false;
try
{
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//提供一个 IP 地址,指示服务器应侦听所有网络接口上的客户端活动
//IPAddress ip = IPAddress.Any;
IPAddress ip = IPAddress.Parse(toolStripComboBoxIP.Text);
ServerInfo = new IPEndPoint(ip, LocalPort);
ServerSocket.Bind(ServerInfo);//将SOCKET接口和IP端口绑定
ServerSocket.Listen(50);//开始监听,并且挂起数为25
ClientSocket = new Socket[200];//为客服端提供连接个数
MsgBuffer = new byte[65535];//消息数据的大小
ClientNumb = 0;//客服端数据从0开始计数
ServerThread = new Thread(new ThreadStart(RecieveAccept));//将接受客户端连接的方法委托给线程
ServerThread.Start();//线程开始运行
CheckForIllegalCrossThreadCalls = false;//不捕获对错误线程的调用
//this.ClientList.Items.Add("服务器" + ip.ToString() + "于" + DateTime.Now.ToString() + "开始运行\n");
string strPathName = Application.StartupPath + "\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
FileStream fs = new FileStream(strPathName, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs); // 创建写入流
string strWrite = "服务器" + ip.ToString() + "于" + DateTime.Now.ToString() + "开始运行" + "\r\n";
toolStripTextBoxPort.Text = LocalPort.ToString();
toolStripTextBoxPort.Enabled = false;
sw.WriteLine(strWrite); // 写入
sw.Close(); //关闭文件
return true;
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("SocketListen", ex);
return flag;
}
}
/// <summary>
/// //接受客户端连接的方法
/// </summary>
private void RecieveAccept()
{
while (true)
{
//Accept 以同步方式从侦听套接字的连接请求队列中提取第一个挂起的连接请求,然后创建并返回新的 Socket。
//在阻止模式中,Accept 将一直处于阻止状态,直到传入的连接尝试排入队列。连接被接受后,原来的 Socket 继续将传入的连接请求排入队列,直到您关闭它。
//bool writeflag = false;
try
{
ClientSocket[ClientNumb] = ServerSocket.Accept();
ClientSocket[ClientNumb].BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), ClientSocket[ClientNumb]);
string strWrite = "客户端" + ClientSocket[ClientNumb].RemoteEndPoint.ToString() + "于" + DateTime.Now.ToString() + "成功连接服务器";
object thisLock = new object();
lock (thisLock)
{
listBox1.Items.Add(strWrite);
string strPathName = Application.StartupPath + "\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
FileStream fs = new FileStream(strPathName, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs); // 创建写入流
sw.WriteLine(strWrite); // 写入
sw.Close(); //关闭文件
//提取多米诺的IP地址
string ip=ClientSocket[ClientNumb].RemoteEndPoint.ToString().Split(':')[0];
foreach (BarcodeEquipmentInfo bei in BarcodeEquipInfo)
{
if (bei.strIp == ip)
{
int id = bei.Num;
ClientSocket[150 - id] = ClientSocket[ClientNumb];
toolStripSplitButton2.Visible = true;
}
}
}
ClientNumb++;
}
catch (SocketException ex)
{
LogExecute.WriteExceptionLog("RecieveAccept", ex);
}
}
}
/// <summary>
/// //回发数据给客户端
/// </summary>
/// <param name="AR"></param>
private void RecieveCallBack(IAsyncResult AR)
{
Socket RSocket = (Socket)AR.AsyncState;
try
{
int REnd = RSocket.EndReceive(AR);
string strRemoteIP= RSocket.RemoteEndPoint.ToString().Split(':')[0];
object obj = new object();
#region//1获取对应的IP地址 分析相应的处理
lock(obj)
{
bool flag = false;
#region 判断是否是条码扫描设备传送过来的值
foreach (ScanConfigInfo scf in ScanInfo)
{
if (scf.Ip == strRemoteIP)
{
//step1: 判断此数据为正确的条码数据
string strMsg = Encoding.ASCII.GetString(MsgBuffer).Substring(0, REnd);
string barcode = "";
object abc = new object();
lock(abc)
{
if (strMsg.Length > 20)//条码数值为20位 最后一位是回车
{
barcode = strMsg.Substring(1, 20);
}
else { break; }
//step2 :判断此条码是否是上次条码
string[] preBarcode = GetPreBarCode(scf.Ip);
if (preBarcode[0] == "")//表示首次启用
{
InsertBarCode(scf.Ip, barcode);
}
else
{
if (preBarcode[0] !=barcode)//表示新条码
{
//step3: 判断原来的旧条码处理完成没
if (preBarcode[1] == "1")//表示处理OK
{
UpdateBarCode(scf, barcode);
}
else
{
BarcodeAlarmRecord(scf.Ip, preBarcode[1]);
UpdateBarCode(scf, barcode);
}
}
}
}
flag = true;
break;
}
}
#endregion
#region 判断是否是贴码设备传送过来的值
if (flag == false)
{
foreach (BarcodeEquipmentInfo bdef in BarcodeEquipInfo)
{
if (bdef.strIp == strRemoteIP)
{
//step1: 判断是否为贴标设备传送的规则数据
string strMsg = Encoding.ASCII.GetString(MsgBuffer).Substring(0, REnd);
if (strMsg != "" && strMsg.Length > 2)
{
if (strMsg.Substring(0, 1) == STX.ToString() && strMsg.Substring(strMsg.Length - 1, 1) == ETX.ToString())
{
#region log记录
string path = Application.StartupPath + "\\" + bdef.strName;
if (Directory.Exists(path) == false)
{
Directory.CreateDirectory(path);
}
string strPathName = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
FileStream fs = new FileStream(strPathName, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs); // 创建写入流
sw.WriteLine("接收数据:" + strMsg + "\r\n");
#endregion
//0起始符 1时间 2数据类型 3内容 4应答信息 5结束符
string[] strRecData = strMsg.Split(',');
if (strRecData.Length == 6)
{
#region//表示数据交互成功!对方接收成功 更新接收记录
if (strRecData[2] == "B" && strRecData[4] == ACK.ToString())
{
string str2 = "Update T_SendBarCode set SendFlag=1,ReceiveTime=getdate() where BarCode='{0}'";
string strSql = string.Format(str2, strRecData[3]);
//step2: 更新数据
if (CSqlHelper.ExecuteNonQuery(strSql) != 0)
{
}
else
{
UpdateText(string.Format("{0} 条码更新失败 返回条码{1}数据出现了问题", bdef.strIp, strRecData[3]));
}
}
#endregion
#region//表示数据条码打印完成 正常情况下
if (strRecData[2] == "P")
{
string str2 = "Update T_SendBarCode set PrintTime=getdate() ,Type = 1 where BarCode='{0}' and IP='{1}'";
string strSql = string.Format(str2, strRecData[3], bdef.strIp);
if (CSqlHelper.ExecuteNonQuery(strSql) != 0)
{
string strRepsonse = string.Format("{0},{1},{2},{3},{4},{5}", STX, DateTime.Now.ToString(), "P", strRecData[3], ACK, ETX);
byte[] sby = Encoding.ASCII.GetBytes(strRepsonse);
if (ClientSocket[150 - bdef.Num].Send(sby) > 0)
{
sw.WriteLine(strRepsonse);
}
}
else
{
string strRepsonse = string.Format("{0},{1},{2},{3},{4},{5}", STX, DateTime.Now.ToString(), "P", strRecData[3], NAK, ETX);
byte[] sby = Encoding.ASCII.GetBytes(strRepsonse);
if (ClientSocket[150 - bdef.Num].Send(sby) > 0)
{
sw.WriteLine(strRepsonse);
}
UpdateText(string.Format("{0} 条码{1}更新打印时间失败", strRemoteIP, strRecData[3]));
}
}
#endregion
#region//表示设备报警
if (strRecData[2] == "E")
{
string insertSql = string.Format("Insert into T_AlarmMessageRecord (AddressID,AlarmMessage,DisplayStatus,InputTime) values ('{0}','{1}',0,getdate())", bdef.AddressID, strRecData[3]);
if (CSqlHelper.ExecuteNonQuery(insertSql) > 0)
{
string strRepsonse = string.Format("{0},{1},{2},{3},{4},{5}", STX, DateTime.Now.ToString(), "E", strRecData[3], ACK, ETX);
byte[] sby = Encoding.ASCII.GetBytes(strRepsonse);
if (ClientSocket[150 - bdef.Num].Send(sby) > 0)
{
sw.WriteLine(strRepsonse);
}
}
}
#endregion
#region //设备手动打印的数据
if (strRecData[2] == "M")
{
string insertSql = string.Format("Insert into T_SendBarcode ( IP,BarCode,Type,PrintTime) values('{0}','{1}',2,getdate())", bdef.strIp, strRecData[3]);
if (CSqlHelper.ExecuteNonQuery(insertSql) > 0)
{
string strRepsonse = string.Format("{0},{1},{2},{3},{4},{5}", STX, DateTime.Now.ToString(), "M", strRecData[3], ACK, ETX);
byte[] sby = Encoding.ASCII.GetBytes(strRepsonse);
if (ClientSocket[150 - bdef.Num].Send(sby) > 0)
{
sw.WriteLine(strRepsonse);
}
}
}
#endregion
sw.Close();
}
else
{
UpdateText(string.Format("设备传送的数据{0}不符合协议格式的长度", strMsg));
}
}
else
{
UpdateText(string.Format("设备传送的数据{0}不符合协议格式STX和ETX结束", strMsg));
}
}
flag = true;
break;
}
}
}
#endregion
}
#endregion
RSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack), RSocket);
}
catch (Exception ex)
{
if (ex is SocketException)
{
SocketException soex = (SocketException)ex;
LogExecute.WriteExceptionLog(soex.ErrorCode + ":" + soex.Message, ex);
if (soex.ErrorCode == 10054)
{
MessageBox.Show(soex.Message);
}
}
else
{
LogExecute.WriteExceptionLog("receievecallback", ex);
RSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack), RSocket);
}
}
}
#endregion
#region 窗体相关的函数
/// <summary>
/// 退出应用程序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripTextBox1_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// 关闭窗体提示
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult res = MessageBox.Show("确定要结束条码监控系统吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (res == DialogResult.Cancel)
{
e.Cancel = true;
}
else
{
this.notifyIcon1.Visible = false;
Application.ExitThread();
}
}
/// <summary>
/// 窗体导入函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
this.Text = string.Format("海尔波轮洗衣机项目-条码控制程序 Beta{0} 时间{1}","1.1.2","20150508" );
this.Visible = true;
}
/// <summary>
/// 隐藏界面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Deactivate(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Visible = false;
}
}
/// <summary>
/// 刷新数据
/// </summary>
private void RefreshData()
{
try
{
//string strSql = "select * from T_BarcodeScan where IsUse=1 order by IP asc";
string strSql = "select top(10) [stationInfoID] ,[IP] ,[OrderID] , a.[barcode] ,a.[InputTime],b.ScheduleTime,b.StartTime,b.orderCode,b.serialNo FROM [T_BarCodeScan] a left join T_BarcodeInfo b on a.barcode=b.BarCode where IsUse=1";
//dataGridView1.DataSource = SqlDBItem.SelectDataBase(strSql);
//dataGridView1.Update();
DataTable dt = CSqlHelper.ExecuteDataset(strSql).Tables[0];
dgv.RefreshDgvData(dt);
string strPLC = "select top(20) * from T_WriteBarCode order by InputTime";
DgvPLC.RefreshDgvData(CSqlHelper.ExecuteDataset(strPLC).Tables[0]);
string strBar = "Select top(20) * from T_SendBarcode order by InputTime";
DgvBarcode.RefreshDgvData(CSqlHelper.ExecuteDataset(strBar).Tables[0]);
}
catch (Exception ex)
{
LogExecute.WriteInfoLog(ex.Message);
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
}
private void toolStripTextBox2_Click(object sender, EventArgs e)
{
AboutBox1 about = new AboutBox1();
about.Show();
}
#endregion
/// <summary>
/// 获取型号值 根据条码信息查询相应的型号信息
/// </summary>
/// <param name="barcode"></param>
/// <returns></returns>
private int[] GetProductType(string barcode)
{
int[] t1 = new int[10];
//获取条码的前9位
string str2 = barcode.Substring(0, 9);
try
{
#region 根据条码查询 相应的型号信息
string strTypeValues = "";//写入给电气的大型号值
string strBarcodeRulesID = "";//具体的型号编号
string strOrderID = "";//订单ID
string strRules = "select * from T_BarcodeRules where Code='{0}'";
string strSql = string.Format(strRules, str2);
DataTable dt = CSqlHelper.ExecuteDataset(strSql).Tables[0];
if (dt.Rows.Count >= 1)
{
strTypeValues = dt.Rows[0]["ProductValues"].ToString();
strBarcodeRulesID = (dt.Rows[0]["C_ID"].ToString());
}
else
{
UpdateText("系统中没有此类条码解析规则:" + barcode);
}
string strSql2 = string.Format("select C_ID from T_OrderInfo where OrderID=(select OrderID from T_BarcodeInfo where barcode='{0}')", barcode);
strOrderID = (string)CSqlHelper.ExecuteScalar(CSqlHelper.ConnectString, CommandType.Text, strSql2);
t1[0] = int.Parse(strTypeValues);
t1[1] = 1001;
t1[2] = int.Parse(strBarcodeRulesID);
t1[3] = int.Parse(strOrderID);
#endregion
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("GetProductType", ex);
}
return t1;
}
private int AppStateFlag = 0;
/// <summary>
/// 定时器事件函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timerScan_Tick(object sender, EventArgs e)//250ms一次
{
//遍历所有的条码标志信息,发现有变化的就检查写入PLC数据
if(AppStateFlag==0)
{
AppStateFlag=1;
}
else
{
AppStateFlag = 0;
}
try
{
RegisterExeState("BarcodeControlExe", "TCP/IP方式条码读取程序", AppStateFlag);
BarcodeProcess();
SendBarCode();
WriteBarcodePLC();
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("BarcodeControlTimeScan", ex);
UpdateText( ex.Message);
}
}
/// <summary>
/// 获取先前的记录的条码信息
/// </summary>
/// <param name="strIP"></param>
private string[] GetPreBarCode(string strIP)
{
//提取T_Barcode中的最新的数据
string[] strPreBarCode =new string[2];
try
{
string str1 = "select top(1) barcode,Status from T_BarcodeScan where IP='{0}' order by InputTime desc";
string strSql = string.Format(str1, strIP);
DataTable dt = CSqlHelper.ExecuteDataset(strSql).Tables[0];
if (dt.Rows.Count == 1)
{
strPreBarCode[0] = dt.Rows[0]["barcode"].ToString();
strPreBarCode[1] = dt.Rows[0]["Status"].ToString();
}
return strPreBarCode;
}
catch (Exception ex)
{
UpdateText(ex.Message);
return strPreBarCode;
}
}
/// <summary>
/// 根据是否校验条码信息的来源情况之后在更新条码信息
/// </summary>
/// <param name="strIP"></param>
/// <returns></returns>
private bool UpdateBarCode(ScanConfigInfo scf,string BarCode)
{
bool flag = false;
try
{
#region 查询条码库
string str = string.Format("select count(1) from T_BarcodeInfo where barcode='{0}'", BarCode);
int cout =(int) CSqlHelper.ExecuteScalar(CSqlHelper.ConnectString, CommandType.Text, str);
if (cout==0)//表示无记录
{
UpdateText(string.Format("条码设备{0} 扫描的条码{1} 在条码库T_BarcodeInfo中没有记录", scf.Ip, BarCode));
if (checkBarcodeSource == true)
{
string str1 = string.Format("Update T_BarcodeScan set barcode='{0}',status=2 where IP='{1}'", BarCode, scf.Ip);
CSqlHelper.ExecuteNonQuery(str1);
return flag;
}
else
{
BarcodeAlarmRecord(scf.Ip, BarCode, "条码库中未出现该条码");
}
}
#endregion
#region 查询记录表格
string strSQL = string.Format("select top(1) * from T_Queue where barcode='{0}' order by InputTime asc", BarCode);
DataTable dt = CSqlHelper.ExecuteDataset(strSQL).Tables[0];
#region
if (dt.Rows.Count <= 0) //表示此条码还没有任何记录
{
//判断是否是首工位 首工位的直接不用判断进入更新
//step2: 判断此条码是否上线成功
if (scf.IsFirst == false)//不是首工位的设备 需要校验
{
UpdateText(string.Format("条码设备{0} 扫描的条码{1} 未进行上线", scf.Ip, BarCode));
if (checkFirstFlag == true) //校验的话 条码设备更新 status=2 表示异常条码 不需要处理
{
string str1 = string.Format("Update T_BarcodeScan set barcode='{0}',status=3 where IP='{1}'", BarCode, scf.Ip);
return flag;
}
else
{
BarcodeAlarmRecord(scf.Ip, BarCode, "条码首工位未上线");
}
}
else //首工位写入
{
string st12 = string.Format("Insert into T_Queue (barcode,stationInfoID,InputTime) values ('{0}','{1}',getdate())", BarCode, scf.StationInfoID);
CSqlHelper.ExecuteNonQuery(st12);
}
}
else //有数据表示肯定已经经过了首工位 这就需要校验是否有漏扫的工位了
{
if (dt.Rows.Count != scf.Index - 1)//正常的情况 只有第几把扫描枪 Index-1 刚好等于这个条码记录的条数
{
UpdateText(string.Format("条码设备{0} 扫描的条码{1} 前面有未经过的工站", scf.Ip, BarCode));
if (checkSequenceFlag == true) //校验的话 条码设备更新 status=2 表示异常条码 不需要处理
{
string str1 = string.Format("Update T_BarcodeScan set barcode='{0}',status=4 where IP='{1}'", BarCode, scf.Ip);
return flag;
}
else
{
BarcodeAlarmRecord(scf.Ip, BarCode, "条码有工位未经过");
}
}
}
#endregion
#endregion
string strUpSql= string.Format("Update T_BarcodeScan set barcode='{0}',status=0 where IP='{1}'", BarCode, scf.Ip);
flag = CSqlHelper.ExecuteNonQuery(strUpSql) == 1 ? true : false;
return flag;
}
catch (Exception ex)
{
UpdateText( ex.Message);
return flag;
}
}
/// <summary>
/// 插入条码信息 status=0 表示插入新数据 status=1 表示此数据已经处理过
/// </summary>
/// <param name="strIP"></param>
/// <param name="BarCode"></param>
/// <returns></returns>
private bool InsertBarCode(string strIP, string BarCode)
{
bool flag = false;
string str1 = "Insert into T_BarcodeScan (barcode,status,IP,InputTime)values('{0}','{1}','{2}',getdate())";
string strSql = string.Format(str1, BarCode,0,strIP);
flag = CSqlHelper.ExecuteNonQuery(strSql) == 1 ? true : false;
return flag;
}
/// <summary>
/// 条码信息处理 将条码设备中的数据进行转移到 需要的地方:
/// 1. 设备工位条码
/// 2. 需要发送给其它设备的
/// 3. 写入PLC信息的
/// </summary>
private void BarcodeProcess()
{
//step1: 查询扫描设备表格中T_BarcodeScan中条码是否已经更新 根据status的状态来确定
//status 0 表示数据已经更新为最新条码
//status 1 表示数据未更新,为老数据
//status 2 表示此条码在条码数据库中未存在
//status 3 表示此条码未经过首工位上线
//status 4 表示此条码上线了,但是中间有遗漏工位存在
//由于这些都异常都已经记录过在T_BarcodeScanAlarm中 这里只处理已经更新过为stauts=0的
string strsql = "select * from T_BarcodeScan where status=0 and IsUse>=1";
DataTable dt = CSqlHelper.ExecuteDataset(strsql).Tables[0];
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
InsertProcessBarcode(dr);
}
}
}
/// <summary>
/// 条码从设备中提取出,存放到相应位置
/// </summary>
/// <param name="dr"></param>
private void InsertProcessBarcode(DataRow dr)
{
SqlConnection conn = CSqlHelper.GetConnection();
SqlTransaction trans = conn.BeginTransaction();
try
{
string stationInfoID=dr["stationInfoID"].ToString();
string scanIp = dr["IP"].ToString();
string barcode = dr["barcode"].ToString();
string actHostAddress = dr["ActHostAddress"].ToString();
string portNumber = dr["PortNumber"].ToString();
string AddressList = dr["AddressList"].ToString();
//step1: 插入 T_Stationbarcode
string strInsertStationBarcode = string.Format("Insert into T_StationBarcode(stationInfoID,barcode,suneastFlag,InputTime) values('{0}','{1}',0,getdatetime())", stationInfoID, barcode);
if (CSqlHelper.ExecuteNonQuery(trans, CommandType.Text, strInsertStationBarcode) > 0)
{
//step2:写入PLC的数据,转移表格T_WriteBarcode
string strInsertWrite = string.Format("Insert into T_WriteBarcode(IP,ActHostAddress,Barcode,PortNumber,AddressList,WriteFlag,WriteCount,InputTime) values('{0}','{1}','{2}','{3}','{4}',0,0,getdate())", scanIp, actHostAddress, barcode, portNumber, AddressList);
if (CSqlHelper.ExecuteNonQuery(strInsertWrite) > 0)
{
//step3: 检测需要发送给其它TCP/IP交互设备的
foreach (BarcodeEquipmentInfo bf in BarcodeEquipInfo)
{
if (bf.ScanIP == scanIp)
{
string ip = bf.strIp;
string strInsertSendBarcode = string.Format("Insert into T_SendBarcode (IP,barcode,SendFlag,SendCount,InputTime) vaules ('{0}','{1}',0,0,getdata())", ip, barcode);
if (CSqlHelper.ExecuteNonQuery(strInsertSendBarcode) < 0)//插入失败
{
trans.Rollback();
return;
}
break;
}
}
trans.Commit();
}
else
{
trans.Rollback();
}
}
else
{
trans.Rollback();
}
}
catch (Exception ex)
{
trans.Rollback();
LogExecute.WriteExceptionLog("InsertBarcode", ex);
}
}
/// <summary>
/// 引导符号 一般用于通信的识别的开头
/// </summary>
public const char STX = '\x02';
/// <summary>
/// 结束符号 一般用于通信的识别的结束
/// </summary>
public const char ETX = '\x03';
/// <summary>
/// 接收正常
/// </summary>
public const char ACK = '\x06';
/// <summary>
/// 接收异常
/// </summary>
public const char NAK = '\xf';
/// <summary>
/// 发送数据给Domino
/// </summary>
/// <returns></returns>
private bool SendBarCode()
{
bool flag=false;
try
{
// 第一步: 找到此待发送数据里时间最靠近的那个(即最晚记录的那个)
foreach (BarcodeEquipmentInfo bfci in BarcodeEquipInfo)
{
string strSend = "";
if (checkSendWay == false)
{
strSend = string.Format("select top(1) * from T_SendBarcode where IP='{0}'and SendFlag=0 order by InputTime asc", bfci.strIp);
}
else
{
strSend = string.Format("select top(1) * from T_SendBarcode where IP='{0}' and SendFlag=0 order by InputTime desc", bfci.strIp);
}
DataTable dt = CSqlHelper.ExecuteDataset(strSend).Tables[0];
#region 发送数据
if (dt.Rows.Count >= 1)
{
string SendBarcode = dt.Rows[0]["BarCode"].ToString();
string SendCount = (int.Parse(dt.Rows[0]["SendCount"].ToString().Trim()) + 1).ToString();
string SendTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string SendFormat = STX.ToString() + "," + SendTime + "," + "B" + "," + SendBarcode + "," + SendCount + "," + ETX.ToString();
//第二步: 发现SendCount小于3的再次发送
if (int.Parse(SendCount) <= 3000)
{
byte[] sendbyte = Encoding.ASCII.GetBytes(SendFormat);
string str23=ClientSocket[150 - bfci.Num].RemoteEndPoint.ToString().Split(':')[0];
if (str23 == bfci.strIp)
{
if (ClientSocket[150 - bfci.Num].Send(sendbyte) > 0)
{
int Count = (int.Parse(SendCount) + 1);
string str1 = "Update T_SendBarCode set SendCount='{0}' ,SendTime=getdate() where BarCode='{1}' and IP='{2}'";
string strSql = string.Format(str1, Count, SendBarcode);
flag = CSqlHelper.ExecuteNonQuery(strSql)==1?true:false;
}
else
{
UpdateText(string.Format("IP终端不对 ClientSocket:{0} and strIP{1}",str23,bfci.strIp));
}
}
else
{
LogExecute.WriteLineDataLog(string.Format("IP终端不对 ClientSocket:{0} and strIP{1}",str23,bfci.strIp));
}
}
}
#endregion
}
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("SendBarcode", ex);
}
return flag;
}
/// <summary>
/// 根据写入的数据
/// </summary>
/// <returns></returns>
private bool WriteBarcodePLC()
{
bool flag = false;
try
{
foreach (ScanConfigInfo sf in ScanInfo)
{
string strWrite = "";
if (checkWritePLC == false)
{
strWrite= string.Format("select top(1) * from T_WriteBarcode where IP='{0}'and WriteFlag=0 order by InputTime asc", sf.Ip);
}
else
{
strWrite = string.Format("select top(1) * from T_WriteBarcode where IP='{0}'and WriteFlag=0 order by InputTime desc", sf.Ip);
}
DataTable dt = CSqlHelper.ExecuteDataset(strWrite).Tables[0];
if (dt.Rows.Count >= 1)
{
string ActHostAddress = dt.Rows[0]["ActHostAddress"].ToString();
string PortNumber = dt.Rows[0]["PortNumber"].ToString();
string AddressList = dt.Rows[0]["AddressList"].ToString();
string barcode = dt.Rows[0]["barcode"].ToString();
string writeCount = dt.Rows[0]["WriteCount"].ToString();
//获取写入的值
int[] writeData = GetProductType(barcode);
#region QNUDECPU模块
if (PortNumber == "" || PortNumber == "5002")//表示使用的QNUDECPU模块
{
AxACTETHERLib.AxActQNUDECPUTCP plc = new AxACTETHERLib.AxActQNUDECPUTCP();
plc.ActHostAddress = ActHostAddress;
int result = plc.Open();
if (result == 0 || string.Format("{0:X8}", result) == "F0000003")
{
int size = AddressList.Split('\n').Length;
string strWriteValues="";
foreach(int data in writeData)
{
strWriteValues+=data.ToString()+",";
}
strWriteValues=strWriteValues.TrimEnd(',');
int t=plc.WriteDeviceRandom(AddressList, size, ref writeData[0]);
if (t == 0)//表示写入成功
{
int count = int.Parse(writeCount) + 1;
string strUpdate = string.Format("Update T_WriteBarcode set WriteFlag=1,WriteValues='{0}',WriteCount='{1}',WriteTime=getdate() where IP='{2}' and barcode='{3}'", strWriteValues, count, sf.Ip, barcode);
}
else
{
UpdateText(string.Format("PLC写入IP:{0],Address:{1},Scan:{2},Barcode:{3},WriteValues:{4}",ActHostAddress,AddressList,sf.Ip,barcode,strWriteValues));
}
plc.Close();
}
}
#endregion
#region QJ71E71TCP模块
else
{
AxACTETHERLib.AxActQJ71E71TCP plc = new AxACTETHERLib.AxActQJ71E71TCP();
plc.ActHostAddress = ActHostAddress;
plc.ActDestinationPortNumber=int.Parse(PortNumber);
int result = plc.Open();
if (result == 0 || string.Format("{0:X8}", result) == "F0000003")
{
int size = AddressList.Split('\n').Length;
string strWriteValues = "";
foreach (int data in writeData)
{
strWriteValues += data.ToString() + ",";
}
strWriteValues = strWriteValues.TrimEnd(',');
int t = plc.WriteDeviceRandom(AddressList, size, ref writeData[0]);
if (t == 0)//表示写入成功
{
int count = int.Parse(writeCount) + 1;
string strUpdate = string.Format("Update T_WriteBarcode set WriteFlag=1,WriteValues='{0}',WriteCount='{1}',WriteTime=getdate() where IP='{2}' and barcode='{3}'", strWriteValues, count, sf.Ip, barcode);
}
else
{
UpdateText(string.Format("PLC写入IP:{0],Address:{1},Scan:{2},Barcode:{3},WriteValues:{4}", ActHostAddress, AddressList, sf.Ip, barcode, strWriteValues));
}
plc.Close();
}
}
#endregion
}
}
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("WriteBarcodePLC", ex);
}
return flag;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
toolStripButton3_Click(null, null);
Application.Exit();
}
/// <summary>
/// 开启服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripButton2_Click(object sender, EventArgs e)
{
if (SocketListen() == true)
{
checkFirstFlag = checkBox1.Checked;
checkSequenceFlag = checkBox2.Checked;
checkBarcodeSource = checkBox3.Checked;
checkSendWay= radioButton2.Checked;
checkWritePLC = radioButton4.Checked;
}
else
{
timerScan.Enabled = false;
toolStripButton2.Enabled = true ;
toolStripButton3.Enabled = true;
}
}
/// <summary>
/// 关闭服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripButton3_Click(object sender, EventArgs e)
{
try
{
if (ServerThread.IsAlive)
{
toolStripComboBoxIP.Enabled = true;
ServerThread.Abort();
ServerSocket.Close();
//MasterPLC2.Close();
}
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("ServerThread", ex);
}
finally
{
toolStripButton2.Enabled = true;
timerScan.Enabled = false;
listBox1.Items.Clear();
toolStripSplitButton1.Visible = false;
toolStripSplitButton2.Visible = false;
}
}
/// <summary>
/// 退出系统
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripButton1_Click(object sender, EventArgs e)
{
toolStripButton3_Click(null, null);
this.Close();
}
private void toolStripComboBoxIP_SelectedIndexChanged(object sender, EventArgs e)
{
if (toolStripComboBoxIP.SelectedIndex >= 0)
{
toolStripComboBoxIP.Text = toolStripComboBoxIP.Items[toolStripComboBoxIP.SelectedIndex].ToString();
}
}
private void toolStripButton4_Click(object sender, EventArgs e)
{
Form2 item = new Form2();
item.ShowDialog();
}
private delegate void DeleUpdateText(string text);
private void UpdateText(string text)
{
if (this.InvokeRequired)
{
this.Invoke(new DeleUpdateText(UpdateText), new object[] { text });
}
else
{
ucErrorDisplay1.ErrText = text;
}
}
/// <summary>
/// 记录异常条码 由于没有及时处理操作的异常
/// </summary>
/// <param name="IP"></param>
/// <param name="barcode"></param>
/// <param name="reason"></param>
private void BarcodeAlarmRecord(string IP,string status)
{
//string str = string.Format("Insert into T_BarcodeScanAlarm(IP,barcode,reason,InputTime) values ('{0}','{1}','{2}',getdate())", IP, barcode, reason);
try
{
string reason="";
if (status == "0") { reason = "条码未被处理"; }
else if (status == "2") { reason = "条码库中未出现该条码"; }
else if (status == "3") { reason = "条码首工位未上线"; }
else if (status == "4") { reason = "条码有工位未经过"; }
else { reason = "未定义错误"; }
string sql = string.Format("select barcode from T_BarcodeScan where IP='{0}'", IP);
string barcode = (string)CSqlHelper.ExecuteScalar(CSqlHelper.ConnectString, CommandType.Text, sql);
string str = string.Format("Insert into T_BarcodeScanAlarm(IP,barcode,reason,InputTime) values ('{0}','{1}','{2}',getdate())", IP, barcode, reason);
CSqlHelper.ExecuteNonQuery(str);
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("BarcodeAlarmRecord", ex);
}
}
/// <summary>
/// 记录异常条码 已经发现的异常
/// </summary>
/// <param name="IP"></param>
/// <param name="barcode"></param>
/// <param name="reason"></param>
private void BarcodeAlarmRecord(string IP, string barcode,string reason)
{
//string str = string.Format("Insert into T_BarcodeScanAlarm(IP,barcode,reason,InputTime) values ('{0}','{1}','{2}',getdate())", IP, barcode, reason);
try
{
string str = string.Format("Insert into T_BarcodeScanAlarm(IP,barcode,reason,InputTime) values ('{0}','{1}','{2}','{3}',getdate())", IP, barcode, reason);
CSqlHelper.ExecuteNonQuery(str);
}
catch (Exception ex)
{
LogExecute.WriteExceptionLog("BarcodeAlarmRecord", ex);
}
}
}
}