From ff18fa3c007656bd37cad91fac9a9cb03f4070b8 Mon Sep 17 00:00:00 2001
From: patrick <patrick.xu@broconcentric.com>
Date: 星期日, 20 十月 2019 14:13:16 +0800
Subject: [PATCH] 1. 修改SeerAGV驱动通信代码 2. 修改机器人通信部分代码 3. 取消原有流程任务队列模式,使用即时方法调用。

---
 src/Bro.Device.AuboRobot/AuboRobotDriver.cs |  216 +++++++++++++++++++++++++++++++++++++++++++++---------
 1 files changed, 180 insertions(+), 36 deletions(-)

diff --git a/src/Bro.Device.AuboRobot/AuboRobotDriver.cs b/src/Bro.Device.AuboRobot/AuboRobotDriver.cs
index 26e7324..d2ae516 100644
--- a/src/Bro.Device.AuboRobot/AuboRobotDriver.cs
+++ b/src/Bro.Device.AuboRobot/AuboRobotDriver.cs
@@ -1,6 +1,8 @@
 锘縰sing Bro.Common.Base;
 using Bro.Common.Helper;
 using Bro.Common.Interface;
+using Bro.Common.Model;
+using Bro.Common.Model.Interface;
 using System;
 using System.Collections.Generic;
 using System.Linq;
@@ -12,9 +14,9 @@
 namespace Bro.Device.AuboRobot
 {
     [Device("AuboRobot", "濂ュ崥鏈哄櫒浜�", EnumHelper.DeviceAttributeType.Device)]
-    public class AuboRobotDriver : DeviceBase
+    public class AuboRobotDriver : DeviceBase, IMonitor
     {
-        public Action<RobotMsg> OnMsgReceived { get; set; }
+        public Action<DateTime, AuboRobotDriver, RobotMsg> OnMsgReceived { get; set; }
 
         AuboRobotInitialConfig IConfig
         {
@@ -32,6 +34,8 @@
 
         protected override void Init()
         {
+            oldValues = new List<int>();
+
             if (string.IsNullOrWhiteSpace(IConfig.EndChar))
             {
                 throw new ProcessException("鍗忚鏂囨湰鐨勭粨鏉熷瓧绗︿笉鍙负绌猴紝璇锋鏌ラ厤缃�", null);
@@ -52,15 +56,28 @@
         {
         }
 
+        RobotMsg scanMsg = new RobotMsg();
         protected override void Start()
         {
             //Query Robot IOs
             //SendMsg(RobotMsgType.Send, 0, true, RobotMsgAction.IO, RobotMsgParas.Query, new List<string>());
+
+            scanMsg = new RobotMsg();
+            scanMsg.Action = RobotMsgAction.IO;
+            scanMsg.Para1 = RobotMsgParas.Query;
+
+            Task.Run(() =>
+            {
+                Monitor();
+            });
         }
 
         protected override void Stop()
         {
-            client.Close();
+            if (client != null && client.Connected)
+            {
+                client.Close();
+            }
         }
         #endregion
 
@@ -78,30 +95,41 @@
             {
                 OnLog?.Invoke(DateTime.Now, this, ex.GetExceptionMessage());
 
+                if (client != null && client.Connected)
+                {
+                    client.Close();
+                }
                 client.BeginConnect(IPAddress.Parse(IConfig.RobotIP), IConfig.RobotPort, OnConnect, null);
             }
         }
 
         private void OnDateReceived(IAsyncResult ar)
         {
-            int dataLength = client.GetStream().EndRead(ar);
-
-            if (dataLength > 0)
+            try
             {
-                byte[] data = buffer.Take(dataLength).ToArray();
+                int dataLength = client.GetStream().EndRead(ar);
 
-                string dataStr = System.Text.Encoding.ASCII.GetString(data).Trim();
-                AnalyzeData(dataStr);
-
-                client.GetStream().BeginRead(buffer, 0, buffer.Length, OnDateReceived, null);
-            }
-            else
-            {
-                if (!client.Connected)
+                if (dataLength > 0)
                 {
-                    OnLog?.Invoke(DateTime.Now, this, "杩斿洖绌烘暟鎹紝杩炴帴涓柇");
-                    client.BeginConnect(IPAddress.Parse(IConfig.RobotIP), IConfig.RobotPort, OnConnect, null);
+                    byte[] data = buffer.Take(dataLength).ToArray();
+
+                    string dataStr = System.Text.Encoding.ASCII.GetString(data).Trim();
+                    AnalyzeData(dataStr);
+
+                    client.GetStream().BeginRead(buffer, 0, buffer.Length, OnDateReceived, null);
                 }
+                else
+                {
+                    if (!client.Connected)
+                    {
+                        OnLog?.Invoke(DateTime.Now, this, "杩斿洖绌烘暟鎹紝杩炴帴涓柇");
+                        client.BeginConnect(IPAddress.Parse(IConfig.RobotIP), IConfig.RobotPort, OnConnect, null);
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                OnLog?.Invoke(DateTime.Now, this, $"{Name}鏁版嵁鎺ユ敹寮傚父锛歿ex.GetExceptionMessage()}");
             }
         }
 
@@ -152,8 +180,24 @@
                      }
                      else
                      {
-                         SendMsg(RobotMsgType.Rec, msg.ID, false);
-                         OnMsgReceived?.Invoke(msg);                         
+                         canMonitor = true;
+
+                         if (msg.Action == RobotMsgAction.IO && msg.Para1 == RobotMsgParas.Query)
+                         {
+                             string resultStr = msg.Datas[0];
+                             newValues = new List<int>();
+
+                             for (int i = resultStr.Length - 1; i >= 0; i--)
+                             {
+                                 newValues.Add(int.Parse(resultStr[i].ToString()));
+                             }
+
+                             monitorHandle.Set();
+                         }
+                         else
+                         {
+                             OnMsgReceived?.BeginInvoke(DateTime.Now, this, msg, null, null);
+                         }
                      }
                  });
             });
@@ -164,7 +208,7 @@
         {
             get
             {
-                if (sid > 999)
+                if (sid > 99)
                 {
                     sid = 1;
                 }
@@ -176,27 +220,33 @@
         List<int> replyHandleList = new List<int>();
         Dictionary<int, AutoResetEvent> replyHandleDict = new Dictionary<int, AutoResetEvent>();
 
-        public void SendMsg(RobotMsgType type, int replyId, bool isWaitReply = true, RobotMsgAction action = RobotMsgAction.Move, RobotMsgParas para1 = RobotMsgParas.None, List<string> paras = null)
+        public void SendMsg(RobotMsgAction action, RobotMsgParas para1, int para2, List<float> paras = null)
+        {
+            RobotMsg msg = new RobotMsg();
+            msg.Type = RobotMsgType.Send;
+            msg.ID = SID;
+
+            msg.Action = action;
+            msg.Para1 = para1;
+            msg.Para2 = para2;
+
+            msg.Datas = new List<string>((paras ?? new List<float>()).ConvertAll(i => i.ToString()));
+
+            SendMsg(msg, true);
+        }
+
+        public void SendReplyMsg(int replyId)
         {
             RobotMsg msg = new RobotMsg();
 
-            msg.Type = type;
-            if (msg.Type == RobotMsgType.Send)
-            {
-                msg.ID = SID;
-            }
-            else
-            {
-                msg.ID = replyId;
-            }
+            msg.Type = RobotMsgType.Rec;
+            msg.ID = replyId;
 
-            msg.Para1 = para1;
-            msg.Paras = new List<string>(paras ?? new List<string>());
-
-            SendMsg(msg, isWaitReply);
+            SendMsg(msg, false);
         }
 
-        public void SendMsg(RobotMsg msg, bool isWaitReply = true)
+        bool canMonitor = true;
+        public void SendMsg(RobotMsg msg, bool isWaitReply = true, bool isMonitorMsg = false)
         {
             if (isWaitReply)
             {
@@ -205,7 +255,19 @@
             }
 
             byte[] bytes = msg.GetMsgBytes(IConfig.Seperator, IConfig.EndChar);
-            client.GetStream().Write(bytes, 0, bytes.Length);
+
+            if (!isMonitorMsg)
+            {
+                canMonitor = false;
+            }
+
+            if (isMonitorMsg && !canMonitor)
+                return;
+
+            //lock (this)
+            {
+                client.GetStream().Write(bytes, 0, bytes.Length);
+            }
 
             if (isWaitReply)
             {
@@ -217,5 +279,87 @@
                 }
             }
         }
+
+        #region IMonitor
+        public event OnMonitorInvokeDelegate OnMonitorInvoke;
+        public event OnMonitorAlarmDelegate OnMonitorAlarm;
+
+        protected List<int> oldValues = new List<int>();
+        List<int> newValues = new List<int>();
+        AutoResetEvent monitorHandle = new AutoResetEvent(false);
+        public List<int> GetMonitorValues(int startAddress, int length)
+        {
+            scanMsg.ID = SID;
+            SendMsg(scanMsg, true, true);
+            monitorHandle.WaitOne(IConfig.ReplyTimeout);
+
+            return newValues;
+        }
+
+        public virtual void Monitor()
+        {
+            while (CurrentState != EnumHelper.DeviceState.DSClose && CurrentState != EnumHelper.DeviceState.DSExcept)
+            {
+                try
+                {
+                    List<int> newValues = GetMonitorValues(0, 0);
+
+                    if (newValues == null || newValues.Count == 0)
+                        continue;
+
+                    if (oldValues.Count == 0)
+                    {
+                        oldValues = newValues.ConvertAll(s => -1).ToList();
+                    }
+
+                    if (oldValues.Count == newValues.Count)
+                    {
+                        var tempNew = new List<int>(newValues);
+                        var tempOld = new List<int>(oldValues);
+                        MonitorCheckAndInvoke(tempNew, tempOld);
+                    }
+                    oldValues = new List<int>(newValues);
+
+                    Thread.Sleep(IConfig.ScanInterval);
+                }
+                catch (Exception ex)
+                {
+                    OnLog?.Invoke(DateTime.Now, this, $"{Name}鐩戝惉寮傚父:{ex.GetExceptionMessage()}");
+                }
+            }
+        }
+
+        protected virtual void MonitorCheckAndInvoke(List<int> tempNew, List<int> tempOld)
+        {
+            IConfig.MonitorSetCollection.ForEach(m =>
+            {
+                if (m.TriggerIndex < 0 || m.TriggerIndex >= tempNew.Count)
+                {
+                    return;
+                }
+
+                int newValue = tempNew[m.TriggerIndex];
+                int oldValue = tempOld[m.TriggerIndex];
+
+                if (newValue != oldValue)
+                {
+                    if (m.TriggerValue == -999 || newValue == m.TriggerValue)
+                    {
+                        if (m.OpConfig == null)
+                        {
+                            m.OpConfig = new OperationConfigBase();
+                        }
+
+                        m.OpConfig.InputPara = m.InputDataIndex.ConvertAll(index =>
+                        {
+                            return tempNew[index];
+                        }).ToList();
+
+                        OnMonitorInvoke?.BeginInvoke(DateTime.Now, this, m, null, null);
+                    }
+                }
+            });
+        }
+        #endregion
     }
 }

--
Gitblit v1.8.0