Пример #1
0
 private void FireRegistrationAttempted(DataChannel channel, int currentTry)
 {
     if (this.RegistrationAttempted != null)
     {
         this.RegistrationAttempted(this, new CustomerRegistrationAttemptedEventArgs(channel, currentTry, this.numberOfRetries));
     }
 }
Пример #2
0
        private static void WriteBytesToFile(FileFrag frag, DataChannel channel)
        {
            //
            SendFileInfo <string> data = new SendFileInfo <string>
            {
                Data         = frag.fileGuid,
                SendFileType = SendFileType.ReciveFileFragSuccess
            };

            channel.SendChannelData(JsonConvert.SerializeObject(data));

            var fileInfo = caches_recive_files.FirstOrDefault(o => o.fileGuid == frag.fileGuid);

            fileInfo.currentFragIndex = frag.currentFragIndex;
            onFragChanged?.Invoke(fileInfo, fileInfo);
            //
            var filepath = localDirectory + frag.fileGuid;

            try
            {
                using (var filestream = File.OpenWrite(filepath))
                {
                    filestream.Seek(frag.currentFragIndex * Params.flagSize, SeekOrigin.Begin);
                    filestream.Write(frag.bytes, 0, frag.bytesLength);
                    filestream.Seek(0, SeekOrigin.Begin);
                }
            }
            catch (Exception)
            {
            }
        }
Пример #3
0
 private void FireRegistrationCompleted(DataChannel channel, bool succeeded)
 {
     if (this.RegistrationCompleted != null)
     {
         this.RegistrationCompleted(this, new CustomerRegistrationCompletedEventArgs(channel, succeeded));
     }
 }
Пример #4
0
 public void OnDataChannel(DataChannel dc)
 {
     outerInstance.RunOnUiThread(() =>
     {
         throw new Exception("AppRTC doesn't use data channels, but got: " + dc.Label() + " anyway!");
     });
 }
 public static void SetHandle(DataChannel dataChannel, IntPtr handle)
 {
     Debug.Assert(handle != IntPtr.Zero);
     // Either first-time assign or no-op (assign same value again)
     Debug.Assert((dataChannel._interopHandle == IntPtr.Zero) || (dataChannel._interopHandle == handle));
     dataChannel._interopHandle = handle;
 }
Пример #6
0
        /// <summary>
        /// Получить минимальную длину пути (для звезды и mesh) или всего пути для шины.
        /// </summary>
        /// <param name="pathes">Пути, по которым КУ соединены с УСПД.</param>
        /// <param name="dataChannel">КПД, которым соединены устройства.</param>
        /// <returns>Значение расстояния.</returns>
        protected double GetMinDistance(IEnumerable <TopologyPath> pathes, DataChannel dataChannel)
        {
            try
            {
                if (pathes == null)
                {
                    return(UNACCEPTABLE);
                }

                switch (dataChannel.Topology)
                {
                // Для звезды и меша проверяем, что длина максимального пути не больше требуемого
                case DataChannelTopology.Mesh:
                case DataChannelTopology.Star:
                    return(pathes.Max(q => q.GetDistance()));

                // Для шины проверяем, что суммарная длина не больше требуемой
                case DataChannelTopology.Bus:
                    return(pathes.Sum(q => q.GetDistance()));

                default:
                    return(UNACCEPTABLE);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetDistance failed! {0}", ex.Message);
                return(UNACCEPTABLE);
            }
        }
        /// <summary>
        /// Декодировать текущую секцию из генотипа.
        /// </summary>
        /// <param name="chromosome">Декодируемая хромосома.</param>
        /// <param name="sectionIndex">Индекс секции в декодируемой хромосоме.</param>
        public void Decode(TopologyChromosome chromosome, int sectionIndex)
        {
            try
            {
                var sectionGenes = chromosome.GetGenes()       // Получаем значения генов только данной секции
                                   .Select((gene, index) => new { Value = (int)gene.Value, Index = index })
                                   .Where(q => GetSectionIndex(q.Index) == sectionIndex)
                                   .Select(q => q.Value)
                                   .ToArray();

                if (sectionGenes.Length < GeneValueGenerationFuncs.Length)
                {
                    throw new Exception("Incorrect section size!");
                }

                // 0-й ген - тип КУ, 1-й ген - узел КУ, 2-й ген - тип УСПД, 3-й ген - узел УСПД, 4-й ген - КПД
                MCDPart.Decode(chromosome.CurrentProject, sectionGenes[0], sectionGenes[1]);
                DADPart.Decode(chromosome.CurrentProject, sectionGenes[2], sectionGenes[3]);

                Channel = chromosome.CurrentProject.Equipments.DCs[sectionGenes[4]];
            }
            catch (Exception ex)
            {
                Console.WriteLine("TopologySection Decode failed! {0}", ex.Message);
            }
        }
Пример #8
0
        public async Task OutOfBand()
        {
            // Disable auto-renegotiation
            suspendOffer1_ = true;
            suspendOffer2_ = true;

            // Add out-of-band data channels
            const int   DataChannelId = 42;
            DataChannel data1         = await pc1_.AddDataChannelAsync(DataChannelId, "my_channel", ordered : true, reliable : true);

            DataChannel data2 = await pc2_.AddDataChannelAsync(DataChannelId, "my_channel", ordered : true, reliable : true);

            // Check consistency
            Assert.AreEqual(data1.ID, data2.ID);
            Assert.AreEqual(data1.Label, data2.Label);

            // Prepare for state change
            var evOpen1 = new ManualResetEventSlim(initialState: false);

            data1.StateChanged += () =>
            {
                if (data1.State == DataChannel.ChannelState.Open)
                {
                    evOpen1.Set();
                }
            };
            var evOpen2 = new ManualResetEventSlim(initialState: false);

            data2.StateChanged += () =>
            {
                if (data2.State == DataChannel.ChannelState.Open)
                {
                    evOpen2.Set();
                }
            };

            // Connect
            StartOfferWith(pc1_);
            WaitForSdpExchangeCompleted();

            // Wait until the data channels are ready
            Assert.True(evOpen1.Wait(TimeSpan.FromSeconds(60.0)));
            Assert.True(evOpen2.Wait(TimeSpan.FromSeconds(60.0)));

            // Send data
            {
                var    c2       = new ManualResetEventSlim(false);
                string sentText = "Some sample text";
                byte[] msg      = Encoding.UTF8.GetBytes(sentText);
                data2.MessageReceived += (byte[] _msg) =>
                {
                    var receivedText = Encoding.UTF8.GetString(_msg);
                    Assert.AreEqual(sentText, receivedText);
                    c2.Set();
                };
                data1.SendMessage(msg);
                Assert.True(c2.Wait(TimeSpan.FromSeconds(60.0)));
            }
        }
Пример #9
0
        private static void ReciveFileError(FileFragInfo info, DataChannel channel)
        {
            var oldfilepath = localDirectory + info.fileGuid;

            File.Delete(oldfilepath);
            removeRecieFileCache(info);
            onFileCountChanged?.Invoke(channel, cuteFileCount(channel));
        }
Пример #10
0
 private void OnDataChannelAdded(DataChannel channel)
 {
     Logger.Log($"Added data channel '{channel.Label}' (#{channel.ID}).");
     ThreadHelper.RunOnMainThread(() =>
     {
         var chat = new ChatChannelModel(channel);
         ChatChannels.Add(chat);
     });
 }
 public ChatChannelModel(DataChannel dataChannel)
 {
     DataChannel = dataChannel;
     dataChannel.MessageReceived += (byte[] message) =>
     {
         string text = System.Text.Encoding.UTF8.GetString(message);
         AppendText($"[remote] {text}\n");
     };
 }
Пример #12
0
 public static void RegisterFileChannel(DataChannel channel)
 {
     if (caches.ContainsKey(channel) == false)
     {
         caches.Add(channel, new List <FileFragHelper_Read>());
         channel.onChannelMessage      += Channel_onChannelMessage;
         channel.onChannelStateChanged += Channel_onChannelStateChanged;
     }
 }
Пример #13
0
 public void LoadLobbiesByChannel(Puppet.Core.Model.DataChannel channel)
 {
     view.ShowLoading();
     selectedChannel = channel;
     lobbies         = new List <DataLobby>();
     IsFiltered      = false;
     view.DrawLobbies(lobbies);
     APILobby.SetSelectChannel(channel, OnCallbackAllLobbyInSelectedChannel);
 }
Пример #14
0
            public void LoadFromChannel(DataChannel channel)
            {
                throw new NotImplementedException();

                //Port = channel.Port;
                //Data.LoadState(channel.Data);
                //PortBuffer.LoadState(channel.PortBuffer);
                //DisplayBuffer.LoadState(channel.DisplayBuffer);
            }
Пример #15
0
 public void OnDataChannelAdded(DataChannel channel)
 {
     Debug.Log("OnDataChannelAdded");
     _mainThreadWorkQueue.Enqueue(() =>
     {
         _dataChannel = channel;
         _dataChannel.MessageReceived += OnWebRTCMessageReceived;
         Debug.Log("OnDataChannelAdded Main Thread");
     });
 }
Пример #16
0
        private static void addFileReader(DataChannel channel, FileFragHelper_Read reader)
        {
            var find = findFileReaderByGuid(reader.CurrentFileInfo.fileGuid);

            if (find == null)
            {
                caches.FirstOrDefault(o => o.Key == channel).Value.Add(reader);
            }
            onFileCountChanged?.Invoke(channel, cuteFileCount(channel));
        }
Пример #17
0
        private void HandleSelectedChannelChanged(object sender, EventArgs e)
        {
            DataChannel dc = w_cbChannel.SelectedItem as DataChannel;

            if (dc == null)
            {
                return;
            }
            w_propertyGrid.SelectedObject = dc.Analyzer;
        }
Пример #18
0
 private void OnDataChannelRemoved(DataChannel channel)
 {
     Logger.Log($"Removed data channel '{channel.Label}' (#{channel.ID}).");
     // FIXME - Delegating to another thread means possible race condition if user initiates
     // some action on the data channel before the delegated remove executes.
     ThreadHelper.RunOnMainThread(() =>
     {
         var chat = ChatChannels.Where(c => c.DataChannel == channel).First();
         ChatChannels.Remove(chat);
     });
 }
Пример #19
0
        private void InitializeDataStream()
        {
            if (Options.DataChannelLabel == null || (RemoteConnectionInfo != null && !RemoteConnectionInfo.HasData))
            {
                return;
            }

            DataChannel = new DataChannel(Options.DataChannelLabel);
            DataStream  = new DataStream(DataChannel);
            DoInitializeDataStream();
        }
Пример #20
0
        public static void readFragError(DataChannel channel, FileFragHelper_Read filereader)
        {
            removeFileReaderByGuid(channel, filereader.CurrentFileInfo.fileGuid);
            SendFileInfo <FileFragInfo> data = new SendFileInfo <FileFragInfo>
            {
                Data         = filereader.CurrentFileInfo,
                SendFileType = SendFileType.SendFileError
            };

            channel.SendChannelData(JsonConvert.SerializeObject(data));
        }
Пример #21
0
        private void InitializeDataStream()
        {
            if (Options.DataChannelLabel == null)
            {
                return;
            }

            DataChannel = new DataChannel(Options.DataChannelLabel);
            DataStream  = new DataStream(DataChannel);
            DoInitializeDataStream();
        }
Пример #22
0
 public void OnDataChannelAdded(DataChannel channel)
 {
     _dataChannel = channel;
     _dataChannel.StateChanged += (() => {
         // if (_dataChannel.State == DataChannel.ChannelState.Open)
         // {
         SendKinectInitialData();
         // }
     });
     Debug.Log("OnDataChannelAdded");
 }
Пример #23
0
        private static int cuteFileCount(DataChannel channel)
        {
            var sendingCount = 0;

            if (caches.ContainsKey(channel) == true)
            {
                sendingCount = caches.FirstOrDefault(o => o.Key == channel).Value.Count;
            }
            var recivingCount = caches_recive_files.Count;

            return(sendingCount + recivingCount);
        }
Пример #24
0
        private void RegisterDataChannelCreatedCallback()
        {
            _webRtcDataChannelCreatedCallback = (handle, dataChannelHandle, _) =>
            {
                Log.Debug(WebRTCLog.Tag, "Invoked");

                DataChannel?.Invoke(this, new WebRTCDataChannelEventArgs(dataChannelHandle));
            };

            NativeDataChannel.SetCreatedByPeerCb(Handle, _webRtcDataChannelCreatedCallback).
            ThrowIfFailed("Failed to set data channel created callback.");
        }
        /// <summary>
        /// Main UI thread callback on WebRTC native plugin initialized.
        /// </summary>
        private void OnPluginPostInit()
        {
            PluginInitialized = true;
            LogMessage("WebRTC native plugin initialized.");

            // It is CRUCIAL to add any data channel BEFORE the SDP offer is sent, if data channels are
            // to be used at all. Otherwise the SCTP will not be negotiated, and then all channels will
            // stay forever in the kConnecting state.
            // https://stackoverflow.com/questions/43788872/how-are-data-channels-negotiated-between-two-peers-with-webrtc
            _peerConnection.AddDataChannelAsync(ChatChannelID, "chat", true, true).ContinueWith((prevTask) =>
            {
                if (prevTask.Exception != null)
                {
                    throw prevTask.Exception;
                }
                var newDataChannel = prevTask.Result;
                RunOnMainThread(() =>
                {
                    _chatDataChannel = newDataChannel;
                    _chatDataChannel.MessageReceived += ChatMessageReceived;
                    chatInputBox.IsEnabled            = true;
                    chatSendButton.IsEnabled          = true;
                });
            });

            createOfferButton.IsEnabled = true;

            // Do not allow starting the local video before the MediaElement told us it was
            // safe to do so (see OnMediaOpened). Otherwise Play() will silently fail.
            startLocalVideo.IsEnabled = false;

            localVideoPlayer.CurrentStateChanged += OnMediaStateChanged;
            localVideoPlayer.MediaOpened         += OnMediaOpened;
            localVideoPlayer.MediaFailed         += OnMediaFailed;
            localVideoPlayer.MediaEnded          += OnMediaEnded;
            localVideoPlayer.RealTimePlayback     = true;
            localVideoPlayer.AutoPlay             = false;
            localVideoSource        = CreateVideoStreamSource(640, 480); //< TODO width,height
            localVideoPlayer.Source = MediaSource.CreateFromMediaStreamSource(localVideoSource);

            remoteVideoPlayer.CurrentStateChanged += OnMediaStateChanged;
            remoteVideoPlayer.MediaOpened         += OnMediaOpened;
            remoteVideoPlayer.MediaFailed         += OnMediaFailed;
            remoteVideoPlayer.MediaEnded          += OnMediaEnded;
            remoteVideoSource        = CreateVideoStreamSource(640, 480); //< TODO width,height
            remoteVideoPlayer.Source = MediaSource.CreateFromMediaStreamSource(remoteVideoSource);

            // Bind the XAML UI control (localVideo) to the MediaFoundation rendering pipeline (localVideoPlayer)
            // so that the former can render in the UI the video frames produced in the background by the later.
            localVideo.SetMediaPlayer(localVideoPlayer);
            remoteVideo.SetMediaPlayer(remoteVideoPlayer);
        }
Пример #26
0
 /// <summary>
 /// creates a dataChannel on the nativePeer and subscribes to its messages.
 /// </summary>
 /// <param name="nativePeer"></param>
 private void DoAutoStartActions(WebRTC.PeerConnection nativePeer)
 {
     //(ushort id), string label, bool ordered, bool reliable
     nativePeer.AddDataChannelAsync((ushort)ChannelID, ChannelID.ToString(), ordered, reliable).ContinueWith((prevTask) =>
     {
         if (prevTask.Exception != null)
         {
             throw prevTask.Exception;
         }
         dataChannel = prevTask.Result;
         dataChannel.MessageReceived += PosMessageReceived;
     });
 }
Пример #27
0
 /// <summary>
 /// Получить стоимость реализации данного пути.
 /// </summary>
 /// <param name="project">Свойства проекта.</param>
 /// <returns>Стоимость реализации проведения данного пути.</returns>
 public double GetCost(Project project)
 {
     try
     {
         // Если путь на одной вершине, то считаем стоимость только её
         return(Path?.Sum(edge => GetDistance() * DataChannel.GetCost(project, edge)) ?? DataChannel.GetCost(project, Source));
     }
     catch (Exception ex)
     {
         Console.WriteLine("TopologyPath GetCost failed! {0}", ex.Message);
         return(TopologyFitness.UNACCEPTABLE);
     }
 }
Пример #28
0
 protected override void PeerConnection_onNewDataChannel(object sender, DataChannel e)
 {
     base.PeerConnection_onNewDataChannel(sender, e);
     if (e.label == nameof(ChannelName.fileChannel))
     {
         FileChannelMessageDeal.RegisterFileChannel(e);
     }
     else
     {
         e.onChannelMessage      += E_onChannelMessage;
         e.onChannelStateChanged += E_onChannelStateChanged;
     }
 }
Пример #29
0
    private void OnDataChannelAdded(DataChannel channel)
    {
        switch (channel.Label)
        {
        case "tcpDataChannel":
            channel.MessageReceived += OnTcpDataChannelMessageReceived;
            break;

        case "udpDataChannel":
            channel.MessageReceived += OnUdpDataChannelMessageReceived;
            break;
        }
    }
Пример #30
0
        private async Task StartDataStream()
        {
            if (DataStream != null)
            {
                DataSource            = CreateDataSource();
                DataSource.OnMessage += (sender, message) =>
                {
                    DataChannel.SendDataString(message);
                };
                await DataSource.Start();

                DoStartDataStream();
            }
        }
Пример #31
0
	public static LobbyTab Create(DataChannel data,UITable parent,int index){
		GameObject gobj = null;
		if (index != 0)
			gobj = GameObject.Instantiate (Resources.Load ("Prefabs/Lobby/LobbyTabCenter")) as GameObject;
		else {
			gobj = GameObject.Instantiate (Resources.Load ("Prefabs/Lobby/LobbyTabLeft")) as GameObject;
		}
        gobj.name = data.zoneId + "-" + data.name;
		gobj.transform.parent = parent.transform;
		gobj.transform.localPosition = Vector3.zero;
		gobj.transform.localScale = Vector3.one;
		LobbyTab item = gobj.GetComponent<LobbyTab> ();
		item.SetData (data,index);
		return item;

	}
Пример #32
0
 public void LoadLobbiesByChannel(Puppet.Core.Model.DataChannel channel)
 {
     view.ShowLoading();
     selectedChannel = channel;
     lobbies = new List<DataLobby>();
     IsFiltered = false;
     view.DrawLobbies(lobbies);
     APILobby.SetSelectChannel(channel, OnCallbackAllLobbyInSelectedChannel);
 }
Пример #33
0
 public void LoadLobbiesByChannel(Puppet.Core.Model.DataChannel channel)
 {
     selectedChannel = channel;
     if (lobbies != null)
         lobbies = null;
     IsFiltered = false;
     APILobby.SetSelectChannel(channel, OnGetAllLobbyInChannel);
 }
Пример #34
0
	void SetData (DataChannel data,int index)
	{
		this.data = data;
		title.text = data.displayName;
	}