Reflect_SeviceClient.cs 15.7 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2 3 4 5 6 7 8 9 10 11 12
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FObjBase.Reflect
{
13
    public abstract class Reflect_SeviceClient : FObjServiceClient
潘栩锋's avatar
潘栩锋 committed
14
    {
15 16 17 18
        #region Core
        /// <summary>
        /// 忽略设置
        /// </summary>
潘栩锋's avatar
潘栩锋 committed
19
        public bool ignoreSet;
20 21 22
        /// <summary>
        /// 代理对象 接口类型
        /// </summary>
23
        protected abstract Type InterfaceType { get; }
潘栩锋's avatar
潘栩锋 committed
24

25 26 27 28 29
        /// <summary>
        /// 已经同步完成;
        /// 已经收到了 CALL_GetAllProperties, 全部属性都与服务器一致
        /// </summary>
        public bool IsSynced { get; private set; }
30 31 32 33 34 35

        /// <summary>
        /// 当前 INotifyPropertyChanged 对象 引发了 PropertyChanged,  是由于 接收到数据导致的
        /// </summary>
        public bool IsInPushValue { get; protected set; }

潘栩锋's avatar
潘栩锋 committed
36 37 38 39 40
        class AnyEvent
        {
            public string name;
            public string triggerName;
            public Type retType;
41
            public MethodInfo methodInfo;
潘栩锋's avatar
潘栩锋 committed
42
        }
43
        class AnyCall
潘栩锋's avatar
潘栩锋 committed
44 45 46 47 48
        {
            public string name;
            public Type retType;
        }

49 50 51 52 53

        List<AnyEvent> anyEvents = new List<AnyEvent>();
        List<AnyCall> anyCalls = new List<AnyCall>();

        SubPropertyNode rootNode;
潘栩锋's avatar
潘栩锋 committed
54 55
        List<string> properties = new List<string>();

56 57 58 59 60 61 62 63 64 65 66

        /// <summary>
        /// 缓存 发出 CALL_GetAllProperties指令,到收到回复 之间时段的 全部推送
        /// </summary>
        List<PushInfoData> pushInfoList = new List<PushInfoData>();
        class PushInfoData
        {
            public bool isPushPropertyChanged;
            public Reflect_OBJ_INTERFACE.ReflectData rData;
        }

67 68
        #endregion

潘栩锋's avatar
潘栩锋 committed
69 70 71 72 73 74 75 76
        public Reflect_SeviceClient(UInt32 id) : base(id) {
            init();
        }

        public Reflect_SeviceClient(UInt32 serviceId, string connName) : base(serviceId, connName) {

            init();
        }
77 78 79 80 81 82 83 84 85 86

        #region Core
        void init()
        {
            rootNode = new SubPropertyNode
            {
                Obj = this,
                InterfaceType = InterfaceType,
                SubPropertyChanged = Sub_PropertyChanged
            };
潘栩锋's avatar
潘栩锋 committed
87 88

            InitPropertyChanged();
89
            COMMON.InitPropertyPush(rootNode);
潘栩锋's avatar
潘栩锋 committed
90 91
            InitEventPush();
            InitCall();
92 93 94 95 96 97 98 99

            this.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(IsConnected))
                {
                    if (IsConnected == false)
                    {
                        IsSynced = false;
100
                        pushInfoList.Clear();
101 102 103
                    }
                }
            };
潘栩锋's avatar
潘栩锋 committed
104 105 106 107 108 109 110
        }
        void InitPropertyChanged()
        {
            if (!typeof(INotifyPropertyChanged).IsAssignableFrom(InterfaceType))
                return;

            //继承了INotifyPropertyChanged
111
            this.PropertyChanged += rootNode.PropertyChanged;
潘栩锋's avatar
潘栩锋 committed
112

113
            var propertyInfos = COMMON.GetAllPropertyInfos(this.InterfaceType);//获取全部属性, 包括父类的属性
潘栩锋's avatar
潘栩锋 committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

            foreach (var propertyInfo in propertyInfos)
            {

                if (propertyInfo.GetCustomAttribute<JsonIgnoreAttribute>() != null)
                    continue;//这个不需要推送

                if (properties.Contains(propertyInfo.Name))
                    continue;
                properties.Add(propertyInfo.Name);
            }
        }

        void InitEventPush()
        {
129
            var interfaceTypes = new List<Type>();//获取全部接口
潘栩锋's avatar
潘栩锋 committed
130 131 132 133 134

            interfaceTypes.Add(InterfaceType);
            interfaceTypes.AddRange(InterfaceType.GetInterfaces());


135
            var eventInfos = new List<EventInfo>();//获取全部接口的全部event
潘栩锋's avatar
潘栩锋 committed
136 137 138 139 140 141 142
            foreach (var ifaceType in interfaceTypes)
            {
                eventInfos.AddRange(ifaceType.GetEvents());
            }

            foreach (var eventInfo in eventInfos)
            {
143
                var pushAttribute = eventInfo.GetCustomAttribute<PushAttribute>();//有[Push]特性的event
潘栩锋's avatar
潘栩锋 committed
144 145 146 147 148
                if (pushAttribute == null)
                    continue;

                if (anyEvents.Any(ae => ae.name == eventInfo.Name))
                    continue;//已经添加了
149

潘栩锋's avatar
潘栩锋 committed
150
                string triggerName;
151
                if (string.IsNullOrEmpty(pushAttribute.TriggerName))//没有定义触发方法的名字,使用默认组合
潘栩锋's avatar
潘栩锋 committed
152
                {
153
                    triggerName = PushAttribute.DefaultTriggerNameHeader + eventInfo.Name;
潘栩锋's avatar
潘栩锋 committed
154
                }
155 156
                else
                {
潘栩锋's avatar
潘栩锋 committed
157 158
                    triggerName = pushAttribute.TriggerName;
                }
159 160 161 162 163 164 165 166 167 168 169 170 171


                //测试触发方法是否存在,没有抛出异常
                var methodInfo = GetType().GetMethod(triggerName);
                if (methodInfo == null)
                {
                    throw new Exception($"客户端 {GetType()} 忘记写 {triggerName}");
                }





潘栩锋's avatar
潘栩锋 committed
172 173 174 175
                var anyEvent = new AnyEvent()
                {
                    name = eventInfo.Name,
                    triggerName = triggerName,
176 177
                    retType = pushAttribute.EventArgsType,
                    methodInfo = methodInfo
潘栩锋's avatar
潘栩锋 committed
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
                };
                anyEvents.Add(anyEvent);

            }
        }

        void InitCall()
        {
            var interfaceTypes = new List<Type>();

            interfaceTypes.Add(InterfaceType);
            interfaceTypes.AddRange(InterfaceType.GetInterfaces());


            var methodInfos = new List<MethodInfo>();
            foreach (var ifaceType in interfaceTypes)
            {
                methodInfos.AddRange(ifaceType.GetMethods());
            }

            foreach (var methodInfo in methodInfos)
            {
                var callAttribute = methodInfo.GetCustomAttribute<CallAttribute>();
                if (callAttribute == null)
                    continue;

                if (anyCalls.Any(ae => ae.name == methodInfo.Name))
                    continue;//已经添加了

                var anyCall = new AnyCall()
                {
                    name = methodInfo.Name,
                    retType = callAttribute.ReponseType
                };
                anyCalls.Add(anyCall);

            }
        }
216 217

        private void Sub_PropertyChanged(SubPropertyNode node, PropertyChangedEventArgs e)
潘栩锋's avatar
潘栩锋 committed
218 219 220 221 222 223 224
        {
            if (!IsConnected)
                return;

            if (ignoreSet)//从服务器接收的数据,不用再推送给服务器
                return;

225
            var type = node.Obj.GetType();
潘栩锋's avatar
潘栩锋 committed
226

227 228 229
            var propertyInfo = type.GetProperty(e.PropertyName);
            if (propertyInfo == null)
                return;//获取失败!!!
潘栩锋's avatar
潘栩锋 committed
230

231 232
            if (propertyInfo.GetCustomAttribute<JsonIgnoreAttribute>() != null)
                return;//这个不需要推送
潘栩锋's avatar
潘栩锋 committed
233

234
            var v = propertyInfo.GetValue(node.Obj);
潘栩锋's avatar
潘栩锋 committed
235
            var jObject = new JObject();
236 237
            if (v == null)
                jObject.Add(propertyInfo.Name, null);
潘栩锋's avatar
潘栩锋 committed
238
            else
239 240 241 242 243 244 245
                jObject.Add(propertyInfo.Name, JToken.FromObject(v));

            var rData = new Reflect_OBJ_INTERFACE.ReflectData
            {
                name = COMMON.GetNodePath(node),
                data = jObject
            };
246
            send_CALL_SetProperty(rData);
247
        }
潘栩锋's avatar
潘栩锋 committed
248 249


250 251 252 253 254 255 256 257 258 259 260 261
        public override void Dispose()
        {
            base.Dispose();

            if (typeof(INotifyPropertyChanged).IsAssignableFrom(InterfaceType))
            {
                //继承了INotifyPropertyChanged
                ((INotifyPropertyChanged)(this)).PropertyChanged -= rootNode.PropertyChanged;
            }

            //释放subProperties
            COMMON.NodeDispose(rootNode);
潘栩锋's avatar
潘栩锋 committed
262 263
        }

264
        protected void Call(string methodName, object parameters, AsyncCBHandler asyncDelegate, object asyncContext)
潘栩锋's avatar
潘栩锋 committed
265
        {
266 267 268 269 270
            var rData = new Reflect_OBJ_INTERFACE.ReflectData()
            {
                name = methodName,
                data = parameters == null ? null : JObject.FromObject(parameters)
            };
271
            send_CALL_MethodInvoke(rData, asyncDelegate, asyncContext);
272
        }
潘栩锋's avatar
潘栩锋 committed
273

274 275 276 277
        protected void Call(string methodName, object parameters)
        {
            Call(methodName, parameters, null, null);
        }
潘栩锋's avatar
潘栩锋 committed
278

279 280 281 282
        protected void Call(string methodName)
        {
            Call(methodName, null, null, null);
        }
潘栩锋's avatar
潘栩锋 committed
283

284 285 286 287 288 289

        /// <summary>
        /// 处理 从服务器 回复的 CALL_GetAllProperties
        /// </summary>
        /// <param name="rData"></param>
        void receive_CALL_GetAllProperties(Reflect_OBJ_INTERFACE.ReflectData rData)
290
        {
291
            receive_PUSH_PropertyChanged(rData);
292 293
            IsSynced = true;
            DealPushInfoList();
294
        }
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317

        /// <summary>
        /// 处理全部 缓存的推送数据
        /// </summary>
        void DealPushInfoList()
        {
            for (int i = 0; i < pushInfoList.Count(); i++)
            {
                var pushInfoData = pushInfoList[i];
                if (pushInfoData.isPushPropertyChanged)
                    receive_PUSH_PropertyChanged(pushInfoData.rData);
                else
                    receive_PUSH_Event(pushInfoData.rData);
            }

            pushInfoList.Clear();
        }

        /// <summary>
        /// 处理 从服务器 回复的 PUSH_PropertyChanged
        /// </summary>
        /// <param name="rData"></param>
        void receive_PUSH_PropertyChanged(Reflect_OBJ_INTERFACE.ReflectData rData)
318 319
        {
            ignoreSet = true;
320
            IsInPushValue = true;
321 322 323 324 325 326 327
            var node = COMMON.FindNode(rootNode, rData.name);
            if (node == null)
            {
                //异常
                //服务器乱发过来
                return;
            }
潘栩锋's avatar
潘栩锋 committed
328

329 330 331
            string json = rData.data.ToString();
            JsonConvert.PopulateObject(json, node.Obj);

332
            IsInPushValue = false;
333 334
            ignoreSet = false;
        }
335 336 337 338 339 340

        /// <summary>
        /// 处理 从服务器 回复的 PUSH_Event
        /// </summary>
        /// <param name="rData"></param>
        void receive_PUSH_Event(Reflect_OBJ_INTERFACE.ReflectData rData)
341 342
        {
            if (InterfaceType == null)
潘栩锋's avatar
潘栩锋 committed
343 344
                return;

345 346
            var anyEvent = anyEvents.Find(ae => ae.name == rData.name);
            if (anyEvent == null)
347
                return;//异常!!!, 在构造客户端时,已经检查完了,现在服务器乱发东西过来。
潘栩锋's avatar
潘栩锋 committed
348

349
            //触发事件!!!
350 351 352
            var methodInfo = anyEvent.methodInfo;

            //事件的数据转为 EventArgs 类型 
353
            var obj = rData.data.ToObject(anyEvent.retType);
354

355 356 357
            //出错,就提示,肯定是客户端忘记写 "Trigger_XXXX"
            methodInfo.Invoke(this, new object[] { obj });
        }
358 359 360 361 362 363 364 365

        /// <summary>
        /// 处理 从服务器 回复的 CALL_MethodInvoke
        /// </summary>
        /// <param name="rData"></param>
        /// <param name="asyncDelegate"></param>
        /// <param name="asyncContext"></param>
        void receive_CALL_MethodInvoke(Reflect_OBJ_INTERFACE.ReflectData rData, AsyncCBHandler asyncDelegate, object asyncContext)
366 367 368
        {
            var anyCall = anyCalls.Find(ac => ac.name == rData.name);
            if (anyCall == null)
潘栩锋's avatar
潘栩锋 committed
369
            {
370 371
                //异常!!!应该有[Call]注明返回的类型
                throw new Exception($"{rData.name} 异常!!!应该有[Call]注明返回的类型");
潘栩锋's avatar
潘栩锋 committed
372 373
            }

374
            var retData = rData.data.ToObject(anyCall.retType);
潘栩锋's avatar
潘栩锋 committed
375

376 377 378 379
            asyncDelegate.Invoke(asyncContext, retData);
        }
        #endregion

380 381 382 383 384 385 386 387

        /// <summary>
        /// 发送 CALL_MethodInvoke 请求到服务器
        /// </summary>
        /// <param name="rData"></param>
        /// <param name="asyncDelegate"></param>
        /// <param name="asyncContext"></param>
        void send_CALL_MethodInvoke(Reflect_OBJ_INTERFACE.ReflectData rData, AsyncCBHandler asyncDelegate, object asyncContext)
388 389 390 391 392 393 394 395
        {
            string json = JsonConvert.SerializeObject(rData);

            CurrObjSys.CallFunctionEx(mConn, mServerID, ID,
                Reflect_OBJ_INTERFACE.CALL_MethodInvoke,
                Misc.Converter.StringToBytes(json),
                asyncDelegate, asyncContext);
        }
潘栩锋's avatar
潘栩锋 committed
396

397 398 399 400 401
        /// <summary>
        /// 发送 CALL_SetProperty 请求到服务器
        /// </summary>
        /// <param name="rData"></param>
        void send_CALL_SetProperty(Reflect_OBJ_INTERFACE.ReflectData rData)
402 403 404 405 406
        {
            string json = JsonConvert.SerializeObject(rData);

            CurrObjSys.CallFunctionEx(mConn, mServerID, ID,
                Reflect_OBJ_INTERFACE.CALL_SetProperty,
潘栩锋's avatar
潘栩锋 committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
                Misc.Converter.StringToBytes(json));
        }

        #region FObj
        public override void ConnectNotify(IFConn from)
        {
            base.ConnectNotify(from);

            if (from.IsConnected)
            {
                //获取所有数据,设置推送
                 CurrObjSys.CallFunctionEx(
                    mConn, mServerID, ID,
                    Reflect_OBJ_INTERFACE.CALL_GetAllProperties, null);

                CurrObjSys.SenseConfigEx(
                    mConn, mServerID, ID,
                    0xffffffff,
                    SENSE_CONFIG.ADD);
            }
        }

429 430 431



潘栩锋's avatar
潘栩锋 committed
432 433 434 435 436 437 438 439 440
        public override void PushInfo(IFConn from, uint srcid, ushort infoid, byte[] infodata)
        {
            switch (infoid)
            {
                case Reflect_OBJ_INTERFACE.PUSH_PropertyChanged:
                case Reflect_OBJ_INTERFACE.PUSH_Event:
                    {
                        string json = Misc.Converter.BytesToString(infodata);
                        var rData = JsonConvert.DeserializeObject<Reflect_OBJ_INTERFACE.ReflectData>(json);
441 442 443 444 445 446 447 448 449 450 451 452

                        if (!IsSynced)
                        {
                            //还没同步完成,先缓存
                            pushInfoList.Add(
                                new PushInfoData() { 
                                    isPushPropertyChanged = (infoid == Reflect_OBJ_INTERFACE.PUSH_PropertyChanged),
                                    rData = rData });
                            return;
                        }

                        if(infoid == Reflect_OBJ_INTERFACE.PUSH_PropertyChanged)
453
                            receive_PUSH_PropertyChanged(rData);
454
                        else
455
                            receive_PUSH_Event(rData);
456

潘栩锋's avatar
潘栩锋 committed
457 458 459 460 461 462
                    }
                    break;
            }

        }

463

464
        public override void PushCallFunction(IFConn from, uint srcid, uint magic, ushort funcid, byte[] retdata, AsyncCBHandler asyncDelegate, object asyncContext)
潘栩锋's avatar
潘栩锋 committed
465 466 467 468 469 470
        {
            switch (funcid)
            {
                case Reflect_OBJ_INTERFACE.CALL_GetAllProperties:
                    {
                        string json = Misc.Converter.BytesToString(retdata);
471 472
                        var rData = JsonConvert.DeserializeObject<Reflect_OBJ_INTERFACE.ReflectData>(json);

473
                        receive_CALL_GetAllProperties(rData);
潘栩锋's avatar
潘栩锋 committed
474 475 476 477 478 479 480 481
                    }
                    break;
                case Reflect_OBJ_INTERFACE.CALL_MethodInvoke:
                    {
                        if (InterfaceType == null)
                            return;

                        string json = Misc.Converter.BytesToString(retdata);
482 483
                        var rData = JsonConvert.DeserializeObject<Reflect_OBJ_INTERFACE.ReflectData>(json);

484
                        receive_CALL_MethodInvoke(rData, asyncDelegate, asyncContext);
潘栩锋's avatar
潘栩锋 committed
485 486 487 488 489 490 491 492
                    }
                    break;
            }
        }
        
        #endregion
    }
}