schangxiang@126.com
2025-11-04 f5ed29dc26c7cd952d56ec5721a2efc43cd25992
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
using Newtonsoft.Json.Linq;
using Sodao.FastSocket.Server.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using BiosenSocketService.Entity;
using BiosenSocketService.Exceptions;
using XImaging.Automation.Service;
using XImaging.Automation.Service.Interface;
using System.Configuration;
using Sodao.FastSocket.SocketBase.Utils;
using System.Net.NetworkInformation;
using XImaging.Automation.Library.HxDriverLib;
using System.Threading;
 
namespace XImaging.Automation.Service.Instruction
{
    public class InsProtocol
    {
        private IRuntime m_runtime;
        //private ConveyerControl m_conveyerControl = new ConveyerControl("192.168.0.7", 2022);
 
        public InsProtocol()
        {
            CreateRuntime();
        }
 
        private IProtocolArgs ProtocolParse(HxMessage message)
        {
            IProtocolArgs command;
            Type type;
 
            # region 解析Message中的参数
 
            type = Type.GetType("XImageSystem.Service.Instruction." + message.Method + "InsArgs");
            if (type == null) //没有参数
            {
                command = null;
            }
            else
            {
                try
                {
                    command = (IProtocolArgs)Activator.CreateInstance(type, message.Parameters);
                }
                catch (Exception ex)
                {
                    throw new UndefinedInstructionException("执行方法不存在:" + message.Method);
                }
            }
            # endregion
 
            return command;
        }
 
        /// <summary>
        /// 创建关于Cytomat的Runtime
        /// </summary>
        private void CreateRuntime()
        {
            //m_runtime = new IRuntime[2] { new DeviceSimulator(), new DeviceSimulator() };
            string typeName = "";
            string isSimulator = ConfigurationManager.AppSettings.Get("IsSimulator");
            if(isSimulator=="true")
                typeName = ConfigurationManager.AppSettings.Get("Simulator");
            else
                typeName = ConfigurationManager.AppSettings.Get("Runtime");
            Type type = Type.GetType(typeName);
            m_runtime = (IRuntime)Activator.CreateInstance(type);
        }
 
        /// <summary>
        /// 销毁Venus应用的Runtime
        /// </summary>
        public void DestroyRuntime()
        {
        }
 
        public void OnConnect(bool isConnect)
        {
            Task task = Task.Run(() =>
            {
                MethodInfo method = m_runtime.GetType().GetMethod("OnConnected");
                if (method != null)
                {
                    method.Invoke(m_runtime, new object[1] { isConnect });
                }
 
            });
        }
 
        public void AsyncTask(ref TaskInstruction tIns, OnTaskFinishDelegate finishCallback, OnTaskAbortDelegate abortCallback)
        {
            //JObject command = tIns.Message.Parameters;
            JObject Obj = tIns.Message.OriginJSON;
 
            tIns.ErrorHandler.AbortTrigger += m_runtime.ReplyAbort;
            tIns.ErrorHandler.RetryTrigger += m_runtime.ReplyRetry;
            tIns.ErrorHandler.IgnoreTrigger += m_runtime.ReplyIgnore;
            //if(m_runtime.errorHandle!=null)
            //    m_runtime.errorHandle -= tIns.OnTaskError;
            m_runtime.errorHandle += tIns.OnTaskError;
            //if(m_runtime.abortHandle!=null)
            //    m_runtime.abortHandle -= tIns.OnTaskAbort;
            m_runtime.abortHandle += tIns.OnTaskAbort;
 
            TaskInstruction instruction = tIns;
 
            string InsName = tIns.InsName;
            Task task = new Task(() =>
            {
                try
                {
                    LogConstant.logger.Print($"Task Method={InsName} ---- 开始");
                    MethodInfo method = m_runtime.GetType().GetMethod(InsName);
                    if (method != null)
                    {
                        LogConstant.logger.Print($"Method={method.Name} ---- run");
                        JObject data = (JObject)method.Invoke(m_runtime, new object[1] { Obj });
                        if (data == null)
                            data = new JObject();
 
                        LogConstant.logger.Print($"Method={method.Name} ---- run finish");
                        finishCallback(instruction, data, HxMessage.METHOD_STATUS_COMPLETED);
                    }
                    else
                    {
                        LogConstant.logger.Print($"Method={method.Name} ---- Not Support this method");
                        abortCallback(instruction, "EC_000_UNKNOWN", "Not Support this method: " + InsName);
                    }
                    m_runtime.Dispose(method.Name);
                }
                catch(Exception ex)
                {
                    LogConstant.logger.Print($"Catch expeption Method={InsName} ---- {ex.InnerException.Message}");
                    abortCallback(instruction, "EC_000_UNKNOWN", ex.InnerException.Message);
                    m_runtime.Dispose(InsName);
                }
            });
            task.ContinueWith(r =>
            {
                LogConstant.logger.Print($"Task 错误结束 Method={InsName} ---- task.Exception.InnerException.InnerException.Message");
                abortCallback(instruction, "EC_000_UNKNOWN", task.Exception.InnerException.InnerException.Message);
 
            }, TaskContinuationOptions.OnlyOnFaulted);
            task.Start();
            //task.Wait();
 
            tIns.Execute();
        }
 
        public JObject Query(QueryInstruction qIns)
        {
            //IProtocolArgs command = ProtocolParse(qIns.Message);
            //try
            {
                HxMessage command = qIns.Message;
                MethodInfo method = m_runtime.GetType().GetMethod(qIns.InsName);
                JObject obj = (JObject)method.Invoke(m_runtime, new object[1] { command });
                return obj;
            }
            //catch (Exception ex)
            //{
            //    throw ex;
            //}
            return new JObject();
        }
 
        # region 调用Runtime接口执行上位指令的函数实现
 
        /*public JObject Count(IProtocolArgs args)
        {
            try
            {
                return m_runtime[DeviceEnvrionment.Run_Mode].Count_APIWrapper();
                
            }
            catch (Exception ex)
            {
                return JObject.FromObject(ex);
            }
 
        }
 
        public int OpenDoor(IProtocolArgs args)
        {
            try
            {
                m_runtime[DeviceEnvrionment.Run_Mode].OpenDoor_APIWrapper();
                return HxMessage.METHOD_STATUS_COMPLETED;
            }
            catch (Exception ex)
            {
                return HxMessage.METHOD_STATUS_FAILED;
            }
 
        }
 
        public int CloseDoor(IProtocolArgs args)
        {
            try
            {
                m_runtime[DeviceEnvrionment.Run_Mode].CloseDoor_APIWrapper();
                return HxMessage.METHOD_STATUS_COMPLETED;
            }
            catch (Exception ex)
            {
                return HxMessage.METHOD_STATUS_FAILED;
            }
 
        }
 
        public int ClawClose(IProtocolArgs args)
        {
            try
            {
                m_runtime[DeviceEnvrionment.Run_Mode].ClawClose_APIWrapper();
                return HxMessage.METHOD_STATUS_COMPLETED;
            }
            catch (Exception ex)
            {
                return HxMessage.METHOD_STATUS_FAILED;
            }
 
        }
 
        public int ClawOpen(IProtocolArgs args)
        {
            try
            {
                m_runtime[DeviceEnvrionment.Run_Mode].ClawOpen_APIWrapper();
                return HxMessage.METHOD_STATUS_COMPLETED;
            }
            catch (Exception ex)
            {
                return HxMessage.METHOD_STATUS_FAILED;
            }
 
        }
        */
        //public JObject GetState(IProtocolArgs args)
        //{
        //    RuntimeState status = m_runtime[DeviceEnvrionment.Run_Mode].GetStatus_APIWrapper();
        //    string statusCode = "";
        //    if (status == RuntimeState.OnBusy)
        //        statusCode = "S002";
        //    else if (status == RuntimeState.OnIdle)
        //        statusCode = "S001";
        //    else
        //        statusCode = m_runtime[DeviceEnvrionment.Run_Mode].ErrorState;
        //    PairItem[] items = { new PairItem("Device", "QSPCR"), new PairItem("Status", statusCode) };
 
        //    return GetDeviceStatusInsArgs.ReturnDataWrapper(items);
 
        //}
        #endregion
    }
}