/// <summary> /// Add this delegate to the tracker so that it can run. /// </summary> /// <param name = "millisecondTimeOut">The time that the thread can run before it is forcefully stopped.</param> /// <param name = "hb">The delegate to run.</param> public void StartTrackingThread(int millisecondTimeOut, Heartbeat hb) { lock (m_lock) { m_heartbeats.Add(new InternalHeartbeat {heartBeat = hb, millisecondTimeOut = millisecondTimeOut}); } }
/// <summary> /// Cleans up resources /// </summary> /// <param name="disposing">Flag if being disposed</param> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { if (_heartbeat != null) { _heartbeat.Dispose(); _heartbeat = null; } _disposed = true; } } }
private void DoWork(Heartbeat heartbeat, long taskIndex, long finalTaskIndex) { if (heartbeat == null) Trace.WriteLine("Heartbeat is null"); heartbeat.IncrementCount(); //fake work: if (RandomValueGenerator.GetRandomBool()) { Thread.Sleep(RandomValueGenerator.GetRandomInt(100)); } if (taskIndex == finalTaskIndex) { heartbeat.SetComplete("StubComponent.Process finished"); } }
public void Process() { long countInterval = 7000; long countTo = RandomValueGenerator.GetRandomInt(20000, 50000); double timerInterval = 300; //0.3 seconds _heartbeat = new Heartbeat(this, countInterval, timerInterval); _heartbeat.Start("StubComponent.Process started, countInterval: {0}, countTo: {1}, timerInterval: {2}" .FormatWith(countInterval, countTo, timerInterval)); var tasks = new Task[countTo]; long finalTaskIndex = countTo - 1; for (long i = 0; i < countTo; i++) { var heartbeat = _heartbeat; //don't pass the instance directly var taskIndex = i; tasks[i] = Task.Factory.StartNew(() => DoWork(heartbeat, taskIndex, finalTaskIndex)); } }
public ClusterHeartbeatSender() { _cluster = Cluster.Get(Context.System); _selfHeartbeat = new Heartbeat(_cluster.SelfAddress); _state = new ClusterHeartbeatSenderState( new HeartbeatNodeRing(_cluster.SelfUniqueAddress, new[] { _cluster.SelfUniqueAddress }, _cluster.Settings.MonitoredByNrOfMembers), ImmutableHashSet.Create<UniqueAddress>(), FailureDetector); //start periodic heartbeat to other nodes in cluster _heartbeatTask = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable( _cluster.Settings.PeriodicTasksInitialDelay.Max(_cluster.Settings.HeartbeatInterval), _cluster.Settings.HeartbeatInterval, Self, new HeartbeatTick(), Self); Initializing(); }
/// <summary> /// Call the method and wait for it to complete or the max time. /// </summary> /// <param name="timeout"></param> /// <param name="enumerator"></param> /// <param name="isRunning"></param> /// <returns></returns> public static bool CallAndWait(int timeout, Heartbeat enumerator, out bool isRunning) { isRunning = false; bool RetVal = false; if (timeout == 0) { isRunning = enumerator(); RetVal = true; } else { //The action to fire FireEvent wrappedAction = delegate(Heartbeat en) { // Set this culture for the thread // to en-US to avoid number parsing issues Culture.SetCurrentCulture(); en(); RetVal = true; }; //Async the action (yeah, this is bad, but otherwise we can't abort afaik) IAsyncResult result = wrappedAction.BeginInvoke(enumerator, null, null); if (((timeout != 0) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted)) { isRunning = false; return false; } else { wrappedAction.EndInvoke(result); isRunning = true; } } //Return what we got return RetVal; }
public void Ping(Heartbeat.Pulse pulse) { if (pulse.Id == lastPulseId_) { return; } SetState(PingReceiverState.Detected); // Use this transform's Y so that the pulse appears to come from the same plane as the object. pulsePosition_ = new Vector3(pulse.Center.x, pulse.Center.y, this.transform.position.z); pulseRadius_ = pulse.Radius; pulseMaxRadius_ = pulse.MaxRadius; pulseWaveSpeed_ = pulse.Speed; pulseFade_ = 0.0f; pulseFadeTime_ = 0.0f; pulsing_ = true; lastPulseId_ = pulse.Id; DestroyBlipInstance(); blipInstance_ = Instantiate(metagame_.Blip, this.transform.position, this.transform.rotation) as GameObject; if (blipInstance_ != null) { pulseEchoMaterial_ = blipInstance_.renderer.material; Camera mainCamera = this.camera ? this.camera : Camera.main; Quaternion cameraRotation = mainCamera.transform.rotation; blipInstance_.transform.LookAt(blipInstance_.transform.position + (cameraRotation * Vector3.back), cameraRotation * Vector3.up); blipInstance_.renderer.enabled = true; } OnPing(); }
public void CheckPulseCollisions(Heartbeat.Pulse pulse) { // Look at all ping receivers that are active, but not already detected. var activeReceivers = receivers_.Where(r => r.GetState() == PingReceiverState.Active); foreach (PingReceiver receiver in activeReceivers) { Rect receiverRect = receiver.GetPingRect(); Vector2 receiverCenter = receiver.GetPingPoint(); // Skip enemies that are inside of the player's visible circle. if (IsRectInCircle(receiverRect, heartbeat_.GetCenter(), heartbeat_.visbleAreaRadius) || IsPointInCircle(receiverCenter, heartbeat_.GetCenter(), heartbeat_.visbleAreaRadius)) { continue; } if (IsRectInCircle(receiverRect, pulse.Center, pulse.Radius) || IsPointInCircle(receiverCenter, pulse.Center, pulse.Radius)) { receiver.Ping(pulse); } } }
/// <summary> /// This method will be called every time a slave sends a heartbeat (-> very often; concurrency is important!) /// </summary> /// <returns>a list of actions the slave should do</returns> public List <MessageContainer> ProcessHeartbeat(Heartbeat heartbeat) { List <MessageContainer> actions = new List <MessageContainer>(); var pm = PersistenceManager; var slaveDao = pm.SlaveDao; var taskDao = pm.TaskDao; var slave = pm.UseTransaction(() => slaveDao.GetById(heartbeat.SlaveId)); if (slave == null) { actions.Add(new MessageContainer(MessageContainer.MessageType.SayHello)); } else { if (heartbeat.HbInterval != slave.HbInterval) { actions.Add(new MessageContainer(MessageContainer.MessageType.NewHBInterval)); } if (slaveDao.SlaveHasToShutdownComputer(slave.ResourceId)) { actions.Add(new MessageContainer(MessageContainer.MessageType.ShutdownComputer)); } // update slave data slave.FreeCores = heartbeat.FreeCores; slave.FreeMemory = heartbeat.FreeMemory; slave.CpuUtilization = heartbeat.CpuUtilization; slave.SlaveState = (heartbeat.JobProgress != null && heartbeat.JobProgress.Count > 0) ? DA.SlaveState.Calculating : DA.SlaveState.Idle; slave.LastHeartbeat = DateTime.Now; pm.UseTransaction(() => { slave.IsAllowedToCalculate = slaveDao.SlaveIsAllowedToCalculate(slave.ResourceId); pm.SubmitChanges(); }); // update task data actions.AddRange(UpdateTasks(pm, heartbeat, slave.IsAllowedToCalculate)); // assign new task if (heartbeat.AssignJob && slave.IsAllowedToCalculate && heartbeat.FreeCores > 0) { bool mutexAquired = false; var mutex = new Mutex(false, MutexName); try { mutexAquired = mutex.WaitOne(Properties.Settings.Default.SchedulingPatience); if (mutexAquired) { var waitingTasks = pm.UseTransaction(() => taskDao.GetWaitingTasks(slave) .Select(x => new TaskInfoForScheduler { TaskId = x.TaskId, JobId = x.JobId, Priority = x.Priority }) .ToList() ); var availableTasks = TaskScheduler.Schedule(waitingTasks).ToArray(); if (availableTasks.Any()) { var task = availableTasks.First(); AssignTask(pm, slave, task.TaskId); actions.Add(new MessageContainer(MessageContainer.MessageType.CalculateTask, task.TaskId)); } } else { LogFactory.GetLogger(this.GetType().Namespace).Log("HeartbeatManager: The mutex used for scheduling could not be aquired."); } } catch (AbandonedMutexException) { LogFactory.GetLogger(this.GetType().Namespace).Log("HeartbeatManager: The mutex used for scheduling has been abandoned."); } catch (Exception ex) { LogFactory.GetLogger(this.GetType().Namespace).Log(string.Format("HeartbeatManager threw an exception in ProcessHeartbeat: {0}", ex)); } finally { if (mutexAquired) { mutex.ReleaseMutex(); } } } } return(actions); }
public IdleHandler(Heartbeat loop) { _loop = loop; }
/// <summary> /// Sets up the heartbeat to be executed during the application's idle state and calls /// Application.Run() using the supplied application context. /// </summary> /// <param name="context">Application thread context</param> /// <param name="mainLoop">Heartbeat update/render loop</param> public static void Run(ApplicationContext context, Heartbeat mainLoop) { Application.Idle += new EventHandler(new IdleHandler(mainLoop).OnIdle); Application.Run(context); }
public HeartbeatTests() { instance = new Heartbeat(); }
public HeartbeatEventArgs(Heartbeat heartbeat) { this.Heartbeat = heartbeat; }
public MsgHeartbeat(Heartbeat hearbeat) : base(3) { this.Data = hearbeat; }
private void TCPReadCallBack(IAsyncResult ar) { //lock(m_stream) { m_totalBytesRead = m_stream.EndRead(ar); m_profiler.RecvDataCount(m_totalBytesRead); } m_readTimeCounter = 0.0f; m_processed = 0; _recvPacks.Clear(); if (m_totalBytesRead > 0) { m_beginRead = false; int processed = 0; while ((processed = DecodeBuffer(m_buffer, ref _recvPacks)) > 0) { m_processed += processed; if (m_totalBytesRead == m_processed) { break; } } if (_recvPacks.Count != 0) { foreach (Pack pack in _recvPacks) { long now = System.DateTime.Now.Ticks; MsgID msgID = (MsgID)pack.MessageID; if (msgID == MsgID.GameMsgID) { GameMsg msg = Serializer.Deserialize <GameMsg>(new MemoryStream(pack.buffer)); List <Player> players = GameSystem.Instance.mClient.mPlayerManager.m_Players; Player sender = players.Find((Player player) => { return(player.m_roomPosId == msg.senderID); }); GameMatch match = GameSystem.Instance.mClient.mCurMatch; if (match == null) { break; } if (sender == null && match is GameMatch_PVP) { Debug.LogError("Can not find sender: " + msg.senderID + " for command: " + msg.eState); break; } { /* * SimulateCommand cmd = match.GetSmcCommandByGameMsg(sender, msg); * if( cmd != null && sender.m_smcManager != null ) * { * if( cmd is SMC_BackCompete || cmd is SMC_BackBlock ) * Debug.Log("SMC: " + cmd + " cnt: " + _recvPacks.Count ); * NetworkManager nm = GameSystem.Instance.mNetworkManager; * double dConsumeTime = (DateTime.Now.Ticks - msg.curTime) * 0.0001; * if( dConsumeTime > 50.0f ) * { * lock(m_log) * { * m_log = "Command: " + cmd.m_state + " time consume: " + string.Format("{0:f4}", dConsumeTime); * } * } * } */ } } //心跳包的立即回发 if (msgID == MsgID.HeartbeatID) { Heartbeat data = Serializer.Deserialize <Heartbeat>(new MemoryStream(pack.buffer)); GameSystem.mTime = (long)data.server_time + 1; //检查是否加速外挂作弊 if (CheatingDeath.Instance.mAntiSpeedUp.m_beginWatch) { //Debug.LogWarning(string.Format("local=>{0:f4} server=>{1:f4} diff=>{2:f4} ", // CheatingDeath.Instance.mAntiSpeedUp.m_clientTime, data.server_time, // CheatingDeath.Instance.mAntiSpeedUp.m_clientTime - data.server_time)); data.server_time = CheatingDeath.Instance.mAntiSpeedUp.m_clientTime; ErrorDisplay.Instance.HandleLog("watch time: " + data.server_time, "watch", LogType.Log); //System.DateTime timenow = System.DateTime.Now; //string strLog = string.Format("({0:D2}:{1:D2}:{2:D2}.{3:D3})", timenow.Hour, timenow.Minute, timenow.Second, timenow.Millisecond); //ErrorDisplay.Instance.HandleLog("system time: " + strLog, "watch", LogType.Log); } else { if (CheatingDeath.Instance.mAntiSpeedUp.BeginWatch(this, data.server_time)) { ErrorDisplay.Instance.HandleLog("Begin watch: " + data.server_time, "watch", LogType.Log); } } PlatNetwork.Instance.SendHeartbeatMsg(data); //GameSystem.Instance.mNetworkManager.m_platMsgHandler.HeartbeatHandle(pack); } if (msgID == MsgID.GameBeginRespID) { GameBeginResp resp = Serializer.Deserialize <GameBeginResp>(new MemoryStream(pack.buffer)); GameSystem.Instance.mNetworkManager.m_dServerTime = resp.cur_time; GameSystem.Instance.mNetworkManager.m_dLocalTime = DateTime.Now.Ticks * 0.0001; } } lock (m_MsgQueue) { if (_recvPacks.Count != 0) { m_MsgQueue.AddRange(_recvPacks); } } } AsyncRead(); } else { if (m_type != Type.eVirtualServer) { ErrorDisplay.Instance.HandleLog(m_type + " Client: connection is closed, can not read data.", "", LogType.Error); m_serverDisconnectedFlag_Passive = true; ErrorDisplay.Instance.HandleLog(m_type + " App paused, skip this failure.", "", LogType.Log); } } }
private void crash(string reason, Exception ex) { //disable everything try { p_Hotloader.ForceDispose(); p_RenderHeartbeat.ForceStop(); p_LogicHeartbeat.ForceStop(); } catch { } //completely renew the window p_Window.Controls.Clear(); p_Window.UnhookCoreEvents(); p_Window.Click -= handleMouseClick; p_Window.MouseMove -= handleMouseMove; p_Window.MouseUp -= handleMouseUp; p_Window.MouseDown -= handleMouseDown; p_Window.MouseWheel -= handleMouseScroll; p_Window.KeyDown -= handleKeyDown; p_Window.KeyUp -= handleKeyUp; p_Window.Resize -= handleResize; p_Window.GotFocus -= handleFocusChanged; p_Window.LostFocus -= handleFocusChanged; p_Cursor.UnhookEvents(); //save string filename; string repString = crashToFile(ex, null, out filename); //re-enable mouse Cursor.Show(); //any key to exit p_Window.FormClosing += delegate(object sender, FormClosingEventArgs e) { System.Diagnostics.Process.GetCurrentProcess().Kill(); }; p_Window.KeyDown += delegate(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F3) { p_RenderHeartbeat.Stop(); RichTextBox rtb = new RichTextBox() { ReadOnly = true, Dock = DockStyle.Fill }; rtb.Text = repString; p_Window.Controls.Add(rtb); if (p_Window.IsFullScreen) { p_Window.ToggleFullscreen(); } return; } p_Window.Close(); }; crashAnimateInit(); //fallback on GDI+ renderer //RenderFactory.FailSafe(); //re-initialize renderer since we have left the previous //one in an unknown state. p_Window.RecreateContext(); //hijack rendering p_RenderHeartbeat = new Heartbeat("render"); p_RenderHeartbeat.Speed(4); p_RenderHeartbeat.Start(this, delegate(object st) { Game gm = st as Game; IRenderContext ctx = gm.p_Window.Context; IRenderer renderer = gm.p_Window.Renderer; renderer.BeginFrame(ctx); renderer.SetColor(Color.Black); renderer.Clear(); crashAnimateDraw(ctx, renderer); Font crashFont = new Font("Arial", 70, FontStyle.Bold); IFont font = renderer.SetFont(crashFont); Size crashTxtSize = renderer.MeasureString(":(", font); /*title*/ Rectangle crashBounds = new Rectangle( (ctx.Width / 2) - (crashTxtSize.Width / 2), (ctx.Height / 2) - (crashTxtSize.Height / 2), crashTxtSize.Width, crashTxtSize.Height); renderer.SetBrush(Brushes.White); renderer.DrawString(":(", crashBounds.X, crashBounds.Y); /*reason*/ Font regFont = new Font("Arial", 12, FontStyle.Regular); font = renderer.SetFont(regFont); Size reasonTxtSize = renderer.MeasureString(reason, font); renderer.DrawString( reason, (ctx.Width / 2) - (reasonTxtSize.Width / 2), crashBounds.Y + crashBounds.Height + 20); /*advice*/ string advice = "Press any key to exit or press F3 to view report"; Size adviceTxtSize = renderer.MeasureString(advice, font); renderer.DrawString( advice, (ctx.Width / 2) - (adviceTxtSize.Width / 2), crashBounds.Y + crashBounds.Height + 20 + reasonTxtSize.Height + 5); renderer.EndFrame(); }); }
public async Task Should_send_heartbeat_to_vhofficers_group_from_judge() { const string participantUsername = "******"; var conference = InitConference(participantUsername); var judge = conference.Participants.First(x => x.Role == Role.Judge); var judgeUserName = judge.Username; var conferenceId = conference.Id; var judgeId = judge.Id; var heartbeat = new Heartbeat { BrowserName = "test_browser", BrowserVersion = "1", IncomingAudioPercentageLostRecent = 10.3m, OperatingSystem = "Mac OS X", OperatingSystemVersion = "10.15" }; ConferenceCacheMock.Setup(cache => cache.GetOrAddConferenceAsync(conference.Id, It.IsAny <Func <Task <ConferenceDetailsResponse> > >())) .Callback(async(Guid anyGuid, Func <Task <ConferenceDetailsResponse> > factory) => await factory()) .ReturnsAsync(conference); var mockAdminClient = new Mock <IEventHubClient>(); var mockParticipantClient = new Mock <IEventHubClient>(); var mockJudgeClient = new Mock <IEventHubClient>(); EventHubClientMock.Setup(x => x.Group(EventHub.Hub.EventHub.VhOfficersGroupName)).Returns(mockAdminClient.Object); EventHubClientMock.Setup(x => x.Group(participantUsername.ToLowerInvariant())).Returns(mockParticipantClient.Object); EventHubClientMock.Setup(x => x.Group(judgeUserName.ToLowerInvariant())).Returns(mockJudgeClient.Object); HeartbeatMapper.Setup(x => x.MapToHealth(heartbeat)).Returns(HeartbeatHealth.Good); var addHeartbeatRequest = new AddHeartbeatRequest { BrowserName = heartbeat.BrowserName, BrowserVersion = heartbeat.BrowserVersion, IncomingAudioPercentageLostRecent = 10.3m }; HeartbeatMapper.Setup(x => x.MapToRequest(heartbeat)).Returns(addHeartbeatRequest); await Hub.SendHeartbeat(conferenceId, judgeId, heartbeat); mockAdminClient.Verify ( x => x.ReceiveHeartbeat ( conferenceId, judgeId, HeartbeatHealth.Good, heartbeat.BrowserName, heartbeat.BrowserVersion, heartbeat.OperatingSystem, heartbeat.OperatingSystemVersion ), Times.Once ); mockParticipantClient.Verify ( x => x.ReceiveHeartbeat ( conferenceId, judgeId, HeartbeatHealth.Good, heartbeat.BrowserName, heartbeat.BrowserVersion, heartbeat.OperatingSystem, heartbeat.OperatingSystemVersion ), Times.Never ); VideoApiClientMock.Verify ( x => x.SaveHeartbeatDataForParticipantAsync(conferenceId, judgeId, addHeartbeatRequest), Times.Once ); }
/// <summary> /// Update message handler /// </summary> /// <param name="eventType">Value of "event-type" in the JSON body</param> /// <param name="body">full JSON message body</param> protected void ProcessEventType(string eventType, JObject body) { switch (eventType) { case "SwitchScenes": SceneChanged?.Invoke(this, (string)body["scene-name"]); break; case "ScenesChanged": SceneListChanged?.Invoke(this, EventArgs.Empty); break; case "SourceOrderChanged": SourceOrderChanged?.Invoke(this, (string)body["scene-name"]); break; case "SceneItemAdded": SceneItemAdded?.Invoke(this, (string)body["scene-name"], (string)body["item-name"]); break; case "SceneItemRemoved": SceneItemRemoved?.Invoke(this, (string)body["scene-name"], (string)body["item-name"]); break; case "SceneItemVisibilityChanged": SceneItemVisibilityChanged?.Invoke(this, (string)body["scene-name"], (string)body["item-name"]); break; case "SceneCollectionChanged": SceneCollectionChanged?.Invoke(this, EventArgs.Empty); break; case "SceneCollectionListChanged": SceneCollectionListChanged?.Invoke(this, EventArgs.Empty); break; case "SwitchTransition": TransitionChanged?.Invoke(this, (string)body["transition-name"]); break; case "TransitionDurationChanged": TransitionDurationChanged?.Invoke(this, (int)body["new-duration"]); break; case "TransitionListChanged": TransitionListChanged?.Invoke(this, EventArgs.Empty); break; case "TransitionBegin": TransitionBegin?.Invoke(this, EventArgs.Empty); break; case "ProfileChanged": ProfileChanged?.Invoke(this, EventArgs.Empty); break; case "ProfileListChanged": ProfileListChanged?.Invoke(this, EventArgs.Empty); break; case "StreamStarting": StreamingStateChanged?.Invoke(this, OutputState.Starting); break; case "StreamStarted": StreamingStateChanged?.Invoke(this, OutputState.Started); break; case "StreamStopping": StreamingStateChanged?.Invoke(this, OutputState.Stopping); break; case "StreamStopped": StreamingStateChanged?.Invoke(this, OutputState.Stopped); break; case "RecordingStarting": RecordingStateChanged?.Invoke(this, OutputState.Starting); break; case "RecordingStarted": RecordingStateChanged?.Invoke(this, OutputState.Started); break; case "RecordingStopping": RecordingStateChanged?.Invoke(this, OutputState.Stopping); break; case "RecordingStopped": RecordingStateChanged?.Invoke(this, OutputState.Stopped); break; case "StreamStatus": if (StreamStatus != null) { var status = new StreamStatus(body); StreamStatus(this, status); } break; case "RecordingPaused": RecordingPaused?.Invoke(this, EventArgs.Empty); break; case "RecordingResumed": RecordingResumed?.Invoke(this, EventArgs.Empty); break; case "PreviewSceneChanged": PreviewSceneChanged?.Invoke(this, (string)body["scene-name"]); break; case "StudioModeSwitched": StudioModeSwitched?.Invoke(this, (bool)body["new-state"]); break; case "ReplayStarting": ReplayBufferStateChanged?.Invoke(this, OutputState.Starting); break; case "ReplayStarted": ReplayBufferStateChanged?.Invoke(this, OutputState.Started); break; case "ReplayStopping": ReplayBufferStateChanged?.Invoke(this, OutputState.Stopping); break; case "ReplayStopped": ReplayBufferStateChanged?.Invoke(this, OutputState.Stopped); break; case "Exiting": OBSExit?.Invoke(this, EventArgs.Empty); break; case "Heartbeat": Heartbeat?.Invoke(this, new Heartbeat(body)); break; case "BroadcastCustomMessage": BroadcastCustomMessageReceived?.Invoke(this, new BroadcastCustomMessage(body)); break; case "SceneItemDeselected": SceneItemDeselected?.Invoke(this, (string)body["scene-name"], (string)body["item-name"], (string)body["item-id"]); break; case "SceneItemSelected": SceneItemSelected?.Invoke(this, (string)body["scene-name"], (string)body["item-name"], (string)body["item-id"]); break; case "SceneItemTransformChanged": SceneItemTransformChanged?.Invoke(this, new SceneItemTransformInfo(body)); break; case "SourceAudioMixersChanged": SourceAudioMixersChanged?.Invoke(this, new AudioMixersChangedInfo(body)); break; case "SourceAudioSyncOffsetChanged": SourceAudioSyncOffsetChanged?.Invoke(this, (string)body["sourceName"], (int)body["syncOffset"]); break; case "SourceCreated": SourceCreated?.Invoke(this, new SourceSettings(body)); break; case "SourceDestroyed": SourceDestroyed?.Invoke(this, (string)body["sourceName"], (string)body["sourceType"], (string)body["sourceKind"]); break; case "SourceRenamed": SourceRenamed?.Invoke(this, (string)body["newName"], (string)body["previousName"]); break; case "SourceMuteStateChanged": SourceMuteStateChanged?.Invoke(this, (string)body["sourceName"], (bool)body["muted"]); break; case "SourceVolumeChanged": SourceVolumeChanged?.Invoke(this, (string)body["sourceName"], (float)body["volume"]); break; case "SourceFilterAdded": SourceFilterAdded?.Invoke(this, (string)body["sourceName"], (string)body["filterName"], (string)body["filterType"], (JObject)body["filterSettings"]); break; case "SourceFilterRemoved": SourceFilterRemoved?.Invoke(this, (string)body["sourceName"], (string)body["filterName"]); break; case "SourceFilterVisibilityChanged": SourceFilterVisibilityChanged?.Invoke(this, (string)body["sourceName"], (string)body["filterName"], (bool)body["filterEnabled"]); break; case "SourceFiltersReordered": List <FilterReorderItem> filters = new List <FilterReorderItem>(); JsonConvert.PopulateObject(body["filters"].ToString(), filters); SourceFiltersReordered?.Invoke(this, (string)body["sourceName"], filters); break; /* * default: * var header = "-----------" + eventType + "-------------"; * Console.WriteLine(header); * Console.WriteLine(body); * Console.WriteLine("".PadLeft(header.Length,'-')); * break; */ } }
protected override IEnumerator OnRequest(HttpListenerContext context) { string dataString = ""; HttpListenerRequest request = context.Request; StreamReader reader = new StreamReader(request.InputStream); string s = reader.ReadToEnd(); JSONWrapper j = new JSONWrapper(s); CommandPanel cp; try { cp = PlayerRegisterRule.PlayerRegister[j["username"]]; cp.Pulse(); Alliance playerTeam = cp.Team; // List of other players List<PlayerJSON> pj = new List<PlayerJSON>(); foreach (CommandPanel c in PlayerRegisterRule.PlayerRegister.Values) { pj.Add((PlayerJSON)c.ToJSON()); } // List of characters List<CharacterJSON> cj = new List<CharacterJSON>(); foreach (CharacterBehavior c in FindObjectsOfType<CharacterBehavior>()) { // if you're allies OR you're made visible if(c.Team == cp.Team || c.IsVisible) cj.Add((CharacterJSON)c.ToJSON()); } Heartbeat h = new Heartbeat(); h.state = GameStateManager.Instance.GameState; h.players = pj.ToArray(); if (cp.Character != null) h.myCharacter = (CharacterJSON) cp.Character.ToJSON(); h.characters = cj.ToArray(); dataString = JsonUtility.ToJson(h); } catch (Exception e) { // Put code here to refresh the web page Debug.Log(e.Message); } Debug.Log(dataString); byte[] data = Encoding.ASCII.GetBytes(dataString); yield return null; HttpListenerResponse response = context.Response; response.ContentType = "text/plain"; Stream responseStream = response.OutputStream; try { int count = data.Length; int i = 0; while (i < count) { if (i != 0) yield return null; int writeLength = Math.Min((int)writeStaggerCount, count - i); responseStream.Write(data, i, writeLength); i += writeLength; } } finally { // Nothing needs to go here, try-finally used to safely fail if a client disconnects mid-write // Which doesn't really have any negative consequences } }
private void RunHeartBeatThread() { while (!threadStopped) { try { SlaveClientCom.Instance.StatusChanged(ConfigManager.Instance.GetStatusForClientConsole()); } catch (Exception ex) { EventLogManager.LogMessage("Couldn't sent status information to client ui. Exception is: " + Environment.NewLine + ex.ToString()); } try { lock (locker) { if (wcfService.ConnState != NetworkEnum.WcfConnState.Connected) { // login happens automatically upon successfull connection wcfService.Connect(ConfigManager.Instance.GetClientInfo()); SlaveStatusInfo.LoginTime = DateTime.Now; } if (wcfService.ConnState == NetworkEnum.WcfConnState.Connected) { Slave info = ConfigManager.Instance.GetClientInfo(); Heartbeat heartBeatData = new Heartbeat { SlaveId = info.Id, FreeCores = info.Cores.HasValue ? info.Cores.Value - SlaveStatusInfo.UsedCores : 0, FreeMemory = ConfigManager.Instance.GetFreeMemory(), CpuUtilization = ConfigManager.Instance.GetCpuUtilization(), JobProgress = ConfigManager.Instance.GetExecutionTimeOfAllJobs(), AssignJob = !ConfigManager.Instance.Asleep, HbInterval = (int)interval.TotalSeconds }; SlaveClientCom.Instance.LogMessage("Send HB: " + heartBeatData); List<MessageContainer> msgs = wcfService.SendHeartbeat(heartBeatData); if (msgs == null) { SlaveClientCom.Instance.LogMessage("Error getting response from HB"); } else { SlaveClientCom.Instance.LogMessage("HB Response received (" + msgs.Count + "): "); msgs.ForEach(mc => SlaveClientCom.Instance.LogMessage(mc.Message.ToString())); msgs.ForEach(mc => MessageQueue.GetInstance().AddMessage(mc)); } } } } catch (Exception e) { SlaveClientCom.Instance.LogMessage("Heartbeat thread failed: " + e.ToString()); } waitHandle.WaitOne(this.interval); } SlaveClientCom.Instance.LogMessage("Heartbeat thread stopped"); }
protected virtual void OnSending(string payload) { Heartbeat.MarkConnection(this); }
/// <summary> /// Starts the timer to update map objects and the handler to update position /// </summary> public static async Task InitializeDataUpdate() { #region Compass management SettingsService.Instance.PropertyChanged += (object sender, PropertyChangedEventArgs e) => { if (e.PropertyName == nameof(SettingsService.Instance.MapAutomaticOrientationMode)) { switch (SettingsService.Instance.MapAutomaticOrientationMode) { case MapAutomaticOrientationModes.Compass: _compass = Compass.GetDefault(); _compass.ReportInterval = Math.Max(_compass.MinimumReportInterval, 50); _compass.ReadingChanged += compass_ReadingChanged; break; case MapAutomaticOrientationModes.None: case MapAutomaticOrientationModes.GPS: default: if (_compass != null) { _compass.ReadingChanged -= compass_ReadingChanged; _compass = null; } break; } } }; //Trick to trigger the PropertyChanged for MapAutomaticOrientationMode ;) SettingsService.Instance.MapAutomaticOrientationMode = SettingsService.Instance.MapAutomaticOrientationMode; #endregion _geolocator = new Geolocator { DesiredAccuracy = PositionAccuracy.High, DesiredAccuracyInMeters = 5, ReportInterval = 1000, MovementThreshold = 5 }; Busy.SetBusy(true, Resources.CodeResources.GetString("GettingGpsSignalText")); Geoposition = Geoposition ?? await _geolocator.GetGeopositionAsync(); GeopositionUpdated?.Invoke(null, Geoposition); _geolocator.PositionChanged += GeolocatorOnPositionChanged; // Before starting we need game settings GameSetting = await DataCache.GetAsync(nameof(GameSetting), async() => (await _client.Download.GetSettings()).Settings, DateTime.Now.AddMonths(1)); // Update geolocator settings based on server _geolocator.MovementThreshold = GameSetting.MapSettings.GetMapObjectsMinDistanceMeters; if (_heartbeat == null) { _heartbeat = new Heartbeat(); } await _heartbeat.StartDispatcher(); // Update before starting timer Busy.SetBusy(true, Resources.CodeResources.GetString("GettingUserDataText")); //await UpdateMapObjects(); await UpdateInventory(); await UpdateItemTemplates(); Busy.SetBusy(false); }
public void SendHeartbeatMsg(Heartbeat data) { GameSystem.Instance.mNetworkManager.m_platConn.SendPack <Heartbeat>(0, data, MsgID.HeartbeatID); GameSystem.Instance.SendHeartbeatMsg(); }
private void HandleHeartbeat(GuidPrefix senderGuidPrefix, Heartbeat hb) { #if TODO Reader reader = participant.getReader(hb.getReaderId(), hb.getWriterId()); if (reader != null) { reader.onHeartbeat(senderGuidPrefix, hb); } else { log.DebugFormat("No Reader({0}) to handle Heartbeat from {1}", hb.getReaderId(), hb.getWriterId()); } #endif throw new NotImplementedException(); }
public Task UpdateAsync(Heartbeat heartBeat) { return(_heartbeatRepository.UpdateAsync(heartBeat)); }
private bool Equals(Heartbeat other) { return Equals(From, other.From); }
static void InitHeartbeat(SchedulerTask task) { Heartbeat.Start(); }
public List <MessageContainer> SendHeartbeat(Heartbeat heartbeat) { return(CallHiveService(s => s.Heartbeat(heartbeat))); }
private static void sendTestMessages(UtopiaClient utopiaClient, int offset) { // write some test messages.. int[] objIDs = new int[10]; for (int i = 0; (i < objIDs.Length); i++) { objIDs[i] = i; } int[] objState = new int[objIDs.Length]; // send some test StimulusEvents for (int i = 0; (i < 5); i++) { for (int j = 0; (j < objState.Length); j++) { objState[j] = (i + offset); } StimulusEvent e = new StimulusEvent(utopiaClient.getTimeStamp(), objIDs, objState); Console.WriteLine("Sending: " + e.ToString() + " -> server"); try { utopiaClient.sendMessage(e); } catch (IOException ex) { Console.WriteLine(ex); } System.Threading.Thread.Sleep(1000); } { // PREDICTEDTARGETPROB PredictedTargetProb e = new PredictedTargetProb(utopiaClient.getTimeStamp(), 1, ((float)(0.99))); Console.WriteLine("Sending: " + e.ToString() + " -> server"); utopiaClient.sendMessage(e); System.Threading.Thread.Sleep(1000); } { // PREDICTEDTARGETDIST PredictedTargetDist e = new PredictedTargetDist(utopiaClient.getTimeStamp(), new int[] { 1, 2, 3 }, new float[] { .1f, .2f, .3f }); Console.WriteLine("Sending: " + e.ToString() + " -> server"); utopiaClient.sendMessage(e); System.Threading.Thread.Sleep(1000); } { // HEARTBEAT V.2.0 Heartbeat e = new Heartbeat(utopiaClient.getTimeStamp(), "TestMessage"); Console.WriteLine("Sending: " + e.ToString() + " -> server"); utopiaClient.sendMessage(e); System.Threading.Thread.Sleep(1000); } // LOG { Log e = new Log(utopiaClient.getTimeStamp(), "ClientTest"); Console.WriteLine("Sending: " + e.ToString() + " -> server"); utopiaClient.sendMessage(e); System.Threading.Thread.Sleep(1000); } { // MODECHANGE ModeChange e = new ModeChange(utopiaClient.getTimeStamp(), "ClientTest"); Console.WriteLine("Sending: " + e.ToString() + " -> server"); utopiaClient.sendMessage(e); System.Threading.Thread.Sleep(1000); } { // RESET Reset e = new Reset(utopiaClient.getTimeStamp()); Console.WriteLine("Sending: " + e.ToString() + " -> server"); utopiaClient.sendMessage(e); System.Threading.Thread.Sleep(1000); } { // NEWTARGET NewTarget e = new NewTarget(utopiaClient.getTimeStamp()); Console.WriteLine("Sending: " + e.ToString() + " -> server"); utopiaClient.sendMessage(e); System.Threading.Thread.Sleep(1000); } }
protected virtual void RaiseHeartbeat(TimeEventArgs args) { Heartbeat?.Invoke(this, args); }
public UtopiaMessage decodePayload() { // Decode the payload UtopiaMessage evt = null; if ((this.msgID == StimulusEvent.MSGID)) { if ((VERBOSITY > 2)) { System.Console.WriteLine("Trying to read " + StimulusEvent.MSGNAME + " message"); } evt = StimulusEvent.deserialize(this.msgbuffer); } else if ((this.msgID == PredictedTargetProb.MSGID)) { if ((VERBOSITY > 2)) { System.Console.WriteLine("Trying to read " + PredictedTargetProb.MSGNAME + " message"); } evt = PredictedTargetProb.deserialize(this.msgbuffer); } else if ((this.msgID == ModeChange.MSGID)) { if ((VERBOSITY > 2)) { System.Console.WriteLine("Trying to read " + ModeChange.MSGNAME + " message"); } evt = ModeChange.deserialize(this.msgbuffer); } else if ((this.msgID == Reset.MSGID)) { if ((VERBOSITY > 2)) { System.Console.WriteLine("Trying to read " + Reset.MSGNAME + " message"); } evt = Reset.deserialize(this.msgbuffer); } else if ((this.msgID == NewTarget.MSGID)) { if ((VERBOSITY > 2)) { System.Console.WriteLine("Trying to read " + NewTarget.MSGNAME + " message"); } evt = NewTarget.deserialize(this.msgbuffer); } else if ((this.msgID == Heartbeat.MSGID)) { if ((VERBOSITY > 2)) { System.Console.WriteLine("Trying to read " + Heartbeat.MSGNAME + " message"); } evt = Heartbeat.deserialize(this.msgbuffer); } else { throw new ClientException("Unsupported Message type: " + this.msgID); } if ((VERBOSITY > 1)) { System.Console.WriteLine("Got message: " + evt.ToString()); } return(evt); }
/// <summary> /// Sets up the heartbeat to be executed during the application's idle state and /// aclls Application.Run(). /// </summary> /// <param name="mainLoop">Heartbeat update/render loop</param> public static void Run(Heartbeat mainLoop) { Application.Idle += new EventHandler(new IdleHandler(mainLoop).OnIdle); Application.Run(); }
private void RaiseHeartbeat() { Heartbeat?.Invoke(); }
/// <summary> /// Update the progress of each task /// Checks if all the task sent by heartbeat are supposed to be calculated by this slave /// </summary> private IEnumerable <MessageContainer> UpdateTasks(IPersistenceManager pm, Heartbeat heartbeat, bool isAllowedToCalculate) { var taskDao = pm.TaskDao; var assignedResourceDao = pm.AssignedResourceDao; var actions = new List <MessageContainer>(); if (heartbeat.JobProgress == null || !heartbeat.JobProgress.Any()) { return(actions); } if (!isAllowedToCalculate && heartbeat.JobProgress.Count != 0) { actions.Add(new MessageContainer(MessageContainer.MessageType.PauseAll)); } else { // select all tasks and statelogs with one query var taskIds = heartbeat.JobProgress.Select(x => x.Key).ToList(); var taskInfos = pm.UseTransaction(() => (from task in taskDao.GetAll() where taskIds.Contains(task.TaskId) let lastStateLog = task.StateLogs.OrderByDescending(x => x.DateTime).FirstOrDefault() select new { TaskId = task.TaskId, Command = task.Command, SlaveId = lastStateLog != null ? lastStateLog.SlaveId : default(Guid) }).ToList() ); // process the jobProgresses foreach (var jobProgress in heartbeat.JobProgress) { var progress = jobProgress; var curTask = taskInfos.SingleOrDefault(x => x.TaskId == progress.Key); if (curTask == null) { actions.Add(new MessageContainer(MessageContainer.MessageType.AbortTask, progress.Key)); LogFactory.GetLogger(this.GetType().Namespace).Log("Task on slave " + heartbeat.SlaveId + " does not exist in DB: " + jobProgress.Key); } else { var slaveId = curTask.SlaveId; if (slaveId == Guid.Empty || slaveId != heartbeat.SlaveId) { // assigned slave does not match heartbeat actions.Add(new MessageContainer(MessageContainer.MessageType.AbortTask, curTask.TaskId)); LogFactory.GetLogger(this.GetType().Namespace).Log("The slave " + heartbeat.SlaveId + " is not supposed to calculate task: " + curTask.TaskId); } else if (!assignedResourceDao.TaskIsAllowedToBeCalculatedBySlave(curTask.TaskId, heartbeat.SlaveId)) { // assigned resources ids of task do not match with slaveId (and parent resourceGroupIds); this might happen when slave is moved to different group actions.Add(new MessageContainer(MessageContainer.MessageType.PauseTask, curTask.TaskId)); } else { // update task execution time pm.UseTransaction(() => { taskDao.UpdateExecutionTime(curTask.TaskId, progress.Value.TotalMilliseconds); }); switch (curTask.Command) { case DA.Command.Stop: actions.Add(new MessageContainer(MessageContainer.MessageType.StopTask, curTask.TaskId)); break; case DA.Command.Pause: actions.Add(new MessageContainer(MessageContainer.MessageType.PauseTask, curTask.TaskId)); break; case DA.Command.Abort: actions.Add(new MessageContainer(MessageContainer.MessageType.AbortTask, curTask.TaskId)); break; } } } } } return(actions); }
static MapDat() { if (!Heartbeat.ClassiCube()) //if using mc.net { Mapping[50] = (byte)Block.Air; // torch Mapping[51] = (byte)Block.Lava; // fire Mapping[52] = (byte)Block.Glass; // spawner Mapping[53] = (byte)Block.Stair; // wood stairs Mapping[54] = (byte)Block.Wood; // chest Mapping[55] = (byte)Block.Air; // redstone wire Mapping[56] = (byte)Block.IronOre; // diamond ore Mapping[57] = (byte)Block.Aqua; // diamond block Mapping[58] = (byte)Block.Log; // workbench Mapping[59] = (byte)Block.Leaves; // crops Mapping[60] = (byte)Block.Dirt; // soil Mapping[61] = (byte)Block.Stone; // furnace Mapping[62] = (byte)Block.Stone; // burning furnance Mapping[63] = (byte)Block.Air; // sign post Mapping[64] = (byte)Block.Air; // wooden door Mapping[65] = (byte)Block.Air; // ladder } else //classicube { Mapping[50] = (byte)Block.CobbleSlab; // torch Mapping[51] = (byte)Block.Rope; // fire Mapping[52] = (byte)Block.Sandstone; // spawner Mapping[53] = (byte)Block.Snow; // wood stairs Mapping[54] = (byte)Block.Fire; // chest Mapping[55] = (byte)Block.LightPink; // redstone wire Mapping[56] = (byte)Block.DarkGreen; // diamond ore Mapping[57] = (byte)Block.Brown; // diamond block Mapping[58] = (byte)Block.DarkBlue; // workbench Mapping[59] = (byte)Block.Turquoise; // crops Mapping[60] = (byte)Block.Ice; // soil Mapping[61] = (byte)Block.Tile; // furnace Mapping[62] = (byte)Block.Magma; // burning furnance Mapping[63] = (byte)Block.Pillar; // sign post Mapping[64] = (byte)Block.Crate; // wooden door Mapping[65] = (byte)Block.StoneBrick; // ladder } Mapping[66] = (byte)Block.Air; // rails Mapping[67] = (byte)Block.Stair; // cobblestone stairs Mapping[68] = (byte)Block.Air; // wall sign Mapping[69] = (byte)Block.Air; // lever Mapping[70] = (byte)Block.Air; // pressure plate Mapping[71] = (byte)Block.Air; // iron door Mapping[72] = (byte)Block.Air; // wooden pressure plate Mapping[73] = (byte)Block.IronOre; // redstone ore Mapping[74] = (byte)Block.IronOre; // glowing redstone ore Mapping[75] = (byte)Block.Air; // redstone torch (off) Mapping[76] = (byte)Block.Air; // redstone torch (on) Mapping[77] = (byte)Block.Air; // stone button Mapping[78] = (byte)Block.Air; // snow Mapping[79] = (byte)Block.Glass; // ice Mapping[80] = (byte)Block.White; // snow block Mapping[81] = (byte)Block.Leaves; // cactus Mapping[82] = (byte)Block.Gray; // clay Mapping[83] = (byte)Block.Leaves; // reed Mapping[84] = (byte)Block.Log; // jukebox Mapping[85] = (byte)Block.Wood; // fence Mapping[86] = (byte)Block.Orange; // pumpkin Mapping[87] = (byte)Block.Dirt; // netherstone Mapping[88] = (byte)Block.Gravel; // slow sand Mapping[89] = (byte)Block.Sand; // lightstone Mapping[90] = (byte)Block.Violet; // portal Mapping[91] = (byte)Block.Orange; // jack-o-lantern // all others default to 0/air }
private void ReadMessages(Uri heartBeatUrl, Uri configUrl) { if (this.stopEvent.WaitOne(0)) { return; } #if DEBUG_RETRY ThreadPool.QueueUserWorkItem(o => { Thread.Sleep(4000); CleanupRequests(); }); if (this.currentRetryCount > 0) { throw new IOException(); } #endif this.AbortRequests(); this.request = this.requestFactory.GetWebRequest(configUrl, configUrl.GetHashCode().ToString()); this.response = this.request.GetResponse(); // the url is supposed to send data indefinitely // the only way out of here is either calling Stop() or failing by an exception // (somehow stream.Dispose() hangs, so we'll not use the 'using' construct) var stream = this.response.GetResponseStream(); var reader = new StreamReader(stream, Encoding.UTF8, false); // TODO make the 10 seconds configurable (it if makes sense) using (this.heartbeat = new Heartbeat(new HeartbeatSettings { Uri = this.heartbeatUri ?? heartBeatUrl, Timeout = this.ConnectionTimeout, Interval = this.heartbeatInterval, IsEnabled = this.isHeartbeatEnabled, AbortAction = this.AbortRequests, Credentials = this.Credentials })) { string line; var emptyCounter = 0; var messageBuilder = new StringBuilder(); while ((line = reader.ReadLine()) != null) { if (this.stopEvent.WaitOne(0)) { return; } // we're successfully reading the stream, so reset the retry counter this.currentRetryCount = 0; if (line.Length == 0) { emptyCounter++; // messages are separated by 3 empty lines if (emptyCounter == 3) { this.Trigger(messageBuilder.ToString()); messageBuilder.Length = 0; emptyCounter = 0; } } else { emptyCounter = 0; messageBuilder.Append(line); } } } if (log.IsErrorEnabled) { log.Error("The infinite loop just finished, probably the server closed the connection without errors. (?)"); } throw new IOException("Remote host closed the streaming connection"); }
private bool Equals(Heartbeat other) { return(Equals(From, other.From)); }
protected virtual void OnSendingResponse(PersistentResponse response) { Heartbeat.MarkConnection(this); }
/// <summary> /// Update message handler /// </summary> /// <param name="eventType">Value of "event-type" in the JSON body</param> /// <param name="body">full JSON message body</param> protected void ProcessEventType(string eventType, JObject body) { StreamStatus status; switch (eventType) { case "SwitchScenes": SceneChanged?.Invoke(this, (string)body["scene-name"]); break; case "ScenesChanged": SceneListChanged?.Invoke(this, EventArgs.Empty); break; case "SourceOrderChanged": SourceOrderChanged?.Invoke(this, (string)body["scene-name"]); break; case "SceneItemAdded": SceneItemAdded?.Invoke(this, (string)body["scene-name"], (string)body["item-name"]); break; case "SceneItemRemoved": SceneItemRemoved?.Invoke(this, (string)body["scene-name"], (string)body["item-name"]); break; case "SceneItemVisibilityChanged": SceneItemVisibilityChanged?.Invoke(this, (string)body["scene-name"], (string)body["item-name"], (bool)body["item-visible"]); break; case "SceneItemLockChanged": SceneItemLockChanged?.Invoke(this, (string)body["scene-name"], (string)body["item-name"], (int)body["item-id"], (bool)body["item-locked"]); break; case "SceneCollectionChanged": SceneCollectionChanged?.Invoke(this, EventArgs.Empty); break; case "SceneCollectionListChanged": SceneCollectionListChanged?.Invoke(this, EventArgs.Empty); break; case "SwitchTransition": TransitionChanged?.Invoke(this, (string)body["transition-name"]); break; case "TransitionDurationChanged": TransitionDurationChanged?.Invoke(this, (int)body["new-duration"]); break; case "TransitionListChanged": TransitionListChanged?.Invoke(this, EventArgs.Empty); break; case "TransitionBegin": TransitionBegin?.Invoke(this, (string)body["name"], (string)body["type"], (int)body["duration"], (string)body["from-scene"], (string)body["to-scene"]); break; case "TransitionEnd": TransitionEnd?.Invoke(this, (string)body["name"], (string)body["type"], (int)body["duration"], (string)body["to-scene"]); break; case "TransitionVideoEnd": TransitionVideoEnd?.Invoke(this, (string)body["name"], (string)body["type"], (int)body["duration"], (string)body["from-scene"], (string)body["to-scene"]); break; case "ProfileChanged": ProfileChanged?.Invoke(this, EventArgs.Empty); break; case "ProfileListChanged": ProfileListChanged?.Invoke(this, EventArgs.Empty); break; case "StreamStarting": StreamingStateChanged?.Invoke(this, OutputState.Starting); break; case "StreamStarted": StreamingStateChanged?.Invoke(this, OutputState.Started); break; case "StreamStopping": StreamingStateChanged?.Invoke(this, OutputState.Stopping); break; case "StreamStopped": StreamingStateChanged?.Invoke(this, OutputState.Stopped); break; case "RecordingStarting": RecordingStateChanged?.Invoke(this, OutputState.Starting); break; case "RecordingStarted": RecordingStateChanged?.Invoke(this, OutputState.Started); break; case "RecordingStopping": RecordingStateChanged?.Invoke(this, OutputState.Stopping); break; case "RecordingStopped": RecordingStateChanged?.Invoke(this, OutputState.Stopped); break; case "RecordingPaused": RecordingPaused?.Invoke(this, EventArgs.Empty); break; case "RecordingResumed": RecordingResumed?.Invoke(this, EventArgs.Empty); break; case "StreamStatus": if (StreamStatus != null) { status = new StreamStatus(body); StreamStatus(this, status); } break; case "PreviewSceneChanged": PreviewSceneChanged?.Invoke(this, (string)body["scene-name"]); break; case "StudioModeSwitched": StudioModeSwitched?.Invoke(this, (bool)body["new-state"]); break; case "ReplayStarting": ReplayBufferStateChanged?.Invoke(this, OutputState.Starting); break; case "ReplayStarted": ReplayBufferStateChanged?.Invoke(this, OutputState.Started); break; case "ReplayStopping": ReplayBufferStateChanged?.Invoke(this, OutputState.Stopping); break; case "ReplayStopped": ReplayBufferStateChanged?.Invoke(this, OutputState.Stopped); break; case "Exiting": OBSExit?.Invoke(this, EventArgs.Empty); break; case "Heartbeat": Heartbeat?.Invoke(this, new Heartbeat(body)); break; case "SceneItemDeselected": SceneItemDeselected?.Invoke(this, (string)body["scene-name"], (string)body["item-name"], (string)body["item-id"]); break; case "SceneItemSelected": SceneItemSelected?.Invoke(this, (string)body["scene-name"], (string)body["item-name"], (string)body["item-id"]); break; case "SceneItemTransformChanged": SceneItemTransformChanged?.Invoke(this, new SceneItemTransformInfo(body)); break; case "SourceAudioMixersChanged": SourceAudioMixersChanged?.Invoke(this, new AudioMixersChangedInfo(body)); break; case "SourceAudioSyncOffsetChanged": SourceAudioSyncOffsetChanged?.Invoke(this, (string)body["sourceName"], (int)body["syncOffset"]); break; case "SourceCreated": SourceCreated?.Invoke(this, new SourceSettings(body)); break; case "SourceDestroyed": SourceDestroyed?.Invoke(this, (string)body["sourceName"], (string)body["sourceType"], (string)body["sourceKind"]); break; case "SourceRenamed": SourceRenamed?.Invoke(this, (string)body["newName"], (string)body["previousName"]); break; case "SourceMuteStateChanged": SourceMuteStateChanged?.Invoke(this, (string)body["sourceName"], (bool)body["muted"]); break; case "SourceVolumeChanged": SourceVolumeChanged?.Invoke(this, (string)body["sourceName"], (float)body["volume"]); break; case "SourceFilterAdded": SourceFilterAdded?.Invoke(this, (string)body["sourceName"], (string)body["filterName"], (string)body["filterType"], (JObject)body["filterSettings"]); break; case "SourceFilterRemoved": SourceFilterRemoved?.Invoke(this, (string)body["sourceName"], (string)body["filterName"]); break; case "SourceFiltersReordered": if (SourceFiltersReordered != null) { List <FilterReorderItem> filters = new List <FilterReorderItem>(); JsonConvert.PopulateObject(body["filters"].ToString(), filters); SourceFiltersReordered?.Invoke(this, (string)body["sourceName"], filters); } break; case "SourceFilterVisibilityChanged": SourceFilterVisibilityChanged?.Invoke(this, (string)body["sourceName"], (string)body["filterName"], (bool)body["filterEnabled"]); break; case "BroadcastCustomMessage": BroadcastCustomMessageReceived?.Invoke(this, (string)body["realm"], (JObject)body["data"]); break; default: var message = $"Unsupported Event: {eventType}\n{body}"; Console.WriteLine(message); Debug.WriteLine(message); break; } }
private void Awake() { if (this.player == null) { Debug.LogError("Attach the Player GameObject to the Metagame component."); this.enabled = false; return; } if (this.playerSpawn == null) { playerSpawnPosition_ = this.player.transform.position; playerSpawnRotation_ = this.player.transform.rotation; } else { playerSpawnPosition_ = this.playerSpawn.position; playerSpawnRotation_ = this.playerSpawn.rotation; } if (this.enemies == null) { Debug.LogWarning("Attach a GameObject containing enemies to the Metagame component."); } if (this.items == null) { Debug.LogWarning("Attach a GameObject containing items to the Metagame component."); } heartbeat_ = this.player.GetComponent<Heartbeat>(); heartbeat_.SetMetagame(this); // Load the Blip object used for displaying pings on the radar. blip_ = Resources.Load("Blip") as GameObject; if (blip_ == null) { Debug.LogWarning("Couldn't load the Blip resource."); } }
void HeartbeatRoutine(object a_worker) { Worker worker = (Worker)a_worker; ProtocolType protocol = worker.m_socket.ProtocolType; IPEndPoint dest; if (protocol == ProtocolType.Udp) { dest = m_subServerAddr_udp; worker.m_poller.Start(worker.m_socket); } else { Debug.Assert(protocol == ProtocolType.Tcp); dest = m_subServerAddr_tcp; } Heartbeat heartbeat = new Heartbeat(GetName(worker.m_socket)); Message ping = new Message(); int pingPongCtx = 0; ping.m_contextSeq = 1; ping.m_contextID = pingPongCtx; string errComment = ""; while (m_run) { heartbeat.WaitForInterval(errComment); ping.m_pingTime = System.Environment.TickCount; bool succeedPing = false; switch (protocol) { case ProtocolType.Tcp: if (worker.m_poller.IsRegstered(worker.m_socket)) succeedPing = worker.m_poller.Send(worker.m_socket, ping, true); else { if (ping.m_contextSeq > 1) { ping.m_contextSeq = 1; worker.m_socket.Close(); worker.m_socket = Function.CreateSocket(ProtocolType.Tcp, null, false); } succeedPing = worker.m_poller.ConnectAndSend(worker.m_socket, dest, ping); } break; case ProtocolType.Udp: succeedPing = worker.m_poller.SendTo(worker.m_socket, dest, ping, true); break; default: Debug.Assert(false); break; } if (succeedPing == false) { errComment = "failed request."; heartbeat.Timeout(); continue; } Message pong; Socket sock; IPEndPoint sender; bool isTimeout = ! worker.m_poller.WaitForMessage(Config.Response_Timeout_Ms, out pong, out sock, out sender); if (isTimeout) { errComment = "response timeout."; heartbeat.Timeout(); continue; } if (pong.m_contextID != pingPongCtx) { heartbeat.Timeout(); errComment = "wrong message."; Config.OnErrorDelegate("잘못된 메시지를 수신 : " + pong.ToString()); continue; } heartbeat.Reset(); if (ping.AddressIsEmpty()) { ping.m_address = pong.m_address; ping.m_port = pong.m_port; } ++ping.m_contextSeq; } }
public Task UpdateNodeAsync(Heartbeat model) { return(_heartbeatRepository.UpdateAsync(model)); }
private void AbortRequests() { if (this.request != null) { try { this.request.Abort(); } catch { } } if (this.response != null) { try { ((IDisposable)this.response).Dispose(); } catch { } } if (this.heartbeat != null) { try { ((IDisposable)this.heartbeat).Dispose(); } catch { } } this.request = null; this.response = null; this.heartbeat = null; }
public override void Process() { if (GameManager.Instance.World == null) { SendOutput("The world isn't loaded"); return; } if (Params.Count == 0) { SendOutput(GetHelp()); return; } switch (Params[0]) { case "save": //todo: save current settings to system.xml file break; case "on": if (Heartbeat.IsAlive) { SendOutput("Heart is already beating"); return; } Heartbeat.IsAlive = true; Heartbeat.Start(); SendOutput("Heatbeat started"); break; case "off": Heartbeat.IsAlive = false; SendOutput("Heatbeat stopped"); break; case "bpm": if (Params.Count < 2) { SendOutput($"Current beats per minute is {Heartbeat.Bpm}"); return; } if (!int.TryParse(Params[1], out var bpm)) { SendOutput($"Unable to parse bpm from: {Params[1]}"); return; } if (bpm > 300) { SendOutput($"Woah, {bpm} is a bit high, are you trying to give the server a heartattack!? Max is 300"); return; } if (bpm <= 0) { SendOutput("Check your pulse, you might be dead! Bpm must be greater than 0"); return; } Heartbeat.Bpm = bpm; SendOutput($"Bpm now set to {bpm}"); break; case "state": case "toggle": case "disable": case "enable": { if (Params.Count != 2) { SendOutput("Select an event neuron to view/alter the state, * for all"); SendOutput(string.Join(",", Brain.Synapses.Select(s => s.Name).ToArray())); return; } if (Params[1] == "*") { foreach (var s in Brain.Synapses) { ProcessSynapseState(s); } return; } var synapse = Brain.GetSynapse(Params[1]); ProcessSynapseState(synapse); return; } case "deadisdead": ConfigDeadIsDead(); return; case "pingkicker": ConfigPingKicker(); return; case "tracker": ConfigTracker(); return; case "spawnmutator": ConfigSpawnMutator(); return; case "spawnmanager": ConfigSpawnManager(); return; case "logcache": ConfigLogCache(); return; default: SendOutput($"Unknown neuron name {Params[0]}"); return; } }
/// <summary> /// Call the method and wait for it to complete or the max time. /// </summary> /// <param name="timeout"></param> /// <param name="enumerator"></param> /// <returns></returns> protected bool CallAndWait(int timeout, Heartbeat enumerator) { bool RetVal = false; if (timeout == 0) { enumerator(); RetVal = true; } else { //The action to fire FireEvent wrappedAction = delegate(Heartbeat en) { en(); RetVal = true; }; //Async the action (yeah, this is bad, but otherwise we can't abort afaik) IAsyncResult result = wrappedAction.BeginInvoke(enumerator, null, null); if (((timeout != 0) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted)) { return false; } else { wrappedAction.EndInvoke(result); } } //Return what we got return RetVal; }
private void AbortRequests() { if (this.request != null) { try { this.request.Abort(); } catch(Exception e){log.Error(e);} } if (this.response != null) { try { ((IDisposable)this.response).Dispose(); } catch(Exception e){log.Error(e);} } if (this.heartbeat != null) { try { ((IDisposable)this.heartbeat).Dispose(); } catch(Exception e){log.Error(e);} } this.request = null; this.response = null; this.heartbeat = null; }
private void reloadHeartbeatInterval() { _cdsInfo.cdsBackendSetting.HeartbeatIntervalInSec = getHeartbeatIntervalInSec(); Heartbeat.UpdateHBInterval(_cdsInfo.cdsBackendSetting.HeartbeatIntervalInSec); }
private void OnMessageReceived(object sender, MessageEventArgs e) { Message message = e.Message; if (this.MessageIn != null) { this.MessageIn(this, new MessageEventArgs(message)); } switch (message.Type) { case 1000: if (this.Tick != null) { this.Tick(this, new TickEventArgs(((MsgTick)message).Data)); } break; case 1001: if (this.Tick != null) { this.Tick(this, new TickEventArgs((Tick)((MsgLevel2)message).Data)); } break; case 1101: if (this.Report != null) { this.Report(this, new ExecutionReportEventArgs(((MsgReport)message).Data)); } break; case 1102: if (this.OrderCancelReject != null) { this.OrderCancelReject(this, new OrderCancelRejectEventArgs(((MsgOrderCancelReject)message).Data)); } break; case 2001: if (this.BrokerInfo != null) { this.BrokerInfo(this, new BrokerInfoEventArgs(((MsgBrokerInfo)message).Data)); } break; case 2: LogonStatus data1 = ((MsgLogonStatus)message).Data; if (data1.IsLoggedIn) { this.EmitLoggedIn(data1.Text); break; } else { this.EmitLoggedOut(data1.Text); break; } case 3: Heartbeat data2 = ((MsgHeartbeat)message).Data; if (this.Heartbeat != null) { this.Heartbeat(this, new HeartbeatEventArgs(data2)); } break; case 12: if (this.ProviderError != null) { this.ProviderError(this, new ProviderErrorEventArgs(((MsgProviderError)message).Data)); } break; case 13: if (this.SubscriptionStatus != null) { this.SubscriptionStatus(this, new SubscriptionStatusEventArgs(((MsgSubscriptionStatus)message).Data)); } break; } }
public void HandleHeartbeat(Heartbeat heartbeat) { Heartbeat = heartbeat; Heartbeats.Add(heartbeat); ChartModel.InvalidatePlot(true); }
public void SendHearbeat(Heartbeat heartbeat) { this.SendMessage(new MsgHeartbeat(heartbeat)); }
public void SendHearbeat(Heartbeat heartbeat) { this.SendMessage(new MsgHeartbeat(heartbeat)); }
private void ReadMessages(Uri heartBeatUrl, Uri configUrl) { if (this.stopEvent.WaitOne(0)) return; #if DEBUG_RETRY ThreadPool.QueueUserWorkItem(o => { Thread.Sleep(4000); CleanupRequests(); }); if (this.currentRetryCount > 0) throw new IOException(); #endif this.AbortRequests(); this.request = this.requestFactory.GetWebRequest(configUrl, configUrl.GetHashCode().ToString()); this.response = this.request.GetResponse(); // the url is supposed to send data indefinitely // the only way out of here is either calling Stop() or failing by an exception // (somehow stream.Dispose() hangs, so we'll not use the 'using' construct) var stream = this.response.GetResponseStream(); var reader = new StreamReader(stream, Encoding.UTF8, false); // TODO make the 10 seconds configurable (it if makes sense) using (this.heartbeat = new Heartbeat(heartBeatUrl, this.ConnectionTimeout, 10 * 1000, this.AbortRequests, this.Credentials)) { string line; var emptyCounter = 0; var messageBuilder = new StringBuilder(); while ((line = reader.ReadLine()) != null) { if (this.stopEvent.WaitOne(0)) return; // we're successfully reading the stream, so reset the retry counter this.currentRetryCount = 0; if (line.Length == 0) { emptyCounter++; // messages are separated by 3 empty lines if (emptyCounter == 3) { this.Trigger(messageBuilder.ToString()); messageBuilder.Length = 0; emptyCounter = 0; } } else { emptyCounter = 0; messageBuilder.Append(line); } } } if (log.IsErrorEnabled) log.Error("The infinite loop just finished, probably the server closed the connection without errors. (?)"); throw new IOException("Remote host closed the streaming connection"); }
public void Heartbeat_Should_Return_Url() { var req = new Heartbeat(); var res = service.Get(req); res.Should().BeOfType<Heartbeat>().Which.Url.Should().Be("http://localhost"); }