VServerComm.cs
20.4 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
using OnlineStore;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public class VServerComm
{
volatile StoreStatus _storeStatus = StoreStatus.Debugging;
/// <summary>
/// 出库,reelid
/// </summary>
public event EventHandler<JobInfo> OutStoreEvent;
public StoreStatus storeStatus {
get => _storeStatus;
set {
if (_storeStatus!= value)
VLog.Info($"set storeStatus to {value}");
_storeStatus = value;
}
}
static string server = Setting_Init.Device_Server_Address;
static string CID;//= Setting_Init.Device_CID;
int StoreID = 1;
string StoreName="";
string WarnMsg = "";
System.Timers.Timer serverConnectTimer = new System.Timers.Timer();
VLog VLog;
object serverclock = new object();
public VServerComm(string cid , VLog vLog) {
VLog = vLog;
CID = cid;
serverConnectTimer.Interval = 1000;
serverConnectTimer.AutoReset = true;
serverConnectTimer.Enabled = true;
serverConnectTimer.Elapsed += ServerConnectTimer_Elapsed;
GC.KeepAlive(serverConnectTimer);
VLog.Info($"server:{server},cid:{CID}");
}
private void ServerConnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
if (!RobotManage.isRunning)
ProcessMsg(VMsg.msg);
SendLineStatus();
}
catch (Exception ex)
{
VLog.Error($"ServerConnectTimer_Elapsed:{ex}");
}
finally {
//Monitor.Exit(serverConnectTimer);
}
}
public void ProcessMsg(List<Msg> msg) {
WarnMsg = string.Join(",", msg.Select(x =>
{
if (x.msgLevel == MsgLevel.warning || x.msgLevel == MsgLevel.alarm)
{
return x.msgtxt;
}
return null;
}
).Where(x=>!string.IsNullOrEmpty(x)));
}
public void SendInStoreRequest(string[] codelist, ReelParam reel,bool printlog=false) {
if (RobotManage.InoutDebugMode)
return;
lock (serverclock)
{
var code = ProcessCode(codelist, reel.PlateW, reel.PlateH);
Operation operation = getLineBoxStatus();
operation.op = 1;
operation.data = new Dictionary<string, string>() { { "code", code }, { "boxId", StoreID.ToString() }, { "doorReelSignal", "1" } };
int retrytimes = 0;
retry:
Operation resultOperation = HttpHelper.Post(GetPostApi(), operation, 15000, printlog);
if (RobotManage.isRunning &&( resultOperation==null || operation.seq != resultOperation.seq))
{
Thread.Sleep(1000);
//SendInStoreRequest(codelist, reel, printlog);
retrytimes++;
if (retrytimes <= 3)
goto retry;
}
ResultProcess(resultOperation);
}
}
public bool SendStoreState(string posid, StoreStatus storeStatus)
{
lock (serverclock)
{
Operation operation = getLineBoxStatus();
if (!string.IsNullOrEmpty(posid))
operation.boxStatus[StoreID].data.Add(ParamDefine.posId, posid);
if (storeStatus == StoreStatus.OutStoreEnd ||
storeStatus == StoreStatus.OutStoreBoxEnd ||
storeStatus == StoreStatus.InStoreEnd)
{
}
else
operation.boxStatus[StoreID].status = (int)storeStatus;
LogUtil.info(JsonHelper.SerializeObject(operation));
if (RobotManage.InoutDebugMode)
return true;
Operation resultOperation = HttpHelper.Post(GetPostApi(), operation, 15000);
if (resultOperation == null)
{
VLog.Error($"SendStoreState error,posid:{posid}, storeStatus:{storeStatus}");
return false;
}
if (operation.seq != resultOperation.seq)
{
VLog.Error($"SendStoreState seq error,posid:{posid}, storeStatus:{storeStatus}");
return false;
}
VLog.Info($"SendStoreState success,posid:{posid}, storeStatus:{storeStatus}");
ResultProcess(resultOperation);
this.storeStatus = StoreStatus.StoreOnline;
}
return true;
}
public string spiltStr = "##";
private string ProcessCode(string[] codeList,int reelw,int reelh)
{
string message = "";
//= 7x12 = CODE
foreach (string str in codeList)
{
string code = str.Replace("\r", "");
code = code.Replace("\n", "");
//根据二维码开头获取固定尺寸
string codeSize = $"{reelw}x{reelh}";
message = message + "=" + "1+0x0-" + codeSize + "=" + code + spiltStr;
}
return message;
}
/// <summary>
/// 获取整个料仓的状态
/// </summary>
Operation getLineBoxStatus()
{
//构建发送给服务器的对象
Operation lineOperation = new Operation();
lineOperation.msg = "";
lineOperation.alarmList = new List<AlarmInfo>();
lineOperation.cid = CID;
lineOperation.seq = ConfigAppSettings.nextSeq();
lineOperation.status = 1;
//lineOperation.data = GetBtnStatus();
lineOperation.status = (int)storeStatus;
//判断如果是等待料盘拿走超时,状态改为4Warning
//if (alarmType.Equals(StoreAlarmType.IoSingleTimeOut) && StoreMove.MoveType.Equals(StoreMoveType.OutStore))
//{
// if (StoreMove.MoveStep.Equals(StoreMoveStep.SO_15_WaitTake) || StoreMove.MoveStep.Equals(StoreMoveStep.SO_16_CheckIsTake))
// {
// lineOperation.status = (int)StoreStatus.Warning;
// }
//}
BoxStatus boxStatus = new BoxStatus();
boxStatus.boxId = StoreID;
boxStatus.humidity = Humidity.ToString();
boxStatus.temperature = Temperature.ToString();
//状态
boxStatus.status = (int)storeStatus;
string sendmsg = "";
if (commandResultMsg.Count() > 0)
{
if (commandResultMsg.TryDequeue(out string msg))
{
sendmsg = msg.Trim().Trim(',');
}
}
else if (!string.IsNullOrEmpty(WarnMsg))
{
sendmsg = string.Join(",", new string[] { WarnMsg });
}
else if (!RobotManage.isRunning){
sendmsg = crc.GetString("Res0155","设备未启动");
}
lineOperation.msg = sendmsg;
lineOperation.msg = lineOperation.msg.Trim().Trim(',');
boxStatus.msg = lineOperation.msg;
lineOperation.msgEn = lineOperation.msg;
lineOperation.msgJp = lineOperation.msg;
lineOperation.boxStatus.Add(StoreID, boxStatus);
return lineOperation;
}
private static string api_communication = "service/store/communication"; //流水线状态通信接口
public static string GetPostApi()
{
var host = server;
if (!host.StartsWith("http://"))
{
host = "http://" + host;
}
if (!host.EndsWith("/"))
{
host = host + "/";
}
return host + api_communication;
}
int getthtime = 0;
int laststatus = 0;
public void SendLineStatus()
{
if (RobotManage.InoutDebugMode)
return;
lock (serverclock)
{
bool printlog = false;
DateTime time = DateTime.Now;
//构建发送给服务器的对象
Operation lineOperation = getLineBoxStatus();
//如果还没湿度范围,先获取
if (getthtime < 3)
{
if (Max_Humidity <= 0 || (Max_Temperature <= 0))
{
lineOperation.op = 5;
VLog.Info(StoreName + "没有湿度预警范围,需要从服务器获取,发送OP=" + lineOperation.op);
getthtime++;
}
}
if (lineOperation.status != laststatus) {
laststatus = lineOperation.status;
printlog = true;
}
Operation resultOperation = HttpHelper.Post(GetPostApi(), lineOperation,700, printlog);
if (resultOperation != null)
getthtime = 0;
//LogUtil.info(JsonHelper.SerializeObject(resultOperation.data));
ResultProcess(resultOperation);
TimeSpan span = DateTime.Now - time;
if (span.TotalMilliseconds > 700)
{
VLog.Info(StoreName + "TimerProcess[" + span.TotalMilliseconds + "]");
}
}
}
public int queueTaskCount=-1;
ConcurrentQueue<string> commandResultMsg = new ConcurrentQueue<string>();
void ResultProcess(Operation resultOperation)
{
//发送状态信息到服务器
if (resultOperation == null)
{
//判断服务端是否返回出库操作
return;
}
if (resultOperation.op.Equals(1))
{
var barcode = "";
if (resultOperation.data.ContainsKey("code"))
barcode = resultOperation.data["code"];
ReviceInStoreProcess(barcode, resultOperation);
}
else if (resultOperation.op.Equals(2))
{
ReviceOutStoreProcess(resultOperation);
}
else if (resultOperation.op.Equals(5))
{
//ProcessHumidityCMD(resultOperation);
}
ProcessHumidityCMD(resultOperation);
if (resultOperation.data != null)
{
string result = "";
Dictionary<string, string> dataMap = resultOperation.data;
if (dataMap.ContainsKey(ParamDefine.queueTaskCount))
{
var s = dataMap[ParamDefine.queueTaskCount];
if (int.TryParse(s, out int c))
{
queueTaskCount = c;
}
else
{
queueTaskCount = -1;
}
}
}
}
/// <summary>
/// 处理服务器入库库位消息
/// </summary>
/// <param name="message"></param>
/// <param name="resultOperation"></param>
private void ReviceInStoreProcess(string message, Operation resultOperation)
{
Dictionary<string, string> data = resultOperation.data;
if (data != null && data.ContainsKey(ParamDefine.posId) && data.ContainsKey(ParamDefine.plateH) && data.ContainsKey(ParamDefine.plateW))
{
//服务器返回时有:posId库位编号,plateW:料盘宽度,plateH:料盘高度,
//postId格式BoxId#位置
string posId = data[ParamDefine.posId];
int.TryParse(data[ParamDefine.plateW], out int plateW);
int.TryParse(data[ParamDefine.plateH], out int plateH);
//根据发送的posId获取位置列表
ACStorePosition position = CSVPositionReader<ACStorePosition>.GetPositon(posId);
if (position == null)
{
//出入库没有找到服务器发送的库位,需要打印日志方便查询原因
//SetWarnMsg(ResourceControl.InStoreNoPosition, message, posId);
WarnMsg = crc.GetString("Res0049","入库未找到库位:") + posId;//0505
VLog.Info("收到服务器入库命令:入库未找到库位:二维码【" + message + "】库位【" + posId + "】");
return;
}
//TODO:判断BOX是否处于可以入库状态,如果调试或急停中,需要返回给服务器;
//if (RobotManage.mainMachine.IsInStoreReady)
//{
// WarnMsg = "";
// if (plateH > 56)
// plateH = 56;
// JobInfo inStoreJob = new JobInfo(message, posId, plateW, plateH);
// RobotManage.mainMachine.StartInStore(inStoreJob);
// //如果当前正在出入库中,需要记录下来,等待空闲时执行
// VLog.Info(StoreName + " 收到服务器入库命令:库位号【" + posId + "】二维码【" + message + "】 开始入库!");
//}
//else
{
SendStoreState("", StoreStatus.InStoreError);
}
}
}
public double Max_Humidity;
public double Max_Temperature;
public double Humidity;
public double Temperature;
/// <summary>
/// 处理服务器温湿度消息
/// </summary>
/// <param name="resultOperation"></param>
private void ProcessHumidityCMD(Operation resultOperation)
{
if (resultOperation.data == null)
return;
Dictionary<string, string> data = resultOperation.data;
if (data.ContainsKey(ParamDefine.maxHumidity) && data.ContainsKey(ParamDefine.maxTemperature))
{
string maxHumidity = data[ParamDefine.maxHumidity];
string maxTemp = data[ParamDefine.maxTemperature];
VLog.Info( "收到服务器温湿度预警值:maxHumidity=" + maxHumidity + ",maxTemperature=" + maxTemp);
try
{
this.Max_Humidity = (float)Convert.ToDouble(maxHumidity);
this.Max_Temperature = (float)Convert.ToDouble(maxTemp);
VLog.Info( "保存温湿度预警值:Max_Humidity=" + Max_Humidity + ",Max_Temperature=" + Max_Temperature);
}
catch (Exception ex)
{
VLog.Error("转换温湿度失败:" + ex.ToString());
}
}
}
/// <summary>
/// 处理服务器出库任务消息
/// </summary>
/// <param name="resultOperation"></param>
private void ReviceOutStoreProcess(Operation resultOperation)
{
DateTime time = DateTime.Now;
Dictionary<string, string> data = resultOperation.data;
if (data != null && data.ContainsKey(ParamDefine.posId)
&& data.ContainsKey(ParamDefine.plateH) && data.ContainsKey(ParamDefine.plateW))
{
string posIdStr = data[ParamDefine.posId];
//string cid = data[ParamDefine.cid];
string plateWStr = data[ParamDefine.plateW];
string plateHStr = data[ParamDefine.plateH];
string singleOut = data[ParamDefine.singleOut];
string code = "";
if (!data.TryGetValue("code", out code))
data.TryGetValue(ParamDefine.barcode, out code);
VLog.Info("收到服务器出库消息:poaIs=" + posIdStr + ",platew=" + plateWStr + ",plateh=" + plateHStr + ",code=" + code);
int.TryParse(plateWStr, out int plateW);
int.TryParse(plateHStr, out int plateH);
//根据发送的posId获取位置列表
if (string.IsNullOrEmpty(code))
{
//WarnMsg = StoreName + "没有:【" + cid + "】";
VLog.Error("收到服务器出库命令:没有code");
}
else
{
JobInfo jobInfo = new JobInfo(code, posIdStr, plateW, plateH);
OutStoreEvent?.Invoke("服务器", jobInfo);
}
TimeSpan span = DateTime.Now - time;
if (span.TotalMilliseconds > 100)
{
VLog.Info(StoreName + "执行 ReviceOutStoreProcess 共处理了【" + span.TotalMilliseconds + "】毫秒");
}
}
}
private static string Addr_cancelPutInTask = "/service/store/cancelPutInTask";
public string cancelPutInTask(string deviceName, string barcode)
{
string msg = "";
try
{
Dictionary<string, string> paramMap = new Dictionary<string, string>();
paramMap.Add("barcode", barcode);
string server = GetAddr(Addr_cancelPutInTask, paramMap);
DateTime startTime = DateTime.Now;
string resultStr = HttpHelper.Post(server, "");
VLog.Info(deviceName + "cancelPutInTask " + FormUtil.GetSpanStr(DateTime.Now - startTime) + " 【" + server + "】【" + resultStr + "】");
ResultData data = JsonHelper.DeserializeJsonToObject<ResultData>(resultStr);
if (data == null)
{
return msg = deviceName + " cancelPutInTask【 " + barcode + "】 没有收到服务器反馈";
}
else if (data.code.Equals(0).Equals(false))
{
return msg = deviceName + " cancelPutInTask【 " + barcode + "】 :" + data.msg;
}
return "";
}
catch (Exception ex)
{
VLog.Error(deviceName + " " + ex.ToString());
}
return msg;
}
public string DisabledPos(string posId, string barcode)
{
string msg = "";
try
{
Dictionary<string, string> paramMap = new Dictionary<string, string>();
paramMap.Add("posId", posId);
paramMap.Add("barcode", barcode);
string server = GetAddr("/service/store/disabledPos", paramMap);
DateTime startTime = DateTime.Now;
string resultStr = HttpHelper.Post(server, "");
VLog.Info("DisabledPos " + FormUtil.GetSpanStr(DateTime.Now - startTime) + " 【" + server + "】【" + resultStr + "】");
ResultData data = JsonHelper.DeserializeJsonToObject<ResultData>(resultStr);
if (data == null)
{
return msg = " DisabledPos【 " + posId + "】 没有收到服务器反馈";
}
else if (data.code.Equals(0).Equals(false))
{
return msg = " DisabledPos【 " + posId + "】 :" + data.msg;
}
return "";
}
catch (Exception ex)
{
VLog.Error("DisabledPos: " + ex.ToString());
}
return msg;
}
private static string GetAddr(string addr, Dictionary<string, string> paramsMap)
{
if (server.EndsWith("/"))
{
server = server.Substring(0, server.Length - 1);
}
string path = server + addr.Trim() + "?";
foreach (string paramName in paramsMap.Keys)
{
string par = System.Web.HttpUtility.UrlEncode(paramsMap[paramName], System.Text.Encoding.UTF8);
path += paramName + "=" + par + "&";
}
path = path.Substring(0, path.Length - 1);
return path;
}
}
}