1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
using Bro.Common.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bro.Common.Helper;
using System.Reflection;
using Newtonsoft.Json;
using System.Threading;
using System.Diagnostics;
using System.Dynamic;
using System.Linq.Expressions;
//using BroCComn.PubSub;
using static Bro.Common.Helper.EnumHelper;
using System.ComponentModel;
 
namespace Bro.Common.Base
{
    //public delegate void DeviceStateChangedDelegate(EnumHelper.DeviceState initialState);
    public abstract class DeviceBase : IDevice, IDisposable
    {
        #region Event
        [JsonIgnore]
        public Action<IDevice, Exception> OnDeviceException { get; set; }
        [JsonIgnore]
        public Action<DateTime, IDevice, string> OnLog { get; set; }
        [JsonIgnore]
        public Action<EnumHelper.DeviceState> OnDeviceStateChanged { get; set; }
        #endregion
 
 
        int RetryTime = 3;
        /// <summary>
        /// 和设备暂停状态关联的信号量
        /// </summary>
        private ManualResetEvent pauseHandle = new ManualResetEvent(true);
 
        Timer stateChangedTimer;
 
        internal bool stateChangedFlag = false;
 
        private EnumHelper.DeviceState _currentStateToBe = EnumHelper.DeviceState.DSUninit;
        /// <summary>
        /// 当前设备状态
        /// </summary>
        [JsonIgnore]
        internal EnumHelper.DeviceState CurrentStateToBe
        {
            get
            {
                return _currentStateToBe;
            }
            set
            {
                if (value != _currentStateToBe)
                {
                    var initialState = _currentStateToBe;
                    _currentStateToBe = value;
 
                    if (_currentStateToBe != EnumHelper.DeviceState.DSExcept)
                    {
                        OnStateChanged(initialState);
                    }
                    else
                    {
                        stateChangedTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
            }
        }
 
        private EnumHelper.DeviceState initialState = EnumHelper.DeviceState.DSUninit;
        private EnumHelper.DeviceState _currentState = EnumHelper.DeviceState.DSUninit;
        public EnumHelper.DeviceState CurrentState
        {
            get
            {
                return _currentState;
            }
            set
            {
                _currentState = value;
 
                if (value != EnumHelper.DeviceState.TBD)
                {
                    OnDeviceStateChanged?.Invoke(initialState);
                    OnDeviceStateChangedWithDeviceInfo?.Invoke(this, _currentState);
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentState"));
                }
                else
                {
                    initialState = _currentState;
                }
            }
        }
 
        /// <summary>
        /// 设备状态 编辑时或者运行时
        /// </summary>
        public EnumHelper.DeviceMode DeviceMode { get; set; } = EnumHelper.DeviceMode.Edit;
 
        /// <summary>
        /// 设备标识符 从数据库获取
        /// </summary>
        public string Id { get; set; }
 
        /// <summary>
        /// 设备名称 从数据库获取
        /// </summary>
        public string Name { get; set; }
 
        private IInitialConfig initialConfig = null;
        /// <summary>
        /// 设备初始化配置 从数据库获取
        /// </summary>
        public virtual IInitialConfig InitialConfig
        {
            get => initialConfig;
            set
            {
                initialConfig = value;
                this.Id = initialConfig.ID;
                this.Name = initialConfig.Name;
            }
        }
 
        #region IPorcessId
        /// <summary>
        /// 设备当前执行工序编号
        /// </summary>
        [JsonIgnore]
        public string ProcessId { get; set; }
 
        /// <summary>
        /// 设备当前执行工序名称
        /// </summary>
        [JsonIgnore]
        public string ProcessName { get; set; }
        #endregion
 
        [JsonIgnore]
        public Dictionary<DeviceOutputMethodAttribute, MethodInfo> OutputMethods { get; set; } = new Dictionary<DeviceOutputMethodAttribute, MethodInfo>();
        #region 延迟加载方法字典方式 现转移到构造函数中实现
        //{
        //    get
        //    {
        //        if (outputMethods == null)
        //        {
        //            this.GetType().GetMethods().ToList().ForEach(m =>
        //            {
        //                var attr = m.GetCustomAttribute<DeviceOutputMethodAttribute>();
        //                if (attr != null)
        //                {
        //                    outputMethods[attr.MethodName] = m;
        //                }
        //            });
        //        }
 
        //        return outputMethods;
        //    }
        //    set
        //    {
        //        outputMethods = value;
        //    }
        //}
        #endregion
 
        [JsonIgnore]
        public Dictionary<DeviceInputMethodAttribute, MethodInfo> InputMethods { get; set; } = new Dictionary<DeviceInputMethodAttribute, MethodInfo>();
 
 
 
        //public event DeviceStateChangedDelegate OnDeviceStateChanged;
 
        public DeviceBase()
        {
            //预先获取所有设备输出方法
            this.GetType().GetMethods().ToList().ForEach(m =>
            {
                var attrOut = m.GetCustomAttribute<DeviceOutputMethodAttribute>();
                if (attrOut != null)
                {
                    OutputMethods[attrOut] = m;
                }
 
                var attrIn = m.GetCustomAttribute<DeviceInputMethodAttribute>();
                if (attrIn != null)
                {
                    InputMethods[attrIn] = m;
                }
            });
 
 
            stateChangedTimer = new Timer(new TimerCallback(CheckDeviceOpTimeOut), null, Timeout.Infinite, Timeout.Infinite);
 
            //StateMachine.OnUserLogin = OnCurrentUserLogin;
        }
 
        protected abstract void Init();
 
        protected abstract void Pause();
 
        protected abstract void Resume();
 
        protected abstract void Start();
 
        protected abstract void Stop();
 
        public virtual void Dispose()
        {
 
        }
 
        object OpLock = new Object(); //操作锁,一个设备,一次只能做一个动作
 
        public event DeviceStateChangedDelegate OnDeviceStateChangedWithDeviceInfo;
        public event PropertyChangedEventHandler PropertyChanged;
 
        /// <summary>
        /// 设备Run之前工序进入Running状态,设备Run完成之后工序进入Done状态
        /// 发生异常时,设备和工序都进入异常状态
        /// 考虑使用AOP切面实现前后状态变化
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        [DeviceExceptionAspect]
        [DeviceRunAspect]
        public virtual IOperationConfig SetAndRun(IOperationConfig config)
        {
            //try
            //{
            //lock (OpLock)
            //{
            //if (string.IsNullOrWhiteSpace(config.ProcessId))
            //{
            //    DeviceMode = EnumHelper.DeviceMode.Edit;
            //}
            //else
            //{
            //    DeviceMode = EnumHelper.DeviceMode.Run;
 
            //    ProcessId = config.ProcessId;
            //    ProcessName = config.ProcessName;
            //}
 
            //pauseHandle.WaitOne();
            //if (config.DeviceConfig != null)
            //{
            //    DeviceSet(config.DeviceConfig);
            //}
 
            //bool inputFlag = false;
            //do
            //{
            //    pauseHandle.WaitOne();
            //    inputFlag = DeviceInput(config);
            //} while (!inputFlag);
 
            //if (CurrentState != EnumHelper.DeviceState.DSOpen)
            //{
            //    return null;
            //}
 
            pauseHandle.WaitOne();
 
            if (config.IsEnabled)
            {
                DeviceRun(config);
            }
            pauseHandle.WaitOne();
            IOperationConfig output = DeviceOutput(config);
 
            //config.InputConfig?.Dispose();
 
            return output;
            //}
            //catch (Exception ex)
            //{
            //    return null;            
            //}
            //}
        }
 
        /// <summary>
        /// 根据设备配置信息配置设备参数
        /// </summary>
        /// <param name="config"></param>
        protected abstract void DeviceSet(IDeviceConfig config);
 
        protected virtual bool DeviceInput(IOperationConfig config)
        {
            ////如果需要设备输入配置判断
            //if (config.InputConfig != null && config.InputConfig.IsInputNeed)
            //{
            //    //config.InputConfig.BoundFlag = true;
            //    //等待输入配置信号量
            //    //config.InputConfig.InputHanlderDict[config.ProcessId]?.WaitOne();
            //    //while (config.InputConfig.InputFlagDict[config.ProcessId] == false && CurrentState == EnumHelper.DeviceState.DSOpen)
            //    //{
            //    //    Thread.Sleep(10);
            //    //}
 
            //    //config.InputConfig.InputFlagDict[config.ProcessId] = false;
 
            //    config.InputConfig.InputHandle.WaitOne();
            //    //Debug.WriteLine(DateTime.Now.ToString("mm:ss.fff") + "\t输入完成,编号:" + config.InputConfig.ProcessId);
 
            //    if (CurrentState != EnumHelper.DeviceState.DSOpen)
            //    {
            //        return true;
            //    }
 
            //    //config.InputConfig.InputHanlderDict[config.ProcessId].Reset();
 
            //    if (!string.IsNullOrWhiteSpace(config.InputConfig.InputMethodName))
            //    {
            //        var attr = InputMethods.Keys.FirstOrDefault(u => u.MethodName == config.InputConfig.InputMethodName);
            //        if (attr != null)
            //        {
            //            return Convert.ToBoolean(InputMethods[attr].Invoke(this, new object[] { config }));
            //        }
            //        else
            //        {
            //            //throw new UserException(string.Format("未能获取{0}的方法信息!", config.InputConfig.InputMethodName), EnumHelper.LogType.Exception_Fatal);
            //            throw new Exception(string.Format("未能获取{0}的方法信息!", config.InputConfig.InputMethodName));
            //        }
            //    }
            //}
 
            return true;
        }
 
        /// <summary>
        /// 设备运行
        /// </summary>
        /// <param name="config"></param>
        protected abstract void DeviceRun(IOperationConfig config);
 
        /// <summary>
        /// 具体的输出方法返回IOperationConfig,必须包括ProcessId和ResultOutput
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        protected virtual IOperationConfig DeviceOutput(IOperationConfig config)
        {
            //if (string.IsNullOrWhiteSpace(config.OutputMethodName))
            //{
            return null;
            //}
            //else
            //{
            //    #region 实时获取输出方法 考虑到效率问题,将方法字典转移到构造函数中实现
            //    //var methodInfo = this.GetType().GetMethods().FirstOrDefault(m =>
            //    //  {
            //    //      var attr = m.GetCustomAttribute<DeviceOutputMethodAttribute>();
 
            //    //      return attr != null && attr.MethodName == config.OutputMethodName;
            //    //  });
 
            //    //if (methodInfo == null)
            //    //{
            //    //    throw new UserException(string.Format("未能获取{0}的方法信息!", config.OutputMethodName));
            //    //}
            //    //else
            //    //{
            //    //    return (methodInfo.Invoke(this, new object[] { config })) as IOperationConfig;
            //    //}
            //    #endregion
 
            //    var attr = OutputMethods.Keys.FirstOrDefault(u => u.MethodName == config.OutputMethodName);
            //    if (attr != null)
            //    {
            //        return (OutputMethods[attr].Invoke(this, new object[] { config })) as IOperationConfig;
            //    }
            //    else
            //    {
            //        //throw new UserException(string.Format("未能获取{0}的方法信息!", config.OutputMethodName), EnumHelper.LogType.Exception_Fatal);
            //        throw new Exception(string.Format("未能获取{0}的方法信息!", config.OutputMethodName));
            //    }
            //}
        }
 
        [DeviceExceptionAspect]
        public void StateChange(EnumHelper.DeviceState stateToBe)
        {
            if (CurrentState == stateToBe)
            {
                return;
            }
 
            if (!stateToBe.CheckPreStateValid((int)CurrentStateToBe))
            {
                string currentStateStr = CurrentStateToBe.GetEnumDescription();
                string stateToBeStr = stateToBe.GetEnumDescription();
                throw new ProcessException($"{InitialConfig.Name}设备的当前状态为{currentStateStr},无法切换至{stateToBeStr}", null);
            }
 
            CurrentState = EnumHelper.DeviceState.TBD;
            CurrentStateToBe = stateToBe;
        }
 
        [DeviceStateChangedAspect]
        [DeviceExceptionAspect]
        private void OnStateChanged(EnumHelper.DeviceState initialState)
        {
            try
            {
                if (CurrentStateToBe != EnumHelper.DeviceState.DSExcept)
                {
                }
                else
                {
                    if (CurrentState == EnumHelper.DeviceState.DSExcept)
                    {
                        return;
                    }
                    else
                    {
                        throw new ProcessException($"{InitialConfig.Name}设备操作超时", null);
                    }
                }
 
                if (RetryTime >= 0)
                {
                    if (initialState == CurrentStateToBe)
                    {
                        CurrentState = CurrentStateToBe;
                        return;
                    }
 
                    #region 状态切换操作
                    switch (CurrentStateToBe)
                    {
                        case EnumHelper.DeviceState.DSInit:
                            if (initialState == EnumHelper.DeviceState.DSOpen)
                            {
                                return;
                            }
                            else
                            {
                                Init();
                            }
                            break;
                        case EnumHelper.DeviceState.DSOpen:
                            if (initialState == EnumHelper.DeviceState.DSInit)
                            {
                                Start();
                            }
                            else if (initialState == EnumHelper.DeviceState.DSPause)
                            {
                                Resume();
                                pauseHandle.Set();
                            }
                            break;
                        case EnumHelper.DeviceState.DSPause:
                            pauseHandle.Reset();
                            Pause();
                            break;
                        case EnumHelper.DeviceState.DSClose:
                            if (initialState != DeviceState.DSUninit)
                            {
                                Stop();
                            }
                            break;
                        default:
                            break;
                    }
 
                    RetryTime = 3;
                    CurrentState = CurrentStateToBe;
                    #endregion
                }
 
                stateChangedTimer.Change(Timeout.Infinite, Timeout.Infinite);
            }
            catch (Exception ex)
            {
                RetryTime--;
                if (RetryTime > 0)
                {
                    OnStateChanged(initialState);
                }
                else
                {
 
                    if (this.CurrentState != EnumHelper.DeviceState.DSExcept)
                    {
                        //this.CurrentState = EnumHelper.DeviceState.DSExcept;
                        //this.CurrentStateToBe = EnumHelper.DeviceState.DSExcept;
 
                        throw new ProcessException($"设备{InitialConfig.Name}的{CurrentStateToBe.GetEnumDescription()}操作重复3次失败", ex);
                    }
                }
            }
        }
 
        [DeviceExceptionAspect]
        private void CheckDeviceOpTimeOut(object state)
        {
            stateChangedTimer?.Change(Timeout.Infinite, Timeout.Infinite);
 
            if (CurrentState != EnumHelper.DeviceState.DSExcept)
            {
                StateChange(EnumHelper.DeviceState.DSExcept);
            }
        }
 
        #region 用户信息
        [JsonIgnore]
        public string CurrentUserId { get; set; }
 
        private void OnCurrentUserLogin(string obj)
        {
            CurrentUserId = obj;
        }
        #endregion
    }
}