public async Task CloseAsync() { ThrowIfNotStarted(); Logger.LogInformation("Closing socket connection."); try { State = ReadyState.Closing; //don't receive anything from underlying socket anymore _pingPongSubscription.Dispose(); _messageSubscription.Dispose(); _disconnectSubscription.Dispose(); //clean anything set during socket startup/run time _packetId = -1; _currentHandshake = null; _sentPingPackets.Clear(); //finally stop the socket await _socket.StopOrFail(WebSocketCloseStatus.NormalClosure, string.Empty); } catch (Exception ex) { Logger.LogError(ex, "Error while stopping socket."); throw; } finally { Logger.LogInformation("Socket connection closed."); State = ReadyState.Closed; } }
private void Destroy() { if (_jsThis.IsUndefined()) { return; } _state = ReadyState.UNSENT; _code = 0; _jsThis = JSApi.JS_UNDEFINED; var runtime = ScriptEngine.GetRuntime(_jsContext); if (runtime != null) { runtime.OnDestroy -= Destroy; } if (_jsContext.IsValid()) { JSApi.JS_FreeValue(_jsContext, _onreadystatechange); _onreadystatechange = JSApi.JS_UNDEFINED; JSApi.JS_FreeValue(_jsContext, _onerror); _onerror = JSApi.JS_UNDEFINED; _jsContext = JSContext.Null; } }
public async Task OpenAsync(Uri uri, SocketIoOpenOptions options = null) { ThrowIfStarted(); try { Logger.LogInformation($"Opening socket connection to: {uri}"); State = ReadyState.Opening; _namespace = uri.LocalPath; _query = string.IsNullOrEmpty(uri.Query) ? null : uri.Query.TrimStart('?'); var socketIoUri = uri.ToSocketIoWebSocketUri(path: options?.Path); _socket = new WebsocketClient(socketIoUri) { MessageEncoding = Encoding, IsReconnectionEnabled = false }; Events.HandshakeSubject.Subscribe(OnHandshake); Events.OnPong.Subscribe(OnPong); Events.OnOpen.Subscribe(OnOpen); await StartSocketAsync(); State = ReadyState.Open; Logger.LogInformation("Socket connection successfully established."); } catch (Exception ex) { Logger.LogError(ex, "Error while starting socket."); State = ReadyState.Closed; throw; } }
internal void ReportReady(ReadyState state) { if (OnReady != null) { OnReady(this, new HttpReadyEventArgs(state)); } }
public void UpdateState(string txt, bool isPartial) { /* * Current Ready | IsPartial | blank | new value for Ready * -------------------|-----------|-------|-------------------- * StartExpression | false | false | StartExpression * StartExpression | false | true | <INVALID> * StartExpression | true | false | ContinueExpression * StartExpression | true | true | StartExpression * ContinueExpression | false | x | StartExpression * ContinueExpression | true | x | ContinueExpression */ if (State == ReadyState.StartExpression) { bool isBlank = string.IsNullOrWhiteSpace(txt); if (!isPartial && isBlank) { throw new InvalidOperationException( ); } State = isPartial == isBlank ? ReadyState.StartExpression : ReadyState.ContinueExpression; } else { State = isPartial ? ReadyState.ContinueExpression : ReadyState.StartExpression; } }
public static bool WaitReadyState(int maxWaitTimeInMillis, params ReadyState[] expected) { expected = expected ?? PageLoaded; var driver = Driver; try { return(Executor.Until(() => { ReadyState state = driver.GetReadyState(); return expected.Contains(state); }, maxWaitTimeInMillis)); } catch (UnhandledAlertException) { string alertText; WebDriverManager.AcceptDialog(out alertText); Logger.W("UnhandledAlert accepted: {0}", alertText); return(WaitPageReady(20 * 1000)); } finally { if (Driver.Url != LastDriverUrl) { Logger.V("Driver Url changed from '{0}' to '{1}'.", LastDriverUrl, Driver.Url); WebDriverManager.CurrentSwitchTo(""); LastDriverUrl = Driver.Url; } } }
private async void Send() { if (_state != ReadyState.OPENED) { throw new InvalidOperationException(); } _state = ReadyState.LOADING; OnReadyStateChange(); if (_state != ReadyState.LOADING) { return; } var rsp = await _request.GetResponseAsync() as HttpWebResponse; if (_state != ReadyState.LOADING) { return; } var reader = new StreamReader(rsp.GetResponseStream()); _reseponseText = await reader.ReadToEndAsync(); if (_state != ReadyState.LOADING) { return; } _state = ReadyState.DONE; _code = rsp.StatusCode; OnReadyStateChange(); }
private void UpdateUI(ReadyState state) { messageTextField.Enabled = state == ReadyState.Open; sendButton.Enabled = state == ReadyState.Open; pingButton.Enabled = state == ReadyState.Open; var working = state == ReadyState.Connecting || state == ReadyState.Closing; connectButton.Enabled = !working; if (working) { connectionActivity.StartAnimating(); } else { connectionActivity.StopAnimating(); } if (state == ReadyState.Open) { connectButton.SetTitle("Disconnect", UIControlState.Normal); } else if (state == ReadyState.Closed) { connectButton.SetTitle("Connect", UIControlState.Normal); } }
public FSM_GameSystem(int fsmID) : base(fsmID) { //create State //Init InitState state_Init = new InitState((int)GameSystemState_ID.Init); state_Init.Initialize(this, null, () => { }); //Ready ReadyState state_Ready = new ReadyState((int)GameSystemState_ID.Ready); state_Ready.Initialize(this, null, () => { }); //SpawnNewBlock SpawnNewBlockState state_SpawnNewBlock = new SpawnNewBlockState((int)GameSystemState_ID.SpawnNewBlock); state_SpawnNewBlock.Initialize(this, null, () => { }); //Wait WaitState state_Wait = new WaitState((int)GameSystemState_ID.Wait); state_Wait.Initialize(this, null, () => { }); //JudgeEliminate JudgeEliminateState state_JudgeEliminate = new JudgeEliminateState((int)GameSystemState_ID.JudgeEliminate); state_JudgeEliminate.Initialize(this, null, () => { }); //Eliminate EliminateState state_Eliminate = new EliminateState((int)GameSystemState_ID.Eliminate); state_Eliminate.Initialize(this, null, () => { }); }
protected override void DoOpen() { var log = LogManager.GetLogger(Global.CallerName()); log.Info("DoOpen: Entry"); do { if (FirstTimePoll) { log.Info("DoOpen: Initial Poll - ReadyState=" + ReadyState.ToString()); FirstTimePoll = false; Poll(); IsPolling = false; Emit(EVENT_POLL_COMPLETE); } else if (OnDataReceived && ReadyState == ReadyStateEnum.OPEN) { log.Info("DoOpen: General Poll - ReadyState=" + ReadyState.ToString()); OnDataReceived = false;// Don't poll again, unless signaled by _onData Poll(); IsPolling = false; Emit(EVENT_POLL_COMPLETE); } else { log.Info(string.Format("DoOpen: ignoring poll - transport state {0}", ReadyState)); } System.Threading.Thread.Sleep(100); }while (ReadyState != ReadyStateEnum.CLOSED); }
private void WebRequestOK(string response) { if (this.state == ReadyState.WakingServiceUp) { this.state = ReadyState.CommunicationVerified; } }
public static ReadyState GetReadyState(this RemoteWebDriver driver) { try { string stateStr = driver.ExecuteScript(getReadyStateScript).ToString(); ReadyState result = ReadyState.unknown; Enum.TryParse <ReadyState>(stateStr, out result); return(result); } catch (UnhandledAlertException) { return(ReadyState.loaded); } catch (Exception ex) { Logger.E(ex); string temp = driver.ExecuteScript("return frames;").ToString(); if (temp != "undefined") { temp = driver.ExecuteScript("return frames[0].outerHTML;").ToString(); Logger.D(temp); } else { temp = driver.ExecuteScript("return frames;").ToString(); Logger.D(temp); } return(ReadyState.unknown); } }
public void SendData(string data) { if (ReadyState.Equals(WebSocketState.Open)) { Send(data); Console.WriteLine(String.Format("sent: {0}", BitConverter.ToString(Encoding.UTF8.GetBytes(data)))); } }
public void SendData(byte[] data) { if (ReadyState.Equals(WebSocketState.Open)) { Send(data); Console.WriteLine(string.Format("sent: {0}", BitConverter.ToString(data))); } }
public void UpdateState(ScannerItem si, SimPe.Cache.PackageState ps, System.Windows.Forms.ListViewItem lvi) { if (ps.State != TriState.Null) { ReadyState cs = (ReadyState)ps.Data[0]; AbstractScanner.SetSubItem(lvi, this.StartColum, cs.ToString(), ps); } }
private void HelloResponseOK(string message) { if (this.state == ReadyState.WakingServiceUp) { this.state = ReadyState.CommunicationVerified; Debug.Log("Woke up"); } }
/// <summary> /// Send textures to GPU<para/> /// Отправка текстур на GPU /// </summary> public void SendTextures() { foreach (KeyValuePair <string, Texture> k in Textures) { k.Value.Send(); } State = ReadyState.Complete; }
public void HandleError(object sender, ExceptionEventArgs e) { ErrorReceived = e.Exception; SourceStateReceived = _source.ReadyState; if (CloseEventSourceOnError) { _source.Close(); } }
/// <summary> /// 构造方法 /// </summary> /// <param name="hsInfo">心跳信息</param> public RunningHeart(HeartServerInfo hsInfo) : base(hsInfo) { readyState = new ReadyState(this); runningState = new RunningState(this); pauseState = new PauseState(this); runState = readyState; }
/// <summary> /// Creating textures<para/> /// Создание текстур /// </summary> public void BuildTextures() { Textures = new Dictionary<string, Texture>(); foreach (KeyValuePair<string, TextureFile.Entry> k in File.Textures) { string tName = k.Key.ToLower(); Texture t = new Texture(tName, this); Textures.Add(tName, t); } State = ReadyState.NotSent; }
private void WebRequestErr(string error) { if (this.state == ReadyState.WakingServiceUp) { this.state = ReadyState.TimeoutGivingUp; this.messageQueue.Clear(); } // NOTE: not worrying about a lost logged message: !!!TBD!!! should we be? Only concerned about first HelloWorld success or not. }
/// <summary> /// Create submesh from ModelFile's Geometry entry<para/> /// Создание сабмеша из данных Geometry /// </summary> /// <param name="g">Loaded Geometry<para/>Загруженая Geometry</param> public SubMesh(Branch parent, Model model, ModelFile.Geometry g) { // Setting up the fields // Настройка полей State = ReadyState.Empty; Parent = parent; ParentModel = model; geometry = g; }
private ReadyState() { if (_instance != null) { return; } _instance = this; }
public ReadyState GetReadyState() { object returned = ExecuteScript(getReadyStateScript); string state = returned == null ? "unknown" : returned.ToString(); ReadyState result = ReadyState.unknown; Enum.TryParse <ReadyState>(state, out result); return(result); }
/// <summary> /// Creating textures<para/> /// Создание текстур /// </summary> public void BuildTextures() { Textures = new Dictionary <string, Texture>(); foreach (KeyValuePair <string, TextureFile.Entry> k in File.Textures) { string tName = k.Key.ToLower(); Texture t = new Texture(tName, this); Textures.Add(tName, t); } State = ReadyState.NotSent; }
private void WebRequestErr(string error) { //Debug.Log(LOGGING_SERVICE_URL); if (this.state == ReadyState.WakingServiceUp) { this.state = ReadyState.TimeoutGivingUp; this.messageQueue.Clear(); } Debug.Log("Web request not ok: " + error); // NOTE: not worrying about a lost logged message: !!!TBD!!! should we be? Only concerned about first HelloWorld success or not. }
private void Open(string requestUriString, string method, bool bAsync) { if (_state != ReadyState.UNSENT) { throw new InvalidOperationException(); } _bAsync = bAsync; _method = method; _requestUriString = requestUriString; _state = ReadyState.OPENED; OnReadyStateChange(); }
/// <summary> /// Send submeshes to GPU<para/> /// Отправка данных на GPU /// </summary> public void SendSubMeshes() { if (State != ReadyState.NotSent) { return; } foreach (Branch b in Children) { RecursiveProcessBranch(b, true); } State = ReadyState.Complete; }
/// <summary> /// Remove texture data<para/> /// Удаление данных текстур /// </summary> public void Destroy() { if (Textures != null) { foreach (KeyValuePair <string, Texture> k in Textures) { k.Value.Release(); } Textures = null; } State = ReadyState.Obsolette; }
/// <summary> /// Remove model data<para/> /// Удаление данных модели /// </summary> public void Destroy() { if (Children != null) { foreach (Branch b in Children) { RecursiveDestroyBranch(b); } Children = null; } State = ReadyState.Obsolette; }
/// <summary> /// Initializes a new instance of the <see cref="EventSource" /> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <exception cref="ArgumentNullException">client /// or /// configuration</exception> public EventSource(Configuration configuration) { _readyState = ReadyState.Raw; _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _logger = _configuration.Logger ?? LogManager.GetLogger(typeof(EventSource)); _retryDelay = _configuration.DelayRetryDuration; _backOff = new ExponentialBackoffWithDecorrelation(_retryDelay, Configuration.MaximumRetryDuration); }
private void UpdateUI (ReadyState state) { messageTextField.Enabled = state == ReadyState.Open; sendButton.Enabled = state == ReadyState.Open; pingButton.Enabled = state == ReadyState.Open; var working = state == ReadyState.Connecting || state == ReadyState.Closing; connectButton.Enabled = !working; if (state == ReadyState.Open) { connectButton.SetTitle ("Disconnect", UIControlState.Normal); } else if (state == ReadyState.Closed) { connectButton.SetTitle ("Connect", UIControlState.Normal); } }
/// <summary> /// Create model from model file<para/> /// Создание модели из ModelFile /// </summary> /// <param name="f">Complete model file<para/>Прочитанный файл модели</param> /// <param name="sendNow">Send submeshes to GPU instantly<para/>Сразу же отправить данные меша на видеокарту</param> public Model(ModelFile f, bool important = false, bool sendNow = false) { // Checking completeness of model file // Проверка прочитанности модели if (sendNow && f.State != RenderWareFile.LoadState.Complete) { throw new Exception("[Model] Trying to create model from incomplete ModelFile"); } State = ReadyState.Empty; // Initializing fields // Инициализация полей File = f; Important = important; // Send submeshes // Отправка сабмешей if (sendNow) { BuildSubMeshes(); SendSubMeshes(); } }
/// <summary> /// Send vertex data to GL<para/> /// Отправка вершинных данных в GL /// </summary> public void Send() { if (State!=ReadyState.NotSent) { if (State == ReadyState.Empty) { Build(); }else{ return; } } // Sending positions // Отправка позиций if (vertexData!=null) { vertexBuffer = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBuffer); GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(vertexData.Length * sizeof(float)), vertexData, BufferUsageHint.StaticDraw); vertexData = null; } // Sending normals // Отправка нормалей if (normalData != null) { normalBuffer = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, normalBuffer); GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(normalData.Length * sizeof(float)), normalData, BufferUsageHint.StaticDraw); normalData = null; } // Sending colors // Отправка цвета if (colorData != null) { colorBuffer = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, colorBuffer); GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(colorData.Length * sizeof(byte)), colorData, BufferUsageHint.StaticDraw); colorData = null; } // Sending tex coords // Отправка текстурных координат if (texCoord1Data != null) { tex1Buffer = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, tex1Buffer); GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(texCoord1Data.Length * sizeof(float)), texCoord1Data, BufferUsageHint.StaticDraw); texCoord1Data = null; } if (texCoord2Data != null) { tex2Buffer = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, tex2Buffer); GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(texCoord2Data.Length * sizeof(float)), texCoord2Data, BufferUsageHint.StaticDraw); texCoord2Data = null; } // Sending indices // Отправка индексов вершин foreach (Surface s in Surfaces) { s.IndexBuffer = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ElementArrayBuffer, s.IndexBuffer); GL.BufferData(BufferTarget.ElementArrayBuffer, new IntPtr(s.IndexData.Length * sizeof(ushort)), s.IndexData, BufferUsageHint.StaticDraw); s.IndexCount = s.IndexData.Length; s.IndexData = null; } // Releasing buffers // Освобождаем буфферы GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); State = ReadyState.Complete; }
/// <summary> /// Send textures to GPU<para/> /// Отправка текстур на GPU /// </summary> public void SendTextures() { foreach (KeyValuePair<string, Texture> k in Textures) { k.Value.Send(); } State = ReadyState.Complete; }
/// <summary> /// Remove model data<para/> /// Удаление данных модели /// </summary> public void Destroy() { if (Children!=null) { foreach (Branch b in Children) { RecursiveDestroyBranch(b); } Children = null; } State = ReadyState.Obsolette; }
/// <summary> /// Generate submesh temporary data<para/> /// Генерация временных GL-данных /// </summary> public void BuildSubMeshes() { // Analyze sub-branches // Выборка дочерних веток List<Branch> ch = new List<Branch>(); for (int i = 0; i < File.Frames.Length; i++) { ModelFile.Frame fr = File.Frames[i]; if (fr.Parent == -1) { ch.Add(new Branch(this, null, i)); } } Children = ch.ToArray(); foreach (Branch b in Children) { RecursiveProcessBranch(b, false); } State = ReadyState.NotSent; }
/// <summary> /// Render this submesh<para/> /// Отрисовка этого меша /// </summary> /// <param name="td">Textures to use<para/>Текстуры для использования</param> /// <param name="trans">Transparent mode<para/>Полупрозрачный режим</param> public void Render(RendererBase renderer, TextureDictionary td, bool trans, bool force = false) { if (State != ReadyState.Obsolette) { if (State == ReadyState.Empty) { Build(); State = ReadyState.NotSent; } else if (State == ReadyState.Complete) { DrawGL(renderer, td, trans, force); } } ParentModel.UseCount++; }
/// <summary> /// Build vertex data from specified geometry<para/> /// Построение геометрических данных из вершин /// </summary> public void Build() { if (State!=ReadyState.Empty) { return; } State = ReadyState.Reading; // Decoding vertices // Разбираем вершины if (geometry.Vertices!=null) { vertexData = new float[geometry.Vertices.Length]; for (int i = 0; i < vertexData.Length; i+=3) { vertexData[i] = geometry.Vertices[i]; vertexData[i+1] = geometry.Vertices[i+2]; vertexData[i+2] = -geometry.Vertices[i+1]; } } // Decoding normals // Разбираем нормали if (geometry.Normals != null) { normalData = new float[geometry.Normals.Length]; for (int i = 0; i < normalData.Length; i += 3) { normalData[i] = geometry.Normals[i]; normalData[i + 1] = geometry.Normals[i + 2]; normalData[i + 2] = -geometry.Normals[i + 1]; } } // Decoding colors // Разбираем цвета if (geometry.Colors != null) { colorData = new byte[geometry.Colors.Length]; Array.Copy(geometry.Colors, colorData, geometry.Colors.Length); } // Decoding first texture coords // Разбираем первые текстурные координаты if (geometry.TextureCoords != null) { texCoord1Data = new float[geometry.TextureCoords.Length]; for (int i = 0; i < texCoord1Data.Length; i+=2) { texCoord1Data[i] = geometry.TextureCoords[i]; texCoord1Data[i+1] = geometry.TextureCoords[i+1]; } } // Decoding second texture coords // Разбираем вторые текстурные координаты if (geometry.SecondTextureCoords != null) { texCoord2Data = new float[geometry.SecondTextureCoords.Length]; for (int i = 0; i < texCoord2Data.Length; i += 2) { texCoord2Data[i] = geometry.SecondTextureCoords[i]; texCoord2Data[i + 1] = geometry.SecondTextureCoords[i + 1]; } } // Decoding indices // Разбор индексов List<Surface> surfs = new List<Surface>(); if (geometry.Binary!=null) { // Detect binary meshes // Разбор бинарных мешей foreach (ModelFile.BinaryMesh m in geometry.Binary) { surfs.Add(new Surface() { IndexData = m.Indices.ToArray(), IsTriangleStrip = m.Mode == ModelFile.SplitMode.TriangleStrip, Material = new Material(m.BinaryMaterial) }); } }else{ // Detect normal meshes // Разбор обычных мешей List<ushort>[] indices = new List<ushort>[geometry.Materials.Length]; for (int i = 0; i < geometry.Materials.Length; i++) { indices[i] = new List<ushort>(); } for (int idx = 0; idx < geometry.Indices.Length; idx += 4) { indices[geometry.Indices[idx + 2]].AddRange(new ushort[]{ geometry.Indices[idx+0], geometry.Indices[idx+1], geometry.Indices[idx+3] }); } // Creating surfaces // Создание сурфейсов for (int i = 0; i < geometry.Materials.Length; i++) { surfs.Add(new Surface() { IndexData = indices[i].ToArray(), IsTriangleStrip = false, Material = new Material(geometry.Materials[i]) }); } } Surfaces = surfs.ToArray(); State = ReadyState.NotSent; }
private void WebRequestOK(string response) { if (this.state == ReadyState.WakingServiceUp) this.state = ReadyState.CommunicationVerified; }
/// <summary> /// Writes the given message to the web service. /// </summary> /// <param name="message">The string to be written to the web service.</param> public void Write(string message) { //Debug.Log(LOGGING_SERVICE_URL); if (this.state == ReadyState.Initializing) { Debug.Log("Trying to wake up..."); WakeUpService(); this.state = ReadyState.WakingServiceUp; } if (this.state == ReadyState.WakingServiceUp) { if (Time.time > this.timeout) { // Drat! Didn't hear back from service, so give up and don't queue // messages further, clear queue, don't log, don't try to recover. this.state = ReadyState.TimeoutGivingUp; this.messageQueue.Clear(); } else { // keep state as WakingServiceUp until our timeout reached or we get ack // back from service moving us to state of CommunicationVerified: // queue messages during this period this.messageQueue.Enqueue(message); } } else if (this.state == ReadyState.CommunicationVerified) { // Service is there. Dequeue all that we have and send those off, // then mark state as Ready so that queue no longer needs to be used. while (this.messageQueue.Count > 0) { this.SendMessage(this.messageQueue.Dequeue()); } this.state = ReadyState.Ready; } if (this.state == ReadyState.Ready) { this.SendMessage(message); } }
/// <summary> /// Remove texture data<para/> /// Удаление данных текстур /// </summary> public void Destroy() { if (Textures!=null) { foreach (KeyValuePair<string, Texture> k in Textures) { k.Value.Release(); } Textures = null; } State = ReadyState.Obsolette; }
private void UpdateUI(ReadyState state) { messageTextField.Enabled = state == ReadyState.Open; sendButton.Enabled = state == ReadyState.Open; pingButton.Enabled = state == ReadyState.Open; var working = state == ReadyState.Connecting || state == ReadyState.Closing; connectButton.Enabled = !working; if (working) { connectionActivity.StartAnimation(this); } else { connectionActivity.StopAnimation(this); } if (state == ReadyState.Open) { connectButton.Title = "Disconnect"; } else if (state == ReadyState.Closed) { connectButton.Title = "Connect"; } }