|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370 |
- //#define Debug
- extern alias aliyun;
- using BPA.Helper;
- using BPASmartClient.CustomResource.Pages.Model;
- using BPASmartClient.CustomResource.UserControls;
- using BPASmartClient.CustomResource.UserControls.MessageShow;
- using BPASmartClient.DosingSystem.ViewModel;
- using BPASmartClient.Model;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.ObjectModel;
- using System.Collections.Specialized;
- using System.Diagnostics;
- using System.Linq;
- using System.Threading;
- using System.Threading.Tasks;
- using aliyun.uPLibrary.Networking.M2Mqtt.Messages;
- using System.Collections.Generic;
- using aliyun::BPA.PahoMQ;
- using System.Configuration;
- using BPA.Communication;
- using Newtonsoft.Json;
- using System.Reflection;
- using System.Text;
- using BPASmartClient.DosingSystem.Model;
- using Microsoft.EntityFrameworkCore.Metadata.Internal;
- using System.Collections;
- using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
- using System.Windows.Navigation;
- using System.Text.RegularExpressions;
- using static System.Resources.ResXFileRef;
- using BPASmartClient.DosingSystem.Model.Dto;
- using BPASmartClient.DosingSystem.Model.MQTT;
-
- namespace BPASmartClient.DosingSystem
- {
- /// <summary>
- /// 业务逻辑执行类
- /// </summary>
- public class ExcuteControl
- {
- private static ExcuteControl Instance;
- public static ExcuteControl GetInstance => Instance ??= new ExcuteControl();
-
- public ConcurrentDictionary<string, aliyun.BPA.PahoMQ.MessageHandler> mqttCollection = new ConcurrentDictionary<string, aliyun.BPA.PahoMQ.MessageHandler>();
-
- public ConcurrentDictionary<string, string> aliyun = new ConcurrentDictionary<string, string>();
- public ObservableCollection<RecipeModel> Recipes { get; set; } = Json<LocalRecipe>.Data.Recipes;
- public ObservableCollection<StockStatusModel> StockStatus = new ObservableCollection<StockStatusModel>();
-
- public string CurrentRecipeName { get; set; }
- /// <summary>
- /// 当前正在制作的配方
- /// </summary>
- public ObservableCollection<RecipeModel> recipeProcesses { get; set; } = new ObservableCollection<RecipeModel>();
-
- /// <summary>
- /// 等待制作的配方
- /// </summary>
- public ObservableCollection<RecipeModel> UserTreeWait { get; set; } = new ObservableCollection<RecipeModel>();
-
- /// <summary>
- /// 已完成的配方
- /// </summary>
- public ObservableCollection<RecipeModel> UserTreeCompelete { get; set; } = new ObservableCollection<RecipeModel>();
- public ConcurrentQueue<string> RecipeNames = new ConcurrentQueue<string>();
- /// <summary>
- /// 配料完成计数
- /// </summary>
- int Comcount = 0;
- public static bool PropertySet = false;//云端属性设置回调主题订阅标志
- public static bool PropertyReport = false; //属性上报主题订阅标志
-
- public static bool EventReport = false; //事件上报主题订阅标志
-
- public static bool ServiceCall = false;//服务调用回调主题订阅标志
-
- public NameValueCollection produtInfo;
- public NameValueCollection mqttInfo;
- public NameValueCollection ConveyerInfo;
- public NameValueCollection ServicesInfo;
-
- public bool AliyunIsConnect = false;
- public ExcuteControl()
- {
- ActionManage.GetInstance.Register<object>(new Action<object>((o) =>
- {
- if (o != null && o is string recipeName)
- {
- RecipeSend(recipeName);
- }
-
- }), "配方下发");
- ActionManage.GetInstance.Register<object>(new Action<object>((ob) =>
- {
- if (ob != null && ob is string recipeName)
- {
- CancelRecipe(recipeName);
- }
-
- }), "取消配方");
-
- AliYunInit();
- RecipeRun();
- BusinessExcute();
- ConveyerPropertyReport();
- ThreadTaskInit();
- #if Debug
- Task.Run(() => {
- while (true)
- {
- if (AliyunIsConnect)
- {
- for (int i = 0; i < 6; i++)
- {
- AliyunEventReport($"192.168.0.{i+1}0", new AliyunStockEventReportModel { Result = "1" }, "StockJerk1StatusEvent", AliyunMaterialModelType.StockModel);
- AliyunEventReport($"192.168.0.{i + 1}0", new AliyunStockEventReportModel { Result = "1" }, "StockServoFalutEvent", AliyunMaterialModelType.StockModel);
- AliyunEventReport($"192.168.0.{i + 1}0", new AliyunStockEventReportModel { Result = "1" }, "StockJerk2StatusEvent", AliyunMaterialModelType.StockModel);
- AliyunEventReport($"192.168.0.{i + 1}0", new AliyunStockEventReportModel { Result = "1" }, "StockUpLimitEvent", AliyunMaterialModelType.StockModel);
- AliyunEventReport($"192.168.0.{i + 1}0", new AliyunStockEventReportModel { Result = "1" }, "StockDownLimitEvent", AliyunMaterialModelType.StockModel);
-
- AliyunStockPropertyReportModel model = new AliyunStockPropertyReportModel();
- model.StockRealWeight = 1;
- model.BucketRealWeight = 2;
- model.StockDeviceNum = 2;
- model.StockDeviceName = "测试";
- model.StockWorkModel = 0;
- model.StockSlowlyAddWeight = 6;
- model.StockPreCloseValueWeight = 7;
- model.StockRapidAcceleration = 46;
- model.StockSlowAcceleration = 24;
- model.StockServoManualSpeed = 35;
- model.StockUpperLimitWeight = 57;
- model.StockLowerLimitWeight = 34;
- model.StockStirringSpeed = 54;
- model.StockMaterialType = "粉体";
- model.StockBatchStatus = "待机";
- StokcPropertyReport($"192.168.0.{i + 1}0", model);
- }
- AliyunConveyerPropertyReportModel model1 = new AliyunConveyerPropertyReportModel();
- model1.TopBucketControlStatus = 1;
- model1.DownBucketControlStatus =1;
- model1.RunStatus = 1;
- model1.WorkModel = 1;
- model1.TopBucketSigleCheck = 1;
- model1.ButtonBucketSigleCheck = 1;
- model1.ConveyerOnlineStatus =1;
- var mqdeviceTestProperty = new PostPropertyParams<AliyunConveyerPropertyReportModel>();
- mqdeviceTestProperty.sys = new Sys { ack = 1 };
- mqdeviceTestProperty.method = "thing.event.property.post";
- mqdeviceTestProperty.version = "1.0";
- mqdeviceTestProperty.ModelName = $"{produtInfo.Get("Conveyer")}";
- mqdeviceTestProperty.Model = model1;
- mqdeviceTestProperty.Init();
- var message = JsonConvert.SerializeObject(mqdeviceTestProperty);
- var topic = $"/sys/{produtInfo.Get("ProductKey")}/Conveyer/thing/event/property/post";//发布主题
-
- var topicReply = $"/sys/{produtInfo.Get("ProductKey")}/Conveyer/thing/event/property/post_reply";//订阅主题
- if (mqttCollection.ContainsKey("Conveyer"))
- {
- try
- {
- mqttCollection["Conveyer"].Publish((op) =>
- {
- op.Message = message;
- op.Topic = topic;
- op.TopicReply = topicReply;
- //if (!PropertyReport)
- //{
- // op.ThresholdCallback += MqttPostProperty_MqttMsgPublishReceived; // MqttPostProperty_MqttMsgPublishReceived;
- // PropertyReport = true;
- //}
- });
- }
- catch (Exception)
- {
-
- //throw;
- }
- }
- SystemEventReport("ProcessRecipe", new { RecipeName = "测试5" });//正在执行配方上报
- if (UserTreeWait.Count > 0)
- {
- string[] recipeNames = new string[UserTreeWait.Count];
- for (int i = 0; i < recipeNames.Length; i++)
- {
- recipeNames[i] = UserTreeWait.ElementAt(i).RecipeName;
- }
- SystemEventReport("WaitProcessRecipe", new { RecipeNames = recipeNames });//等待执行配方上报
- }
- else
- {
- SystemEventReport("WaitProcessRecipe", new { RecipeNames = new string[] { } });//等待执行配方上报
- }
- }
- Thread.Sleep(5000);
- }
- });
- #endif
-
- }
- /// <summary>
- /// 阿里云连接检查
- /// </summary>
- private void AliyunMqConnectCheck()
- {
-
- }
-
- public void MqttDisConnect()
- {
- ThreadManage.GetInstance.Dispose();
- foreach (var item in mqttCollection)
- {
- item.Value._mqttClient?.Disconnect();
- }
- }
- /// <summary>
- /// 连接阿里云Iot物联网平台
- /// </summary>
- /// <exception cref="NotImplementedException"></exception>
- private async void AliYunInit()
- {
-
- produtInfo = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("FlexBatchSystem/ProductInfo");
- mqttInfo = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("FlexBatchSystem/MqttInfo");
- ConveyerInfo = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("FlexBatchSystem/ConveyerInfo");
- ServicesInfo = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("FlexBatchSystem/Services");
- int count = Json<DevicePar>.Data.BaseParModel.StockCount;//料仓数
-
- #region 料仓连接阿里云
- for (int i = 0; i < count; i++)
- {
- if (!mqttCollection.ContainsKey($"Stock{i + 1}")) //创建料仓设备mqtt连接
- {
- await Task.Run(() =>
- {
- try
- {
- int num = i + 1;
- NameValueCollection StockInfo = ((NameValueCollection)System.Configuration.ConfigurationManager.GetSection($"FlexBatchSystem/StockInfo{num}"));
-
- var mes = new aliyun.BPA.PahoMQ.MessageHandler(new aliyun.BPA.PahoMQ.PahoMQOption()
- {
- Broker = mqttInfo.Get("mqttHostUrl"),
- ProductKey = produtInfo.Get("ProductKey"),
- DeviceName = StockInfo.Get("DeviceName"),
- DeviceSecret = StockInfo.Get("DeviceSecret"),
- Port = 1883
- });
- if (mes._mqttClient.IsConnected)
- {
- MessageLog.GetInstance.Show($"阿里云--料仓{num}设备激活成功!");
- }
- else
- {
- MessageLog.GetInstance.Show($"阿里云--料仓{num}设备激活失败!");
- return;
- }
-
- mes.Subscribe((op) =>
- {
- op.TopicReply = $"/sys/{produtInfo.Get("ProductKey")}/{StockInfo.Get("DeviceName")}/thing/service/property/set";
- //if (!PropertySet)
- //{
- op.ThresholdCallback += StockPropertySetCallback;
- PropertyReport = true;
- //}
- });
- MessageLog.GetInstance.Show($"阿里云--料仓{num}设备属性设置订阅成功!");
- mqttCollection.TryAdd($"Stock{i + 1}", mes);
- if (!aliyun.ContainsKey($"{Json<DevicePar>.Data.BaseParModel.NetworkSegAddress}{i + 1}0"))
- {
- aliyun.TryAdd($"{Json<DevicePar>.Data.BaseParModel.NetworkSegAddress}{i + 1}0", $"Stock{i + 1}");
- }
- }
- catch (Exception)
- {
- MessageLog.GetInstance.Show($"阿里云--料仓{i}设备激活失败!");
- return;
- }
-
- });
- }
- }
- #endregion
-
- #region 输送线连接阿里云
- if (!mqttCollection.ContainsKey($"Conveyer"))//创建输送线Mqtt连接
- {
- await Task.Run(() =>
- {
- try
- {
- var res = new aliyun.BPA.PahoMQ.MessageHandler(new aliyun.BPA.PahoMQ.PahoMQOption()
- {
- Broker = mqttInfo.Get("mqttHostUrl"),
- ProductKey = produtInfo.Get("ProductKey"),
- DeviceName = ConveyerInfo.Get("DeviceName"),
- DeviceSecret = ConveyerInfo.Get("DeviceSecret"),
- Port = 1883
- });
- if (res._mqttClient.IsConnected)
- {
- MessageLog.GetInstance.Show($"阿里云--输送线设备激活成功!");
- }
- else
- {
- MessageLog.GetInstance.Show($"阿里云--输送线设备激活失败!");
- return;
- }
- //属性订阅
- res.Subscribe((op) =>
- {
- op.TopicReply = $"/sys/{produtInfo.Get("ProductKey")}/{ConveyerInfo.Get("DeviceName")}/thing/service/property/set";
- //if (!PropertySet)
- //{
- op.ThresholdCallback += ConveyerPropertySetCallback;
- PropertyReport = true;
- // }
- });
- MessageLog.GetInstance.Show($"阿里云---输送线设备属性设置订阅成功!");
- //服务订阅
- for (int j = 0; j < ServicesInfo.AllKeys.Length; j++)
- {
- res.Subscribe((op) =>
- {
- op.TopicReply = $"/sys/{produtInfo.Get("ProductKey")}/{ConveyerInfo.Get("DeviceName")}/thing/service/{ServicesInfo.Get(j)}";
- if (!ServiceCall)
- {
- op.ThresholdCallback += ServiceCallback;
- ServiceCall = true;
- }
- });
- MessageLog.GetInstance.Show($"阿里云--服务'{ServicesInfo.Get(j)}'订阅成功!");
- }
- mqttCollection.TryAdd($"Conveyer", res);
-
- }
- catch (Exception)
- {
- MessageLog.GetInstance.Show($"阿里云--输送线设备激活失败!");
- return;
- }
- });
-
- }
- if (mqttCollection.ContainsKey("Conveyer")&& mqttCollection["Conveyer"]._mqttClient.IsConnected)
- {
-
- AliyunSystemPropertyReportModel m1 = new AliyunSystemPropertyReportModel();
- m1.RecipeCollection = new string[Json<LocalRecipe>.Data.Recipes.Count];
- for (int i = 0; i < Json<LocalRecipe>.Data.Recipes.Count; i++)
- {
- m1.RecipeCollection[i] = Json<LocalRecipe>.Data.Recipes[i].RecipeName;
- }
- SystemPropertyReport(m1);
- }
- #endregion
-
- }
-
-
- /// <summary>
- /// 料仓属性上报
- /// </summary>
- /// <param name="ipaddres"></param>
- /// <param name="model"></param>
- public void StokcPropertyReport<T>(string ipaddres, T model)
- {
- var mqdeviceTestProperty = new PostPropertyParams<T>();
- mqdeviceTestProperty.sys = new Sys { ack = 1 };
- mqdeviceTestProperty.method = "thing.event.property.post";
- mqdeviceTestProperty.version = "1.0";
- mqdeviceTestProperty.ModelName = $"{produtInfo.Get("Stock")}";
- mqdeviceTestProperty.Model= model;
- mqdeviceTestProperty.Init();
- var message = JsonConvert.SerializeObject(mqdeviceTestProperty);
- var topic = $"/sys/{produtInfo.Get("ProductKey")}/{aliyun[ipaddres]}/thing/event/property/post";//发布主题
- var topicReply = $"/sys/{produtInfo.Get("ProductKey")}/{aliyun[ipaddres]}/thing/event/property/post_reply";//订阅主题
- if (mqttCollection.ContainsKey(aliyun[ipaddres]))
- {
- try
- {
- mqttCollection[aliyun[ipaddres]].Publish((op) =>
- {
- op.Message = message;
- op.Topic = topic;
- op.TopicReply = topicReply;
- //if (!PropertyReport)
- //{
- // op.ThresholdCallback += MqttPostProperty_MqttMsgPublishReceived; // MqttPostProperty_MqttMsgPublishReceived;
- // PropertyReport = true;
- //}
- });
- }
- catch (Exception)
- {
-
- //throw;
- }
- }
-
- }
-
-
- /// <summary>
- /// 料仓模板或输送线模板事件上报
- /// </summary>
- /// <param name="ipaddres"></param>
- /// <param name="model"></param>
- /// <param name="eventFlag"></param>
- public void AliyunEventReport<T>(string ipaddres, T model, string eventFlag, AliyunMaterialModelType type)
- {
- string eventIdentifier;
- string deviceName;
- MessageHandler messageHandler = null;
- if (type == AliyunMaterialModelType.StockModel)
- {
- eventIdentifier = $"{produtInfo.Get("Stock")}:{eventFlag}";//格式:模板名:事件名
- deviceName = aliyun[ipaddres];
- if (!mqttCollection.ContainsKey(aliyun[ipaddres]))
- return;
- messageHandler = mqttCollection[aliyun[ipaddres]];
- }
- else
- {
- eventIdentifier = $"{produtInfo.Get("Conveyer")}:{eventFlag}";
- deviceName = $"{ConveyerInfo.Get("DeviceName")}";
- if (!mqttCollection.ContainsKey("Conveyer"))
- return;
- messageHandler = mqttCollection["Conveyer"];
-
- }
-
- var mqdeviceTestEvent = new PostEventParams<T>();
- mqdeviceTestEvent.id = Guid.NewGuid().ToString();
- mqdeviceTestEvent.sys = new Sys { ack = 1 };
- mqdeviceTestEvent.method = $"thing.event.{eventIdentifier}.post";
- mqdeviceTestEvent.version = "1.0";
- mqdeviceTestEvent.@params = new EventParam<T> { value = model, time = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds() };
- var eventMessage = JsonConvert.SerializeObject(mqdeviceTestEvent);
- //事件上报
- var eventTopic = $"/sys/{produtInfo.Get("ProductKey")}/{deviceName}/thing/event/{eventIdentifier}/post";
- //事件订阅主题
- var eventTopicReply = $"/sys/{produtInfo.Get("ProductKey")}/{deviceName}/thing/event/{eventIdentifier}/post_reply";
-
- try
- {
- messageHandler.Publish((op) =>
- {
- op.Message = eventMessage;
- op.Topic = eventTopic;
- op.TopicReply = eventTopicReply;
- //if (!EventReport)
- //{
- // op.ThresholdCallback += MqttPostEvent_MqttMsgPublishReceived; // MqttPostProperty_MqttMsgPublishReceived;
- // EventReport = true;
- //}
- });
- }
- catch (Exception)
- {
-
- //throw;
- }
- }
- /// <summary>
- /// 输送线模板属性上报
- /// </summary>
- public void ConveyerPropertyReport()
- {
- TaskManage.GetInstance.StartLong(() =>
- {
- if (mqttCollection.ContainsKey("Conveyer") && mqttCollection["Conveyer"]._mqttClient.IsConnected)
- {
- AliyunConveyerPropertyReportModel model = new AliyunConveyerPropertyReportModel();
- model.TopBucketControlStatus = Convert.ToInt32(SiemensDevice.GetInstance.MySiemens.Read<bool>("DB5.DBX4.0").Content);
- model.DownBucketControlStatus = Convert.ToInt32(SiemensDevice.GetInstance.MySiemens.Read<bool>("DB5.DBX4.1").Content);
- model.RunStatus = Convert.ToInt32(SiemensDevice.GetInstance.MySiemens.Read<bool>("M10.0").Content);
- model.WorkModel = Convert.ToInt32(SiemensDevice.GetInstance.MySiemens.Read<bool>("M10.1").Content);
- model.TopBucketSigleCheck = Convert.ToInt32(GlobalDevice.PlcData.OnDetection);
- model.ButtonBucketSigleCheck = Convert.ToInt32(GlobalDevice.PlcData.UnderDetection);
- model.ConveyerOnlineStatus = Convert.ToInt32(SiemensDevice.GetInstance.MySiemens.IsConnected());
- var mqdeviceTestProperty = new PostPropertyParams<AliyunConveyerPropertyReportModel>();
- mqdeviceTestProperty.sys = new Sys { ack = 1 };
- mqdeviceTestProperty.method = "thing.event.property.post";
- mqdeviceTestProperty.version = "1.0";
- mqdeviceTestProperty.ModelName = $"{produtInfo.Get("Conveyer")}";
- mqdeviceTestProperty.Model = model;
- mqdeviceTestProperty.Init();
- var message = JsonConvert.SerializeObject(mqdeviceTestProperty);
- var topic = $"/sys/{produtInfo.Get("ProductKey")}/Conveyer/thing/event/property/post";//发布主题
-
- var topicReply = $"/sys/{produtInfo.Get("ProductKey")}/Conveyer/thing/event/property/post_reply";//订阅主题
- if (mqttCollection.ContainsKey("Conveyer"))
- {
- try
- {
- mqttCollection["Conveyer"].Publish((op) =>
- {
- op.Message = message;
- op.Topic = topic;
- op.TopicReply = topicReply;
- //if (!PropertyReport)
- //{
- // op.ThresholdCallback += MqttPostProperty_MqttMsgPublishReceived; // MqttPostProperty_MqttMsgPublishReceived;
- // PropertyReport = true;
- //}
- });
- }
- catch (Exception)
- {
-
- //throw;
- }
- }
- }
-
- Thread.Sleep(1000);
-
- }, "输送线属性上报", true);
-
-
- }
- /// <summary>
- /// 业务系统事件上报
- /// </summary>
- /// <param name="eventFlag"></param>
- /// <param name="param"></param>
- public void SystemEventReport<T>(string eventFlag, T t)
- {
- var eventIdentifier = eventFlag;
- var mqdeviceTestEvent = new PostEventParams<T>();
- mqdeviceTestEvent.id = Guid.NewGuid().ToString();
- mqdeviceTestEvent.sys = new Sys { ack = 1 };
- mqdeviceTestEvent.method = $"thing.event.{eventIdentifier}.post";
- mqdeviceTestEvent.version = "1.0";
- mqdeviceTestEvent.@params = new EventParam<T> { value = t, time = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds() };
- var eventMessage = JsonConvert.SerializeObject(mqdeviceTestEvent);
- //事件上报
- var eventTopic = $"/sys/{produtInfo.Get("ProductKey")}/Conveyer/thing/event/{eventIdentifier}/post";
- //事件订阅主题
- var eventTopicReply = $"/sys/{produtInfo.Get("ProductKey")}/Conveyer/thing/event/{eventIdentifier}/post_reply";
- if (mqttCollection.ContainsKey("Conveyer"))
- {
- try
- {
- mqttCollection["Conveyer"].Publish((op) =>
- {
- op.Message = eventMessage;
- op.Topic = eventTopic;
- op.TopicReply = eventTopicReply;
- //if (!EventReport)
- //{
- // op.ThresholdCallback += MqttPostEvent_MqttMsgPublishReceived; // MqttPostProperty_MqttMsgPublishReceived;
- // EventReport = true;
- //}
- });
- }
- catch (Exception)
- {
-
- // throw;
- }
-
- }
- }
-
- /// <summary>
- /// 业务系统属性上报
- /// </summary>
- public void SystemPropertyReport<T>(T model)
- {
- var mqdeviceTestProperty = new PostPropertyParams<T>();
- mqdeviceTestProperty.sys = new Sys { ack = 1 };
- mqdeviceTestProperty.method = "thing.event.property.post";
- mqdeviceTestProperty.version = "1.0";
- mqdeviceTestProperty.Model = model;
- mqdeviceTestProperty.Init();
- var message = JsonConvert.SerializeObject(mqdeviceTestProperty);
- var topic = $"/sys/{produtInfo.Get("ProductKey")}/Conveyer/thing/event/property/post";//发布主题
-
- var topicReply = $"/sys/{produtInfo.Get("ProductKey")}/Conveyer/thing/event/property/post_reply";//订阅主题
- if (mqttCollection.ContainsKey("Conveyer"))
- {
- try
- {
- mqttCollection["Conveyer"].Publish((op) =>
- {
- op.Message = message;
- op.Topic = topic;
- op.TopicReply = topicReply;
- //if (!PropertyReport)
- //{
- // op.ThresholdCallback += MqttPostProperty_MqttMsgPublishReceived; // MqttPostProperty_MqttMsgPublishReceived;
- // PropertyReport = true;
- //}
- });
- }
- catch (Exception)
- {
-
- //throw;
- }
- }
-
- }
- /// <summary>
- /// 云端属性设置回调方法-输送线模板
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- /// <exception cref="NotImplementedException"></exception>
- private void ConveyerPropertySetCallback(object sender, MqttMsgPublishEventArgs e)
- {
- if (Regex.IsMatch(e.Topic, "[0-9a-zA-Z/]*(thing/service/property/set)$"))
- {
- var rtn = JsonConvert.DeserializeObject<ServiceBaseResponse<object>>(Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
- PropertyInfo property = rtn.@params.GetType().GetProperty("Root");
- string result = property.GetValue(rtn.@params).ToString();
- var array = result.Replace("\r\n", "").Replace(" ", "").Replace("{", "").Replace("}", "").Replace("\"", "").Split(',');
- foreach (var item in array)
- {
- var str = item.Split(":"); //数据格式:
-
- if (str.Length >= 3)
- {
- switch (str[1])
- {
- case "TopBucketControlStatus": SiemensDevice.GetInstance.MySiemens.Write("DB5.DBX4.0", Convert.ToBoolean(int.Parse(str[2]))); MessageNotify.GetInstance.ShowRunLog($"云端控制上桶位气缸,状态值:{str[2]}"); break;
- case "DownBucketControlStatus": SiemensDevice.GetInstance.MySiemens.Write("DB5.DBX4.1", Convert.ToBoolean(int.Parse(str[2]))); MessageNotify.GetInstance.ShowRunLog($"云端控制下桶位气缸,状态值:{str[2]}"); break;
- }
- }
-
- }
- }
- }
-
-
-
- /// <summary>
- /// 云端属性设置回调方法-料仓模板
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public void StockPropertySetCallback(object sender, MqttMsgPublishEventArgs e)
- {
- if (Regex.IsMatch(e.Topic, "[0-9a-zA-Z/]*(thing/service/property/set)$"))
- {
- var rtn = JsonConvert.DeserializeObject<ServiceBaseResponse<object>>(Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
- PropertyInfo property = rtn.@params.GetType().GetProperty("Root");
- string result = property.GetValue(rtn.@params).ToString();
- var array = result.Replace("\r\n", "").Replace(" ", "").Replace("{", "").Replace("}", "").Replace("\"", "").Split(',');
- foreach (var item in array)
- {
- var str = item.Split(":"); //数据格式:
- string ip = $"{Json<DevicePar>.Data.BaseParModel.NetworkSegAddress}{e.Topic.Split('/')[3].Substring(e.Topic.Split('/')[3].Length - 1, 1)}0";
- switch (str[1])
- {
- case "StockSlowlyAddWeight": DeviceInquire.GetInstance.GetDevice(ip).modbusTcp.Write(DeviceAddress.SlowlyAddWeight.ToAdd(), float.Parse(str[2])); MessageNotify.GetInstance.ShowRunLog($"云端对料仓设备{ip}设置慢加重量:值:{str[2]}"); break;
- case "StockPreCloseValueWeight": DeviceInquire.GetInstance.GetDevice(ip).modbusTcp.Write(DeviceAddress.PreCloseValveWeight.ToAdd(), float.Parse(str[2])); MessageNotify.GetInstance.ShowRunLog($"云端对料仓设备{ip}设置提前关阀重量:值:{str[2]}"); break;
- case "StockRapidAcceleration": DeviceInquire.GetInstance.GetDevice(ip).modbusTcp.Write(DeviceAddress.RapidAcceleration.ToAdd(), uint.Parse(str[2])); MessageNotify.GetInstance.ShowRunLog($"云端对料仓设备{ip}设置快加速:值:{str[2]}"); break;
- case "StockSlowAcceleration": DeviceInquire.GetInstance.GetDevice(ip).modbusTcp.Write(DeviceAddress.SlowAcceleration.ToAdd(), uint.Parse(str[2])); MessageNotify.GetInstance.ShowRunLog($"云端对料仓设备{ip}设置慢慢重量:值:{str[2]}"); break;
- case "StockServoManualSpeed": DeviceInquire.GetInstance.GetDevice(ip).modbusTcp.Write(DeviceAddress.ServoManualSpeed.ToAdd(), uint.Parse(str[2])); MessageNotify.GetInstance.ShowRunLog($"云端对料仓设备{ip}设置伺服手动速度:值:{str[2]}"); break;
- case "StockUpperLimitWeight": DeviceInquire.GetInstance.GetDevice(ip).modbusTcp.Write(DeviceAddress.SiloUpperLimitWeight.ToAdd(), uint.Parse(str[2])); MessageNotify.GetInstance.ShowRunLog($"云端对料仓设备{ip}设置上限重量:值:{str[2]}"); break;
- case "StockLowerLimitWeight": DeviceInquire.GetInstance.GetDevice(ip).modbusTcp.Write(DeviceAddress.LowerLimitWeightOfSilo.ToAdd(), uint.Parse(str[2])); MessageNotify.GetInstance.ShowRunLog($"云端对料仓设备{ip}设置下限重量:值:{str[2]}"); break;
- case "StockStrringSpeed": DeviceInquire.GetInstance.GetDevice(ip).modbusTcp.Write(DeviceAddress.StirringSpeed.ToAdd(), uint.Parse(str[2])); MessageNotify.GetInstance.ShowRunLog($"云端对料仓设备{ip}设置搅拌速度:值:{str[2]}"); break;
- }
- }
- }
- }
-
-
- /// <summary>
- /// 云端服务调用回调方法
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- /// <exception cref="NotImplementedException"></exception>
- private void ServiceCallback(object sender, MqttMsgPublishEventArgs e)
- {
- if (Regex.IsMatch(e.Topic, "[0-9a-zA-Z/]*thing/service/[0-9a-zA-Z:]*$"))
- {
- var rtn = JsonConvert.DeserializeObject<ServiceBaseResponse<object>>(Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
- PropertyInfo property = rtn.@params.GetType().GetProperty("Root");
- string result = property.GetValue(rtn.@params).ToString();
- var array = result.Replace("\r\n", "").Replace(" ", "").Replace("{", "").Replace("}", "").Replace("\"", "").Split(',');
- //单一服务调用
- string res = e.Topic.Split("/")[e.Topic.Split("/").Length - 1];
- if (res.Contains(":")) //自定义模板
- {
- var arr = res.Split(":");
- switch (arr[0])
- {
- case "ConveyerModel":
- switch (arr[1])
- {
- case "RunControlService":
- if (array.Count() == 1)
- {
- SiemensDevice.GetInstance.MySiemens.Write("M10.0", Convert.ToBoolean(int.Parse(array[0].Split(":")[1])));//输送下启停控制
- MessageNotify.GetInstance.ShowRunLog($"云端对输送线进行启动控制,值:{array[0].Split(":")[1]}");
- }
- break;
- case "StockAirControlService":
- if (array.Count() == 2)
- {
- var info = array[0].Split(":");
- var info1 = array[1].Split(":");
- if (info[0].Equals("StockNum"))
- {
- var addRes = SiemensDevice.GetInstance.GetSiemensBitSingleAdd("DB5.DBX", int.Parse(info[1]));//输送线配料气杠控制
- SiemensDevice.GetInstance.MySiemens.Write(addRes, Convert.ToBoolean(int.Parse(info1[1])));
- MessageNotify.GetInstance.ShowRunLog($"云端对输送线配料{info[1]}气缸进行升降控制,值:{info1[1]}");
- }
- else
- {
- var addRes = SiemensDevice.GetInstance.GetSiemensBitSingleAdd("DB5.DBX", int.Parse(info1[1]));
- SiemensDevice.GetInstance.MySiemens.Write(addRes, Convert.ToBoolean(int.Parse(info[1])));
- MessageNotify.GetInstance.ShowRunLog($"云端对输送线配料{info[1]}气缸进行升降控制,值:{info[1]}");
- }
- }
-
- break;
- }
- break;
- case "StockModel": break;
- }
- }
- else //默认模板
- {
- switch (res)
- {
- case "RecipeSendService":
- var info = array[0].Split(":");
- RecipeSend(info[1]);
- MessageNotify.GetInstance.ShowRunLog($"云端下发配方:{info[1]}");
- break;
- case "CancelRecipeService":
- var info2 = array[0].Split(":");
- CancelRecipe(info2[1]);
- MessageNotify.GetInstance.ShowRunLog($"云端取消配方:{info2[1]}");
- break;
- }
-
-
- }
- }
- }
-
-
-
- /// <summary>
- /// 多线程接收工单配方数据。
- /// </summary>
- private void ThreadTaskInit()
- {
- TaskManage.GetInstance.StartLong(new Action(() =>
- {
- while (MqttServer.GetInstance.WorkOrders.Count > 0)
- {
- if (MqttServer.GetInstance.WorkOrders.TryDequeue(out WorkOrderPusht wod))
- {
- App.Current?.Dispatcher?.Invoke(new Action(() =>
- {
- //TODO:工单数据处理,直接新建配方。
- foreach (var recipe in wod.ProductList)
- {
- var tempRecipe = new RecipeModel();
- var tempMaterials = new ObservableCollection<RawMaterialModel>();
-
- if (Json<LocalRecipe>.Data.Recipes.Any(p => p.RecipCode == recipe.Id))
- {
- continue;
- }
- else
- {
- tempRecipe.RecipCode = recipe.Id;
- }
-
- tempRecipe.RecipeName = recipe.Name;
-
-
- foreach (var material in recipe.BOMEntryList)
- {
- tempMaterials.Add(new RawMaterialModel()
- {
- RawMaterialName = material.MaterialName,
- DeviceIp="",
- Loc=1,
- RawMaterialWeight=(uint)material.BomQty,
- RawMaterialSource=0,
- RawMaterialId=material.MaterialId,
- });
- }
- tempRecipe.RawMaterials = tempMaterials;
- Json<LocalRecipe>.Data.Recipes.Add(tempRecipe);
- }
- }));
- }
- }
- Thread.Sleep(500);
- }), "工单信息监听");
- }
-
-
-
-
- /// <summary>
- /// 取消配方
- /// </summary>
- /// <param name="RecipeName"></param>
- public async void CancelRecipe(string RecipeName)
- {
- if (RecipeName != null)
- {
- //var res = MessageNotify.GetInstance.ShowDialog($"是否取消配方 【{RecipeName}】制作", DialogType.Warning);
- //if (res)
- //{
- int index = Recipes.ToList().FindIndex(p => p.RecipeName == RecipeName);
- if (index >= 0 && index < Recipes.Count)
- {
- await Task.Factory.StartNew(new Action(() =>
- {
- Recipes.ElementAt(index).IsEnable = true;
- Json<LocalRecipe>.Data.Recipes.ElementAt(index).IsEnable = true;
- Recipes.ElementAt(index).Are.Set();
- App.Current.Dispatcher.Invoke(new Action(() => { recipeProcesses.Clear(); }));
- SiemensDevice.GetInstance.MySiemens.Write("M10.5", true);
- MessageNotify.GetInstance.ShowRunLog($"M10.5:true");
- Thread.Sleep(1000);
- SiemensDevice.GetInstance.MySiemens.Write("M10.5", false);
- MessageNotify.GetInstance.ShowRunLog($"M10.5:false");
- App.Current.Dispatcher.Invoke(() =>
- {
- NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, App.MainWindow, "提示", $"配方 [{RecipeName}] 取消成功");
- });
- MessageNotify.GetInstance.ShowUserLog($"取消配方制作 {RecipeName}");
- //取消成功
- }));
- }
- else
- {
- //取消失败
- }
- //}
- }
- else
- {
- MessageNotify.GetInstance.ShowUserLog($"配方 {RecipeName}取消失败");
- }
-
- }
- /// <summary>
- /// 配方下发
- /// </summary>
- public void RecipeSend(string RecipeName)
- {
- if (RecipeName != null)
- {
- int index = Array.FindIndex(Recipes.ToArray(), p => p.RecipeName == RecipeName);
- if (index >= 0 && index < Recipes.Count)
- {
- for (int i = 0; i < Recipes.ElementAt(index).RawMaterials.Count; i++)
- {
- if (Recipes.ElementAt(index).RawMaterials.ElementAt(i).RawMaterialSource == 1)
- {
- string ip = Recipes.ElementAt(index).RawMaterials.ElementAt(i).DeviceIp;
- var device = DeviceInquire.GetInstance.GetDevice(ip);
- if (ip == null && ip == "")
- {
- MessageNotify.GetInstance.ShowDialog($"原料 【{Recipes.ElementAt(index).RawMaterials.ElementAt(i).RawMaterialName}】配料系统无法配料,请人工配置此原料:原料{Recipes.ElementAt(index).RawMaterials.ElementAt(i).RawMaterialName},重量{Recipes.ElementAt(index).RawMaterials.ElementAt(i).RawMaterialWeight}", DialogType.Information);
- return;
- }
- if (!device.IsConnected)
- {
- MessageNotify.GetInstance.ShowDialog($"设备 【{device.DeviceName}】 未连接,不允许下发此配方", DialogType.Error);
- return;
- }
- }
-
- }
- Recipes.ElementAt(index).IsEnable = false;
- Json<LocalRecipe>.Data.Recipes.ElementAt(index).IsEnable = false;
- }
- MessageNotify.GetInstance.ShowUserLog($"下发工单 {Recipes.ElementAt(index).RecipeName}");
- RecipeNames.Enqueue(RecipeName);
-
- var res = Recipes.FirstOrDefault(p => p.RecipeName == RecipeName);
- App.Current.Dispatcher.Invoke(() => { UserTreeWait.Add(new RecipeModel { RecipStatus = "等待制作", SerialNum = UserTreeWait.Count + 1, RecipeName = RecipeName, RawMaterials = res.RawMaterials }); });
- }
- App.Current.Dispatcher.Invoke(() => { NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, App.MainWindow, "提示", $"配方下发成功!"); });
-
- }
- /// <summary>
- /// 配方业务执行
- /// </summary>
- private void RecipeRun()
- {
- TaskManage.GetInstance.StartLong(new Action(() =>
- {
- if (RecipeNames.Count > 0)
- {
- int index = Array.FindIndex(Recipes.ToArray(), p => p.RecipeName == RecipeNames.ElementAt(0));
- if (index >= 0 && index < Recipes.Count)
- {
- Recipes.ElementAt(index).Are.Reset();
- Recipes.ElementAt(index).IsEnable = false;
- StockStatus.Clear();
- App.Current.Dispatcher.Invoke(new Action(() =>
- {
- recipeProcesses.Clear();
- if (UserTreeWait.Count > 0) App.Current.Dispatcher.Invoke(() =>
- {
- UserTreeWait.RemoveAt(0);
- });
- }));
- CurrentRecipeName = Recipes.ElementAt(index).RecipeName;
- #region 执行配方以及等待执行配方上报
- SystemEventReport("ProcessRecipe", new { RecipeName = CurrentRecipeName });//正在执行配方上报
- if (UserTreeWait.Count > 0)
- {
- string[] recipeNames = new string[UserTreeWait.Count];
- for (int i = 0; i < recipeNames.Length; i++)
- {
- recipeNames[i] = UserTreeWait.ElementAt(i).RecipeName;
- }
- SystemEventReport("WaitProcessRecipe", new { RecipeNames = recipeNames });//等待执行配方上报
- }
- else
- {
- SystemEventReport("WaitProcessRecipe", new { RecipeNames=new string[] { } });//等待执行配方上报
- }
- #endregion
- #region 配方下发到PLC操作相关
- //配方数据写入到输送机
- var res = Json<LocalRecipe>.Data.Recipes.FirstOrDefault(p => p.RecipeName == CurrentRecipeName);
- List<int> BarrelNum = new List<int>();
- ConcurrentDictionary<string, int[]> values = new();
- if (res != null)
- {
- var tInfo = res.RawMaterials.GroupBy(p => p.Loc);//获取桶号信息
- if (tInfo != null)
- {
- for (int i = 0; i < tInfo.Count(); i++)
- {
- int data = 0;
- for (int m = 0; m < tInfo.ElementAt(i).Count(); m++)
- {
- var TempName = tInfo.ElementAt(i).ElementAt(m).RawMaterialName;
- var tempDevice = DeviceInquire.GetInstance.devices.FirstOrDefault(p => p.DeviceName == TempName);
- if (tempDevice != null)
- {
- /*data = data.SetBitValue((byte)tempDevice.DeviceNum, true);*/
- if (tempDevice.DeviceNum > 0)
- {
- // //int a = data.SetBitValue((byte)tInfo.ElementAt(i).ElementAt(m).Loc, true);
- // //byte[] test1 = a.ToBytes(BPA.Helper.DataFormat.BADC);
- // //int item = test1.ToInt();
- // int item = data.SetBitValue((byte)tInfo.ElementAt(i).ElementAt(m).Loc, true).ToBytes(BPA.Helper.DataFormat.BADC).ToInt();
- // int item1 = SiemensDevice.GetInstance.MySiemens.Read<int>($"DB4.DBD{2 + (tempDevice.DeviceNum - 1) * 4}").Content;
- ////prop1:
- // var RE = SiemensDevice.GetInstance.MySiemens.Write($"DB4.DBD{2 + (tempDevice.DeviceNum - 1) * 4}", item + item1);
- // //var values = SiemensDevice.GetInstance.MySiemens.Read<int>($"DB4.DBD{2 + (tempDevice.DeviceNum - 1) * 4}");
- // //if ((values != null && values.ToString() != (item + item1).ToString()) || values == null)
- // // goto prop1;
- // if (RE.IsSuccess)
- // MessageNotify.GetInstance.ShowRunLog($"下发配方DB4.DBD{2 + (tempDevice.DeviceNum - 1) * 4} :{(byte)tInfo.ElementAt(i).ElementAt(m).Loc}-{item + item1}-{(item + item1).ToBinString()}");
- // else
- // MessageNotify.GetInstance.ShowRunLog($"下发配方DB4.DBD{2 + (tempDevice.DeviceNum - 1) * 4} 失败");
-
-
-
- int item = data.SetBitValue((byte)tInfo.ElementAt(i).ElementAt(m).Loc, true).ToBytes(BPA.Helper.DataFormat.BADC).ToInt();
- string tempAdd = $"DB4.DBD{2 + (tempDevice.DeviceNum - 1) * 4}";
- if (!values.ContainsKey(tempAdd)) values.TryAdd(tempAdd, new int[2] { 0, 0 });
- values[tempAdd][0] = values[tempAdd][0] + item;
- values[tempAdd][1] = tInfo.ElementAt(i).ElementAt(m).Loc;
- }
- }
- if (tInfo.ElementAt(i).ElementAt(m).Loc > 0)
- {
- if (!BarrelNum.Contains(tInfo.ElementAt(i).ElementAt(m).Loc))
- {
- BarrelNum.Add(tInfo.ElementAt(i).ElementAt(m).Loc);
- }
- }
- }
- }
- }
- }
-
- values?.ToList().ForEach(x =>
- {
- SiemensDevice.GetInstance.MySiemens.Write(x.Key, x.Value[0]).OnSuccess(() =>
- {
- MessageNotify.GetInstance.ShowRunLog($"下发配方-{x.Key} :桶数:[{x.Value[1]}]-{x.Value[0].ToBinString()}");
- }).OnFail(s =>
- {
- MessageNotify.GetInstance.ShowRunLog($"下发配方-{x.Key} 失败");
- });
- });
-
-
- SiemensDevice.GetInstance.MySiemens.Write("DB4.DBD198", BarrelNum.Count);//配方使用桶数写入
-
- SiemensDevice.GetInstance.MySiemens.Write("DB4.DBX0.1", true);//配方执行启动
- Stopwatch sw = new Stopwatch();
- var recipe = Recipes.ElementAt(index);
- ObservableCollection<RawMaterialModel> RawMater = new ObservableCollection<RawMaterialModel>();
- foreach (var item in recipe.RawMaterials)
- {
- RawMater.Add(new RawMaterialModel()
- {
- RawMaterialName = item.RawMaterialName,
- DeviceIp = item.DeviceIp,
- DownLimtFeedback = item.DownLimtFeedback,
- Loc = item.Loc,
- RawMaterialId = item.RawMaterialId,
- RawMaterialSource = item.RawMaterialSource,
- RawMaterialType = item.RawMaterialType,
- RawMaterialWeight = item.RawMaterialWeight,
- RecipeStatus = item.RecipeStatus,
- SelectIndex = item.SelectIndex,
- Status = item.Status,
- UpLimtFeedback = item.UpLimtFeedback,
- UpLimtWeightFeedback = item.UpLimtWeightFeedback,
- WeightFeedback = item.WeightFeedback,
- });
- }
- App.Current.Dispatcher.Invoke(() =>
- {
- recipeProcesses.Add(new RecipeModel()
- {
- RawMaterials = RawMater,
- IsEnable = recipe.IsEnable,
- RecipeName = recipe.RecipeName,
- SerialNum = recipe.SerialNum,
- RecipCode = recipe.RecipCode,
- });
- });
- sw.Restart();
- while (true)
- {
- if (sw.ElapsedMilliseconds >= 3000 && !GlobalDevice.PlcData.ResComplete)
- {
- MessageNotify.GetInstance.ShowRunLog("获取配方下发反馈超时");
- break;
- }
- if (GlobalDevice.PlcData.ResComplete)
- {
- SiemensDevice.GetInstance.MySiemens.Write("DB3.DBX0.1", false);
- break;
- }
- Thread.Sleep(100);
- }
- #endregion
-
- Recipes.ElementAt(index).Are.WaitOne();//阻塞,直到当前配方完成
- RecipeNames.TryDequeue(out string deviceName);
- var recipeComple = Recipes.ElementAt(index);
- ObservableCollection<RawMaterialModel> RawMaterComple = new ObservableCollection<RawMaterialModel>();
- foreach (var item in recipeComple.RawMaterials)
- {
- RawMaterComple.Add(new RawMaterialModel()
- {
- RawMaterialName = item.RawMaterialName,
- DeviceIp = item.DeviceIp,
- DownLimtFeedback = item.DownLimtFeedback,
- Loc = item.Loc,
- RawMaterialId = item.RawMaterialId,
- RawMaterialSource = item.RawMaterialSource,
- RawMaterialType = item.RawMaterialType,
- RawMaterialWeight = item.RawMaterialWeight,
- RecipeStatus = item.RecipeStatus,
- SelectIndex = item.SelectIndex,
- Status = item.Status,
- UpLimtFeedback = item.UpLimtFeedback,
- UpLimtWeightFeedback = item.UpLimtWeightFeedback,
- WeightFeedback = item.WeightFeedback,
- });
- }
- App.Current.Dispatcher.Invoke(() =>
- {
- UserTreeCompelete.Add(new RecipeModel()
- {
- RawMaterials = RawMaterComple,
- IsEnable = recipeComple.IsEnable,
- RecipeName = recipeComple.RecipeName,
- SerialNum = UserTreeCompelete.Count + 1,
- RecipCode = recipeComple.RecipCode,
- RecipStatus = "制作完成"
- });
- });
- App.Current.Dispatcher.Invoke(new Action(() =>
- {
- recipeProcesses.Clear();
- CurrentRecipeName = string.Empty;
- }));//完成后清空当前配方
- }
- }
- Thread.Sleep(100);
- }), "启动配方下发", true);
- }
- /// <summary>
- /// 配料逻辑
- /// </summary>
- /// <param name="recipeModel">当前执行的配方</param>
- public void BusinessExcute()
- {
- ThreadManage.GetInstance.StartLong(new Action(() =>
- {
-
- #region 测试
- ////拿到当前配方
- //for (int j = 0; j < GlobalDevice.PlcData.IsAllowIngredients.Length; j++)//遍历允许配料的料桶
- //{
-
- // if (GlobalDevice.PlcData.IsAllowIngredients[j])
- // {
- // int barrelNum = j + 1;//桶号
- // int stockLoc = GlobalDevice.PlcData.LocationFeedback[j];//允许配料的料仓位置 0~6 双仓情况下返回的位置是否一样,料仓ip设置顺序怎样的
- // if (stockLoc >= 1 && stockLoc <= Json<DevicePar>.Data.BaseParModel.StockCount)
- // {
- // int index = Array.FindIndex(DeviceInquire.GetInstance.devices.ToArray(), p => p.DeviceNum == stockLoc);
- // if (index >= 0)
- // {
- // //查出到配料位置的原料
- // int result = Array.FindIndex(recipeModel.RawMaterials.ToArray(), p => (p.Loc == barrelNum && p.DeviceIp == DeviceInquire.GetInstance.devices.ElementAt(index).IpAddress));//待定
- // if (result != -1 && DeviceInquire.GetInstance.GetDevice(recipeModel.RawMaterials[result].DeviceIp).deviceStatus.RunStatus == 1 && RecipeControlViewModel.recipeProcesses.ElementAt(0).RawMaterials[result].Status == Status.等待配料)
- // {
- // var weight = recipeModel.RawMaterials[result].RawMaterialWeight;
- // DeviceInquire.GetInstance.GetDevice(recipeModel.RawMaterials.ElementAt(index).DeviceIp).Start(weight);//所有参数下发并启动配料
- // MessageNotify.GetInstance.ShowRunLog($"{recipeModel.RawMaterials[result].DeviceIp}:正在配料");
- // RecipeControlViewModel.recipeProcesses.ElementAt(0).RawMaterials[result].Status = Status.正在配料;
- // }
- // }
- // }
- // else
- // {
- // continue;
- // }
- // }
-
- //}
- ////配料完成后逻辑
- //for (int k = 0; k < recipeModel.RawMaterials.Count; k++)
- //{
- // if (DeviceInquire.GetInstance.GetDevice(recipeModel.RawMaterials.ElementAt(k).DeviceIp).deviceStatus.RunStatus == 3 && RecipeControlViewModel.recipeProcesses.ElementAt(0).RawMaterials[k].Status != Status.配料完成)//配料完成
- // {
- // int DeviceNum = DeviceInquire.GetInstance.GetDevice(recipeModel.RawMaterials.ElementAt(k).DeviceIp).deviceStatus.DeviceNum;
- // Comcount++;
- // DeviceInquire.GetInstance.GetDevice(recipeModel.RawMaterials.ElementAt(k).DeviceIp).StatusReset();//料仓复位
- // SiemensDevice.GetInstance.MySiemens.Write($"DB4.DBX130.{DeviceNum - 1}", true);
- // Task.Run(() =>
- // {
- // int cout = DeviceNum - 1;
- // while (!SiemensDevice.GetInstance.MySiemens.Read<bool>($"DB3.DBX148.{cout}").Content) //DB3.DBX148.0-31 148.0-148.5代表6个料仓位置
- // {
- // SiemensDevice.GetInstance.MySiemens.Write($"DB4.DBX130.{cout}", true);
- // Thread.Sleep(200);
- // }
- // while (SiemensDevice.GetInstance.MySiemens.Read<bool>($"DB3.DBX148.{cout}").Content)
- // {
- // SiemensDevice.GetInstance.MySiemens.Write($"DB4.DBX130.{cout}", false);
- // }
- // MessageNotify.GetInstance.ShowRunLog($"{cout}号气缸复位信号写入成功!");
- // });
- // RecipeControlViewModel.recipeProcesses.ElementAt(0).RawMaterials[k].Status = Status.配料完成;
- // if (Comcount >= recipeModel.RawMaterials.Count) //配方配料完成 StockStatus.Count >= Recipes.ElementAt(i).RawMaterials.Count &&
- // {
- // Comcount = 0;
- // App.Current.Dispatcher.Invoke(new Action(() => { RecipeControlViewModel.recipeProcesses.Clear(); }));
- // MessageNotify.GetInstance.ShowUserLog($"配方:{recipeModel.RecipeName},配料完成");
-
- // SiemensDevice.GetInstance.MySiemens.Write("DB4.DBX202.0", true);//配料完成
- // MessageNotify.GetInstance.ShowRunLog($"配方:{recipeModel.RecipeName},配料完成");
-
- // recipeModel.Are.Set();//待定
- // Thread.Sleep(100);
- // }
- // }
- //}
- #endregion
- #region 正式版
- for (int i = 0; i < Recipes.Count; i++)
- {
- for (int m = 0; m < Recipes.ElementAt(i).RawMaterials.Count; m++)
- {
- var RunStatus = DeviceInquire.GetInstance.GetDevice(Recipes.ElementAt(i).RawMaterials.ElementAt(m).DeviceIp).deviceStatus.RunStatus;
- //设备状态显示
- if (Recipes.ElementAt(i).RecipeName == CurrentRecipeName)
- {
- string tempRawMaterialName = DeviceInquire.GetInstance.GetDevice(Recipes.ElementAt(i).RawMaterials.ElementAt(m).DeviceIp).DeviceName;
- int recIndex = recipeProcesses.ToList().FindIndex(p => p.RecipeName == CurrentRecipeName);
- if (recIndex >= 0 && recIndex < recipeProcesses.Count)
- {
- int index = recipeProcesses.ElementAt(recIndex).RawMaterials.ToList().FindIndex(p => p.RawMaterialName == tempRawMaterialName);
-
- if (index >= 0 && index < recipeProcesses.ElementAt(recIndex).RawMaterials.Count)
- {
- //测试使用
- recipeProcesses.ElementAt(recIndex).RawMaterials.ElementAt(index).RecipeStatus = RunStatus;
- }
- for (int j = 0; j < GlobalDevice.PlcData.IsAllowIngredients.Length; j++)
- {
- if (GlobalDevice.PlcData.IsAllowIngredients[j])
- {
- int barrel = j + 1;//桶号
- int cnt = GlobalDevice.PlcData.LocationFeedback[j];//允许配料的位置 1~6
- if (RTrig.GetInstance($"a{j}").Start(GlobalDevice.PlcData.IsAllowIngredients[j]))
- {
- MessageNotify.GetInstance.ShowRunLog($"桶号:{barrel},位置:{cnt},允许配料");
- }
- int Location1 = 0;
- int Location2 = 0;
- if (cnt == -1)
- {
- MessageNotify.GetInstance.ShowRunLog("错误");
- return;
- }
- else
- {
- if (cnt >= 1 && cnt <= 6)
- {
- int a1 = Array.FindIndex(DeviceInquire.GetInstance.devices.ToArray(), p => p.DeviceNum == cnt);
- if (a1 >= 0)
- {
- Location1 = Array.FindIndex(Recipes.ElementAt(i).RawMaterials.ToArray(), p => p.RawMaterialName == DeviceInquire.GetInstance.devices.ElementAt(a1).DeviceName && p.Loc == barrel);
- }
-
- }
- }
- if (Location1 >= 0)
- {
- string RawName = Recipes.ElementAt(i).RawMaterials.ElementAt(Location1).RawMaterialName;
- int abc = Array.FindIndex(DeviceInquire.GetInstance.devices.ToArray(), p => p.DeviceName == RawName);
- int DeviceNum = DeviceInquire.GetInstance.devices.ElementAt(abc).DeviceNum;
- if (DeviceNum > 0)
- {
- float weight = Recipes.ElementAt(i).RawMaterials.ElementAt(Location1).RawMaterialWeight;
-
- int loc = Array.FindIndex(Recipes.ElementAt(i).RawMaterials.ToArray(), p => (p.RawMaterialName == RawName));
- if (loc >= 0 && RawName != null && weight >= 0)
- {
- int St_index = Array.FindIndex(StockStatus.ToArray(), p => p.MaterialName == RawName);
-
- if (St_index < 0) //|| (StockStatus.Count < materialCount && St_index > 0)
- {
- StockStatus.Add(new StockStatusModel()
- {
- MaterialName = RawName,
- IssueWeight = weight,
- IssueStatus = 0,
- });
- }
- St_index = Array.FindIndex(StockStatus.ToArray(), p => p.MaterialName == RawName);//&& p.IssueStatus == 0)
- if (St_index >= 0)
- {
-
- if (RTrig.GetInstance($"ac{j}-{St_index}").Start(GlobalDevice.PlcData.IsAllowIngredients[j]))
- {
- MessageNotify.GetInstance.ShowRunLog($"{St_index}-{j}--》允许配料");
- if (StockStatus.ElementAt(St_index).IssueStatus == 2)
- {
- StockStatus.ElementAt(St_index).IssueStatus = 0;
- MessageNotify.GetInstance.ShowRunLog($"{St_index}-复位");
- }
- }
- var rrr = DeviceInquire.GetInstance.GetDevice(Recipes.ElementAt(i).RawMaterials.ElementAt(loc).DeviceIp).deviceStatus.RunStatus;
- if ((recipeProcesses.ElementAt(recIndex).RawMaterials.ElementAt(loc).RecipeStatus == 1 && StockStatus.ElementAt(St_index).IssueStatus == 0))//
- {
-
- StockStatus.ElementAt(St_index).IssueStatus = 1;
- DeviceInquire.GetInstance.GetDevice(Recipes.ElementAt(i).RawMaterials.ElementAt(loc).DeviceIp).Start(weight);
- var res = recipeProcesses.ElementAt(recIndex).RawMaterials.FirstOrDefault(p => p.Status != Status.正在配料 && p.Status != Status.配料完成 && p.RawMaterialName == tempRawMaterialName && p.Loc == j + 1);
- if (res != null)
- res.Status = Status.正在配料;
-
- MessageNotify.GetInstance.ShowRunLog($"设备执行状态:{rrr}");
- MessageNotify.GetInstance.ShowRunLog($"柔性味魔方{Recipes.ElementAt(i).RawMaterials.ElementAt(loc).DeviceIp},开始出料");
- }
- if (recipeProcesses.ElementAt(recIndex).RawMaterials.ElementAt(loc).RecipeStatus == 3 && StockStatus.ElementAt(St_index).IssueStatus == 1)
- {
- //GlobalDevice.PlcData.IsAllowIngredients[j] = false;//测试使用
-
- Comcount++;
- StockStatus.ElementAt(St_index).IssueStatus = 2;
- DeviceInquire.GetInstance.GetDevice(Recipes.ElementAt(i).RawMaterials.ElementAt(loc).DeviceIp).StatusReset();
- //int a = 0.SetBitValue((byte)(DeviceNum), true);
- //byte[] test1 = a.ToBytes(BPA.Helper.DataFormat.BADC);
- //int item = test1.ToInt();
- //prop1:
- // SiemensDevice.GetInstance.MySiemens.Write("DB4.DBD130", item);
- SiemensDevice.GetInstance.MySiemens.Write($"DB4.DBX130.{DeviceNum - 1}", true);
- Task.Run(() =>
- {
- int cout = DeviceNum - 1;
- while (!SiemensDevice.GetInstance.MySiemens.Read<bool>($"DB3.DBX148.{cout}").Content) //DB3.DBX148.0-31 148.0-148.5代表6个料仓位置
- {
- SiemensDevice.GetInstance.MySiemens.Write($"DB4.DBX130.{cout}", true);
- Thread.Sleep(200);
- }
- while (SiemensDevice.GetInstance.MySiemens.Read<bool>($"DB3.DBX148.{cout}").Content)
- {
- SiemensDevice.GetInstance.MySiemens.Write($"DB4.DBX130.{cout}", false);
- }
- MessageNotify.GetInstance.ShowRunLog($"{cout}号气缸复位信号写入成功!");
- });
- var res = recipeProcesses.ElementAt(recIndex).RawMaterials.FirstOrDefault(p => p.Status != Status.配料完成 && p.RawMaterialName == tempRawMaterialName && p.Loc == j + 1);
- if (res != null)
- res.Status = Status.配料完成;
-
-
- MessageNotify.GetInstance.ShowRunLog($"设备完成执行状态:{rrr}");
- MessageNotify.GetInstance.ShowRunLog($"柔性味魔方{Recipes.ElementAt(i).RawMaterials.ElementAt(loc).DeviceIp},出料完成,状态复位");
-
- }
-
-
- }
- }
- }
- }
- }
-
- }
-
- if (Comcount >= Recipes.ElementAt(i).RawMaterials.Count) //配方配料完成 StockStatus.Count >= Recipes.ElementAt(i).RawMaterials.Count &&
- {
- SystemEventReport<AliyunSystemEventReportModel>("RecipeCompleteEvent", new AliyunSystemEventReportModel { RecipeName = CurrentRecipeName });
- int cc = recipeProcesses.ElementAt(recIndex).RawMaterials.OrderBy(p => p.RawMaterialName).Count();
- for (int k = 0; k < 32; k++)
- {
- for (int l = 0; l < cc; l++)
- {
- RTrig.GetInstance($"ac{k}-{l}").Start(false);
- }
- }
- Comcount = 0;
-
- StockStatus.Clear();
- MessageNotify.GetInstance.ShowUserLog($"配方:{recipeProcesses.ElementAt(recIndex).RecipeName},配料完成");
- foreach (var item in recipeProcesses.ElementAt(recIndex).RawMaterials)
- {
- MessageNotify.GetInstance.ShowUserLog($"原料:{item.RawMaterialName},桶号:{item.Loc},设定配料重量{item.RawMaterialWeight}g,实际配料重量{item.UpLimtWeightFeedback}g");
- }
- SiemensDevice.GetInstance.MySiemens.Write("DB4.DBX202.0", true);//配料完成
- MessageNotify.GetInstance.ShowRunLog($"配方:{CurrentRecipeName},配料完成");
- int recipIndex = Array.FindIndex(Recipes.ToArray(), p => p.RecipeName == CurrentRecipeName);
- App.Current.Dispatcher.Invoke(new Action(() => { recipeProcesses.Clear(); }));
- Recipes.ElementAt(recipIndex).IsEnable = true;
- Json<LocalRecipe>.Data.Recipes.ElementAt(recipIndex).IsEnable = true;
- Recipes.ElementAt(recipIndex).Are.Set();
- Thread.Sleep(100);
- }
- }
- }
- }
- }
- #endregion
-
- Thread.Sleep(10);
- }), "配料业务逻辑");
-
- }
-
- }
- }
|