SendDataTo.cs
51.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
using HHECS.BLL.Services;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Linq;
using HHECS.Model.Enums.Machine;
using HHECS.BllModel;
using HHECS.Infrastructure.Notice;
using HHECS.Infrastructure.Enums;
using NPOI.SS.Formula.Functions;
using System.Threading.Tasks;
using System.Collections;
using Polly;
using HHECS.Model.Entities;
using HHECS.Dal.Repository;
using static FreeSql.Internal.GlobalFilter;
using System.Configuration;
namespace HHECS.BLL.EquipmentExcute.Marking
{
public class SendDataTo
{
public static Dictionary<string, Socket> DicSocket = new Dictionary<string, Socket>();
public static Dictionary<string, List<string>> dicTemplate = new Dictionary<string, List<string>>();
//是否喷二维码
public static int IsQRCodetValue;
/// <summary>
/// 交互协议的编码格式
/// </summary>
private static Encoding encodingDefault = Encoding.ASCII;
/// <summary>
/// 打标机服务端是否开启
/// </summary>
public static bool isStart;
/// <summary>
/// 是否为打标状态
/// </summary>
public static bool isMarkState;
/// <summary>
/// 打标机工作状态
/// </summary>
public static MarkingFlag markingFlag = MarkingFlag.初始;
/// <summary>
/// 连接状态
/// </summary>
public static ConnectFlag connectStatus = ConnectFlag.初始;
/// <summary>
/// 连接命令
/// </summary>
public static ConnectFlag connectComd = ConnectFlag.初始;
/// <summary>
/// 是否再等待打标机的应答,因为打标机的指令只能应答后,在发一条
/// </summary>
public static bool waitACK = true;
/// <summary>
/// 打标模板地址
/// </summary>
public static string fileUrl;
/// <summary>
/// 打标机反馈内容
/// </summary>
public static string printRecive;
/// <summary>
/// 客户端ip
/// </summary>
private static string RemoteEndPointIP = string.Empty;
//创建Socket
public static Socket? tcpClient;
public static TcpClient? tcpClient1;
//创建取消数据源
private static CancellationTokenSource cts = new CancellationTokenSource();
#region 创建TCP服务端
/// <summary>
/// 开启服务端,等待打码机连接
/// </summary>
/// <param name="markingPort">端口号</param>
/// <returns></returns>
public static bool Start(int markingPort)
{
try
{
if (isStart)
{
return true;
}
//当点击开始监听的时候,在服务器端创建一个负责监听IP地址跟端口号的Socket
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
//IPAddress ip = IPAddress.Parse("169.254.135.234");
//创建端口号对象
IPEndPoint point = new IPEndPoint(ip, markingPort);
socketWatch.Bind(point);
//ShowMsg("监听成功");
socketWatch.Listen(10);
Thread th = new Thread(Listen);
th.IsBackground = true;
//把负责监听的socketWatch传进去
th.Start(socketWatch);
return true;
}
catch (Exception ex)
{
NoticeBus.Notice($"创建Socket服务出现异常,原因:{ex.Message}", Level.Exception, ex);
return false;
}
}
/// <summary>
/// 监听打码机的连接
/// </summary>
/// <param name="o"></param>
public static void Listen(object o)
{
try
{
Socket socketWatch = o as Socket;
while (true)
{
//等待客户端的连接,并创建一个负责通讯的socket
//由负责监听的socket通过调用accept方法(accept方法指一直等待客户端的响应,没有回应就一直等待),去创建一个负责通讯的socket
var socketSend = socketWatch.Accept();
var dicKey = socketSend.RemoteEndPoint.ToString();
if (DicSocket.ContainsKey(dicKey))
{
DicSocket.Remove(dicKey); //将远程的客户端的ip地址和socket存入集合
}
//将远程的客户端的ip地址和socket存入集合
DicSocket.Add(RemoteEndPointIP = socketSend.RemoteEndPoint.ToString(), socketSend);
//ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");//172.16.35.127:连接成功
SendDataTo.markingFlag = MarkingFlag.空闲;
SendDataTo.waitACK = false;
//开启一个新线程去接收客户端发来的消息
Thread th = new Thread(Recive);
th.IsBackground = true;
th.Start(socketSend);
}
}
catch (Exception ex)
{
NoticeBus.Notice($"接收客户端信息出现异常,异常原因{ex.Message}", Level.Exception);
}
}
private static void GetValue()
{
while (!cts.IsCancellationRequested)
{
byte[] buffer = new byte[1024 * 10];
int length = -1;
try
{
length = tcpClient.Receive(buffer, SocketFlags.None);
}
catch (Exception ex)
{
break;
}
if (length > 0)
{
byte[] result = new byte[length];
Buffer.BlockCopy(buffer, 0, result, 0, length);
string str = System.Text.Encoding.UTF8.GetString(result);
if (str.Contains("MarkCount"))
{
SendDataTo.markingFlag = MarkingFlag.打标完成;
SendDataTo.waitACK = false;
}
if (str.Contains("Ok;;"))
{
//SendDataTo.waitACK = false;
}
if (str == "2;;")
{
SendDataToMarking.isMarkState = true;
}
if (str == "0;;" || str == "1;;" || str == "3;;" || str == "4;;" || str == "5;;" || str == "6;;" || str == "7;;")
{
SendDataToMarking.isMarkState = false;
}
//if (str == "2;;")
//{
// SendDataToMarking.isMarkState = true;
//}
//if (str == "0;;" || str == "1;;" || str == "3;;" || str == "4;;" || str == "5;;" || str == "6;;" || str == "7;;")
//{
// SendDataToMarking.isMarkState = false;
//}
//输出日志会导致线程死锁,主线程一直在while循环,当前线程一致写入不进去,就导致死锁
//NoticeBus.Notice($"打标机反馈内容:{str}", Level.Info);
}
}
}
/// <summary>
/// 接受打码机返回的数据
/// </summary>
/// <param name="o"></param>
public static void Recive(object o)
{
try
{
Socket socketSend = o as Socket;
while (true)
{
//客户端接收消息
byte[] buffer = new byte[1024 * 1024 * 2];
int r = socketSend.Receive(buffer);
if (r == 0)
{
break;
}
printRecive = encodingDefault.GetString(buffer, 0, r);
//if (printRecive.ToLower().Contains("failed"))
//{
// markingFlag = MarkingFlag.空闲;
//}
if (printRecive.ToLower().Contains("StartCleanMark"))
{
SendDataTo.waitACK = false;
}
else if (printRecive.ToLower().Contains("StopMark"))
{
SendDataTo.waitACK = false;
}
SendDataTo.waitACK = false;
NoticeBus.Notice($"打标机反馈内容:{printRecive}", Level.Info);
}
}
catch (Exception ex)
{
NoticeBus.Notice($"接收客户端消息出现异常,异常原因{ex.Message}", Level.Exception);
}
}
/// <summary>
/// 测试用的,已废弃
/// </summary>
/// <param name="barcode"></param>
/// <param name="pipeDiameter"></param>
/// <returns></returns>
public static BllResult SendData(string barcode, decimal? pipeDiameter)
{
try
{
#region 数据效验
if (string.IsNullOrWhiteSpace(barcode))
{
return BllResultFactory.Error("打标数据为空");
}
//if (string.IsNullOrWhiteSpace(RemoteEndPointIP))
//{
// return BllResultFactory.Error("打标机设备未连接ECS服务。");
//}
var checkResult = CheckStatus(RemoteEndPointIP);
if (!checkResult.Success)
{
return checkResult;
}
#endregion
byte[] openFileByte = null;
switch (pipeDiameter)
{
case 28:
openFileByte = encodingDefault.GetBytes("open D:\\打标文件\\28.Tx7");
break;
case 34:
openFileByte = encodingDefault.GetBytes("open D:\\打标文件\\34.Tx7");
break;
case 42:
openFileByte = encodingDefault.GetBytes("open D:\\打标文件\\42.Tx7");
break;
default:
return BllResultFactory.Error($"未找到对应的打标文件!检查当前管径{pipeDiameter}");
}
#region 数据发送
Thread.Sleep(10);
DicSocket[RemoteEndPointIP].Send(openFileByte);
Thread.Sleep(10);
DicSocket[RemoteEndPointIP].Send(encodingDefault.GetBytes("setall content=" + barcode));
Thread.Sleep(10);
DicSocket[RemoteEndPointIP].Send(encodingDefault.GetBytes("start"));
return BllResultFactory.Success();
//string content = "setall content=项目,123,材质,123,预制管线生产线编号:,123,尺寸,123,单管号,123,壁厚,123,管段编号,123,炉批号,123,123";
//dicSocket【ipForStart】.Send(asciiEncoding.GetBytes(content));
#endregion
}
catch (Exception ex)
{
return BllResultFactory.Error($"发送打标指令出现异常,异常原因{ex.Message}");
}
}
/// <summary>
/// 找出每一个线体对应的打标机设备IP
/// </summary>
/// <param name="lineCode"></param>
/// <returns></returns>
private static string LineCodeGetToIp(string lineCode)
{
BllService bllService = new BllService();
var dict = bllService.GetDictWithDetails(a => a.Code == "Marking").Data;
if (lineCode == null) return dict.DictDetails.FirstOrDefault()?.Value;
return dict.DictDetails.Find(x => x.Code == lineCode)?.Value;
}
private static BllResult CheckStatus(string ip)
{
if (DicSocket[ip].Connected)
{
if (DicSocket[ip].Poll(10, SelectMode.SelectRead))
{
DicSocket.Remove(ip);
return BllResultFactory.Error($"打标机设备断开连接,导致无法进行激光打码,{ip}地址,请检查打标机网络情况!");
}
else
{
return BllResultFactory.Success();
}
}
else
{
return BllResultFactory.Error($"打标机设备断开连接,导致无法进行激光打码,{ip}地址,请检查打标机网络情况!");
}
}
/// <summary>
/// 判断激光打码是否连接成功
/// </summary>
/// <returns></returns>
private static BllResult CheckStatus(string lineCode, string ip)
{
if (DicSocket[ip].Connected)
{
//if (DicSocket[ip].Poll(100, SelectMode.SelectRead))
//{
// DicSocket.Remove(ip);
// NoticeBus.Notice($"{ip}:当前线体{lineCode},打标机设备断开连接,导致无法进行激光打码,{ip}地址,请检查打标机网络情况!", NoticeLevel.Warning);
// return BllResultFactory.Error();
//}
//else
//{
return BllResultFactory.Success();
//}
}
else
{
DicSocket.Remove(ip);
NoticeBus.Notice($"{ip}:当前线体{lineCode},打标机设备断开连接,导致无法进行激光打码,{ip}地址,请检查打标机网络情况!", Level.Warning);
return BllResultFactory.Error();
}
}
/// <summary>
/// 检测设备连接之后是否一直在线
/// </summary>
public static bool CheckOnLine(string lineCode, string ip)
{
string dicip = DicSocket.Keys.Where(x => x.Contains(ip)).FirstOrDefault();
if (string.IsNullOrWhiteSpace(dicip))
{
NoticeBus.Notice($"当前线体{lineCode},打标机设备断开连接,导致无法进行激光打码,{ip}地址,请检查打标机网络情况!", Level.Warning);
return false;
}
return CheckStatus(lineCode, dicip).Success;
}
public static bool CheckTCPOnLine(string lineCode, string ip)
{
if (!tcpClient.Connected)
{
NoticeBus.Notice($"当前线体{lineCode},打标机设备断开连接,导致无法进行激光打码,{ip}地址,请检查打标机网络情况!", Level.Warning);
return false;
}
return true;
}
#endregion
#region 创建TCP客户端
/// <summary>
/// 开启客户端
/// </summary>
/// <param name="markingPort">端口号</param>
/// <returns></returns>
public static bool StartClient(string lineCode, string ip, int markingPort)
{
try
{
DictTemplate(lineCode);
if (isStart)
{
return true;
}
tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint ep = new IPEndPoint(IPAddress.Parse(ip), markingPort);
try
{
tcpClient.Connect(ep);
if (tcpClient.Connected)
{
SendDataTo.markingFlag = MarkingFlag.空闲;
//SendDataTo.waitACK = false;
}
}
catch (Exception ex)
{
return false;
}
Task.Run(new Action(() =>
{
GetValue();
}));
return true;
}
catch (Exception ex)
{
NoticeBus.Notice($"创建Socket服务出现异常,原因:{ex.Message}", Level.Error);
return false;
}
}
//读数据
public static void GetValue(object o)
{
try
{
Socket socketSend = o as Socket;
while (true)
{
//客户端接收消息
byte[] buffer = new byte[1024 * 1024 * 2];
int r = socketSend.Receive(buffer);
if (r == 0)
{
break;
}
printRecive = encodingDefault.GetString(buffer, 0, r);
//if (printRecive.ToLower().Contains("failed"))
//{
// markingFlag = MarkingFlag.空闲;
//}
if (printRecive.ToLower().Contains("StartCleanMark"))
{
SendDataTo.waitACK = false;
}
else if (printRecive.ToLower().Contains("StopMark"))
{
SendDataTo.waitACK = false;
}
SendDataTo.waitACK = false;
NoticeBus.Notice($"打标机反馈内容:{printRecive}", Level.Info);
}
}
catch (Exception ex)
{
NoticeBus.Notice($"接收客户端消息出现异常,异常原因{ex.Message}", Level.Exception);
}
}
//public static void SetValue()
//{
// byte[] buffer = System.Text.Encoding.Default.GetBytes("1111");
// //if (tcpClient)
// //{
// //}
// if (tcpClient.Connected)
// {
// try
// {
// tcpClient.Send(buffer);
// }
// catch (Exception ex)
// {
// return;
// }
// }
//}
//写数据
public static BllResult SetValue(string str)
{
byte[] buffer = System.Text.Encoding.Default.GetBytes(str);
if (!tcpClient.Connected)
{
tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint ep = new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings["TCPServiceIp1"]), Convert.ToInt32(ConfigurationManager.AppSettings["TCPWeldPort1"]));
try
{
tcpClient.Connect(ep);
if (tcpClient.Connected)
{
SendDataTo.markingFlag = MarkingFlag.空闲;
//SendDataToMarking.waitACK = false;
}
}
catch (Exception ex)
{
return BllResultFactory.Error<Object>($"下发打标数据失败后重新开启连接失败");
}
//StartClient(ConfigurationManager.AppSettings["LineCode"], ConfigurationManager.AppSettings["TCPServiceIp"], Convert.ToInt32(ConfigurationManager.AppSettings["TCPServicePort"]));
}
try
{
tcpClient.Send(buffer);
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error<Object>($"向打标机发送数据失败");
}
}
/// <summary>
/// 发送要打印的条码
/// </summary>
/// <param name="barcode"></param>
/// <param name="pipeDiameter"></param>
/// <param name="lineCode"></param>
/// <returns></returns>
public static BllResult SendData(string barcode)
{
try
{
#region 数据发送,尽量减少等待时间,避免外面的数据库事务一直挂起
SendDataTo.markingFlag = MarkingFlag.打标中;
//检查打标状态1
//SendDataTo.isMarkState = false;
//SetValue("GetMarkStatus;;");
////Thread.Sleep(5000);
//if (!SendDataTo.isMarkState)
//{
// SetValue("StartMark;;");
// return BllResultFactory.Error("不是打标状态,正在重启打标状态");
//}
//if (!SendDataTo.isMarkState)
//{
// SendDataTo.SetValue("StartMark;;");
//}
SendDataTo.waitACK = true;
//打标状态下切换指定模板
// SetValue("SwitchDoc,QINGXI.bpd;;");
//手动触发(模拟光电触发)
var result = SendDataTo.SetValue("SetShapeData,DM," + barcode + ";;");
if (!result.Success)
{
return BllResultFactory.Error(result.Msg);
}
Thread.Sleep(500);//间隔五秒
result = SendDataTo.SetValue("StartMark;;");
if (!result.Success)
{
return BllResultFactory.Error(result.Msg);
}
Thread.Sleep(500);//间隔
result = SendDataTo.SetValue("ManualTrgger;;");
if (!result.Success)
{
return BllResultFactory.Error(result.Msg);
}
//while (SendDataTo.waitACK) Thread.Sleep(1000);
//SetValue();
return BllResultFactory.Success();
#endregion
}
catch (Exception ex)
{
return BllResultFactory.Error($"发送打标指令出现异常,异常原因{ex.Message}");
}
}
//public static BllResult SendData(string stop)
//{
// try
// {
// #region 数据发送,尽量减少等待时间,避免外面的数据库事务一直挂起
// SendDataTo.markingFlag = MarkingFlag.空闲;
// //检查打标状态
// //SendDataTo.isMarkState = false;
// //SetValue("GetMarkStatus;;");
// ////Thread.Sleep(5000);
// //if (!SendDataTo.isMarkState)
// //{
// // SetValue("StartMark;;");
// // return BllResultFactory.Error("不是打标状态,正在重启打标状态");
// //}
// //if (!SendDataTo.isMarkState)
// //{
// // SendDataTo.SetValue("StartMark;;");
// //}
// //SendDataTo.waitACK = true;
// ////打标状态下切换指定模板
// ////SetValue("SwitchDoc,QINGXI.bpd;;");
// //SendDataTo.waitACK = true;
// ////手动触发(模拟光电触发)
// SendDataTo.waitACK = true;
// SetValue("StopMark;;");
// while (SendDataTo.waitACK) Thread.Sleep(1000);
// //SetValue();
// return BllResultFactory.Success();
// #endregion
// }
// catch (Exception ex)
// {
// return BllResultFactory.Error($"发送打标指令出现异常,异常原因{ex.Message}");
// }
//}
/// <summary>
/// 发送要打印的条码
/// </summary>
/// <param name="barcode"></param>
/// <param name="pipeDiameter"></param>
/// <param name="lineCode"></param>
/// <returns></returns>
public static BllResult SendData(string barcode, decimal? pipeDiameter, string lineCode)
{
try
{
#region 数据效验
if (SendDataTo.markingFlag == MarkingFlag.打标中)
{
return BllResultFactory.Create(BllResultCode.Warning, "打标机正在打印中,请稍后再试!");
}
if (string.IsNullOrWhiteSpace(barcode))
{
return BllResultFactory.Error("打标数据为空");
}
//取出对应的线体ip地址
//string dicIp = LineCodeGetToIp(lineCode);
//if (string.IsNullOrWhiteSpace(dicIp))
//{
// return BllResultFactory.Error($"当前线体{lineCode},字典未配置对应的IP");
//}
#endregion
////找到对应打标模板文件
//BllService bllService = new BllService();
//var dict = bllService.GetDictWithDetails(a => a.Code == "PrintFile").Data;
////根据管径找到字典存放的打码模板地址 ;
//fileUrl = dict.DictDetails.Find(x => x.Code == lineCode && x.Expend1 == pipeDiameter.ToString())?.Value;
////如果没有当前管径专用的打码模板地址,就采用通用模板
//if (string.IsNullOrEmpty(fileUrl))
//{
// fileUrl = dict.DictDetails.Find(x => x.Code == lineCode && x.Expend1 == "normal")?.Value;
//}
//if (string.IsNullOrEmpty(fileUrl))
//{
// return BllResultFactory.Error($"当前线体【{lineCode}】在字典中没有配置当前管径【{pipeDiameter}】的专用模板,也没有通用模板,无法打码!");
//}
#region 数据发送,尽量减少等待时间,避免外面的数据库事务一直挂起
//SendDataTo.markingFlag = MarkingFlag.打标中;
//开启打标状态
//SetValue("StartMark;;\n");
//while (SendDataTo.waitACK) Thread.Sleep(1);
//SendDataTo.waitACK = true;
//模版
var templates = "0005";
//管径和长度 ,小管径短管 2行小字
//小管径短管 2行小字
//大管径短管 3行小字
//大管径长管 1行大字
//短管 减少字符
// 定义控制字符
char stx = (char)2; // STX (Start of Text)
char lf = (char)16; // LF (Line Feed)
char us = (char)49; // US (Unit Separator)
char etx = (char)3; // ETX (End of Text)
char f1 = (char)31;
char a = (char)50;
char space = (char)32;
var print = $"{stx}{lf}{us}{barcode}{lf}{a}{space}{barcode}{etx}";
string switchTemplates = $"{stx}{f1}{space}{us}{templates}{etx}";
var f = (char)5;
//检查连接
SendDataTo.connectComd = ConnectFlag.检查连接;
SendDataTo.SetValue($"{f}");
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(1000);
//打标状态下切换指定模板
SetValue(switchTemplates);
SendDataTo.markingFlag = MarkingFlag.切换模版;
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(1000);
//发送内容
SetValue(print);
SendDataTo.markingFlag = MarkingFlag.发送完成;
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(1000);
////打标状态下切换指定模板
//SetValue("SwitchDoc,DMMA.bpd;;");
//SendDataTo.waitACK = true;
////设置指定图元文本内容、位置、角度
//while (SendDataTo.waitACK) Thread.Sleep(1000);
//SetValue("SetShapeData,DM," + barcode + ";;");
//SendDataTo.waitACK = true;
////手动触发(模拟光电触发)
//while (SendDataTo.waitACK) Thread.Sleep(1000);
//SetValue("ManualTrgger;;");
return BllResultFactory.Success();
#endregion
}
catch (Exception ex)
{
return BllResultFactory.Error($"发送打标指令出现异常,异常原因{ex.Message}");
}
}
public static BllResult SendData(string TemplateInput, string QRCodeContent, string PlainText1, string PlainText2, string PlainText3)
{
try
{
//模版
//var templates = "0001";
//管径和长度 ,小管径短管 2行小字
//小管径短管 2行小字
//大管径短管 3行小字
//大管径长管 1行大字
//短管 减少字符
// 定义控制字符
char stx = (char)2; // STX (Start of Text)
char lf = (char)16; // LF (Line Feed)
char us = (char)49; // US (Unit Separator)
char etx = (char)3; // ETX (End of Text)
char f1 = (char)31;
char a = (char)50;
char b = (char)51;
char c = (char)52;
char space = (char)32;
var print = $"";
if (!string.IsNullOrEmpty(QRCodeContent))
{
print = $"{stx}{lf}{us}{QRCodeContent}{lf}{a}{space}{PlainText1}";
if (!string.IsNullOrEmpty(PlainText2))
{
print += $"{lf}{b}{space}{PlainText2}";
}
if (!string.IsNullOrEmpty(PlainText3))
{
print += $"{lf}{c}{space}{PlainText3}";
}
}
else
{
print = $"{stx}{lf}{us}{PlainText1}";
if (!string.IsNullOrEmpty(PlainText2))
{
print += $"{lf}{a}{space}{PlainText2}";
}
if (!string.IsNullOrEmpty(PlainText3))
{
print += $"{lf}{b}{space}{PlainText3}";
}
}
print += etx;
string switchTemplates = $"{stx}{f1}{space}{us}{TemplateInput}{etx}";
var f = (char)5;
//检查连接
SendDataTo.connectComd = ConnectFlag.检查连接;
SendDataTo.SetValue($"{f}");
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
//打标状态下切换指定模板
SetValue(switchTemplates);
SendDataTo.markingFlag = MarkingFlag.切换模版;
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
//发送内容
SetValue(print);
SendDataTo.markingFlag = MarkingFlag.发送完成;
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
return BllResultFactory.Success();
#endregion
}
catch (Exception ex)
{
return BllResultFactory.Error($"发送打标指令出现异常,异常原因{ex.Message}");
}
}
/// <summary>
/// 发送要打印的条码
/// </summary>
/// <param name="barcode"></param>
/// <param name="pipeDiameter"></param>
/// <param name="lineCode"></param>
/// <returns></returns>
public static BllResult SendData(string barcode, string tBarcode, int length, bool isSurplus = false)
{
try
{
#region 数据效验
if (SendDataTo.markingFlag == MarkingFlag.打标中)
{
return BllResultFactory.Create(BllResultCode.Warning, "打标机正在打印中,请稍后再试!");
}
if (string.IsNullOrWhiteSpace(barcode))
{
return BllResultFactory.Error("打标数据为空");
}
//取出对应的线体ip地址
//string dicIp = LineCodeGetToIp(lineCode);
//if (string.IsNullOrWhiteSpace(dicIp))
//{
// return BllResultFactory.Error($"当前线体{lineCode},字典未配置对应的IP");
//}
#endregion
////找到对应打标模板文件
//BllService bllService = new BllService();
//var dict = bllService.GetDictWithDetails(a => a.Code == "PrintFile").Data;
////根据管径找到字典存放的打码模板地址 ;
//fileUrl = dict.DictDetails.Find(x => x.Code == lineCode && x.Expend1 == pipeDiameter.ToString())?.Value;
////如果没有当前管径专用的打码模板地址,就采用通用模板
//if (string.IsNullOrEmpty(fileUrl))
//{
// fileUrl = dict.DictDetails.Find(x => x.Code == lineCode && x.Expend1 == "normal")?.Value;
//}
//if (string.IsNullOrEmpty(fileUrl))
//{
// return BllResultFactory.Error($"当前线体【{lineCode}】在字典中没有配置当前管径【{pipeDiameter}】的专用模板,也没有通用模板,无法打码!");
//}
#region 数据发送,尽量减少等待时间,避免外面的数据库事务一直挂起
//SendDataTo.markingFlag = MarkingFlag.打标中;
//开启打标状态
//SetValue("StartMark;;\n");
//while (SendDataTo.waitACK) Thread.Sleep(1);
//SendDataTo.waitACK = true;
//模版
var templates = "0005";
//管径和长度 ,小管径短管 2行小字
//小管径短管 2行小字
//大管径短管 3行小字
//大管径长管 1行大字
//短管 减少字符
// 定义控制字符
char stx = (char)2; // STX (Start of Text)
char lf = (char)16; // LF (Line Feed)
char us = (char)49; // US (Unit Separator)
char etx = (char)3; // ETX (End of Text)
char f1 = (char)31;
char a = (char)50;
char b = (char)51;
char c = (char)52;
char space = (char)32;
var print = "";
if (length > 230 || isSurplus)
{
templates = "0001";
print = $"{stx}{lf}{us}{tBarcode}{lf}{a}{space}{barcode}{etx}";
}
else if (length > 100 && length <= 230)
{
templates = "0002";
int dashCount = 0;
int splitIndex = -1;
// 遍历字符串,找到第8个 `-`
for (int i = 0; i < barcode.Length; i++)
{
if (barcode[i] == '-')
{
dashCount++;
if (dashCount == 8)
{
splitIndex = i;
break;
}
}
}
string firstPart = barcode.Substring(0, splitIndex);
string secondPart = barcode.Substring(splitIndex + 1); // 分割点之后的部分
print = $"{stx}{lf}{us}{tBarcode}{lf}{a}{space}{firstPart}{lf}{b}{space}{secondPart}{etx}";
}
else if (length <= 100)
{
templates = "0003";
int dashCount = 0; // 计数 `-` 符号
int firstDashIndex = -1; // 第6个 `-` 的索引
int secondDashIndex = -1; // 第9个 `-` 的索引
bool insideParentheses = false; // 判断是否在括号内
// 遍历字符串,找到第6个和第9个非括号内的 `-`
for (int i = 0; i < barcode.Length; i++)
{
if (barcode[i] == '(') // 如果遇到左括号,进入括号内
insideParentheses = true;
if (barcode[i] == ')') // 如果遇到右括号,离开括号
insideParentheses = false;
// 如果不是在括号内且当前字符是 `-`
if (!insideParentheses && barcode[i] == '-')
{
dashCount++;
if (dashCount == 6)
{
firstDashIndex = i; // 记录第6个 `-` 的位置
}
if (dashCount == 9)
{
secondDashIndex = i; // 记录第9个 `-` 的位置
break; // 找到第9个 `-` 后退出循环
}
}
}
string firstPart = barcode.Substring(0, firstDashIndex); // 第6个 `-` 之前的部分
string secondPart = barcode.Substring(firstDashIndex + 1, secondDashIndex - firstDashIndex - 1); // 第6个和第9个 `-` 之间的部分
string thirdPart = barcode.Substring(secondDashIndex + 1); // 第9个 `-` 之后的部分
print = $"{stx}{lf}{us}{tBarcode}{lf}{a}{space}{firstPart}{lf}{b}{space}{secondPart}{lf}{c}{space}{thirdPart}{etx}";
}
//string switchTemplates = $"{stx}{f1}{space}{us}{TemplateInput}{etx}";
//var print = $"{stx}{lf}{us}{tBarcode}{lf}{a}{space}{barcode}{etx}";
string switchTemplates = $"{stx}{f1}{space}{us}{templates}{etx}";
var f = (char)5;
//检查连接
SendDataTo.connectComd = ConnectFlag.检查连接;
SendDataTo.SetValue($"{f}");
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
//打标状态下切换指定模板
SetValue(switchTemplates);
SendDataTo.markingFlag = MarkingFlag.切换模版;
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
//发送内容
SetValue(print);
SendDataTo.markingFlag = MarkingFlag.发送完成;
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
////打标状态下切换指定模板
//SetValue("SwitchDoc,DMMA.bpd;;");
//SendDataTo.waitACK = true;
////设置指定图元文本内容、位置、角度
//while (SendDataTo.waitACK) Thread.Sleep(1000);
//SetValue("SetShapeData,DM," + barcode + ";;");
//SendDataTo.waitACK = true;
////手动触发(模拟光电触发)
//while (SendDataTo.waitACK) Thread.Sleep(1000);
//SetValue("ManualTrgger;;");
return BllResultFactory.Success();
#endregion
}
catch (Exception ex)
{
return BllResultFactory.Error($"发送打标指令出现异常,异常原因{ex.Message}");
}
}
/// <summary>
/// 发送要打印的条码
/// </summary>
/// <param name="barcode"></param>
/// <param name="pipeDiameter"></param>
/// <param name="lineCode"></param>
/// <returns></returns>
public static BllResult SendData(bool isSurplus, CutPlanTask cutPlanTask)
{
try
{
#region 数据效验
if (SendDataTo.markingFlag == MarkingFlag.打标中)
{
return BllResultFactory.Create(BllResultCode.Warning, "打标机正在打印中,请稍后再试!");
}
if (string.IsNullOrWhiteSpace(cutPlanTask.PrintCode))
{
return BllResultFactory.Error("打标数据为空");
}
#endregion
//模版
var templateAndRow = ("", 0);
foreach (var item in dicTemplate)
{
if (item.Value.Count != 7)
{
return BllResultFactory.Error("模版参数不正确,【是否余料-是否存在二维码-喷码行数-最短长度-最长长度-最小管径-最大管径】");
}
var issurplus = Convert.ToBoolean(Convert.ToInt16(item.Value[0]));
var isTbarcode = Convert.ToInt16(item.Value[1]);//二维码去配置文件
var row = Convert.ToInt16(item.Value[2]);
var minLength = Convert.ToInt32(item.Value[3]);
var maxLength = Convert.ToInt32(item.Value[4]);
var minDiameter = Convert.ToDecimal(item.Value[5]);
var maxDiameter = Convert.ToDecimal(item.Value[6]);
if (issurplus == isSurplus && (isSurplus || isTbarcode == IsQRCodetValue) && cutPlanTask.CuttingLength >= minLength && cutPlanTask.CuttingLength <= maxLength && cutPlanTask.OuterDiameter >= minDiameter && cutPlanTask.OuterDiameter <= maxDiameter)
{
templateAndRow = (item.Key, row);
break;
}
}
if (string.IsNullOrEmpty(templateAndRow.Item1) || templateAndRow.Item2 == 0)
{
return BllResultFactory.Error("模版参数不正确,字典中模版为空");
}
#region 数据发送,尽量减少等待时间,避免外面的数据库事务一直挂起
//管径和长度 ,小管径短管 2行小字
//小管径短管 2行小字
//大管径短管 3行小字
//大管径长管 1行大字
//短管 减少字符
// 定义控制字符
char stx = (char)2; // STX (Start of Text)
char lf = (char)16; // LF (Line Feed)
char us = (char)49; // US (Unit Separator)
char etx = (char)3; // ETX (End of Text)
char f1 = (char)31;
char a = (char)50;
char b = (char)51;
char c = (char)52;
char space = (char)32;
var print = "";
if (isSurplus)
{
var printCode = $"{cutPlanTask.PipeStandards}-{cutPlanTask.PipeType}-{cutPlanTask.OuterDiameter}-{cutPlanTask.Thickness}-{cutPlanTask.ResidualLength}-{cutPlanTask.ExcelCreateTime}";
print = $"{stx}{lf}{us}{printCode}{etx}";
}
else if (templateAndRow.Item2 == 1)
{
print = $"{stx}{lf}{us}{cutPlanTask.QRCodeContent}{lf}{a}{space}{cutPlanTask.PrintCode}{etx}";
}
else if (templateAndRow.Item2 == 2)
{
int dashCount = 0;
int splitIndex = -1;
// 遍历字符串,找到第8个 `-`
for (int i = 0; i < cutPlanTask.PrintCode.Length; i++)
{
if (cutPlanTask.PrintCode[i] == '-')
{
dashCount++;
if (dashCount == 8)
{
splitIndex = i;
break;
}
}
}
string firstPart = cutPlanTask.PrintCode.Substring(0, splitIndex);
string secondPart = cutPlanTask.PrintCode.Substring(splitIndex + 1); // 分割点之后的部分
print = $"{stx}{lf}{us}{cutPlanTask.QRCodeContent}{lf}{a}{space}{firstPart}{lf}{b}{space}{secondPart}{etx}";
}
else if (templateAndRow.Item2 == 3)
{
int dashCount = 0; // 计数 `-` 符号
int firstDashIndex = -1; // 第6个 `-` 的索引
int secondDashIndex = -1; // 第9个 `-` 的索引
bool insideParentheses = false; // 判断是否在括号内
// 遍历字符串,找到第6个和第9个非括号内的 `-`
for (int i = 0; i < cutPlanTask.PrintCode.Length; i++)
{
if (cutPlanTask.PrintCode[i] == '(') // 如果遇到左括号,进入括号内
insideParentheses = true;
if (cutPlanTask.PrintCode[i] == ')') // 如果遇到右括号,离开括号
insideParentheses = false;
// 如果不是在括号内且当前字符是 `-`
if (!insideParentheses && cutPlanTask.PrintCode[i] == '-')
{
dashCount++;
if (dashCount == 6)
{
firstDashIndex = i; // 记录第6个 `-` 的位置
}
if (dashCount == 9)
{
secondDashIndex = i; // 记录第9个 `-` 的位置
break; // 找到第9个 `-` 后退出循环
}
}
}
string firstPart = cutPlanTask.PrintCode.Substring(0, firstDashIndex); // 第6个 `-` 之前的部分
string secondPart = cutPlanTask.PrintCode.Substring(firstDashIndex + 1, secondDashIndex - firstDashIndex - 1); // 第6个和第9个 `-` 之间的部分
string thirdPart = cutPlanTask.PrintCode.Substring(secondDashIndex + 1); // 第9个 `-` 之后的部分
print = $"{stx}{lf}{us}{cutPlanTask.QRCodeContent}{lf}{a}{space}{firstPart}{lf}{b}{space}{secondPart}{lf}{c}{space}{thirdPart}{etx}";
}
string switchTemplates = $"{stx}{f1}{space}{us}{templateAndRow.Item1}{etx}";
var f = (char)5;
//检查连接
SendDataTo.connectComd = ConnectFlag.检查连接;
SendDataTo.SetValue($"{f}");
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
//打标状态下切换指定模板
SetValue(switchTemplates);
SendDataTo.markingFlag = MarkingFlag.切换模版;
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
//发送内容
SetValue(print);
SendDataTo.markingFlag = MarkingFlag.发送完成;
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
return BllResultFactory.Success();
#endregion
}
catch (Exception ex)
{
return BllResultFactory.Error($"发送打标指令出现异常,异常原因{ex.Message}");
}
}
/// <summary>
/// 发送要切割线打印的条码
/// </summary>
/// <param name="barcode"></param>
/// <param name="pipeDiameter"></param>
/// <param name="lineCode"></param>
/// <returns></returns>
public static BllResult SendData(CutPlanTask cutPlanTask)
{
try
{
#region 数据效验
if (SendDataTo.markingFlag == MarkingFlag.打标中)
{
return BllResultFactory.Create(BllResultCode.Warning, "打标机正在打印中,请稍后再试!");
}
if (string.IsNullOrWhiteSpace(cutPlanTask.PrintCode))
{
return BllResultFactory.Error("打标数据为空");
}
#endregion
#region 数据发送,尽量减少等待时间,避免外面的数据库事务一直挂起
//管径和长度 ,小管径短管 2行小字
//小管径短管 2行小字
//大管径短管 3行小字
//大管径长管 1行大字
//短管 减少字符
// 定义控制字符
char stx = (char)2; // STX (Start of Text)
char lf = (char)16; // LF (Line Feed)
char us = (char)49; // US (Unit Separator)
char etx = (char)3; // ETX (End of Text)
char f1 = (char)31;
char a = (char)50;
char b = (char)51;
char c = (char)52;
char space = (char)32;
var print = "";
string switchTemplates = $"{stx}{f1}{space}{us}{0010}{etx}";
var f = (char)5;
//检查连接
SendDataTo.connectComd = ConnectFlag.检查连接;
SendDataTo.SetValue($"{f}");
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
//发送内容
SetValue(switchTemplates);
SendDataTo.markingFlag = MarkingFlag.发送完成;
SendDataTo.waitACK = true;
while (SendDataTo.waitACK) Thread.Sleep(500);
return BllResultFactory.Success();
#endregion
}
catch (Exception ex)
{
return BllResultFactory.Error($"发送打标指令出现异常,异常原因{ex.Message}");
}
}
static void DictTemplate(string lineCode)
{
if (dicTemplate.Count>0)
{
return;
}
var template = "";
var isQRCodet = "";
if (lineCode == "line3")
{
isQRCodet = "IsSmalQRCodet";
template = "SmallPrintTemplate";
}
else
{
isQRCodet = "IsBigQRCodet";
template = "BigPrintTemplate";
}
ConfigRepository configRepository = new ConfigRepository();
var IsQRCodet = configRepository.Where(t => t.Code == isQRCodet).ToList().First();
IsQRCodetValue = Convert.ToInt16(IsQRCodet.Value);
//找到对应打标模板文件
BllService bllService = new BllService();
var dict = bllService.GetDictWithDetails(a => a.Code == template).Data;
//var temp2 = dict.DictDetails.ToLookup(x => x.Value.First(), y => y.Code.Split("-").ToList());
foreach (var item in dict.DictDetails)
{
var temp = item.Code.Split("-").ToList();
dicTemplate.Add(item.Value, temp);
}
}
}
}