ControllerHelper.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. 
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. using System.Windows.Forms;
  6. using Newtonsoft.Json;
  7. using System.Net;
  8. using System.Threading.Tasks;
  9. using System.Threading;
  10. using System.Text;
  11. using System.Configuration;
  12. using System.IO;
  13. using EasyModbusClient.redis;
  14. using EasyModbusClient.util;
  15. using EasyModbusClient.businessBody;
  16. using Newtonsoft.Json.Serialization;
  17. using EasyModbus;
  18. using YG.Device;
  19. using YG;
  20. using IMCS.Device;
  21. using IMCS.Device.body;
  22. using Newtonsoft.Json.Linq;
  23. using IMCS.Http.businessBody;
  24. using IMCS.Lib;
  25. using System.Linq;
  26. namespace EasyModbusClient
  27. {
  28. /*
  29. * string cmdreceive= CMDLib.Instance.WriteCmd($"netsh http add urlacl url={HttpServerUrlString} user=Everyone");
  30. YG.Log.Instance.WriteLogAdd($"启动HttpServer 默认添加允许项:{cmdreceive}");
  31. System.Threading.Thread.Sleep(500);
  32. */
  33. class ControllerHelper
  34. {
  35. private static string RETVAL = "success";
  36. private static int ASK_TIMES = 20;
  37. private static string VirtualProgram = ConfigurationManager.AppSettings["VirtualProgram"];
  38. private static int HEX_BINARY = 8;
  39. private uint currentToolArea = 1;
  40. private static string ConncetionRedisString = ConfigurationManager.AppSettings["ConncetionRedisString"];
  41. private static string HttpServerUrlString = ConfigurationManager.AppSettings["HttpServerUrlString"];
  42. private static string NcExtendPath = ConfigurationManager.AppSettings["NcExtendPath"];
  43. private static string NcUpLoadPath = ConfigurationManager.AppSettings["NcUpLoadPath"];
  44. private static string LocalNcPath = ConfigurationManager.AppSettings["LocalNcPath"];
  45. private static string ClsSFTP_IP = ConfigurationManager.AppSettings["ClsSFTP_Ip"];
  46. private static string ClsSFTP_Port = ConfigurationManager.AppSettings["ClsSFTP_Port"];
  47. private static string ClsSFTP_UserName = ConfigurationManager.AppSettings["ClsSFTP_UserName"];
  48. private static string ClsSFTP_PWD = ConfigurationManager.AppSettings["ClsSFTP_Pwd"];
  49. private void send(HttpListenerResponse response, short value, string machine = "WL")
  50. {
  51. ResponseBody responseBody = new ResponseBody();
  52. responseBody.Code = 0;
  53. responseBody.Msg = Constants.OPERATE_SUCCESS_MSG;
  54. response.StatusCode = 200;
  55. response.ContentType = "application/json;charset=UTF-8";
  56. response.ContentEncoding = Encoding.UTF8;
  57. response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
  58. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  59. {
  60. string respstring = "";
  61. if (value == -3)
  62. {
  63. respstring = "关状态";
  64. }
  65. else if (value == -4)
  66. {
  67. respstring = "开状态";
  68. }
  69. if (machine == "JC")
  70. {
  71. switch (value)
  72. {
  73. case 1:
  74. respstring = "执行程序成功";
  75. break;
  76. case 2:
  77. respstring = "执行程序失败";
  78. break;
  79. case 3:
  80. respstring = "不满足前置条件";
  81. break;
  82. }
  83. }
  84. if (machine == "WL")
  85. {
  86. switch (value)
  87. {
  88. case 1:
  89. respstring = "执行取动作";
  90. break;
  91. case 4:
  92. respstring = "执行放动作";
  93. break;
  94. case 7:
  95. respstring = "执行移动动作";
  96. break;
  97. case 2:
  98. respstring = "取执行中";
  99. break;
  100. case 3:
  101. respstring = "取完成";
  102. break;
  103. case 5:
  104. respstring = "放执行中";
  105. break;
  106. case 6:
  107. respstring = "放完成";
  108. break;
  109. case 8:
  110. respstring = "移动完成";
  111. break;
  112. case 9:
  113. respstring = "机器人故障";
  114. break;
  115. case 10:
  116. respstring = "打标完成";
  117. break;
  118. case 11:
  119. respstring = "清洗剂执行中";
  120. break;
  121. case 12:
  122. respstring = "不满足清晰条件";
  123. break;
  124. }
  125. }
  126. else if (machine == "LHT")
  127. {
  128. switch (value)
  129. {
  130. case 1:
  131. respstring = "执行取动作";
  132. break;
  133. case 2:
  134. respstring = "取完成";
  135. break;
  136. case 3:
  137. respstring = "执行放动作";
  138. break;
  139. case 4:
  140. respstring = "放完成";
  141. break;
  142. case 5:
  143. respstring = "取执行中";
  144. break;
  145. case 6:
  146. respstring = "放执行中";
  147. break;
  148. }
  149. }
  150. writer.Write(respstring);
  151. writer.Close();
  152. response.Close();
  153. }
  154. }
  155. //httpser服务
  156. public void StartHttpServer()
  157. {
  158. CommonUtil.InitXml();
  159. HttpListener listener = new HttpListener();// HTTP 协议侦听器
  160. LibCMD.Instance.WriteCmd(HttpServerUrlString);
  161. listener.Prefixes.Add(HttpServerUrlString);// 配置访问权限地址
  162. listener.Start();
  163. CommonUtil.WriteAccessLog(DateTime.Now + ">>>监听服务启动Listening>>>>");
  164. Task task = Task.Factory.StartNew(() =>
  165. { // 创建异步task
  166. while (listener.IsListening)
  167. {
  168. HttpListenerContext context = listener.GetContext();
  169. HttpListenerRequest request = context.Request;
  170. HttpListenerResponse response = context.Response;
  171. try
  172. {
  173. Servlet servlet = new MyServlet();
  174. servlet.onCreate();
  175. if (!request.Url.ToString().Contains("favicon"))
  176. {
  177. if (request.HttpMethod == "POST")
  178. {
  179. Stream stream = context.Request.InputStream;
  180. StreamReader reader = new StreamReader(stream, Encoding.UTF8);
  181. string body = reader.ReadToEnd();
  182. YG.Log.Instance.WriteLogAdd(">>>===收到POST数据 : >>>>===" + body);
  183. CcsRequestBody ccsRequestBody = JsonJavaScriptSerializer.FromJSON<CcsRequestBody>(body);
  184. string url = (ccsRequestBody.Url + ":" + ccsRequestBody.Port);
  185. string businessType = ccsRequestBody.BusinessType;
  186. DeviceList conDeviceInfo = DeviceManage.Instance.GetOne(url);
  187. ResponseBody responseBody = ResponseBody.newObject();
  188. response.StatusCode = 200;
  189. response.ContentType = "application/json;charset=UTF-8";
  190. response.ContentEncoding = Encoding.UTF8;
  191. response.AppendHeader("Content-Type", "application/json;charset=UTF-8");
  192. if (conDeviceInfo != null)
  193. {
  194. if (!string.IsNullOrEmpty(businessType))
  195. {
  196. if (businessType.Equals("testwork"))
  197. {
  198. conDeviceInfo.DeviceSend("DB200.52", "1111".ReturnBtyesWtitString(40));
  199. System.Threading.Thread.Sleep(1100);
  200. conDeviceInfo.DeviceSend("DB200.92", "1111".ReturnBtyesWtitString(20));
  201. }
  202. if (businessType.Equals("uploadProgram"))
  203. {
  204. responseBody = UpLoadNc(conDeviceInfo, ccsRequestBody.Data, ccsRequestBody);
  205. }
  206. else if (businessType.Equals("deleteProgram"))
  207. {
  208. responseBody = DeleteNCProgram(conDeviceInfo, ccsRequestBody.Data, ccsRequestBody);
  209. }
  210. else if (businessType.Equals("execProgram"))
  211. {
  212. CcsRequestBody itemrequestbody = ccsRequestBody.clone() as CcsRequestBody;
  213. DeviceOPCUat itemreadopcua = (DeviceOPCUat)conDeviceInfo;
  214. int runcount = 0;
  215. Task.Factory.StartNew(async () =>
  216. {
  217. while (true)
  218. {
  219. runcount++;
  220. if (runcount > 10)
  221. {
  222. break;
  223. }
  224. await Task.Delay(2000);
  225. List<string> itemopcuavalue = itemreadopcua.OpcUa_Read(new List<string> { "/Plc/M1300.0", "/Plc/I37.1" });
  226. if (itemopcuavalue.Where(m => m.Equals("False")).Count() == 0 && itemopcuavalue.Count > 0)
  227. // List<string> itemopcuavalue = itemreadopcua.OpcUa_Read(new List<string> { "/Plc/M1300.0"});
  228. //if (itemopcuavalue.Where(m => m.Equals("False")).Count() == 0 && itemopcuavalue.Count > 0)
  229. {
  230. try
  231. {
  232. if (SelectedNCProgram(conDeviceInfo, itemrequestbody.Data, itemrequestbody))
  233. {
  234. try
  235. {
  236. System.Threading.Thread.Sleep(2000);
  237. responseBody = WriteValue(conDeviceInfo, itemrequestbody, true);
  238. break;
  239. }
  240. catch (Exception eex)
  241. {
  242. YG.Log.Instance.WriteLogAdd($"247-->程序执行中出现了异常情况-->{eex.Message}");
  243. }
  244. }
  245. else
  246. {
  247. YG.Log.Instance.WriteLogAdd($"------------->>>选择程序出现异常");
  248. }
  249. }
  250. catch (Exception ex)
  251. {
  252. YG.Log.Instance.WriteLogAdd($"247-->程序出现异常-->{ex.Message}");
  253. }
  254. }
  255. }
  256. });
  257. //将选中程序和执行程序合并 一个指令执行
  258. }
  259. else
  260. {
  261. responseBody = WriteValue(conDeviceInfo, ccsRequestBody, true);
  262. }
  263. //如果此操作成功,加入回调任务队列
  264. if (responseBody.Code == Constants.RET_SUCCESS_CODE)
  265. {
  266. callResponse(ccsRequestBody, conDeviceInfo.ServerUrl, Constants.RET_SUCCESS_CODE, Constants.OPERATE_SUCCESS_MSG);
  267. }
  268. var serializerSettings = new JsonSerializerSettings()
  269. {
  270. // 设置为驼峰命名
  271. ContractResolver = new CamelCasePropertyNamesContractResolver()
  272. };
  273. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  274. {
  275. YG.Log.Instance.WriteLogAdd($"WMS--->>{responseBody.Json_SerializeObject()}--->>{body}\r\n");
  276. writer.Write(JsonConvert.SerializeObject(responseBody, Formatting.Indented, serializerSettings));
  277. writer.Close();
  278. response.Close();
  279. }
  280. }
  281. }
  282. else
  283. {
  284. using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
  285. {
  286. YG.Log.Instance.WriteLogAdd($"WMS--->>{responseBody.Json_SerializeObject()}--->>{body}\r\n");
  287. responseBody.Code = 3;
  288. responseBody.Msg = "无法找到相关设备,请检查网络是否通畅";
  289. writer.Write(responseBody.Json_SerializeObject());
  290. writer.Close();
  291. response.Close();
  292. }
  293. YG.Log.Instance.WriteLogAdd("---->>没有检测到当前设备");
  294. }
  295. }
  296. }
  297. }
  298. catch (Exception ex)
  299. {
  300. CommonUtil.WriteAccessLog(DateTime.Now + ">>>===HTTP Server监听器异常 {0}信息 : >>>>===" + ex.ToString());
  301. listener.Stop();
  302. StartHttpServer();
  303. }
  304. }
  305. });
  306. task.Wait();
  307. }
  308. bool IsRun = true;
  309. private ResponseBody UpLoadNc(DeviceList device, object data, CcsRequestBody ccsRequestBody)
  310. {
  311. CcsRequestBody itemrequestbody = ccsRequestBody.clone() as CcsRequestBody;
  312. DeviceOPCUat itemreadopcua = (DeviceOPCUat)device;
  313. int runcount = 0;
  314. bool tasksleep = true;
  315. while (tasksleep)
  316. {
  317. List<string> itemopcuavalue = itemreadopcua.OpcUa_Read(new List<string> { "/Plc/M1300.0", "/Plc/I37.1" });
  318. if (itemopcuavalue.Where(m => m.Equals("False")).Count() == 0 && itemopcuavalue.Count > 0)
  319. // List<string> itemopcuavalue = itemreadopcua.OpcUa_Read(new List<string> { "/Plc/M1300.0"});
  320. if (itemopcuavalue.Where(m => m.Equals("False")).Count() == 0 && itemopcuavalue.Count > 0)
  321. {
  322. tasksleep = false;
  323. }
  324. }
  325. SFTPDeviceBody sftpBody = DeviceManage.Instance.GetSFTPOne(device.Ip);
  326. ResponseBody resBody = ResponseBody.newObject();
  327. //将对象转为文件名数组
  328. //string json = JsonConvert.SerializeObject(data);
  329. JArray array = (JArray)JsonConvert.DeserializeObject(data.ToString());
  330. List<UploadFileBody> list = array.ToObject<List<UploadFileBody>>();
  331. foreach (UploadFileBody uploadBody in list)
  332. {
  333. string fileName = uploadBody.fileName;
  334. DeviceSFTP helper = new DeviceSFTP(sftpBody);
  335. try
  336. {
  337. bool ifcon = helper.Connect();
  338. if (ifcon)
  339. {
  340. var cc = helper.Put(LocalNcPath + fileName, sftpBody.Path + fileName);
  341. helper.Disconnect();
  342. }
  343. else
  344. {
  345. resBody.Msg = "upload failed";
  346. resBody.Code = Constants.RET_FAILURE_CODE;
  347. return resBody;
  348. }
  349. }
  350. catch (Exception ex)
  351. {
  352. YG.Log.Instance.WriteLogAdd($"297-->{ex.Message}");
  353. resBody.Msg = ex.Message;
  354. resBody.Code = Constants.RET_FAILURE_CODE;
  355. return resBody;
  356. }
  357. }
  358. return resBody;
  359. }
  360. //选中机床中的NC程序
  361. public bool SelectedNCProgram(DeviceList device, object data, CcsRequestBody ccsRequestBody)
  362. {
  363. string fileName = data.ObjectToString();
  364. SFTPDeviceBody sftpBody = DeviceManage.Instance.GetSFTPOne(device.Ip);
  365. DeviceOPCUat opc = (DeviceOPCUat)device;
  366. bool flag = opc.OpcUa_Select(sftpBody.NcExtendPath, fileName);
  367. return flag;
  368. }
  369. //删除机床中的NC程序
  370. public ResponseBody DeleteNCProgram(DeviceList device, object data, CcsRequestBody ccsRequestBody)
  371. {
  372. ResponseBody resBody = ResponseBody.newObject();
  373. SFTPDeviceBody sftpBody = DeviceManage.Instance.GetSFTPOne(device.Ip);
  374. DeviceOPCUat opc = (DeviceOPCUat)device;
  375. //将对象转为文件名数组
  376. //string json = JsonConvert.SerializeObject(data);
  377. JArray array = (JArray)JsonConvert.DeserializeObject(data.ToString());
  378. List<UploadFileBody> list = array.ToObject<List<UploadFileBody>>();
  379. foreach (UploadFileBody uploadBody in list)
  380. {
  381. string fileName = uploadBody.fileName;
  382. DeviceSFTP helper = new DeviceSFTP(sftpBody);
  383. helper.DeleteFile(sftpBody, fileName);
  384. //string status = opc.OpcUa_DeleteFile(sftpBody.Path,fileName);
  385. }
  386. resBody.Msg = Constants.DEL_PROGRAME_SUCCESS_MSG;
  387. resBody.Code = Constants.RET_SUCCESS_CODE;
  388. return resBody;
  389. }
  390. private void callResponse(CcsRequestBody ccsRequestBody, string serverUrl, int code = -1, string msg = "")
  391. {
  392. if (code == -1)
  393. {
  394. code = Constants.RET_SUCCESS_CODE;
  395. }
  396. if (string.IsNullOrWhiteSpace(msg))
  397. {
  398. msg = Constants.OPERATE_SUCCESS_MSG;
  399. }
  400. //如果此操作成功,加入回调任务队列
  401. ccsRequestBody.Data = code + "";
  402. ccsRequestBody.Msg = msg;
  403. CommonUtil.ResponseTaskList(ccsRequestBody, serverUrl);
  404. }
  405. //写入对应的值
  406. public ResponseBody WriteValue(DeviceList device, CcsRequestBody ccsRequestBody, bool isCheck)
  407. {
  408. string parentKey = ccsRequestBody.BusinessType;
  409. ResponseBody resBody = ResponseBody.newObject();
  410. Node parentNode = CommonUtil.GetTargetNode(device.ServerUrl, parentKey);
  411. //将读类型赋予设备,供s7协议使用
  412. device.ReadType = parentNode.ReadType;
  413. bool isAsk = parentNode.IsAsk;
  414. try
  415. {
  416. //校验条件是否满足
  417. resBody = CheckCondition(parentKey, device, isAsk);
  418. if (resBody.Code != 2)
  419. {
  420. resBody.Msg = Constants.CONDITUIN_CHECK_FAILURE_MSG;
  421. resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE;
  422. return resBody;
  423. }
  424. if (device.Dtype.Equals(DeviceType.OPCUa))
  425. {
  426. DeviceOPCUat opcua = (DeviceOPCUat)device;
  427. bool flag = opcua.OpcUa_WriteValue(parentNode.Address, parentNode.Value);
  428. //如果此操作失败返回
  429. if (!flag)
  430. {
  431. YG.Log.Instance.WriteLogAdd($"------------------>>>>>>>>>>>>>>>>>>>>>>>机床执行程序出现错误");
  432. resBody.Data = Constants.RET_FAILURE_CODE + "";
  433. resBody.Msg = Constants.OPERATE_FAILURE_MSG;
  434. return resBody;
  435. }
  436. }
  437. else if (device.Dtype.Equals(DeviceType.PLC_S7))
  438. {
  439. DeviceS7 s7 = (DeviceS7)device;
  440. //当是智能取或放时 先调智能单元取和放的方法,再执行,如果是柔性产线 需在此处再加一个判断
  441. //取物品
  442. if (parentKey.ToUpper().Equals("FETCHMATERIAL") || parentKey.ToUpper().Equals("PUTMATERIAL"))
  443. {
  444. #region 取物品
  445. if (parentKey.ToUpper().Equals("FETCHMATERIAL") && ccsRequestBody.Data != null)
  446. {
  447. if (parentNode.Title.Contains("智能单元"))
  448. {
  449. int v = ccsRequestBody.Data.ObjectToInt();
  450. s7.DeviceSend("DB3.6", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType);
  451. }
  452. else if (parentNode.Title.Contains("柔性线"))
  453. {
  454. int v = ccsRequestBody.Data.ObjectToInt();
  455. s7.DeviceSend("DB200.46", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType);
  456. }
  457. else if (parentNode.Title.Contains("质量中心"))
  458. {
  459. int v = ccsRequestBody.Data.ObjectToInt();
  460. s7.DeviceSend("DB200.46", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType);
  461. }
  462. Thread.Sleep(50);
  463. }
  464. #endregion
  465. #region 放物品
  466. //放物品
  467. if (parentKey.ToUpper().Equals("PUTMATERIAL") && ccsRequestBody.Data != null)
  468. {
  469. if (parentNode.Title.Contains("智能单元"))
  470. {
  471. s7.DeviceSend("DB3.8", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType);
  472. }
  473. else if (parentNode.Title.Contains("柔性线"))
  474. {
  475. int v = ccsRequestBody.Data.ObjectToInt();
  476. s7.DeviceSend("DB200.48", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType);
  477. }
  478. else if (parentNode.Title.Contains("质量中心"))
  479. {
  480. int v = ccsRequestBody.Data.ObjectToInt();
  481. s7.DeviceSend("DB200.48", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType);
  482. }
  483. Thread.Sleep(50);
  484. }
  485. #endregion
  486. System.Threading.Thread.Sleep(1100);
  487. s7.DeviceSend(parentNode.Address, parentNode.Value, parentNode.ReadType);
  488. #region 取,放下发动作之后,上报mes
  489. //resBody.Code = Constants.RET_SUCCESS_CODE;
  490. //resBody.Msg = Constants.OPERATE_SUCCESS_MSG;
  491. //如果此操作成功,加入回调任务队列
  492. //ccsRequestBody.Data = resBody.Code + "";
  493. //ccsRequestBody.Msg = resBody.Msg;
  494. // CommonUtil.RequestTaskList(ccsRequestBody);
  495. #endregion
  496. }
  497. #region 移动
  498. //移动
  499. if (parentKey.ToUpper().Equals("MOVEMATERIAL") && parentNode.Title.Contains("柔性线") && ccsRequestBody.Data != null)
  500. {
  501. int v = ccsRequestBody.Data.ObjectToInt();
  502. short pintindex = s7.DeviceRead<short>("DB200.40");
  503. var cc = DeviceConfig.Instance.PointDefaultList.Where(m => m.Train_Index.Equals(pintindex)).FirstOrDefault();
  504. //if (cc.Point.Where(m => m.Equals(ccsRequestBody.Data.ObjectToShort())).Count() == 0)
  505. //{
  506. s7.DeviceSend("DB200.48", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType);
  507. System.Threading.Thread.Sleep(500);
  508. s7.DeviceSend(parentNode.Address, parentNode.Value, parentNode.ReadType);
  509. //}
  510. //response(ccsRequestBody, Constants.RET_SUCCESS_CODE, Constants.OPERATE_SUCCESS_MSG);
  511. }
  512. #endregion
  513. #region 清洗剂操作
  514. if (parentKey.ToUpper().Equals("CLEAN"))
  515. {
  516. //if (s7.DeviceRead<bool>("DB300.0.7"))
  517. // {
  518. // s7.DeviceSend("DB300.1.2", true);
  519. s7.DeviceSend("DB300.1.2", true, "2");
  520. System.Threading.Thread.Sleep(500);
  521. s7.DeviceSend("DB300.1.0", true, "2");
  522. //s7.DeviceSend("DB300.1.0", true);
  523. System.Threading.Thread.Sleep(1000);
  524. s7.DeviceSend("DB300.1.0", false, "2");
  525. System.Threading.Thread.Sleep(1000);
  526. //s7.DeviceSend("DB300.1.0", false);
  527. // response(ccsRequestBody, Constants.RET_SUCCESS_CODE, Constants.OPERATE_SUCCESS_MSG);
  528. }
  529. #endregion
  530. #region 三坐标处理
  531. if (parentKey.ToUpper().Equals("TESTWORK"))
  532. {
  533. TestWorkData testWorkData = Newtonsoft.Json.JsonConvert.DeserializeObject<TestWorkData>(ccsRequestBody.Data.ToString());
  534. if (testWorkData != null)
  535. {
  536. var te = testWorkData.WorkId.ReturnBtyesWtitString(40);
  537. device.DeviceSend("DB200.52", testWorkData.WorkId.ReturnBtyesWtitString(40));
  538. System.Threading.Thread.Sleep(1100);
  539. device.DeviceSend("DB200.92", testWorkData.WorkType.ReturnBtyesWtitString(20));
  540. System.Threading.Thread.Sleep(1000);
  541. short mc = 1;
  542. device.DeviceSend("DB200.34", mc);
  543. System.Threading.Thread.Sleep(1000);
  544. mc = 0;
  545. device.DeviceSend("DB200.34", mc);
  546. }
  547. }
  548. #endregion
  549. #region 打标
  550. if (parentKey.ToUpper().Equals("PRINT"))
  551. {
  552. try
  553. {
  554. DeviceList devicesocket = DeviceManage.Instance.deviceList.Where(m => m.Key.Equals("192.168.170.76:8074")).FirstOrDefault().Value;
  555. devicesocket.DeviceSend(ccsRequestBody.Data);
  556. short mc = 1;
  557. mc = 0;
  558. device.DeviceSend("DB200.24", mc);
  559. System.Threading.Thread.Sleep(1000);
  560. mc = 1;
  561. s7.DeviceSend("DB200.28", mc, "1");
  562. System.Threading.Thread.Sleep(1000);
  563. mc = 0;
  564. //s7.DeviceSend("DB200.28", mc);
  565. s7.DeviceSend("DB200.28", mc, "1");
  566. }
  567. catch (Exception ex)
  568. {
  569. YG.Log.Instance.WriteLogAdd($"498-->{ex.Message}");
  570. //response(ccsRequestBody, Constants.RET_CONDITUIN_CHECK_FAILURE_CODE, Constants.CONDITUIN_CHECK_FAILURE_MSG);
  571. YG.Log.Instance.WriteLogAdd($"{ex.Message}");
  572. }
  573. }
  574. #endregion
  575. #region RFID读写
  576. if (parentKey.ToUpper().Equals("RFIDREAD"))
  577. {
  578. try
  579. {
  580. //List<RfidDefaultList> testWorkData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RfidDefaultList>>(ccsRequestBody.Data.ToString());
  581. //var te = ccsRequestBody.Data.ToString().ReturnBtyesWtitString(256);
  582. ////device.DeviceSend("DB200.938", testWorkData.WorkId.ReturnBtyesWtitString(40));
  583. ////System.Threading.Thread.Sleep(1100);
  584. ////device.DeviceSend("DB200.92", testWorkData.WorkType.ReturnBtyesWtitString(20));
  585. //short mc = 1;
  586. //device.DeviceSend("DB200.112", mc);
  587. //System.Threading.Thread.Sleep(1000);
  588. //mc = 0;
  589. //device.DeviceSend("DB200.112", mc);
  590. //string rfidvalue = s7.DeviceRead("DB200.116.0", "5", 256);
  591. ccsRequestBody.IsCallBackFlag = 0;
  592. resBody.Data = DeviceRfid.Instance.DeviceRead($"{ccsRequestBody.Url}:{ccsRequestBody.Port}").Json_SerializeObject();
  593. YG.Log.Instance.WriteLogAdd($"RFIDREAD-->{resBody.Json_SerializeObject()}");
  594. }
  595. catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"549--->{ex.Message}"); }
  596. }
  597. if (parentKey.ToUpper().Equals("RFIDWRITE"))
  598. {
  599. try
  600. {
  601. List<RfidDefaultList> testWorkData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RfidDefaultList>>(ccsRequestBody.Data.ToString());
  602. ////TestWorkData testWorkData = Newtonsoft.Json.JsonConvert.DeserializeObject<TestWorkData>(ccsRequestBody.Data.ToString());
  603. //device.DeviceSend("DB200.372.0", ccsRequestBody.Data.ToString().ReturnBtyesWtitString(256));
  604. //short mc = 1;
  605. //device.DeviceSend("DB200.114", mc);
  606. //System.Threading.Thread.Sleep(1000);
  607. //mc = 0;
  608. //device.DeviceSend("DB200.114", mc);
  609. //YG.Log.Instance.WriteLogAdd($"RFIDWRITE-->");
  610. ccsRequestBody.IsCallBackFlag = 0;
  611. resBody.Data = "RFID写入结果->" + DeviceRfid.Instance.DeviceSend(testWorkData, $"{ccsRequestBody.Url}:{ccsRequestBody.Port}").Json_SerializeObject();
  612. YG.Log.Instance.WriteLogAdd($"RFIDREAD-->{resBody.Json_SerializeObject()}");
  613. }
  614. catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"567--->{ex.Message}"); }
  615. }
  616. #endregion
  617. }
  618. }
  619. catch (Exception ex)
  620. {
  621. YG.Log.Instance.WriteLogAdd($"508-->{ex.Message}");
  622. resBody.Code = Constants.RET_FAILURE_CODE;
  623. resBody.Msg = ex.Message;
  624. return resBody;
  625. }
  626. resBody.Code = Constants.RET_SUCCESS_CODE;
  627. resBody.Msg = Constants.OPERATE_SUCCESS_MSG;
  628. return resBody;
  629. }
  630. public ResponseBody CheckCondition(string parentKey, DeviceList device, bool isAsk)
  631. {
  632. ResponseBody resBody = ResponseBody.newObject();
  633. List<Node> list = CommonUtil.GetTargetList(device.ServerUrl, parentKey);
  634. if (list.Count == 0)
  635. {
  636. resBody.Code = Constants.RET_CONDITUIN_CHECK_SUCCESS_CODE;
  637. resBody.Msg = Constants.CONDITUIN_CHECK_SUCCESS_MSG;
  638. return resBody;
  639. }
  640. try
  641. {
  642. if (device.Dtype.Equals(DeviceType.OPCUa))
  643. {
  644. DeviceOPCUat opcua = (DeviceOPCUat)device;
  645. List<string> nodeIdStrings = new List<string>();
  646. foreach (Node nd in list)
  647. {
  648. nodeIdStrings.Add(nd.Address);
  649. }
  650. List<string> retValueList = opcua.OpcUa_Read(nodeIdStrings);
  651. //比较目标值是否一致
  652. for (int i = 0; i < list.Count; i++)
  653. {
  654. Node cNode = list[i];
  655. if (!retValueList[i].Equals(cNode.TargetValue))
  656. {
  657. Node parentNode = CommonUtil.GetTargetNode(device.ServerUrl, parentKey);
  658. resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE;
  659. resBody.Msg = cNode.Title + "状态不符合" + parentNode.Title + "条件。";
  660. break;
  661. }
  662. }
  663. }
  664. else if (device.Dtype.Equals(DeviceType.PLC_S7))
  665. {
  666. DeviceS7 s7 = (DeviceS7)device;
  667. foreach (Node nd in list)
  668. {
  669. string respvalue = "";
  670. if (nd == null || nd.Address.StringIsEmpty())
  671. {
  672. Log.Instance.WriteLogAdd($"593-->为空->{s7.DeviceName}");
  673. }
  674. respvalue = s7.DeviceRead(nd.Address.Trim(), nd.ReadType);
  675. int itemnumber = nd.TargetValue.StringToInt();
  676. if (itemnumber < 0)
  677. {
  678. if (respvalue.Equals(Math.Abs(itemnumber).ToString()))
  679. {
  680. Node parentNode = CommonUtil.GetTargetNode(device.ServerUrl, parentKey);
  681. resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE;
  682. resBody.Msg = nd.Title + "状态不符合" + parentNode.Title + "条件。";
  683. break;
  684. }
  685. }
  686. else if (!respvalue.Equals(nd.TargetValue))
  687. {
  688. Node parentNode = CommonUtil.GetTargetNode(device.ServerUrl, parentKey);
  689. resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE;
  690. resBody.Msg = nd.Title + "状态不符合" + parentNode.Title + "条件。";
  691. break;
  692. }
  693. }
  694. }
  695. }
  696. catch (Exception ex)
  697. {
  698. YG.Log.Instance.WriteLogAdd($"582-->{ex.Message}");
  699. resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE;
  700. resBody.Msg = ex.Message;
  701. return resBody;
  702. }
  703. if (resBody.Code == 1)
  704. {
  705. resBody.Code = Constants.RET_CONDITUIN_CHECK_SUCCESS_CODE;
  706. resBody.Msg = Constants.CONDITUIN_CHECK_SUCCESS_MSG;
  707. }
  708. return resBody;
  709. }
  710. private string OperAsk(Node parentNode, ModbusClient server, int times)
  711. {
  712. string ret = RETVAL;
  713. bool isContinue = true;
  714. for (int n = 0; n < times; n++)
  715. {
  716. if (parentNode != null)
  717. {
  718. string[] adresses = (parentNode.Address).Split(util.CommonUtil.SEPLIT_CHAR);
  719. string[] targetValues = (parentNode.TargetValue).Split(util.CommonUtil.SEPLIT_CHAR);
  720. List<string> nodeIdStrings = new List<string>();
  721. //foreach (string row in adresses)
  722. //{
  723. // nodeIdStrings.Add(new NodeId(row, (ushort)2).ToString());
  724. //}
  725. //List<string> readValueList = server.ReadValues(nodeIdStrings);
  726. //for (int i = 0; i < readValueList.Count; i++)
  727. //{
  728. // if (targetValues[i].ToLower().Equals(readValueList[i].ToLower()))
  729. // {
  730. // //ret = parentNode.Title + "当前已是操作状态,无需重复操作。";
  731. // isContinue = false;
  732. // break;
  733. // }
  734. //}
  735. }
  736. Thread.Sleep(1000 * 5);
  737. if (!isContinue)
  738. {
  739. break;
  740. }
  741. }
  742. return ret;
  743. }
  744. //采集信息
  745. public bool GetDeviceCollectData()
  746. {
  747. foreach (ConnectDeviceBody body in DeviceManage.Instance.GetConnectDeviceList())
  748. {
  749. try
  750. {
  751. DeviceList device = DeviceManage.Instance.GetOne(body.ServerUrl);
  752. //read组的配置
  753. List<Node> readNodeList = CommonUtil.GetTargetList(device.ServerUrl, "read");
  754. CollectDataBody deviceRedisState = new CollectDataBody();
  755. //根据配置里边的read组配置, 把读到的值放到这个里边
  756. List<string> readNodeValueStrings = new List<string>();
  757. if (device.Dtype.Equals(DeviceType.OPCUa))
  758. {
  759. try
  760. {
  761. DeviceOPCUat opcua = (DeviceOPCUat)device;
  762. //read组配置的地址列表
  763. List<string> readNodeAddressStrings = new List<string>();
  764. foreach (Node nd in readNodeList)
  765. {
  766. readNodeAddressStrings.Add(nd.Address);
  767. }
  768. Thread.Sleep(20);
  769. readNodeValueStrings = opcua.OpcUa_Read(readNodeAddressStrings);
  770. }
  771. catch (Exception exxx) { YG.Log.Instance.WriteLogAdd($"692-->{exxx.Message}"); }
  772. }
  773. else if (device.Dtype.Equals(DeviceType.PLC_S7))
  774. {
  775. DeviceS7 s7 = (DeviceS7)device;
  776. try
  777. {
  778. foreach (Node nd in readNodeList)
  779. {
  780. if (nd == null || nd.Address.StringIsEmpty())
  781. {
  782. Log.Instance.WriteLogAdd($"709-->为空->{s7.DeviceName}");
  783. }
  784. readNodeValueStrings.Add(s7.DeviceRead(nd.Address, nd.ReadType));
  785. Thread.Sleep(20);
  786. }
  787. }
  788. catch (Exception exxx) { YG.Log.Instance.WriteLogAdd($"706-->{exxx.Message}"); }
  789. }
  790. //将结果值赋给节点
  791. for (int i = 0; i < readNodeList.Count; i++)
  792. {
  793. try
  794. {
  795. if (readNodeValueStrings.Count > 0)
  796. {
  797. Node readValNode = readNodeList[i];
  798. readValNode.Value = readNodeValueStrings[i];
  799. }
  800. }
  801. catch (Exception exxx) { YG.Log.Instance.WriteLogAdd($"719-->{exxx.Message}"); }
  802. }
  803. //反射赋值
  804. Type t = deviceRedisState.GetType();
  805. foreach (PropertyInfo pi in t.GetProperties())
  806. {
  807. try
  808. {
  809. string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
  810. if (pi.Name.Equals("AllowFetchMaterial"))
  811. {
  812. }
  813. foreach (Node nd in readNodeList)
  814. {
  815. if (nd.Key == name)
  816. {
  817. if (nd.IsBinary)
  818. {
  819. //处理二进制值,赋给对象
  820. pi.SetValue(deviceRedisState, CommonUtil.GetBinaryBit(Convert.ToInt32(nd.Value), nd.StartPos, nd.EndPos), null);
  821. }
  822. else
  823. {//主程序取名称
  824. if (name == "MainProgNo" && !string.IsNullOrEmpty(nd.Value))
  825. {
  826. string[] mainProgNoArray = nd.Value.Split('/');
  827. string mainProgNo = mainProgNoArray[mainProgNoArray.Length - 1];
  828. mainProgNo = mainProgNo.StartsWith("_") ? mainProgNo.Substring(1, mainProgNo.Length - 1) : mainProgNo;
  829. pi.SetValue(deviceRedisState, mainProgNo, null);
  830. }
  831. else if (name == "SpActSpeed" && !string.IsNullOrEmpty(nd.Value))
  832. {
  833. pi.SetValue(deviceRedisState, (Convert.ToInt32(Convert.ToDouble(nd.Value)) + ""), null);
  834. }
  835. else
  836. {
  837. pi.SetValue(deviceRedisState, nd.Value, null);//给对象赋值
  838. }
  839. }
  840. }
  841. }
  842. }
  843. catch (Exception exx)
  844. {
  845. YG.Log.Instance.WriteLogAdd($"764-->{exx.Message}");
  846. }
  847. }
  848. try
  849. {
  850. deviceRedisState.NowDate = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
  851. string jsonData = JsonConvert.SerializeObject(deviceRedisState);
  852. ServiceStackRedisHelper.SetValue(device.ServerUrl, jsonData.ToString());
  853. }
  854. catch (Exception exs)
  855. {
  856. YG.Log.Instance.WriteLogAdd($"916------>>{exs.Message}");
  857. }
  858. //回调请求 每隔5秒调一次
  859. int currentSencond = DateTime.Now.Second;
  860. // if (currentSencond % 3 == 0)
  861. {
  862. try
  863. {
  864. CommonUtil.CallBackRequest(device);
  865. }
  866. catch(Exception exs)
  867. {
  868. YG.Log.Instance.WriteLogAdd($"922------>>{exs.Message}");
  869. }
  870. }
  871. }
  872. catch (Exception ex)
  873. {
  874. YG.Log.Instance.WriteLogAdd($"776-->{ex.Message}");
  875. return false;
  876. }
  877. }
  878. return true;
  879. }
  880. }
  881. public class Servlet
  882. {
  883. public virtual void onGet(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response, string info) { }
  884. public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }
  885. public virtual void onCreate()
  886. {
  887. }
  888. }
  889. public class MyServlet : Servlet
  890. {
  891. public override void onCreate()
  892. {
  893. base.onCreate();
  894. }
  895. public override void onGet(HttpListenerRequest request, HttpListenerResponse response, string info)
  896. {
  897. byte[] buffer = Encoding.UTF8.GetBytes(info);
  898. System.IO.Stream output = response.OutputStream;
  899. output.Write(buffer, 0, buffer.Length);
  900. output.Close();
  901. }
  902. public override void onPost(HttpListenerRequest request, HttpListenerResponse response)
  903. {
  904. Console.WriteLine("POST:" + request.Url);
  905. byte[] res = Encoding.UTF8.GetBytes("OK");
  906. response.OutputStream.Write(res, 0, res.Length);
  907. }
  908. }
  909. }