WebApiClient.cs
14.7 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
using Newtonsoft.Json;
using OfficeOpenXml.Drawing.Chart;
using RCS.Model.Comm;
using RCS.Model.Entity;
using RCS.Model.WebApi.Respose;
using RCS.WinClient.WebApi.Common;
using RestSharp;
using System.Data;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows.Documents;
using static RCS.Model.Comm.EnumMsg;
namespace RCS.WinClient.WebApi.Client
{
public class WebApiClient
{
private static HttpClient client = new HttpClient();
private static string url = App.AppConfig.ToWebApi;// ConfigurationManager.AppSettings["ToWebApi"];
private static string iotUrl = App.AppConfig.ToIOTApi;// ConfigurationManager.AppSettings["ToWebApi"];
private static RestClient iotClient = new RestClient(iotUrl, configureSerialization: x => new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true // 可选,用于更具可读性的输出
});
/// <summary>
/// 返回给上层系统结果
/// </summary>
/// <param name="obj"></param>
/// <param name="requestUri"></param>
/// <returns></returns>
private static BllResult FormPost(object obj, string requestUri)
{
try
{
requestUri = url + requestUri;
var json = JsonConvert.SerializeObject(obj);
HttpContent content = GetTextContent(obj);
var tk = App.AppConfig!.WMSToken;
client.DefaultRequestHeaders.Add("token", tk);
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var ret = client.PostAsync(requestUri, content).Result;
if (ret.IsSuccessStatusCode)
{
ret.EnsureSuccessStatusCode();
string temp = ret.Content.ReadAsStringAsync().Result;
//LogExecute.logNet.WriteDebug($"请求WMS接口{url}成功,返回值:{temp}");
App.ExFile.MessageWebApi("AcsWebApiMsg", $"请求接口【{requestUri}】发送数据【{json}】成功,返回值:{temp} \r");
client.DefaultRequestHeaders.Clear();
//var serializerSettings = new JsonSerializerSettings
//{
// // 设置为驼峰命名
// ContractResolver = new CamelCasePropertyNamesContractResolver()
//};
var result = JsonConvert.DeserializeObject<ApiResultModel>(temp);
if (result.Status || result.State)
{
return BllResult.Success(null, result.Message);
}
//else if (result.state)
//{
// //token验证失败,重新登陆
// return BllResult.Error(null, b.message);
//}
else
{
return BllResult.Error(null, $"请求成功,但上游系统报错:{result.Message}");
}
}
else
{
App.ExFile.MessageWebApi("AcsWebApiError", $"请求接口【{requestUri}】发送数据【{json}】失败,原因:{ret.StatusCode}\r");
return BllResult.Error(null, $"请求失败,请检查网络连接,详情:{ret.StatusCode}");
}
}
catch (Exception ex)
{
App.ExFile.MessageWebApi("AcsWebApiError", $"请求接口【{requestUri}】出现异常,原因:{ex.Message}\r 堆栈:{ex.StackTrace} \r");
return BllResult.Error(null, $"请求失败,请检查网络连接或者重启本程序,详情:{ex.Message}");
}
}
private static BllResult<T> FormPost<T>(object obj, string requestUri)
{
try
{
requestUri = url + requestUri;
HttpContent content = GetTextContent(obj);
var ret = client.PostAsync(requestUri, content).Result;
if (ret.IsSuccessStatusCode)
{
ret.EnsureSuccessStatusCode();
string temp = ret.Content.ReadAsStringAsync().Result;
var b = JsonConvert.DeserializeObject<ApiResultModel<T>>(temp);
if (b.State) //(b.State == true) //(b.Code == System.Net.HttpStatusCode.OK) (code == HttpStatusCode.OK)
{
return BllResult<T>.Success(b.Data, b.Message);
}
else
{
return BllResult<T>.Error(default(T), b.Message);
}
}
else
{
return BllResult<T>.Error(default(T), "请求WMS失败,请检查网络连接");
}
}
catch (Exception ex)
{
return BllResult<T>.Error(default(T), "请求WMS失败,请检查网络连接或者重启本程序" + ex.Message);
}
}
private static HttpContent GetTextContent(Object obj)
{
string json = JsonConvert.SerializeObject(obj);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
return content;
}
/// <summary>
/// RCS任务回传WMS
/// </summary>
/// <param name="task"></param>
/// <param name="status"></param>
/// <returns></returns>
public static BllResult ToWebApiTaskRefresh(Base_Task task, int status)
{
ResTaskConfirm taskConfirm = new ResTaskConfirm()
{
TaskNo = task.TaskNo,
state = status
};
return FormPost(taskConfirm, "/TaskRefresh");
}
/// <summary>
/// 任务状态回传
/// </summary>
/// <param name="linkAgv"></param>
/// <returns></returns>
public static BllResult ToAcsWebApiTaskState(Base_Task task, int status)
{
//如果不是wms下发的任务,就不需要回传
if (task.TaskGroup != EnumMsg.TaskGroup.WMS任务.ToString())
{
return BllResult.Success();
}
ResTaskConfirm taskConfirm = new ResTaskConfirm()
{
//原版
//executeDate = task.BeginTime.ToString(),
taskNo = task.TaskNo,
carNo = task.TaskAgvNo,
status = status,
updateBy = "AGV",
updatedTime = DateTime.Now,
TaskNo = task.TaskNo,
//适配周锋南方航空项目
//agvNo = task.TaskAgvNo,// task.TaskAgvNo,
//taskNo = task.TaskNo,
//state = status
};
//var result = FormPost(taskConfirm, "/api/AGV/AGVTaskComplete");
var result = FormPost(taskConfirm, "/wms/api/acs/notifyAGVTask");
if (!result.IsSuccess)
{
result.Message = $"回传WMS任务完成失败,{result.Message}";
}
return result;
}
/// <summary>
/// 获取可用输送线站台
/// </summary>
/// <param name="linkAgv"></param>
/// <returns></returns>
public static BllResult GetAvailableStation(Base_Task task)
{
//如果不是wms下发的任务,就不需要回传
if (task.TaskGroup != EnumMsg.TaskGroup.WMS任务.ToString())
{
return BllResult.Success();
}
ResTaskConfirm taskConfirm = new ResTaskConfirm()
{
taskNo = task.TaskNo,
};
var result = FormPost(taskConfirm, "wms/api/acs/getToAgvPort");
if (!result.IsSuccess)
{
result.Message = $"向WMS请求可用站台失败,{result.Message}";
}
return result;
}
/// <summary>
/// 剪床请求入空托盘
/// </summary>
/// <param name="linkAgv"></param>
/// <returns></returns>
public static BllResult ToAcsWebApiCallContainer(int containerType, string port, int area, string warehouseCode)
{
ResTaskConfirm taskConfirm = new ResTaskConfirm()
{
containerType = containerType,
port = port,
area = 4,
warehouseCode = "CS0001"
};
return FormPost(taskConfirm, "/wms/agv/agvCallEmptyOut");
}
/// <summary>
/// 剪床请求入空托盘
/// </summary>
/// <param name="linkAgv"></param>
/// <returns></returns>
public static BllResult<string> GetEndBarcode(Base_Task task)
{
return BllResult<string>.Success("as", "");
//ResTaskConfirm taskConfirm = new ResTaskConfirm()
//{
// containerType = containerType,
// port = port,
// area = 4,
// warehouseCode = "CS0001"
//};
//return FormPost(taskConfirm, "/wms/agv/agvCallEmptyOut");
}
/// <summary>
/// 給wms物料信息
/// </summary>
/// <param name="containerCode"></param>
/// <param name="weight"></param>
/// <param name="height"></param>
/// <param name="formPort"></param>
/// <returns></returns>
public static BllResult ToWMSContainerInfo(string containerCode, double weight, double height, string formPort)
{
containerCode = containerCode.Replace("\0", "").Trim();
formPort = App.StationList.Find(X => X.Name == formPort)?.Code ?? throw new Exception("站台编码不匹配");
var req = new
{
containerCode,
weight,
height,
formPort,
warehouseCode = "CS0001"
};
return FormPost(req, "/wms/agv/weightAndHeightByContainer");
}
/// <summary>
/// 发送IOT数据
/// </summary>
/// <returns></returns>
public static BllResult SendAGVInfoToIot()
{
try
{
var data = new List<IOTApiRequestModel>();
IOTApiRequestModel model;
object temp;
Base_PathPoint? nextPathPoint;
List<TagItem> list;
foreach (var agv in App.AgvList)
{
model = new IOTApiRequestModel(Guid.NewGuid().ToString(), agv.SN, DateTimeOffset.UtcNow.ToUnixTimeSeconds(), "", 1);
data.Add(model);
nextPathPoint = agv.PathPointList.Skip(1).FirstOrDefault();
temp = new
{
agv.AgvNo,
AgvType = (int)agv.AgvType,
agv.Speed,
CurrentBarcode = agv.Barcode,
agv.AgvHeight,
//InStock=(int)agv.InStock,
Direction = (int)agv.AgvDirection,
DialDirection = (int)agv.DialDirection,
Status = (int)agv.AgvState,
RadarStatus = (int)agv.RadarStatus,
Battery = agv.Voltage,
agv.RadarArea,
agv.IsOnline,
CoordX = agv.XLength,
CoordY = agv.YLength,
agv.Error,
RollerState = (int)agv.RollerState,
agv.FrontBarcode,
AfterBarcode = nextPathPoint == null ? "" : nextPathPoint.Barcode,
};
var props = temp.GetType().GetProperties();
list = new List<TagItem>();
foreach (var item in props)
{
list.Add(new TagItem(item.Name, item.GetValue(temp)?.ToString()));
}
model.Reported = list;
}
var result = SendIotPostRequest<IOTApiResultModel>("/SendEquipmentData", data);
return new BllResult(result.IsSuccess, result.Message, result.Data);
}
catch (Exception ex)
{
App.ExFile.MessageError("SendAGVInfoToIot", $"发送数据到IOT异常,原因:{ex}");
return BllResult.Error($"发送数据到IOT异常,原因:{ex.Message}");
}
}
/// <summary>
/// 更新客户端在线状态
/// </summary>
/// <returns></returns>
public static BllResult UpdateClientStatus()
{
var data = new
{
ClientId = "9E9D0CFF-AB52-4E80-AFB7-6436110D9247"
};
var result = SendIotPostRequest<IOTApiResultModel>("/UpdateClientStatus", data);
return new BllResult(result.IsSuccess, result.Message, result.Data);
}
/// <summary>
/// 发送IOT数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="data"></param>
/// <returns></returns>
public static BllResult<T> SendIotPostRequest<T>(string url, object data)
{
try
{
var request = new RestRequest(url, Method.Post);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
request.AddJsonBody(data);
var json = System.Text.Json.JsonSerializer.Serialize(data);
var res = iotClient.Execute<T>(request);
var absoluteUri = iotClient.BuildUri(request).AbsoluteUri;
if (!res.IsSuccessful)
{
return BllResult<T>.Error($"发送数据到IOT接口【{absoluteUri}】失败,错误码【{res.StatusCode}】,错误信息【{res.ErrorMessage}】");
}
if (res.Data == null)
{
return BllResult<T>.Error($"发送数据到IOT接口【{absoluteUri}】是把,接口返回空");
}
App.ExFile.MessageWebApi("SendAGVInfoToIot", $"发送数据【{json}】到IOT接口【{absoluteUri}】成功!");
return BllResult<T>.Success(res.Data);
}
catch (Exception ex)
{
return BllResult<T>.Error($"发送数据到IOT接口,发生异常,原因:{ex}");
}
}
}
}