Beispiel #1
0
        public static IDisposable WriteValues(this IValueSymbol symbol, IObservable <object> valueObservable)
        {
            Action <Exception> errorHandler = delegate(Exception ex) {
            };

            return(symbol.WriteValues(valueObservable, errorHandler));
        }
Beispiel #2
0
        public static IObservable <SymbolNotification> WhenNotification(this IAdsConnection client, ISymbolCollection symbols, NotificationSettings settings)
        {
            if (symbols == null)
            {
                throw new ArgumentNullException("symbols");
            }
            ISymbol local1 = Enumerable.FirstOrDefault <ISymbol>(symbols);

            if (local1 == null)
            {
                throw new ArgumentOutOfRangeException("Symbols list is empty!", "symbols");
            }
            IValueSymbol symbol = local1 as IValueSymbol;

            if (symbol == null)
            {
                throw new ArgumentOutOfRangeException("Symbols in list are not IValueSymbol", "symbols");
            }
            IAccessorValueFactory      valueFactory = symbol.ValueAccessor.ValueFactory;
            IDisposableSymbolHandleBag bag          = null;
            object userData = new object();

            return(Observable.Where <SymbolNotification>(Observable.Select <EventPattern <AdsNotificationEventArgs>, SymbolNotification>(Observable.Where <EventPattern <AdsNotificationEventArgs> >(Observable.FromEventPattern <AdsNotificationEventHandler, AdsNotificationEventArgs>(delegate(AdsNotificationEventHandler h) {
                client.AdsNotification += h;
                bag = new DisposableNotificationHandleBag(client, symbols, settings, userData);
            }, delegate(AdsNotificationEventHandler h) {
                bag.Dispose();
                bag = null;
                client.AdsNotification -= h;
            }), ev => bag.Contains((uint)ev.get_EventArgs().NotificationHandle)), ev => new SymbolNotification(ev.get_EventArgs(), bag.GetSymbol((uint)ev.get_EventArgs().NotificationHandle), valueFactory)), s => symbols.Contains(s.Symbol)));
        }
        /// <summary>
        /// Reads ADS Array Symbol value(s) into instance of type T[].
        /// </summary>
        /// <typeparam name="T">Type (class or struct Array definition)</typeparam>
        /// <param name="Symbol">ADS array symbol to read</param>
        /// <returns>Object array of type T with values read from Symbol</returns>
        public static T[] DeserializeArrayObject <T>(this ISymbol Symbol) where T : new()
        {
            // cast to IValueSymbol type
            IValueSymbol symbol = (IValueSymbol)Symbol;

            // instantiate new object array of symbol count size
            var obj = new T[symbol.SubSymbols.Count];

            // if primitive / non-struct type
            if (symbol.IsPrimitiveType)
            {
                // cast to appropriate type and return
                return((T[])symbol.ReadValue());
            }
            else
            {
                // iterate through each symbol array element
                for (int i = 0; i < symbol.SubSymbols.Count; i++)
                {
                    // call DeserializeObject on each element
                    obj[i] = DeserializeObject <T>(symbol.SubSymbols[i]);
                }
            }

            // return generated array of type T
            return(obj);
        }
        public void Dispose()
        {
            if (_client != null)
            {
                if (_eventSymbols.Count > 0)
                {
                    // unregister events
                    foreach (string symbol in _eventSymbols)
                    {
                        IValueSymbol symb = (IValueSymbol)_symbolLoader.Symbols[symbol];
                        symb.ValueChanged -= Symbol_ValueChanged;
                    }
                }

                // dispose custom event container
                _dynamicEvents.Dispose();


                // disconnect client
                if (_client.IsConnected)
                {
                    _client.Disconnect();
                }

                _client.Dispose();
            }
        }
Beispiel #5
0
        public static void WriteValues(this IValueSymbol symbol, IObservable <object> valueObservable, CancellationToken cancel)
        {
            Action <Exception> errorHandler = delegate(Exception ex) {
            };

            symbol.WriteValues(valueObservable, errorHandler, cancel);
        }
Beispiel #6
0
 public IValueSymbol WrapSymbol(IValueSymbol symbol)
 {
     if (symbol == null)
     {
         throw new ArgumentNullException("symbol");
     }
     return(this.create(symbol));
 }
Beispiel #7
0
 internal DynamicSymbol(IValueSymbol symbol)
 {
     if (symbol == null)
     {
         throw new ArgumentNullException("symbol");
     }
     this.symbol = symbol;
 }
        public static ExpandoObject GetStruct(this ISymbol Symbol)
        {
            // cast to IValueSymbol
            IValueSymbol symbol = (IValueSymbol)Symbol;

            // create dynamic expandable object to hold data
            dynamic myobj = new ExpandoObject();

            // primitive types
            if (symbol.IsPrimitiveType)
            {
                ((IDictionary <string, object>)myobj).Add(symbol.InstanceName, symbol.ReadValue());
                //return myobj;
            }
            else
            {
                // array of structs
                //***********NOT WORKING************
                if (symbol.Category == DataTypeCategory.Array)
                {
                    // declare sub element array for parallelization
                    // calling dict.Add() in parallel loop will result in
                    // out-of-order elements
                    var sub = new KeyValuePair <string, object> [symbol.SubSymbols.Count];
                    // loop through struct array and call recursively
                    for (int i = 0; i < symbol.SubSymbols.Count; i++)
                    {
                        sub[i] = new KeyValuePair <string, object>(symbol.SubSymbols[i].InstanceName, symbol.SubSymbols[i].GetStruct());
                        //((IDictionary<string, object>)myobj).Add(symbol.InstanceName, symbol.SubSymbols[i].GetStruct());
                    }
                    ((IDictionary <string, object>)myobj).Add(symbol.InstanceName, sub);
                    //return myobj;
                    //// add loaded KVPs into dictionary
                    //foreach (KeyValuePair<string, object> pair in sub)
                    //{
                    //    dict.Add(pair.Key, pair.Value);
                    //}
                }
                // struct
                else if (symbol.Category == DataTypeCategory.Struct)
                {
                    int i = 0;
                    foreach (IValueSymbol symb in symbol.SubSymbols)
                    {
                        if (symb.IsPrimitiveType)
                        {
                            ((IDictionary <string, object>)myobj).Add(symb.InstanceName, symb.ReadValue());
                        }
                        else
                        {
                            ((IDictionary <string, object>)myobj).Add(symb.InstanceName, symb.GetStruct());
                        }
                        i++;
                    }
                }
            }
            return(myobj);
        }
 /// <summary>
 /// Raises 'Method' action when SymbolPath value changes
 /// </summary>
 /// <param name="SymbolName">Path of Symbol to poll for value change</param>
 /// <param name="Method">Action / method executed on value change</param>
 public void SubscribeOnValueChange(string SymbolPath, Action <object> Method)
 {
     if (_dynamicEvents[SymbolPath] == null)
     {
         IValueSymbol symbol = (IValueSymbol)_symbolLoader.Symbols[SymbolPath];
         symbol.ValueChanged += Symbol_ValueChanged;
         _dynamicEvents.AddHandler(symbol.InstancePath, Method);
     }
 }
 public Task Subscribe(IValueSymbol o)
 {
     _eventAggregator.PublishOnCurrentThreadAsync(new SymbolRegisterMessage()
     {
         RegisterType = RegisterType.Subscribe,
         InstancePath = o.InstancePath
     });
     return(Task.CompletedTask);
 }
        /// <summary>
        /// Reads ADS Symbol into Dictionary of key/value pairs.
        /// Experimental. Very slow.
        /// </summary>
        /// <param name="Symbol">ADS symbol to read</param>
        /// <returns>Dictionary of key/value pairs</returns>
        public static Dictionary <string, object> ToDictionary(this ISymbol Symbol)
        {
            // cast to IValueSymbol
            IValueSymbol symbol = (IValueSymbol)Symbol;

            // create new dictionary
            Dictionary <string, object> dict = new Dictionary <string, object>();

            // primitive types
            if (symbol.IsPrimitiveType)
            {
                dict.Add(symbol.InstanceName, symbol.ReadValue());
            }
            else
            {
                // array of structs
                if (symbol.Category == DataTypeCategory.Array)
                {
                    // declare sub element array for parallelization
                    // calling dict.Add() in parallel loop will result in
                    // out-of-order elements
                    var sub = new KeyValuePair <string, object> [symbol.SubSymbols.Count];

                    // loop through struct array and call recursively
                    for (int i = 0; i < symbol.SubSymbols.Count; i++)
                    {
                        sub[i] = new KeyValuePair <string, object>(symbol.SubSymbols[i].InstanceName, symbol.SubSymbols[i].ToDictionary());
                    }

                    // add loaded KVPs into dictionary
                    foreach (KeyValuePair <string, object> pair in sub)
                    {
                        dict.Add(pair.Key, pair.Value);
                    }
                }
                // struct
                else if (symbol.Category == DataTypeCategory.Struct)
                {
                    foreach (IValueSymbol symb in symbol.SubSymbols)
                    {
                        if (symb.IsPrimitiveType)
                        {
                            dict.Add(symb.InstanceName, symb.ReadValue());
                        }
                        else
                        {
                            dict.Add(symb.InstanceName, symb.ToDictionary());
                        }
                    }
                }
            }


            return(dict);
        }
Beispiel #12
0
        public ISymbol CreateReferenceInstance(IPointerType type, ISymbol parent)
        {
            IValueSymbol symbol  = (IValueSymbol)this.inner.CreateReferenceInstance(type, ((DynamicSymbol)parent).InnerSymbol);
            ISymbol      symbol2 = null;

            if (symbol != null)
            {
                symbol2 = this.create(symbol);
            }
            return(symbol2);
        }
Beispiel #13
0
        public ISymbol CreateFieldInstance(IField field, ISymbol parent)
        {
            IValueSymbol symbol  = (IValueSymbol)this.inner.CreateFieldInstance(field, parent);
            ISymbol      symbol2 = null;

            if (symbol != null)
            {
                symbol2 = this.create(symbol);
            }
            return(symbol2);
        }
        public bool TryGetNotificationSettings(ISymbol symbol, out INotificationSettings settings)
        {
            IValueSymbol symbol2 = (IValueSymbol)symbol;

            if (symbol2 != null)
            {
                settings = symbol2.NotificationSettings;
                return(true);
            }
            settings = null;
            return(false);
        }
Beispiel #15
0
        public ISymbol CreateOversamplingElement(ISymbol parent)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }
            IValueSymbol symbol  = (IValueSymbol)((ISymbolFactoryOversampled)this.inner).CreateOversamplingElement(parent);
            ISymbol      symbol2 = null;

            if (symbol != null)
            {
                symbol2 = this.create(symbol);
            }
            return(symbol2);
        }
        /// <summary>
        /// Raises OnSymbolValueChanged event when SymbolPath value changes
        /// </summary>
        /// <param name="SymbolName">Path of Symbol to poll for value change</param>
        public void SubscribeOnValueChange(string SymbolPath)
        {
            if (_eventSymbols == null)
            {
                _eventSymbols = new List <string>();
            }

            if (!_eventSymbols.Contains(SymbolPath))
            {
                IValueSymbol symbol = (IValueSymbol)_symbolLoader.Symbols[SymbolPath];

                symbol.ValueChanged += Symbol_ValueChanged;
                _eventSymbols.Add(symbol.InstancePath);
            }
        }
Beispiel #17
0
        public ISymbol CreateArrayElement(int[] currentIndex, ISymbol parent, IArrayType arrayType)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }
            IValueSymbol symbol  = (IValueSymbol)this.inner.CreateArrayElement(currentIndex, parent, arrayType);
            ISymbol      symbol2 = null;

            if (symbol != null)
            {
                symbol2 = this.create(symbol);
            }
            return(symbol2);
        }
Beispiel #18
0
        public static void WriteValues(this IValueSymbol symbol, IObservable <object> valueObservable, Action <Exception> errorHandler, CancellationToken cancel)
        {
            Action <object> action = delegate(object o) {
                try
                {
                    symbol.WriteValue(o);
                }
                catch (Exception exception)
                {
                    errorHandler(exception);
                }
            };
            Action <Exception> action2 = ex => errorHandler(ex);

            ObservableExtensions.Subscribe <object>(valueObservable, action, action2, delegate {
            }, cancel);
        }
Beispiel #19
0
        private int readArraySize()
        {
            int          num             = 0;
            IValueSymbol arraySizeSymbol = (IValueSymbol)this.ArraySizeSymbol;

            if (arraySizeSymbol != null)
            {
                try
                {
                    num = PrimitiveTypeConverter.Convert <int>(arraySizeSymbol.ReadValue());
                }
                catch (Exception)
                {
                }
            }
            return(num);
        }
Beispiel #20
0
        public static IDisposable WriteValues(this IValueSymbol symbol, IObservable <object> valueObservable, Action <Exception> errorHandler)
        {
            Action <object> action = delegate(object o) {
                try
                {
                    symbol.WriteValue(o);
                }
                catch (Exception exception)
                {
                    errorHandler(exception);
                }
            };
            Action <Exception> action2 = delegate(Exception ex) {
                errorHandler(ex);
            };

            return(ObservableExtensions.Subscribe <object>(valueObservable, action, action2, delegate {
            }));
        }
Beispiel #21
0
 public static IObservable <object> WhenValueChanged(this IValueSymbol symbol) =>
 Observable.Select <EventPattern <ValueChangedArgs>, object>(Observable.FromEventPattern <EventHandler <ValueChangedArgs>, ValueChangedArgs>(delegate(EventHandler <ValueChangedArgs> h) {
     symbol.ValueChanged += h;
 }, delegate(EventHandler <ValueChangedArgs> h) {
     symbol.ValueChanged -= h;
 }), ev => ev.get_EventArgs().Value);
Beispiel #22
0
 public static IObservable <object> PollValues(this IValueSymbol symbol, TimeSpan period)
 {
     long[] numArray1 = new long[] { -1L };
     return(symbol.PollValues(Observable.Select <long, Unit>(Observable.StartWith <long>(Observable.Interval(period), numArray1), e => Unit.get_Default())));
 }
Beispiel #23
0
 public InsufficientAccessRights(IValueSymbol symbol, SymbolAccessRights requested) : base($"The requested rights '{requested}' for symbol '{symbol.InstanceName}' are not sufficient (Current rights: {symbol.AccessRights})!", symbol)
 {
 }
Beispiel #24
0
        private IValueSymbol create(IValueSymbol symbol)
        {
            if (symbol == null)
            {
                throw new ArgumentNullException("symbol");
            }
            DataTypeCategory category = symbol.Category;

            switch (category)
            {
            case DataTypeCategory.Alias:
            {
                IAliasInstance aliasInstance = symbol as IAliasInstance;
                if (aliasInstance != null)
                {
                    return(new DynamicAliasInstance(aliasInstance));
                }
                Module.Trace.TraceWarning($"'{symbol.InstancePath}' cannot be resolved to alias");
                return(new DynamicSymbol(symbol));
            }

            case DataTypeCategory.Enum:
                break;

            case DataTypeCategory.Array:
                if (symbol is IArrayInstance)
                {
                    return(!(symbol is IOversamplingArrayInstance) ? new DynamicArrayInstance((IArrayInstance)symbol) : new DynamicOversamplingArrayInstance((IOversamplingArrayInstance)symbol));
                }
                Module.Trace.TraceWarning($"'{symbol.InstancePath}' cannot be resolved to array");
                return(new DynamicSymbol(symbol));

            case DataTypeCategory.Struct:
            {
                IStructInstance instance3 = symbol as IStructInstance;
                if (instance3 != null)
                {
                    return(!instance3.HasRpcMethods ? new DynamicStructInstance((IStructInstance)symbol) : new DynamicRpcStructInstance((IRpcStructInstance)symbol));
                }
                Module.Trace.TraceWarning($"'{symbol.InstancePath}' cannot be resolved to struct");
                return(new DynamicSymbol(symbol));
            }

            default:
                switch (category)
                {
                case DataTypeCategory.Pointer:
                {
                    IPointerInstance pointerInstance = symbol as IPointerInstance;
                    if (pointerInstance != null)
                    {
                        return(new DynamicPointerInstance(pointerInstance));
                    }
                    Module.Trace.TraceWarning($"'{symbol.InstancePath}' cannot be resolved to pointer");
                    return(new DynamicSymbol(symbol));
                }

                case DataTypeCategory.Union:
                {
                    IUnionInstance unionInstance = symbol as IUnionInstance;
                    if (unionInstance != null)
                    {
                        return(new DynamicUnionInstance(unionInstance));
                    }
                    Module.Trace.TraceWarning($"'{symbol.InstancePath}' cannot be resolved to union");
                    return(new DynamicSymbol(symbol));
                }

                case DataTypeCategory.Reference:
                {
                    IReferenceInstance refInstance = symbol as IReferenceInstance;
                    if (refInstance != null)
                    {
                        return(new DynamicReferenceInstance(refInstance));
                    }
                    Module.Trace.TraceWarning($"'{symbol.InstancePath}' cannot be resolved to reference");
                    return(new DynamicSymbol(symbol));
                }

                default:
                    break;
                }
                break;
            }
            return(new DynamicSymbol(symbol));
        }
Beispiel #25
0
 public static IObservable <ValueChangedArgs> PollValuesAnnotated(this IValueSymbol symbol, IObservable <Unit> trigger) =>
 Observable.Select <object, ValueChangedArgs>(symbol.PollValues(trigger), o => new ValueChangedArgs(symbol, o, DateTime.UtcNow));
Beispiel #26
0
 public static IObservable <ValueChangedArgs> PollValuesAnnotated(this IValueSymbol symbol, TimeSpan period) =>
 Observable.Select <object, ValueChangedArgs>(symbol.PollValues(period), o => new ValueChangedArgs(symbol, o, DateTime.UtcNow));
Beispiel #27
0
 public static IObservable <ValueChangedArgs> WhenValueChangedAnnotated(this IAdsConnection connection, IValueSymbol symbol) =>
 Observable.Select <EventPattern <ValueChangedArgs>, ValueChangedArgs>(Observable.FromEventPattern <EventHandler <ValueChangedArgs>, ValueChangedArgs>(delegate(EventHandler <ValueChangedArgs> h) {
     symbol.ValueChanged += h;
 }, delegate(EventHandler <ValueChangedArgs> h) {
     symbol.ValueChanged -= h;
 }), ev => ev.get_EventArgs());
Beispiel #28
0
        public ISymbol CreateInstance(ISymbolInfo entry, ISymbol parent)
        {
            IValueSymbol symbol = (IValueSymbol)this.inner.CreateInstance(entry, parent);

            return(this.WrapSymbol(symbol));
        }
Beispiel #29
0
        public static IObservable <object> PollValues(this IValueSymbol symbol, IObservable <Unit> trigger)
        {
            Func <Unit, object> func = o => symbol.ReadValue();

            return(Observable.Select <Unit, object>(trigger, func));
        }
        /// <summary>
        /// Writes to ADS symbol from custom object type.
        /// </summary>
        /// <param name="Symbol">ADS Symbol to write</param>
        /// <param name="Data">User defined object (class or struct with matching properties) to write to Symbol</param>
        public static void SerializeObject(this ISymbol Symbol, object Object)
        {
            // cast to IValueSymbol type (for read/write)
            IValueSymbol symbol = (IValueSymbol)Symbol;

            // if primitive type
            if (symbol.IsPrimitiveType)
            {
                // write object to symbol value
                symbol.WriteValue(Object);
            }
            else
            {
                // symbol is array of non-primitive (struct array)
                if (symbol.Category == DataTypeCategory.Array)
                {
                    // validate Object parameter is array
                    if (Object.GetType().IsArray)
                    {
                        // cast Object to array var for indexing
                        var arr = (Array)Object;

                        // loop through elements (with upper bounds check)
                        for (int i = 0; i < Math.Max(symbol.SubSymbols.Count, arr.Length); i++)
                        {
                            // get Object element, call recursively
                            if (arr.GetValue(i) != null)
                            {
                                SerializeObject(symbol.SubSymbols[i], arr.GetValue(i));
                            }
                        }
                    }
                    else
                    {
                        // array type mismatch exception
                        throw new Exception("Type mismatch: Object parameter is not array type.");
                    }
                }
                else
                {
                    foreach (ISymbol symb in symbol.SubSymbols)
                    {
                        // get IValueSymbol
                        IValueSymbol vSymb = (IValueSymbol)symb;

                        // check if Object parameter contains matching property
                        var property = Object.GetType().GetProperty(vSymb.InstanceName);
                        if (property != null)
                        {
                            // if symbol is primitive
                            if (vSymb.IsPrimitiveType)
                            {
                                // write object property value to symbol
                                vSymb.WriteValue(property.GetValue(Object));
                            }
                            else
                            {
                                // if sub symbol is array type
                                if (vSymb.Category == DataTypeCategory.Array)
                                {
                                    // cast property to array var for indexing
                                    var arr = (Array)property.GetValue(Object);

                                    // loop through elements (with upper bounds check)
                                    for (int i = 0; i < Math.Max(vSymb.SubSymbols.Count, arr.Length); i++)
                                    {
                                        // if property array index is initialized, call recursively
                                        if (arr.GetValue(i) != null)
                                        {
                                            SerializeObject(vSymb.SubSymbols[i], arr.GetValue(i));
                                        }
                                    }
                                }
                                else
                                {
                                    // call recursively on struct
                                    SerializeObject(vSymb, property.GetValue(Object));
                                }
                            }
                        }
                    }
                }
            }
        }