Exemplo n.º 1
0
        public async Task <bool> Send <T>(ComNode node, short channelId, T data)
        {
            if (sendPortNumber == 0)
            {
                return(false);
            }

            return(await Task.Run(async() => {
                if (!dataChannelMap.ContainsKey(channelId))
                {
                    return false;
                }

                IDataChannel channel = dataChannelMap[channelId];

                bool isRent = false;
                byte[] buffer = null;
                int bufferSize = 0;

                BuildBuffer(channel, data, ref buffer, ref bufferSize, ref isRent);

                await udpSender.Send(node.IP, bufferSize, buffer);

                if (isRent)
                {
                    arrayPool.Return(buffer);
                }

                return true;
            }));
        }
Exemplo n.º 2
0
 public FilteredChannel(IDataChannel <double> channel, Filter[] filters)
 {
     _sourceChannel             = channel;
     _anyChannel                = new AnyChannel(create_FilteredDoubleChannel(channel.ChannelPtr, filters, (IntPtr)filters.Length));
     _dataChannel               = new DataChannel <double>(_anyChannel);
     _anyChannel.LengthChanged += (sender, length) => LengthChanged?.Invoke(sender, length);
 }
Exemplo n.º 3
0
        void OnTCPReceived(string endPointIp, short channelId, byte[] data, int size)
        {
            if (channelId == (short)PreservedChannelId.Beacon)
            {
            }
            else if (!dataChannelMap.ContainsKey(channelId))
            {
            }
            else
            {
                BytePacker packer = new BytePacker(data);

                if (serverNode == null)
                {
                    ;
                }
                if (endPointIp == serverNode.IP)
                {
                    healthLostCount = 0;

                    IDataChannel channel   = dataChannelMap[channelId];
                    object       container = channel.FromStream(ref packer);

                    channel.Received(serverNode, container);
                }
            }
        }
Exemplo n.º 4
0
        void OnTCPReceived(string endPointIp, short channelId, byte[] data, int size)
        {
            if (channelId == (short)PreservedChannelId.Beacon)
            {
            }
            else if (channelId == (short)PreservedChannelId.Health)
            {
                if (nodeMap.ContainsKey(endPointIp))
                {
                    ComNode node = nodeMap[endPointIp];
                    node.HealthLostCount = 0;
                }
            }
            else if (!dataChannelMap.ContainsKey(channelId))
            {
            }
            else
            {
                BytePacker packer = new BytePacker(data);

                if (nodeMap.ContainsKey(endPointIp))
                {
                    ComNode node = nodeMap[endPointIp];

                    node.HealthLostCount = 0;

                    IDataChannel channel = dataChannelMap[channelId];

                    object container = channel.FromStream(ref packer);

                    channel.Received(node, container);
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// 获取数据通道,如指定的通道类型不存在时,返回null
        /// </summary>
        /// <param name="servicePort"></param>
        /// <param name="cellID"></param>
        /// <param name="channelType"></param>
        /// <returns></returns>
        public IDataChannel getDataChannel(string mac, string channelType)
        {
            var query = from p in _listDataChannel
                        where p.MAC.ToString() == mac && p.ChannelType == channelType
                        select p;
            List <IDataChannel> list = query.ToList();

            if (list != null && list.Count == 1)
            {
                return(list[0]);
            }
            else
            {
                //加载数据通道(服务端口-数据单元-数据通道)
                var queryChannel = from p in DataChannelFactory
                                   where p.ChannelType == channelType
                                   select p;
                List <ICreateDataChannel> cList = queryChannel.ToList();
                if (cList != null && cList.Count > 0)
                {
                    IDataChannel channel = cList[0].CreateDataChannel(mac);
                    this._listDataChannel.Add(channel);
                    return(channel);
                }
                else
                {
                    //找不到指定编码的通道组件
                }
            }


            return(null);
        }
Exemplo n.º 6
0
 public BipolarDoubleChannel(IDataChannel <double> first, IDataChannel <double> second)
 {
     _firstSourceChannel        = first;
     _secondSourceChannel       = second;
     _anyChannel                = new AnyChannel(create_BipolarDoubleChannel(first.ChannelPtr, second.ChannelPtr));
     _dataChannel               = new DataChannel <double>(_anyChannel);
     _anyChannel.LengthChanged += (sender, length) => LengthChanged?.Invoke(sender, length);
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="connectionId"></param>
 /// <param name="channel"></param>
 public virtual void AddChannel(string connectionId, IDataChannel channel)
 {
     if (channel.IsLocal)
     {
         var _channel = m_handler.CreateChannel(connectionId, channel.Label);
         channel.SetChannel(connectionId, _channel);
     }
 }
Exemplo n.º 8
0
 public void AddChannel(IDataChannel channel)
 {
     if (channel.Qos != QosType.Unreliable)
     {
         throw new ArgumentException("Qos type is not valid.");
     }
     dataChannelMap.Add(channel.ChannelID, channel);
 }
Exemplo n.º 9
0
        /// <summary>
        /// A tracker to capture, store, and transmit events to a data channel.
        /// </summary>
        /// <param name="channel"> The channel used to store the data remotely. </param>
        /// <param name="provider"> The repository used to store the data locally. </param>
        /// <param name="elapsedTime"> The amount of time this tracker should have already been running. </param>
        /// <param name="values"> The values to associate with this session. </param>
        public static Tracker Start(IDataChannel channel, IRepositoryProvider provider, TimeSpan elapsedTime, params EventValue[] values)
        {
            var application = (Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly()).GetName();
            var tracker     = new Tracker(channel, provider);

            tracker.Start(application, elapsedTime, values);
            return(tracker);
        }
Exemplo n.º 10
0
 protected override void OnPeerConnectionCreatedInternal(IPeerConnection peerConnection)
 {
     base.OnPeerConnectionCreatedInternal(peerConnection);
     _dataChannel = peerConnection.CreateDataChannel("sendChannel", new DataChannelConfiguration());
     if (_dataChannel != null)
     {
         _dataChannel.OnMessage += DataChannelOnOnMessage;
     }
 }
Exemplo n.º 11
0
        public static PhysicalPosition GetChannelPosition(IDataChannel channel)
        {
            if (!coordinates.ContainsKey(channel.ChannelId))
            {
                coordinates.Add(channel.ChannelId, GetDefaultPosition(coordinates.Count));
            }

            return(coordinates[channel.ChannelId]);
        }
Exemplo n.º 12
0
        void OnUDPReceived(string endPointIp, byte[] data, int size)
        {
            int head = 0;

            while (head < size)
            {
                BytePacker packer   = new BytePacker(data);
                short      datasize = packer.ReadShort();
#if DISABLE_CHANNEL_VARINT
                short channelId = packer.ReadShort();
#else
                int   s         = 0;
                short channelId = VarintBitConverter.ToShort(packer, out s);
#endif

                if (channelId == (short)PreservedChannelId.Beacon)
                {
                }
                else if (channelId == (short)PreservedChannelId.Health)
                {
                    if (nodeMap.ContainsKey(endPointIp))
                    {
                        ComNode node = nodeMap[endPointIp];
                        node.HealthLostCount = 0;
                    }
                }
                else if (!dataChannelMap.ContainsKey(channelId))
                {
                }
                else
                {
                    IDataChannel channel = dataChannelMap[channelId];

                    if (channel.CheckMode == CheckMode.Sequre)
                    {
                        if (nodeMap.ContainsKey(endPointIp))
                        {
                            ComNode node = nodeMap[endPointIp];

                            node.HealthLostCount = 0;

                            object container = channel.FromStream(ref packer);

                            channel.Received(node, container);
                        }
                    }
                    else
                    {
                        object container = channel.FromStream(ref packer);

                        channel.Received(null, container);
                    }
                }

                head += datasize + 4;
            }
        }
Exemplo n.º 13
0
        public void AddChannel(IDataChannel channel, int channelId)
        {
            if (_isRegisteringChannels == true)
            {
                throw new InvalidOperationException("A server that is registering channels cannot add them.");
            }

            _isRegisteringChannels = false;
            InternalAddChannel(channel, channelId);
        }
Exemplo n.º 14
0
        public IDataChannel Apply(IDataChannel input)
        {
            FilteredDataChannel output = new FilteredDataChannel(input, input.SamplesPerSecond, settings.BufferSize == 0 ? input.BufferSize : settings.BufferSize, this);

            this.Input  = input;
            this.Output = output;

            this.Input.DataChanged += InputDataChanged;

            return(output);
        }
Exemplo n.º 15
0
        public DataChannelInfo(IDataChannel dataChannel, int channelId)
        {
            DataChannel    = dataChannel;
            ChannelId      = channelId;
            IsSynchronized = dataChannel.GetType().GetCustomAttribute <SynchronizedChannelAttribute>() != null;
            AsyncLock      = new FifoAsyncLock();

            _disposeLock             = new object();
            _isDisposed              = false;
            _cancellationTokenSource = new CancellationTokenSource();
        }
Exemplo n.º 16
0
        public async Task <bool> Send <T>(ComNode node, short channelId, T data)
        {
            if (!nodeMap.ContainsKey(node.IP))
            {
                return(false);
            }

            if (!dataChannelMap.ContainsKey(channelId))
            {
                return(false);
            }

            IDataChannel channel = dataChannelMap[channelId];

            bool isRent  = true;
            int  bufSize = channel.GetDataSize(data);

            byte[] buf = arrayPool.Rent(bufSize + 6);
            if (buf == null)
            {
                isRent = false;
                buf    = new byte[bufSize + 6];
            }

            BytePacker packer = new BytePacker(buf);

            packer.Write((short)bufSize);

#if DISABLE_CHANNEL_VARINT
            packer.Write(channelId);
#else
            int s = 0;
            VarintBitConverter.SerializeShort(channelId, packer, out s);
#endif
            channel.ToStream(data, ref packer);

            int maxpos = (int)packer.Position;

            if (channel.Qos == QosType.Reliable)
            {
                await node.Connection.Send(maxpos, buf);
            }
            else if (channel.Qos == QosType.Unreliable)
            {
                await udpSender.Send(node.IP, maxpos, buf);
            }

            if (isRent)
            {
                arrayPool.Return(buf);
            }

            return(true);
        }
Exemplo n.º 17
0
        /// <summary>
        /// A tracker to capture, store, and transmit events to a data channel.
        /// </summary>
        /// <param name="channel"> The channel used to store the data remotely. </param>
        /// <param name="provider"> The repository used to store the data locally. </param>
        public Tracker(IDataChannel channel, IRepositoryProvider provider)
        {
            _channel        = channel;
            _provider       = provider;
            _eventProcessor = new BackgroundWorker();
            _eventProcessor.WorkerSupportsCancellation = true;
            _eventProcessor.DoWork += EventProcessorOnDoWork;

            EventProcessingDelay  = 250;
            EventProcessorRunning = false;
        }
Exemplo n.º 18
0
        public TestMeter(string meterId, IDataChannel channel)
        {
            this._channel  = channel;
            this._meterId  = meterId;
            this._protocol = new LoTMeter(this._channel);

            this._channel.OnReceiveData  += this._protocol.ReceiveData;
            this._protocol.OnReceiveData += ReviceData;

            System.Console.WriteLine(this._meterId + "加载通道完成...");
        }
Exemplo n.º 19
0
        private void DataSource_MessageReceive(object sender, SportEvent ev)
        {
            IDataChannel <SportEvent> channel = null;

            channel = _pool.FindRelevantChannel(ev, ev.EventId);
            if (channel != null)
            {
                bool done = channel.PushData(ev);

                log.LogTrace("Receve new event #{0} at @{1}", ev.EventId, Environment.TickCount);
            }
        }
Exemplo n.º 20
0
        public void AddChannel(IDataChannel channel)
        {
            if (channel.Qos != QosType.Unreliable)
            {
                throw new ArgumentException("Qos type is not valid.");
            }

            if (channel.Encryption != Encryption.None)
            {
                throw new ArgumentException("ComTerminal can not use encryption.");
            }
            dataChannelMap.Add(channel.ChannelID, channel);
        }
Exemplo n.º 21
0
        protected void InternalAddChannel(IDataChannel channel, int channelId)
        {
            var channelInfo = new DataChannelInfo(channel, channelId);

            if (!_channels.TryAdd(channelId, channelInfo))
            {
                throw new InvalidOperationException("The channel id is already in use");
            }

            Logger.Debug("Add channel with id {channelId}", channelId);

            channel.Send           = (buffer, offset, count, hasOffset) => ChannelSendData(channelInfo, buffer, offset, count, hasOffset);
            channel.RequiredOffset = _customOffset + 5;
        }
Exemplo n.º 22
0
        void OnUDPReceived(string endPointIp, byte[] data, int size)
        {
            int head = 0;

            while (head < size)
            {
                BytePacker packer   = new BytePacker(data);
                short      datasize = packer.ReadShort();
#if DISABLE_CHANNEL_VARINT
                short channelId = packer.ReadShort();
#else
                int   s         = 0;
                short channelId = VarintBitConverter.ToInt16(packer, out s);
#endif

                if (channelId == (short)PreservedChannelId.Beacon)
                {
                    if (acceptBeacon && !isConnecting && !IsConnected)
                    {
                        string beaconData = (string)DataSerializer.Deserialize <string>(packer);

                        if (BeaconAccept(beaconData))
                        {
                            Connect(endPointIp);
                        }
                    }
                }
                else if (!dataChannelMap.ContainsKey(channelId))
                {
                }
                else
                {
                    if (serverNode == null)
                    {
                        break;
                    }
                    if (endPointIp == serverNode.IP)
                    {
                        healthLostCount = 0;

                        IDataChannel channel   = dataChannelMap[channelId];
                        object       container = channel.FromStream(ref packer);

                        channel.Received(serverNode, container);
                    }
                }

                head += datasize + 4;
            }
        }
Exemplo n.º 23
0
        public int RegisterChannel(IDataChannel channel)
        {
            if (_isRegisteringChannels == false)
            {
                throw new InvalidOperationException("A server that is adding channels cannot register them.");
            }

            _isRegisteringChannels = true;

            var id = Interlocked.Increment(ref _channelCounter);

            InternalAddChannel(channel, id);

            return(id);
        }
Exemplo n.º 24
0
        public static T FindFilter <T>(IDataChannel channel) where T : class, IChannelFilter
        {
            var filteredChannel = channel as FilteredDataChannel;

            if (filteredChannel == null)
            {
                return(null);
            }

            if (filteredChannel.Filter is T)
            {
                return(filteredChannel.Filter as T);
            }

            return(FindFilter <T>(filteredChannel.Input));
        }
Exemplo n.º 25
0
        public IDataChannel <SportEvent> FindRelevantChannel(int tag)
        {
            IDataChannel <SportEvent> channel = null;

            log.LogDebug("Searching for relevant channel with eventId:{0}", tag);

            if (!_links.TryGetValue(tag, out channel))
            {
                channel = (_pool.Count < _maxChannels) ? CreateChannel : RandomChannel;
                AddChannel(channel, tag);

                log.LogDebug("Founded channel {0} for tag {1}", channel.Id, tag);
            }

            return(channel);
        }
Exemplo n.º 26
0
        void BuildBuffer <T>(
            IDataChannel channel, T data, ref byte[] buffer, ref int bufferSize, ref bool isRent, IEncrypter encrypter
            )
        {
            isRent = true;

            if (channel.Encryption == Encryption.Rsa)
            {
                throw new InvalidOperationException("Server cant send data via RSA channel.");
            }

            int bufSize = channel.GetDataSize(data);
            int lz4ext  = 0;

            if (channel.Compression == Compression.LZ4)
            {
                lz4ext = 4;
            }

            buffer = arrayPool.Rent(bufSize + 6 + lz4ext);
            if (buffer == null)
            {
                isRent = false;
                buffer = new byte[bufSize + 6 + lz4ext];
            }

            BytePacker packer = new BytePacker(buffer);

            packer.Write((short)bufSize);

#if DISABLE_CHANNEL_VARINT
            packer.Write(channel.ChannelID);
#else
            int s = 0;
            VarintBitConverter.SerializeShort(channel.ChannelID, packer, out s);
#endif
            int start = packer.Position;

            channel.ToStream(data, ref packer, encrypter);

            bufferSize = (int)packer.Position;

            packer.Position = 0;
            packer.Write((short)(bufferSize - start));
        }
Exemplo n.º 27
0
        public async Task <bool> Broadcast <T>(ComGroup group, short channelId, T data, ComNode exception = null)
        {
            return(await Task.Run(async() => {
                if (!dataChannelMap.ContainsKey(channelId))
                {
                    return false;
                }

                IDataChannel channel = dataChannelMap[channelId];

                bool isRent = false;
                byte[] buffer = null;
                int bufferSize = 0;

                BuildBuffer(channel, data, ref buffer, ref bufferSize, ref isRent);

                foreach (var node in group.NodeList)
                {
                    if (node == exception)
                    {
                        continue;
                    }
                    if (!nodeMap.ContainsKey(node.IP))
                    {
                        continue;
                    }

                    if (channel.Qos == QosType.Reliable)
                    {
                        await((ComTCPNode)node).Connection.Send(bufferSize, buffer);
                    }
                    else if (channel.Qos == QosType.Unreliable)
                    {
                        await udpSender.Send(node.IP, bufferSize, buffer);
                    }
                }

                if (isRent)
                {
                    arrayPool.Return(buffer);
                }

                return true;
            }));
        }
Exemplo n.º 28
0
        public static MultiChannelInput <IDataChannel> ApplyFilters(MultiChannelInput <IDataChannel> mci, params IChannelFilter[] filters)
        {
            MultiChannelInput <IDataChannel> result = new MultiChannelInput <IDataChannel>(mci.SamplesPerSecond, mci.ChannelCount);

            for (int i = 0; i < mci.ChannelCount; i++)
            {
                IDataChannel dataChannel = mci.GetChannel(i);

                foreach (IChannelFilter filter in filters)
                {
                    dataChannel = filter.Copy().Apply(dataChannel);
                }

                result.SetChannel(i, dataChannel);
            }

            return(result);
        }
Exemplo n.º 29
0
        public static PhysicalBoundaries GetChannelInputBoundaries(MultiChannelInput <IDataChannel> mci)
        {
            PhysicalBoundaries result = new PhysicalBoundaries()
            {
                MinX = Int32.MaxValue, MinY = Int32.MaxValue, MinZ = Int32.MaxValue, MaxX = Int32.MinValue, MaxY = Int32.MinValue, MaxZ = Int32.MinValue
            };

            for (int i = 0; i < mci.ChannelCount; i++)
            {
                IDataChannel     ch = mci.GetChannel(i);
                PhysicalPosition pp = ChannelMapper.GetChannelPosition(ch);

                if (pp.X < result.MinX)
                {
                    result.MinX = pp.X;
                }
                if (pp.X > result.MaxX)
                {
                    result.MaxX = pp.X;
                }
                if (pp.Y < result.MinY)
                {
                    result.MinY = pp.Y;
                }
                if (pp.Y > result.MaxY)
                {
                    result.MaxY = pp.Y;
                }
                if (pp.Z < result.MinZ)
                {
                    result.MinZ = pp.Z;
                }
                if (pp.Z > result.MaxZ)
                {
                    result.MaxZ = pp.Z;
                }
            }

            return(result);
        }
Exemplo n.º 30
0
        public async Task <bool> Send <T>(short channelId, T data)
        {
            return(await Task.Run(async() =>
            {
                if (!IsConnected)
                {
                    return false;
                }
                if (!dataChannelMap.ContainsKey(channelId))
                {
                    return false;
                }

                IDataChannel channel = dataChannelMap[channelId];

                bool isRent = false;
                byte[] buffer = null;
                int bufferSize = 0;

                BuildBuffer(channel, data, ref buffer, ref bufferSize, ref isRent);

                if (channel.Qos == QosType.Reliable)
                {
                    await((ComTCPNode)serverNode).Connection.Send(bufferSize, buffer);
                }
                else if (channel.Qos == QosType.Unreliable)
                {
                    await udpSender.Send(serverNode.IP, bufferSize, buffer);
                }

                if (isRent)
                {
                    arrayPool.Return(buffer);
                }

                return true;
            }));
        }
 public TelemetryDiagnosticControls(IConnection connection, IDataChannel dataChannel)
 {
     _connection = connection;
     _dataChannel = dataChannel;
 }
Exemplo n.º 32
0
        private void CreatePhoneControllerServer()
        {
            // capture the current synchronization context
            _synchronizationContext = SynchronizationContext.Current;
            if (_synchronizationContext == null)
            {
                // create a default implementation
                _synchronizationContext = new SynchronizationContext();
            }

            // create all required networking objects
            _broadCastListener = new MulticastListener();

            _controlChannel = _communicationFactory.CreateControlChannel();
            _controlChannel.ClientAccepted += ControlChannel_ClientAccepted;
            _controlChannel.ConnectionClosed += ControlChannel_ConnectionClosed;
            _controlChannel.ControlCommandSent += ControlChannel_ControlCommandSent;
            _controlChannel.Error += ControlChannel_Error;

            _dataChannel = _communicationFactory.CreateDataChannel();
            _dataChannel.ClientAccepted += DataChannel_ClientAccepted;
            _dataChannel.ConnectionClosed += DataChannel_ConnectionClosed;
            _dataChannel.Error += DataChannel_Error;
            _dataChannel.DataMessageReceived += DataChannel_DataMessageReceived;

            // set initial state
            State = PhoneControllerState.Created;
        }
Exemplo n.º 33
0
        private void CreatePhoneControllerClient(IDataSource dataSource)
        {
            if (dataSource == null)
            {
                throw new ArgumentNullException("dataSource");
            }

            // capture the current synchronization context
            _synchronizationContext = SynchronizationContext.Current;
            if (_synchronizationContext == null)
            {
                // create a default implementation
                _synchronizationContext = new SynchronizationContext();
            }

            // store and set up data source
            DataSource = dataSource;
            DataSource.DataAcquired += DataSource_DataAcquired;

            // create all required networking objects
            _broadCaster = new MulticastClient();
            _broadCaster.ServerDiscovered += BroadCaster_ServerDiscovered;
            _broadCaster.TimeoutElapsed += BroadCaster_TimeoutElapsed;

            _controlChannel = _communicationFactory.CreateControlChannel();
            _controlChannel.Error += ControlChannel_Error;
            _controlChannel.ControlCommandReceived += ControlChannel_ControlCommandReceived;
            _controlChannel.Connected += ControlChannel_Connected;
            _controlChannel.ConnectionClosed += ControlChannel_ConnectionClosed;

            _dataChannel = _communicationFactory.CreateDataChannel();
            _dataChannel.Error += DataChannel_Error;
            _dataChannel.Connected += DataChannel_Connected;
            _dataChannel.ConnectionClosed += DataChannel_ConnectionClosed;

            // configure some default values for the configuration here
            // these typically are overridden by a configuration sent down from the server side
            var configuration = new ControllerConfiguration();
            configuration.AutoReconnectOnActivation = false;
            configuration.TouchInputMargin = new Thickness(90, 20, 20, 20);
            configuration.MinAccelerometerDataRate = 0;
            configuration.MinCompassDataRate = 0;
            configuration.MinGyroscopeDataRate = 0;
            configuration.MinMotionDataRate = 0;
            configuration.MinMillisecondsBetweenMessages = 0; // as fast as possible
            configuration.EnableTracing = false;
            configuration.TracingEndpointAddress = null;
            Configure(configuration);

            State = PhoneControllerState.Created;
        }