public void DdpClient_ConnectAsync_SetsSessionId() { var task = this.client.ConnectAsync(); var connected = new Connected() {MessageType = "connected", Session = "TestSession"}; this.testConnection.Reply(JsonConvert.SerializeObject(connected)); task.Wait(); Assert.AreEqual(this.client.SessionId, "TestSession", "Session should be set after successful connection."); }
public void ConnectedResultFilter_HandleReturnObject_ConnectedMessage() { var connectedResultFilter = new ConnectedResultFilter(); var connected = new Connected() {Session = "Test"}; var returnedObject = new ReturnedObject("connected", JObject.FromObject(connected), JsonConvert.SerializeObject(connected)); connectedResultFilter.HandleReturnObject(returnedObject); Assert.IsTrue(connectedResultFilter.IsCompleted()); Assert.AreEqual(returnedObject, connectedResultFilter.GetReturnedObject()); }
public void ResultHandler_WaitForResult_WaitHandler() { var resultHandler = new ResultHandler(); var waitHandle = resultHandler.RegisterWaitHandler(ResultFilterFactory.CreateConnectResultFilter()); var waitTask = resultHandler.WaitForResult(waitHandle); var connected = new Connected() {Session = "TestSession"}; var returnedObject = new ReturnedObject(connected.MessageType, JObject.FromObject(connected), JsonConvert.SerializeObject(connected)); resultHandler.AddResult(returnedObject); waitTask.Wait(); Assert.AreEqual(returnedObject, waitTask.Result); }
public void ReplyMessageHandler_HandleMessage_HandlesConnected() { var connectionMock = new Mock<IDdpConnectionSender>(); var collectionMock = new Mock<ICollectionManager>(); var resultHandlerMock = new Mock<IResultHandler>(); var connected = new Connected() {Session = "1"}; var handler = new ReplyMessageHandler(); handler.HandleMessage(connectionMock.Object, collectionMock.Object, resultHandlerMock.Object, JsonConvert.SerializeObject(connected)); Assert.IsTrue(handler.CanHandle(connected.MessageType)); resultHandlerMock.Verify(resultHandler => resultHandler.AddResult(It.IsAny<ReturnedObject>())); }
public void DdpClient_ConnectAsync_SendsConnectMessage() { var task = this.client.ConnectAsync(); var connected = new Connected() { MessageType = "connected", Session = "TestSession" }; this.testConnection.Reply(JsonConvert.SerializeObject(connected)); task.Wait(); var message = this.testConnection.GetSentMessage(); var connectMessage = JsonConvert.DeserializeObject<Connect>(message); Assert.IsNotNull(connectMessage, "Connect should send an object"); Assert.AreEqual(connectMessage.Version, "1", "Message should support version 1"); Assert.AreEqual(connectMessage.VersionsSupported.Count(), 1, "Client only supports 1 version"); Assert.AreEqual(connectMessage.VersionsSupported.First(), "1", "Client only supports 1 version"); }
public void ResultHandler_RegisterResultCallback_CallbackCalled() { var resultHandler = new ResultHandler(); bool callbackCalled = false; var connected = new Connected() { Session = "TestSession" }; var returnedObject = new ReturnedObject(connected.MessageType, JObject.FromObject(connected), JsonConvert.SerializeObject(connected)); resultHandler.RegisterResultCallback(ResultFilterFactory.CreateConnectResultFilter(), o => { callbackCalled = true; Assert.AreEqual(returnedObject, o); }); resultHandler.AddResult(returnedObject); Assert.IsTrue(callbackCalled); }
public void ResultHandler_WaitForResult_ReactivateWaitHandle() { var resultHandler = new ResultHandler(); var waitHandle = resultHandler.RegisterWaitHandler(ResultFilterFactory.CreateConnectResultFilter()); var waitTask = resultHandler.WaitForResult(waitHandle); var connected = new Connected() { Session = "TestSession" }; var returnedObject = new ReturnedObject(connected.MessageType, JObject.FromObject(connected), JsonConvert.SerializeObject(connected)); resultHandler.AddResult(returnedObject); waitTask.Wait(); Assert.AreEqual(returnedObject, waitTask.Result); PCLTesting.ExceptionAssert.Throws<InvalidOperationException>(() => resultHandler.WaitForResult(waitHandle)); }
public void PublishAsync_Where_No_Publication_Configurations_Which_Results_In_A_NoConfigurationFound_Result() { var _busConfigurationBuilder = new BusConfigurationBuilder(); _busConfigurationBuilder.ConnectionUris.Add(TestingConfiguration.LocalConnectionUri); var _busConfirguration = _busConfigurationBuilder.Build(); var _connectionManager = Substitute.For<IConnectionManager>(); var _context = Substitute.For<IBusContext>(); var _SUT = new Connected( _busConfirguration, _connectionManager, _context); var _theEvent = new MyEvent(Guid.NewGuid(), null, "Some detail", 1); var _publicationResult = _SUT.PublishAsync(_theEvent); _publicationResult.Wait(); Assert.AreEqual(PMCG.Messaging.PublicationResultStatus.NoConfigurationFound, _publicationResult.Result.Status); }
public static string ConnectedToStr(Connected con) { string ret = VisionLabPINVOKE.ConnectedToStr((int)con); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
public static int RemoveGrayScaleBlobs(Int16Image image, Int16Image grayImage, Connected connected, BlobAnalyse ba, double low, double high, UseXOrY xy, BlobAnalyseModifier baMod) { int ret = VisionLabPINVOKE.RemoveGrayScaleBlobs__SWIG_9(Int16Image.getCPtr(image), Int16Image.getCPtr(grayImage), (int)connected, (int)ba, low, high, (int)xy, BlobAnalyseModifier.getCPtr(baMod)); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
public static int FindSpecificGrayScaleHoles(Int32Image image, Int32Image grayImage, Connected connected, BlobAnalyse ba, double low, double high, UseXOrY xy) { int ret = VisionLabPINVOKE.FindSpecificGrayScaleHoles__SWIG_13(Int32Image.getCPtr(image), Int32Image.getCPtr(grayImage), (int)connected, (int)ba, low, high, (int)xy); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
public static bool FindCornersRectangle(Int16Image image, Connected connected, double deltaPhi, Orientation orient, XYCoord leftTop, XYCoord rigthTop, XYCoord leftBottom, XYCoord rightBottom) { bool ret = VisionLabPINVOKE.FindCornersRectangle__SWIG_3(Int16Image.getCPtr(image), (int)connected, deltaPhi, (int)orient, XYCoord.getCPtr(leftTop), XYCoord.getCPtr(rigthTop), XYCoord.getCPtr(leftBottom), XYCoord.getCPtr(rightBottom)); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
public static void BlobAnd(Int32Image image, Int32Image maskImage, Connected connected) { VisionLabPINVOKE.BlobAnd__SWIG_4(Int32Image.getCPtr(image), Int32Image.getCPtr(maskImage), (int)connected); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); }
public void OnConnected(NetConnection con, String message) { _awaitingActions.Enqueue(() => { Connected?.Invoke(this, new ConnectionEventArgs(default(UserHandle), message)); }); }
protected bool Equals(Connected other) { return(Equals(_channel, other._channel)); }
private void FireConnected(TelemetryEventArgs e) { Connected?.Invoke(this, e); }
internal void OnConnected() { Connected.SafeInvoke(); }
/// <summary> /// Raises <see cref="Connected"/> event with specified <paramref name="authStatus"/> value. /// </summary> /// <param name="authStatus">Authentication status (protocol level) of client.</param> protected void OnConnected( AuthStatus authStatus) => Connected?.Invoke(authStatus);
public static int FindBlob(Int32Image src, Int32Image pat, Int32Image dest, Connected connected, float maxError, float beginAngle, float endAngle, int nrOfRotations) { int ret = VisionLabPINVOKE.FindBlob__SWIG_19(Int32Image.getCPtr(src), Int32Image.getCPtr(pat), Int32Image.getCPtr(dest), (int)connected, maxError, beginAngle, endAngle, nrOfRotations); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
private void OnSessionConnected(object sender, RConnectedEventArgs e) => Connected?.Invoke(this, EventArgs.Empty);
public static int FillSpecificGrayScaleHoles(ByteImage image, ByteImage grayImage, Connected connected, BlobAnalyse ba, double low, double high) { int ret = VisionLabPINVOKE.FillSpecificGrayScaleHoles__SWIG_5(ByteImage.getCPtr(image), ByteImage.getCPtr(grayImage), (int)connected, (int)ba, low, high); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
private static void Client_Connected() => Connected?.Invoke();
public static int FindSpecificHoles(Int16Image image, Connected connected, BlobAnalyse ba, double low, double high) { int ret = VisionLabPINVOKE.FindSpecificHoles__SWIG_11(Int16Image.getCPtr(image), (int)connected, (int)ba, low, high); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
private void Connection_OnConnectSuccess(object sender, EventArgs e) { Connected.Fire(this, EventArgs.Empty); }
public static void NrOfNeighbours(Int32Image src, Int32Image dest, Connected connected) { VisionLabPINVOKE.NrOfNeighbours__SWIG_4(Int32Image.getCPtr(src), Int32Image.getCPtr(dest), (int)connected); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); }
public PersonalPageDoctorViewModel(UsersInfoModel doctorInfoModel, CountMessageForPersonalPage countMessageForPersonalPage, Connected connected) { ConnectedID = connected.ConnectedID; _connectionManager = new ConnectionManager(); UserId = doctorInfoModel.Id; FirstName = doctorInfoModel.FirstName; LastName = doctorInfoModel.LastName; DateOfBirthPatient = doctorInfoModel.DateOfBirth.UtcDateTime; PhoneNumber = doctorInfoModel.PhoneNumber; Email = doctorInfoModel.Email; SelectDoctorCommand = new DelegateCommand <InfoUserModel>(SelectDoctor); SelectPatientCommand = new DelegateCommand <InfoUserModel>(SelectPatient); DoctorsList = new ObservableCollection <InfoUserModel>(doctorInfoModel.DortorsList); PatientsList = new ObservableCollection <InfoUserModel>(doctorInfoModel.PatientsList); ButtonMessageCommand = new DelegateCommand(WriteMessageInChat); ActiveMessage(countMessageForPersonalPage.CountMessages); }
public static void RemoveBorderBlobs(Int32Image image, Connected connected) { VisionLabPINVOKE.RemoveBorderBlobs__SWIG_9(Int32Image.getCPtr(image), (int)connected); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); }
private void Pipeclient_Connected(NamedPipeConnection <SAPEvent, SAPEvent> connection) { Connected?.Invoke(); }
public static void ZeroCrossings(DoubleImage src, DoubleImage dest, Connected con) { VisionLabPINVOKE.ZeroCrossings__SWIG_12(DoubleImage.getCPtr(src), DoubleImage.getCPtr(dest), (int)con); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); }
/// <summary> /// /// </summary> /// <param name="args"></param> private void Client_Connected(Sockets.EventArgs.SocketConnectedArgs args) { Connected?.Invoke(); }
public async Task ConnectAsync(string input, IBrowserProfile browserProfile) { CanConnect = false; CanDisconnect = true; _disconnectReason = DisconnectReason.Unknown; InputType inputType; try { while (true) { _first.Reset(); string liveId; if (Tools.IsValidUserId(input)) { inputType = InputType.UserId; var userId = Tools.ExtractUserId(input); liveId = await GetLiveIdAsync(userId);//TODO: //GetLiveIdAsync()を実行中にユーザがDisconnect()するとliveIdがnullになる if (string.IsNullOrEmpty(liveId)) { break; } } else if (Tools.IsValidLiveId(input)) { inputType = InputType.LiveId; liveId = Tools.ExtractLiveId(input); } else { inputType = InputType.Unknown; // break; } var liveInfo = await Api.GetLiveInfo(_server, liveId); MetadataUpdated?.Invoke(this, LiveInfo2Meta(liveInfo)); Connected?.Invoke(this, new ConnectedEventArgs { IsInputStoringNeeded = false, UrlToRestore = null, }); var initialComments = await Api.GetLiveComments(_server, liveId); foreach (var c in initialComments) { var userId = c.UserId; var isFirstComment = _first.IsFirstComment(userId); var user = GetUser(userId); var context = CreateMessageContext(c, true, ""); MessageReceived?.Invoke(this, context); } _provider = CreateMessageProvider(liveInfo.Broadcastkey); _provider.MessageReceived += Provider_MessageReceived; _provider.MetadataUpdated += Provider_MetadataUpdated; var commentTask = _provider.ReceiveAsync(); var metaProvider = new MetadataProvider(_server, _siteOptions, liveId); metaProvider.MetadataUpdated += MetaProvider_MetadataUpdated; var metaTask = metaProvider.ReceiveAsync(); var tasks = new List <Task>(); tasks.Add(commentTask); tasks.Add(metaTask); while (tasks.Count > 0) { var t = await Task.WhenAny(tasks); if (t == commentTask) { try { await commentTask; } catch (Exception ex) { _logger.LogException(ex, "", $"input={input}"); } tasks.Remove(commentTask); metaProvider.Disconnect(); try { await metaTask; } catch (Exception ex) { _logger.LogException(ex, "", $"input={input}"); } tasks.Remove(metaTask); } else if (t == metaTask) { try { await metaTask; } catch (Exception ex) { _logger.LogException(ex, "", $"input={input}"); } tasks.Remove(metaTask); //MetadataProviderの内部でcatchしないような例外が投げられた。メタデータの取得は諦めたほうが良い。多分。 } } //inputTypeがUserIdの場合は if (inputType != InputType.UserId) { break; } if (_disconnectReason == DisconnectReason.User) { break; } } } catch (Exception ex) { _logger.LogException(ex); } finally { CanConnect = true; CanDisconnect = false; } }
public async Task StartAsync(CancellationToken ct = default(CancellationToken)) { if (_hasStarted) { throw new MorseLException($"Cannot call {nameof(StartAsync)} more than once."); } _hasStarted = true; ct.Register(() => _connectionCts.TrySetCanceled(ct)); await Task.Run(async() => { var stopwatch = new Stopwatch(); stopwatch.Start(); await _clientWebSocket.ConnectAsync(new Uri(_uri), ct).ConfigureAwait(false); stopwatch.Stop(); _logger.LogDebug($"Connection to {_uri} established after {stopwatch.Elapsed.ToString("mm\\:ss\\.ff")}"); _receiveLoopTask = Receive(async stream => { _logger.LogTrace($"Received message stream - beginning processing"); var message = await MessageSerializer.DeserializeAsync <Message>(stream, Encoding.UTF8).ConfigureAwait(false); _logger.LogTrace($"Received \"{message}\""); switch (message.MessageType) { case MessageType.ConnectionEvent: _connectionCts.TrySetResult(null); ConnectionId = message.Data; Connected?.Invoke(); break; case MessageType.ClientMethodInvocation: InvocationDescriptor invocationDescriptor = null; try { invocationDescriptor = MessageSerializer.DeserializeInvocationDescriptor(message.Data, _handlers); } catch (Exception exception) { await HandleUnparseableReceivedInvocationDescriptor(message.Data, exception).ConfigureAwait(false); return; } if (invocationDescriptor == null) { // Valid JSON but unparseable into a known, typed invocation descriptor (unknown method name, invalid parameters) await HandleInvalidReceivedInvocationDescriptor(message.Data).ConfigureAwait(false); return; } await InvokeOn(invocationDescriptor).ConfigureAwait(false); break; case MessageType.InvocationResult: InvocationResultDescriptor resultDescriptor; try { resultDescriptor = MessageSerializer.DeserializeInvocationResultDescriptor(message.Data, _pendingCalls); } catch (Exception exception) { await HandleInvalidInvocationResultDescriptor(message.Data, exception).ConfigureAwait(false); return; } HandleInvokeResult(resultDescriptor); break; case MessageType.Error: await HandleErrorMessage(message).ConfigureAwait(false); break; } }, ct); _receiveLoopTask.ContinueWith(task => { if (task.IsFaulted) { Error?.Invoke(task.Exception); } }); }, ct).ConfigureAwait(false); var timeoutTask = Task.Delay(_options.ConnectionTimeout); await Task.WhenAny(_connectionCts.Task, timeoutTask).ConfigureAwait(false); if (!ct.IsCancellationRequested && !_connectionCts.Task.IsCompleted && timeoutTask.IsCompleted) { throw new TimeoutException($"Connection attempt to {_uri} timed out after {_options.ConnectionTimeout}"); } }
public void Handler(Connected @event) { var controller = @event.AggregateGuid; var tenantId = @event.Metadata.TenantId; }
protected virtual void OnConnected(INetChannel channel) { Connected?.Invoke(this, new NetChannelArgs(channel)); }
private void HandleWebsocketOpened(object sender, EventArgs e) { ExecuteOnMainThread(() => { Connected?.Invoke(); }); }
protected virtual void OnConnected(EventArgs e) { Connected?.Invoke(this, e); }
// Connection public static void Connect() { Disconnect(); // Login string username = Account.Username, oauth = Account.OauthToken; try { if (Account.IsAnon) { if (AppSettings.SelectedUser != "") { AppSettings.SelectedUser = ""; AppSettings.Save(); } } else { if (!string.Equals(username, AppSettings.SelectedUser)) { AppSettings.SelectedUser = username; AppSettings.Save(); } } } catch { } LoggedIn?.Invoke(null, EventArgs.Empty); AppSettings.UpdateCustomHighlightRegex(); // fetch ignored users //if (!Account.IsAnon) //{ // Task.Run(() => // { // try // { // var limit = 100; // var count = 0; // string nextLink = // $"https://api.twitch.tv/kraken/users/{username}/blocks?limit={limit}&client_id={Account.ClientId}"; // var request = WebRequest.Create(nextLink + $"&oauth_token={oauth}"); // if (AppSettings.IgnoreSystemProxy) // { // request.Proxy = null; // } // using (var response = request.GetResponse()) // using (var stream = response.GetResponseStream()) // { // dynamic json = new JsonParser().Parse(stream); // dynamic _links = json["_links"]; // nextLink = _links["next"]; // dynamic blocks = json["blocks"]; // count = blocks.Count; // foreach (var block in blocks) // { // dynamic user = block["user"]; // string name = user["name"]; // string display_name = user["display_name"]; // twitchBlockedUsers[name] = null; // } // } // } // catch // { // } // }); //} // fetch available twitch emotes if (!Account.IsAnon) { Task.Run(() => { try { string uid = ""; var idReq = WebRequest.Create($"https://api.twitch.tv/helix/users/?login={Account.Username}") .AuthorizeHelix(); using (var resp = idReq.GetResponse()) using (var stream = resp.GetResponseStream()) { dynamic json = new JsonParser().Parse(stream); dynamic user = json["data"][0]; uid = user["id"]; } var request = WebRequest.Create( $"https://api.twitch.tv/kraken/users/{uid}/emotes") .AuthorizeV5(oauth, Account.ClientId); if (AppSettings.IgnoreSystemProxy) { request.Proxy = null; } using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) { dynamic json = new JsonParser().Parse(stream); Emotes.TwitchEmotes.Clear(); foreach (var set in json["emoticon_sets"]) { int setID; int.TryParse(set.Key, out setID); foreach (var emote in set.Value) { int id; int.TryParse(emote["id"], out id); string code = Emotes.GetTwitchEmoteCodeReplacement(emote["code"]); Emotes.TwitchEmotes[code] = new TwitchEmoteValue { ID = id, Set = setID, ChannelName = "<unknown>" }; } } } } catch { } Emotes.TriggerEmotesLoaded(); }); } // connect read Task.Run(() => { Client = new IrcClient(Account.IsAnon); Client.ReadConnection.Connected += (s, e) => { foreach (var channel in TwitchChannel.Channels) { Client.ReadConnection.WriteLine("JOIN #" + channel.Name); } Connected?.Invoke(null, EventArgs.Empty); }; Client.ReadConnection.Disconnected += (s, e) => { Disconnected?.Invoke(null, EventArgs.Empty); }; if (!Account.IsAnon) { Client.WriteConnection.Connected += (s, e) => { foreach (var channel in TwitchChannel.Channels) { Client.WriteConnection.WriteLine("JOIN #" + channel.Name); } }; } Client.Connect(username, (oauth.StartsWith("oauth:") ? oauth : "oauth:" + oauth)); Client.ReadConnection.MessageReceived += ReadConnection_MessageReceived; Client.WriteConnection.MessageReceived += WriteConnection_MessageReceived; }); // secret telemetry, please ignore :) // anonymously count user on fourtf.com with the first 32 characters of a sha 256 hash of the username if (!Account.IsAnon) { Task.Run(() => { try { string hash; using (var sha = SHA256.Create()) { hash = string.Join("", sha .ComputeHash(Encoding.UTF8.GetBytes(username)) .Select(item => item.ToString("x2"))); } hash = hash.Remove(32); var request = WebRequest.Create($"https://fourtf.com/chatterino/countuser.php?hash={hash}"); if (AppSettings.IgnoreSystemProxy) { request.Proxy = null; } using (var response = request.GetResponse()) using (response.GetResponseStream()) { } } catch { } }); } }
public void Tick() { if (!_clientDriver.IsCreated) { return; } _clientDriver.ScheduleUpdate().Complete(); if (_timeout > 0 && IsConnected && Time.time - LastPongTime > _timeout) { Debug.LogWarning("Disconnected due to timeout"); Disconnect(); return; } // listen for events NetworkEvent.Type eventType; while ((eventType = _clientToServerConnection.PopEvent(_clientDriver, out DataStreamReader streamReader)) != NetworkEvent.Type.Empty) { if (eventType == NetworkEvent.Type.Connect) { Debug.Log("Connected!"); State = ClientState.Connected; Connected?.Invoke(); } else if (eventType == NetworkEvent.Type.Data) { DataReceived?.Invoke(streamReader.Length); int command = streamReader.ReadInt(); switch (command) { case Commands.AssignActorNumber: { ActorNumber = streamReader.ReadInt(); Debug.Log($"Got assigned actor number {ActorNumber}"); DataStreamWriter writer = _clientDriver.BeginSend(_reliablePipeline, _clientToServerConnection); writer.WriteInt(Commands.AcknowledgeActorNumber); _clientDriver.EndSend(writer); DataSent?.Invoke(writer.Length); break; } case Commands.AcceptPlayer: { DataStreamWriter writer = _clientDriver.BeginSend(_reliablePipeline, _clientToServerConnection); writer.WriteInt(Commands.RequestSpawnMessage); writer.WriteInt(SceneManager.sceneCount); for (var i = 0; i < SceneManager.sceneCount; i++) { writer.WriteInt(SceneManager.GetSceneAt(i).buildIndex); } SceneManager.sceneLoaded += OnSceneLoaded; _clientDriver.EndSend(writer); break; } case Commands.Ping: { LastPongTime = Time.time; float sendLocalTime = streamReader.ReadFloat(); float serverTime = streamReader.ReadFloat(); float serverDeltaTime = streamReader.ReadFloat(); RoundTripTime = Time.time - sendLocalTime; Latency = IsHost ? 0 : Mathf.Max(0, (RoundTripTime - serverDeltaTime / 2 - Time.deltaTime / 2) / 2); // estimated server time NOW is received serverTime + latency for one trip + average frame wait on client side float serverTimeOffset = serverTime - Time.time + Latency + Time.deltaTime / 2; _averageServerTimeOffset = Mathf.Abs(_averageServerTimeOffset - serverTime) > 0.5f ? serverTimeOffset : 0.9f * _averageServerTimeOffset + 0.1f * serverTimeOffset; PingReceived?.Invoke(RoundTripTime, Latency); break; } case Commands.SpawnNetObjects: { if (IsHost) { break; } int count = streamReader.ReadInt(); for (var i = 0; i < count; i++) { int netObjID = streamReader.ReadInt(); ushort prefabIndex = streamReader.ReadUShort(); int ownerActorNumber = streamReader.ReadInt(); Vector3 position = streamReader.ReadVector3(); Quaternion rotation = streamReader.ReadQuaternion(); int sceneBuildIndex = streamReader.ReadInt(); int size = streamReader.ReadInt(); int bytesRead = streamReader.GetBytesRead(); Scene scene = SceneManager.GetSceneByBuildIndex(sceneBuildIndex); var deserialized = false; if (scene != null && scene.isLoaded) { NetObject netObject = NetObjectManager.Instance.SpawnOnClient(netObjID, prefabIndex, ownerActorNumber, position, rotation, scene); if (netObject != null) { netObject.Deserialize(ref streamReader, behaviour => true); deserialized = true; } } if (!deserialized) { streamReader.DiscardBytes(size); } if (streamReader.GetBytesRead() - bytesRead != size) { Debug.LogWarning("Did not deserialize properly!"); } } break; } case Commands.UpdateNetAssets: { if (IsHost) { break; } int assetsInMessage = streamReader.ReadInt(); for (var i = 0; i < assetsInMessage; i++) { int assetNetID = streamReader.ReadInt(); int size = streamReader.ReadInt(); int bytesRead = streamReader.GetBytesRead(); try { NetAsset netAsset = NetAssetManager.Instance.Get(assetNetID); netAsset.Deserialize(ref streamReader); } catch (Exception e) { Debug.LogException(new NetException($"Failed to update net asset {assetNetID}", e)); streamReader.DiscardBytes(size + bytesRead - streamReader.GetBytesRead()); } } break; } case Commands.UpdateNetObjects: { if (IsHost) { break; } int objectsInMessage = streamReader.ReadInt(); for (var i = 0; i < objectsInMessage; i++) { int netObjID = streamReader.ReadInt(); int size = streamReader.ReadInt(); if (NetObjectManager.Instance.Exists(netObjID)) { NetObject netObject = NetObjectManager.Instance.Get(netObjID); int bytesRead = streamReader.GetBytesRead(); try { netObject.Deserialize(ref streamReader, behaviour => !behaviour.HasAuthority); } catch (Exception e) { Debug.LogException( new NetException($"Failed to update net object {netObjID}", e)); streamReader.DiscardBytes(size + bytesRead - streamReader.GetBytesRead()); } } else { streamReader.DiscardBytes(size); } } break; } case Commands.UnspawnNetObjects: { if (IsHost) { break; } int count = streamReader.ReadInt(); for (var i = 0; i < count; i++) { int netObjID = streamReader.ReadInt(); NetObjectManager.Instance.Unspawn(netObjID); } break; } case Commands.GameAction: { if (IsHost) { break; } int gameActionID = streamReader.ReadInt(); int actorNumber = streamReader.ReadInt(); float triggerTime = streamReader.ReadFloat(); bool valid = streamReader.ReadBool(); try { GameAction gameAction = GameActionManager.Instance.Get(gameActionID); GameAction.IParameters parameters = gameAction.DeserializeParameters(ref streamReader); gameAction.ReceiveOnClient(parameters, valid, actorNumber, triggerTime); break; } catch (Exception e) { Debug.LogException(e); break; } } case Commands.NetAssetRPC: { if (IsHost) { break; } float sentServerTime = streamReader.ReadFloat(); int netAssetID = streamReader.ReadInt(); NetAsset netAsset = NetAssetManager.Instance.Get(netAssetID); NetAsset.RPC rpc = netAsset.DeserializeRPC(ref streamReader); var messageInfo = new MessageInfo { SentServerTime = sentServerTime, SenderActorNumber = Server.ServerActorNumber }; rpc.Invoke(messageInfo); break; } case Commands.NetObjectRPC: { if (IsHost) { break; } float sentServerTime = streamReader.ReadFloat(); int netObjectID = streamReader.ReadInt(); if (!NetObjectManager.Instance.Exists(netObjectID)) { Debug.LogWarning("Ignoring received RPC, because NetObject was not found."); break; } NetObject netObject = NetObjectManager.Instance.Get(netObjectID); ushort netBehaviourID = streamReader.ReadUShort(); NetBehaviour netBehaviour = netObject.Get(netBehaviourID); NetObjectManager.RPC rpc = NetObjectManager.Instance.DeserializeRPC(ref streamReader, netBehaviour); var messageInfo = new MessageInfo { SentServerTime = sentServerTime, SenderActorNumber = Server.ServerActorNumber }; rpc.Invoke(messageInfo); break; } default: Debug.LogError($"Unknown event type {eventType}"); break; } } else if (eventType == NetworkEvent.Type.Disconnect) { Debug.Log("Disconnected!"); SceneManager.sceneLoaded -= OnSceneLoaded; Disconnected?.Invoke(); State = ClientState.Disconnected; _clientToServerConnection = default; } } }
public static int ApproxPolygon(Int32Image image, Connected connected, double minDistance, int maxVertices, vector_XYCoord tab) { int ret = VisionLabPINVOKE.ApproxPolygon__SWIG_4(Int32Image.getCPtr(image), (int)connected, minDistance, maxVertices, vector_XYCoord.getCPtr(tab)); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
/// <summary> /// Raises Connected event. /// </summary> protected virtual void OnConnected() { Connected?.Invoke(this, EventArgs.Empty); }
public static void DistanceT(Int32Image image, Connected connected) { VisionLabPINVOKE.DistanceT__SWIG_8(Int32Image.getCPtr(image), (int)connected); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); }
private void OnInserted() { _attached = true; Connected?.Invoke(this, EventArgs.Empty); }
public static int FindHoles(Int16Image image, Connected connected) { int ret = VisionLabPINVOKE.FindHoles__SWIG_3(Int16Image.getCPtr(image), (int)connected); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
private void Connect() { #if DEBUG var ipAddresses = new List <IpAddressInfo> { new IpAddressInfo { Ip = "192.168.178.114", Port = 10134 }, new IpAddressInfo { Ip = "127.0.0.1", Port = 10134 } }; #else var ipAddresses = Settings.GetBuilderProperty <ConnectionBuilderProperty>().IpAddresses; #endif var currentIpIndex = 0; while (IsSearching) { var skip = false; foreach (var clientPlugin in PluginLoader.Current.ClientPlugins) { try { if (!clientPlugin.CanTryConnect()) { skip = true; break; } } catch (Exception ex) { ErrorReporter.Current.ReportError(ex, "CanStart() at plugin: \"" + clientPlugin.GetType() + "\""); } } if (!skip) { TcpClient client = null; SslStream stream = null; BinaryReader binaryReader = null; BinaryWriter binaryWriter = null; try { if (currentIpIndex >= ipAddresses.Count) { currentIpIndex = 0; } TryConnectDelegate connectFunction = TryConnect; var connectionModifyingPlugin = PluginLoader.Current.ClientPlugins.FirstOrDefault(x => x.OverwriteTryConnect); if (connectionModifyingPlugin != null) { connectFunction = connectionModifyingPlugin.TryConnect; } if (connectFunction(out client, out stream, ipAddresses[currentIpIndex])) { currentIpIndex = 0; binaryWriter = new BinaryWriter(stream); binaryReader = new BinaryReader(stream); string path; if (!Initialize(binaryWriter, binaryReader, out path)) { stream.Dispose(); client.Close(); if (path != null) { Program.Unload(); var exeName = Process.GetCurrentProcess().MainModule.FileName; var startInfo = new ProcessStartInfo(exeName) { Arguments = $"/wait /upgrade \"{path}\"" }; Process.Start(startInfo); Program.Exit(); } } if (Authenticate(binaryReader, binaryWriter)) { InformationCollector.SendInformation(stream); IsConnected = true; StopConnect(); Connection = new ServerConnection(client, stream, binaryReader, binaryWriter, ClientOperator.Instance.DatabaseConnection, this); Connection.Disconnected += Connection_Disconnected; Connected?.Invoke(this, EventArgs.Empty); break; } } else { currentIpIndex++; } } catch (Exception) { // ignored } binaryReader?.Close(); binaryWriter?.Close(); stream?.Dispose(); client?.Close(); } Thread.Sleep(Settings.GetBuilderProperty <ReconnectDelayProperty>().Delay + _random.Next(1, 340)); } }
public static bool FindCornersRectangleSq(Int32Image image, Connected connected, XYCoord leftTop, XYCoord rigthTop, XYCoord leftBottom, XYCoord rightBottom) { bool ret = VisionLabPINVOKE.FindCornersRectangleSq__SWIG_4(Int32Image.getCPtr(image), (int)connected, XYCoord.getCPtr(leftTop), XYCoord.getCPtr(rigthTop), XYCoord.getCPtr(leftBottom), XYCoord.getCPtr(rightBottom)); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
private void OnConnected(object sender, MqttClientConnectedEventArgs eventArgs) { Connected?.Invoke(this, eventArgs); }
public static int FindSpecificHoles(Int32Image image, Connected connected, BlobAnalyse ba, double low, double high, UseXOrY xy, BlobAnalyseModifier baMod) { int ret = VisionLabPINVOKE.FindSpecificHoles__SWIG_12(Int32Image.getCPtr(image), (int)connected, (int)ba, low, high, (int)xy, BlobAnalyseModifier.getCPtr(baMod)); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
public void OnConnected() { Connected?.Invoke(_quik, EventArgs.Empty); }
public static int LabelBlobs(Int32Image image, Connected connected) { int ret = VisionLabPINVOKE.LabelBlobs__SWIG_4(Int32Image.getCPtr(image), (int)connected); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
public async Task <MqttClientConnectResult> ConnectAsync(IMqttClientOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (options.ChannelOptions == null) { throw new ArgumentException("ChannelOptions are not set."); } ThrowIfConnected("It is not allowed to connect with a server after the connection is established."); try { Options = options; _packetIdentifierProvider.Reset(); _packetDispatcher.Reset(); _cancellationTokenSource = new CancellationTokenSource(); _disconnectGate = 0; _adapter = _adapterFactory.CreateClientAdapter(options, _logger); _logger.Verbose($"Trying to connect with server ({Options.ChannelOptions})."); await _adapter.ConnectAsync(Options.CommunicationTimeout, _cancellationTokenSource.Token).ConfigureAwait(false); _logger.Verbose("Connection with server established."); _packetReceiverTask = Task.Factory.StartNew(() => ReceivePacketsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap(); var connectResponse = await AuthenticateAsync(options.WillMessage, _cancellationTokenSource.Token).ConfigureAwait(false); _logger.Verbose("MQTT connection with server established."); _sendTracker.Restart(); if (Options.KeepAlivePeriod != TimeSpan.Zero) { StartSendingKeepAliveMessages(_cancellationTokenSource.Token); } IsConnected = true; Connected?.Invoke(this, new MqttClientConnectedEventArgs(connectResponse.IsSessionPresent)); _logger.Info("Connected."); return(new MqttClientConnectResult(connectResponse.IsSessionPresent)); } catch (Exception exception) { _logger.Error(exception, "Error while connecting with server."); if (!DisconnectIsPending()) { await DisconnectInternalAsync(null, exception).ConfigureAwait(false); } throw; } }
public static int RemoveBlobs(Int16Image image, Connected connected, BlobAnalyse ba, double low, double high, UseXOrY xy) { int ret = VisionLabPINVOKE.RemoveBlobs__SWIG_10(Int16Image.getCPtr(image), (int)connected, (int)ba, low, high, (int)xy); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
internal void RaiseConnected(string message) { Connected?.Invoke(message); }
public static int RemoveGrayScaleBlobs(Int32Image image, Int32Image grayImage, Connected connected, BlobAnalyse ba, double low, double high) { int ret = VisionLabPINVOKE.RemoveGrayScaleBlobs__SWIG_14(Int32Image.getCPtr(image), Int32Image.getCPtr(grayImage), (int)connected, (int)ba, low, high); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
/// <summary> /// To call the event <see cref="Connected"/>. /// </summary> private void RaiseConnected() { ConnectionState = ConnectionStates.Connected; Connected?.Invoke(); }
public static int SeparateBlobs(Int32Image src, Int32Image dest, Connected connected, int size) { int ret = VisionLabPINVOKE.SeparateBlobs__SWIG_4(Int32Image.getCPtr(src), Int32Image.getCPtr(dest), (int)connected, size); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); return ret; }
/// <summary> /// Raises the Connected event. /// </summary> protected void OnConnected() { Connected?.Invoke(); }
public static void Canny(Int32Image src, Int32Image dest, double sigma, int low, int high, Connected connected) { VisionLabPINVOKE.Canny__SWIG_8(Int32Image.getCPtr(src), Int32Image.getCPtr(dest), sigma, low, high, (int)connected); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); }
internal void InvokeConnected() { Connected?.Invoke(this); }
public static void ThresholdHysteresis(Int32Image image, int low, int high, Connected connected) { VisionLabPINVOKE.ThresholdHysteresis__SWIG_4(Int32Image.getCPtr(image), low, high, (int)connected); if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve(); }
private void WebSocket_Connected(IWebSocket obj) { Connected?.Invoke(this); }