public void Run() { //_talon.SetControlMode(TalonSRX.ControlMode.kVoltage); _talon.ConfigSelectedFeedbackSensor(FeedbackDevice.CTRE_MagEncoder_Relative, 0); _talon.SetSensorPhase(false); _talon.Config_kP(0, 0.80f); _talon.Config_kI(0, 0f); _talon.Config_kD(0, 0f); _talon.Config_kF(0, 0.09724488664269079041176191004297f); _talon.SelectProfileSlot(0, 0); _talon.ConfigNominalOutputForward(0f, 50); _talon.ConfigNominalOutputReverse(0f, 50); _talon.ConfigPeakOutputForward(+1.0f, 50); _talon.ConfigPeakOutputReverse(-1.0f, 50); _talon.ChangeMotionControlFramePeriod(5); _talon.ConfigMotionProfileTrajectoryPeriod(0, 50); /* loop forever */ while (true) { _talon.GetMotionProfileStatus(_motionProfileStatus); Drive(); Watchdog.Feed(); Instrument(); Thread.Sleep(5); } }
// private void DeregisterCaps(UUID agentID, Caps caps) // { // string capUrl; // // if (m_capsDict.TryGetValue(agentID, out capUrl)) // { // MainServer.Instance.RemoveHTTPHandler("", capUrl); // m_capsDict.Remove(agentID); // } // } private static void DoInventoryRequests() { APollRequest poolreq; while (true) { if (!m_queue.TryTake(out poolreq, 4500) || poolreq == null || poolreq.thepoll == null) { Watchdog.UpdateThread(); continue; } Watchdog.UpdateThread(); try { APollRequest req = poolreq; req.thepoll.Process(req); } catch (Exception e) { m_log.ErrorFormat( "[INVENTORY]: Failed to process queued inventory request {0} for {1}. Exception {2}", poolreq.reqID, poolreq.presence != null ? poolreq.presence.Name : "unknown", e); } } }
private void CheckRetries() { while (m_running) { Thread.Sleep(100); // let the world move .. back to faster rate Watchdog.UpdateThread(); lock (m_retryRequests) { while (m_retryRequests.Count > 0 && m_running) { m_requests.Enqueue(m_retryRequests.Dequeue()); } } slowCount++; if (slowCount >= 10) { slowCount = 0; lock (m_slowRequests) { while (m_slowRequests.Count > 0 && m_running) { m_requests.Enqueue(m_slowRequests.Dequeue()); } } } } }
public static void Check(string startBlock, Watchdog wd) { if (startBlock.Contains("interface ")) { var interfaceName = CamelCaseCSharpWatchdog.GetPossibleBlockIdentifier("interface", startBlock); if (interfaceName.Length > 2 && !interfaceName.StartsWith("I")) { wd.IncreaseCount((int)ErrorCodes.InterfaceNamingError); // TODO: The line report is inaccurate, as several lines may have passed. // HACK: Assuming the next line and using CheckedLinesOfCode + 1. // if (wd.woff != null) { wd.woff(string.Format("{0}: '{1}' (line {2})", wd.errorCodeStrings[(int)ErrorCodes.InterfaceNamingError], interfaceName, wd.checkedLinesThisFile)); } } } return; }
public void Test() { int count = 0; Watchdog dog = new Watchdog(100d); dog.Bark += delegate { count++; }; dog.Enabled = true; dog.KeepBarking = false; dog.Feed(); dog.Feed(); dog.Feed(); dog.Feed(); Thread.Sleep(200); Assert.AreEqual(1, count); Thread.Sleep(120); dog.Enabled = false; Assert.IsFalse(dog.Enabled); Assert.IsFalse(dog.KeepBarking); // TODO: 100% coverage in this way? dog.Feed(); Assert.AreEqual(1, count); }
public static void Check(string statement, Watchdog wd) { // Trim leading spaces before check. // Ignore empty statements, e.g. inline 'new' statements. // Ignore comparison operators, as they most probably are part of a 'for' loop. // Ignore single closing braces, most probably closing inline lambdas. // Ignore 'get' and 'set': Properties are OK in a single line. // if (wd.checkedLinesThisFile > 1 && statement.Length > 0 && !statement.TrimStart(char.Parse(" "), char.Parse("\r"), char.Parse("\t")).StartsWith("\n") && !statement.Contains("<") && !statement.Contains(">") && statement != ")" && !statement.Contains("get") && !statement.Contains("set")) { wd.IncreaseCount((int)ErrorCodes.MultipleStatementError); if (wd.woff != null) { wd.woff(string.Format("{0} (line {1})", wd.errorCodeStrings[(int)ErrorCodes.MultipleStatementError], wd.checkedLinesThisFile + 1)); } } return; }
public void RemoveRegion(Scene s) { if (!m_Enabled) { return; } Scene.EventManager.OnRegisterCaps -= RegisterCaps; StatsManager.DeregisterStat(s_processedRequestsStat); StatsManager.DeregisterStat(s_queuedRequestsStat); if (ProcessQueuedRequestsAsync) { if (m_workerThreads != null) { foreach (Thread t in m_workerThreads) { Watchdog.AbortThread(t.ManagedThreadId); } m_workerThreads = null; } } Scene = null; }
public static void Check(string statement, Watchdog wd) { // Check for closing brace, indicating the statement is complete. // // TODO: Use central reserved words list. // if ((statement.Trim().StartsWith("if") || statement.Trim().StartsWith("else") || statement.Trim().StartsWith("while") || statement.Trim().StartsWith("foreach") || statement.Trim().StartsWith("for")) && statement.Contains(")")) { wd.IncreaseCount((int)ErrorCodes.MissingBracesError); // TODO: The line report is inaccurate, as several lines may have passed. // HACK: Assuming the next line and using CheckedLinesOfCode + 1. // if (wd.woff != null) { wd.woff(string.Format("{0} (line {1})", wd.errorCodeStrings[(int)ErrorCodes.MissingBracesError], wd.checkedLinesThisFile + 1)); } } return; }
private static void DoAssetRequests() { try { while (m_NumberScenes > 0) { APollRequest poolreq; if (m_queue.TryTake(out poolreq, 4500)) { if (m_NumberScenes <= 0) { break; } Watchdog.UpdateThread(); if (poolreq.reqID != UUID.Zero) { poolreq.thepoll.Process(poolreq); } poolreq = null; } Watchdog.UpdateThread(); } } catch (ThreadAbortException) { Thread.ResetAbort(); } }
public void Start() { IsRunning = true; if (PerformResponsesAsync) { //startup worker threads for (uint i = 0; i < m_WorkerThreadCount; i++) { m_workerThreads[i] = Watchdog.StartThread( PoolWorkerJob, string.Format("PollServiceWorkerThread{0}:{1}", i, m_server.Port), ThreadPriority.Normal, false, false, null, int.MaxValue); } Watchdog.StartThread( this.CheckLongPollThreads, string.Format("LongPollServiceWatcherThread:{0}", m_server.Port), ThreadPriority.Normal, false, true, null, 1000 * 60 * 10); } }
private static void DoInventoryRequests() { bool running = true; while (running) { try { APollRequest poolreq; if (m_queue.TryTake(out poolreq, 4500)) { Watchdog.UpdateThread(); if (poolreq.thepoll != null) { poolreq.thepoll.Process(poolreq); } poolreq = null; } Watchdog.UpdateThread(); } catch (ThreadAbortException) { Thread.ResetAbort(); running = false; } } }
private static void DoTextureRequests() { APollRequest poolreq; while (m_NumberScenes > 0) { poolreq = null; if (!m_queue.TryTake(out poolreq, 4500) || poolreq == null) { Watchdog.UpdateThread(); continue; } if (m_NumberScenes <= 0) { break; } Watchdog.UpdateThread(); if (poolreq.reqID != UUID.Zero) { poolreq.thepoll.Process(poolreq); } } }
public virtual void HandleThreadsAbort(string module, string[] cmd) { if (cmd.Length != 3) { MainConsole.Instance.Output("Usage: threads abort <thread-id>"); return; } int threadId; if (!int.TryParse(cmd[2], out threadId)) { MainConsole.Instance.Output("ERROR: Thread id must be an integer"); return; } if (Watchdog.AbortThread(threadId)) { MainConsole.Instance.Output("Aborted thread with id {0}", threadId); } else { MainConsole.Instance.Output("ERROR - Thread with id {0} not found in managed threads", threadId); } }
public void RegionLoaded(Scene s) { if (!m_Enabled) { return; } m_InventoryService = m_scene.InventoryService; m_LibraryService = m_scene.LibraryService; // We'll reuse the same handler for all requests. m_webFetchHandler = new WebFetchInvDescHandler(m_InventoryService, m_LibraryService); m_scene.EventManager.OnRegisterCaps += RegisterCaps; if (m_workerThreads == null) { m_workerThreads = new Thread[2]; for (uint i = 0; i < 2; i++) { m_workerThreads[i] = Watchdog.StartThread(DoInventoryRequests, String.Format("InventoryWorkerThread{0}", i), ThreadPriority.Normal, false, true, null, int.MaxValue); } } }
public static void Check(string startBlock, Watchdog wd) { if (startBlock.Contains("(") && startBlock.Contains(")")) { string methodName = CamelCaseCSharpWatchdog.GetPossibleMethodName(startBlock); if (methodName.Length > 2 && char.IsLower(methodName, 0)) { wd.IncreaseCount((int)ErrorCodes.PascalCaseError); // TODO: The line report is inaccurate, as several lines may have passed. // HACK: Assuming the next line and using CheckedLinesOfCode + 1. // if (wd.woff != null) { wd.woff(string.Format("{0}: '{1}' (line {2})", wd.errorCodeStrings[(int)ErrorCodes.PascalCaseError], methodName, wd.checkedLinesThisFile)); } } } return; }
private void CheckLongPollThreads() { // The only purpose of this thread is to check the EQs for events. // If there are events, that thread will be placed in the "ready-to-serve" queue, m_requests. // If there are no events, that thread will be back to its "waiting" queue, m_longPollRequests. // All other types of tasks (Inventory handlers, http-in, etc) don't have the long-poll nature, // so if they aren't ready to be served by a worker thread (no events), they are placed // directly back in the "ready-to-serve" queue by the worker thread. while (IsRunning) { Thread.Sleep(500); Watchdog.UpdateThread(); // List<PollServiceHttpRequest> not_ready = new List<PollServiceHttpRequest>(); if (m_longPollRequests.Count > 0 && IsRunning) { List <PollServiceHttpRequest> ready = m_longPollRequests.FindAll(req => (req.PollServiceArgs.HasEvents(req.RequestID, req.PollServiceArgs.Id) || // there are events in this EQ (Environment.TickCount - req.RequestTime) > req.PollServiceArgs.TimeOutms) // no events, but timeout ); ready.ForEach(req => { m_requests.Enqueue(req); m_longPollRequests.Remove(req); }); } } }
public PollServiceRequestManager(BaseHttpServer pSrv, uint pWorkerThreadCount, int pTimeout) { m_server = pSrv; m_WorkerThreadCount = pWorkerThreadCount; m_workerThreads = new Thread[m_WorkerThreadCount]; m_PollServiceWorkerThreads = new PollServiceWorkerThread[m_WorkerThreadCount]; //startup worker threads for (uint i = 0; i < m_WorkerThreadCount; i++) { m_PollServiceWorkerThreads[i] = new PollServiceWorkerThread(m_server, pTimeout); m_PollServiceWorkerThreads[i].ReQueue += ReQueueEvent; m_workerThreads[i] = Watchdog.StartThread( m_PollServiceWorkerThreads[i].ThreadStart, String.Format("PollServiceWorkerThread{0}", i), ThreadPriority.Normal, false, true, null, int.MaxValue); } Watchdog.StartThread( this.ThreadStart, "PollServiceWatcherThread", ThreadPriority.Normal, false, true, null, 1000 * 60 * 10); }
public async Task WatchdogFailureTestAsync() { var wd = new Watchdog(petTimeout: TimeSpan.FromMilliseconds(100), autoStartOnFirstPet: false); Should.Throw <WatchdogNotStartedException>(() => wd.Cancel()); Should.Throw <WatchdogNotStartedException>(() => wd.Pet(autoReset: false)); wd.Monitor(); wd.IsTriggered.ShouldBe(false); wd.IsCanceled.ShouldBe(false); wd.IsDisposed.ShouldBe(false); wd.IsMonitorStarted.ShouldBe(true); Should.Throw <WatchdogAlreadyStartedException>(() => wd.Monitor()); await 200.TryDelay(CancellationToken.None); wd.IsTriggered.ShouldBe(true); wd.IsCanceled.ShouldBe(false); wd.IsDisposed.ShouldBe(false); wd.IsMonitorStarted.ShouldBe(true); Should.Throw <WatchdogTriggeredException>(() => wd.Monitor()); Should.Throw <WatchdogTriggeredException>(() => wd.Cancel()); wd.AsTask().Result.ShouldBe(true); // Triggered wd.TryDispose(); wd.IsTriggered.ShouldBe(true); wd.IsCanceled.ShouldBe(false); wd.IsDisposed.ShouldBe(true); wd.IsMonitorStarted.ShouldBe(true); Should.Throw <WatchdogDisposedException>(() => wd.Cancel()); Should.Throw <WatchdogDisposedException>(() => wd.Pet(autoReset: false)); Should.Throw <WatchdogDisposedException>(() => wd.Monitor()); Should.Throw <WatchdogDisposedException>(() => throw wd.AsTask().Exception !); }
private static void StartThread() { if (cmdHandlerThread == null) { // Start the thread that will be doing the work cmdHandlerThread = Watchdog.StartThread(CmdHandlerThreadLoop, "AsyncLSLCmdHandlerThread", ThreadPriority.Normal, true); } }
public HttpMessageWriter(IMessageSender messageSender, string baseUrl, OutputPort light, Watchdog[] resetWatchdogsOnSend) { _messageSender = messageSender; _baseUrl = baseUrl; _light = light; _resetWatchdogsOnSend = resetWatchdogsOnSend ?? new Watchdog[] {}; StartThread(); }
private void PoolWorkerJob() { while (IsRunning) { Watchdog.UpdateThread(); WaitPerformResponse(); } }
public void WatchdogCancelAsTaskTest() { var wd = new Watchdog(petTimeout: TimeSpan.FromMilliseconds(100), autoStartOnFirstPet: false); wd.Monitor(); wd.Cancel(); Should.Throw <WatchdogCanceledException>(() => throw wd.AsTask().Exception !); }
/// <inheritdoc /> public void Dispose() { timerCts?.Dispose(); Configuration.Dispose(); Chat.Dispose(); Watchdog.Dispose(); dmbFactory.Dispose(); RepositoryManager.Dispose(); }
/// <inheritdoc /> public Task InstanceRenamed(string newName, CancellationToken cancellationToken) { if (String.IsNullOrWhiteSpace(newName)) { throw new ArgumentNullException(nameof(newName)); } metadata.Name = newName; return(Watchdog.InstanceRenamed(newName, cancellationToken)); }
/// <inheritdoc /> public void Dispose() { timerCts?.Dispose(); compileJobConsumer.Dispose(); Configuration.Dispose(); Chat.Dispose(); Watchdog.Dispose(); RepositoryManager.Dispose(); }
public void WatchdogInitialStateTest() { var wd = new Watchdog(petTimeout: TimeSpan.FromMilliseconds(100), autoStartOnFirstPet: false); wd.IsTriggered.ShouldBe(false); wd.IsCanceled.ShouldBe(false); wd.IsDisposed.ShouldBe(false); wd.IsMonitorStarted.ShouldBe(false); }
public IRCServer(IPAddress listener, int port, Scene baseScene) { m_listener = new TcpListener(listener, port); m_listener.Start(50); Watchdog.StartThread(ListenLoop, "IRCServer", ThreadPriority.Normal, false, true); m_baseScene = baseScene; }
private static void DoTextureRequests() { while (true) { aPollRequest poolreq = m_queue.Dequeue(); Watchdog.UpdateThread(); poolreq.thepoll.Process(poolreq); } }
private void Initialize(CMModel model, CMView view, Scene scene, int channel) { lock (this) { m_estateModule = scene.RequestModuleInterface <IEstateModule>(); Watchdog.StartThread(MainLoop, "Content Management", ThreadPriority.Normal, true); m_state = State.NONE; } }
public void ThreadStart() { while (m_running) { Watchdog.UpdateThread(); ProcessQueuedRequests(); Thread.Sleep(1000); } }
private void DoInventoryRequests() { while (true) { Watchdog.UpdateThread(); WaitProcessQueuedInventoryRequest(); } }
void Drive() { FillBtns(ref _btns); float y = -1 * _gamepad.GetAxis(1); Deadband(ref y); _talon.ProcessMotionProfileBuffer(); /* button handler, if btn5 pressed launch MP, if btn7 pressed, enter percent output mode */ if (_btns[5] && !_btnsLast[5]) { /* disable MP to clear IsLast */ _talon.Set(ControlMode.MotionProfile, 0); Watchdog.Feed(); Thread.Sleep(10); /* buffer new pts in HERO */ TrajectoryPoint point = new TrajectoryPoint(); _talon.ClearMotionProfileHasUnderrun(); _talon.ClearMotionProfileTrajectories(); for (uint i = 0; i < MotionProfile.kNumPoints; ++i) { point.position = (float)MotionProfile.Points[i][0] * kTicksPerRotation; //convert from rotations to sensor units point.velocity = (float)MotionProfile.Points[i][1] * kTicksPerRotation / 600; //convert from RPM to sensor units per 100 ms. point.headingDeg = 0; //not used in this example point.isLastPoint = (i + 1 == MotionProfile.kNumPoints) ? true : false; point.zeroPos = (i == 0) ? true : false; point.profileSlotSelect0 = 0; point.profileSlotSelect1 = 0; //not used in this example point.timeDur = TrajectoryPoint.TrajectoryDuration.TrajectoryDuration_10ms; _talon.PushMotionProfileTrajectory(point); } /* send the first few pts to Talon */ for (int i = 0; i < 5; ++i) { Watchdog.Feed(); Thread.Sleep(10); _talon.ProcessMotionProfileBuffer(); } /*start MP */ _talon.Set(ControlMode.MotionProfile, 1); } else if (_btns[7] && !_btnsLast[7]) { _talon.Set(ControlMode.PercentOutput, 0); } /* if not in motion profile mode, update output percent */ if (_talon.GetControlMode() != ControlMode.MotionProfile) { _talon.Set(ControlMode.PercentOutput, y); } /* copy btns => btnsLast */ System.Array.Copy(_btns, _btnsLast, _btns.Length); }
private void Heartbeat() { uint lastSimulateFrame = 0; while (!_stop) { uint startingFrame = (uint)Environment.TickCount; bool processedCommandsThisIteration = ProcessQueueCommands(); uint uframe = (uint)_frameNum; if (_simulating && (uframe > lastSimulateFrame)) { uint tickCount = (uint)Environment.TickCount; uint ticksSinceLastSimulate = Math.Max(tickCount - _lastSimulate, TIMESTEP); _lastSimulate = (uint)Environment.TickCount; lastSimulateFrame = uframe; if (ticksSinceLastSimulate >= SIMULATE_DELAY_TO_BEGIN_DILATION) { Simulate(DILATED_TIMESTEP_IN_SECONDS, ticksSinceLastSimulate, uframe, true); //m_log.DebugFormat("[PHYSICS]: Dilated simulate {0}", ticksSinceLastSimulate); } else { Simulate(ticksSinceLastSimulate * 0.001f, ticksSinceLastSimulate, uframe, false); } ++_framesSinceLastFpsCalc; if (uframe % UPDATE_WATCHDOG_FRAMES == 0) { Watchdog.UpdateThread(); } if (uframe % CHECK_EXPIRED_KINEMATIC_FRAMES == 0) { this.CheckForExpiredKinematics(); } if (uframe % UPDATE_FPS_FRAMES == 0) { this.UpdateFpsCalc(); //CheckForPhysicsLongFramesAndDebug(); } } _frameTimeAvg.AddValue((uint)Environment.TickCount - startingFrame); ContactDebug.OnFramePassed(); if (_currentCommandQueue.Count == 0) { _timingSignal.Wait(); } _timingSignal.Reset(); } }
public void Stop() { m_running = false; Thread.Sleep(1000); // let the world move foreach (Thread t in m_workerThreads) { Watchdog.AbortThread(t.ManagedThreadId); } // any entry in m_bycontext should have a active request on the other queues // so just delete contents to easy GC foreach (Queue <PollServiceHttpRequest> qu in m_bycontext.Values) { qu.Clear(); } m_bycontext.Clear(); try { foreach (PollServiceHttpRequest req in m_retryRequests) { req.DoHTTPstop(m_server); } } catch { } PollServiceHttpRequest wreq; m_retryRequests.Clear(); lock (m_slowRequests) { while (m_slowRequests.Count > 0) { m_requests.Enqueue(m_slowRequests.Dequeue()); } } while (m_requests.Count() > 0) { try { wreq = m_requests.Dequeue(0); wreq.DoHTTPstop(m_server); } catch { } } m_requests.Clear(); }
public static void Check(string startBlock, Watchdog wd) { if (!startBlock.Contains("class ") && !startBlock.Contains("interface ") && !startBlock.Contains("enum ") && !startBlock.Contains("(") && !startBlock.Contains(")")) { // Assuming it's a property string propertyName = ""; Match propertyNameMatch = Regex.Match(startBlock, @"\s+(\w+)\s*$"); if (propertyNameMatch.Success) { propertyName = propertyNameMatch.Groups[1].Value; Logging.Debug("Property name: " + propertyName); } // TODO: Use central reserved words list. // TODO: Check if any of these aren't already being ruled out by braces etc. checks above // if (propertyName != "if" && propertyName != "else" && propertyName != "while" && propertyName != "foreach" && propertyName != "for" && propertyName != "get" && propertyName != "set" && propertyName != "try" && propertyName != "catch" && propertyName != "delegate" && propertyName != "using" && propertyName != "switch" && propertyName.Length > 2 && char.IsLower(propertyName, 0)) { wd.IncreaseCount((int)ErrorCodes.PascalCaseError); // TODO: The line report is inaccurate, as several lines may have passed. // HACK: Assuming the next line and using CheckedLinesOfCode + 1. // if (wd.woff != null) { wd.woff(string.Format("{0}: '{1}' (line {2})", wd.errorCodeStrings[(int)ErrorCodes.PascalCaseError], propertyName, wd.checkedLinesThisFile)); } } } return; }
private WiFlyGSX GetModule() { using (var initWatchdog = new Watchdog(new TimeSpan(0, 5, 0), () => { Debug.Print("Spent 5 minutes trying to initialize, giving up...."); PowerState.RebootDevice(false, 1000); })) { initWatchdog.Start(); while (null == _module) { _module = SetupModule(); } return _module; } }
public static void Check(string comment, string precedingInput, Watchdog wd) { if (wd.checkedLinesThisFile > 1 && !precedingInput.Contains("\n")) { wd.IncreaseCount((int)ErrorCodes.CommentOnSameLineError); if (wd.woff != null) { wd.woff(string.Format("{0} (line {1})", wd.errorCodeStrings[(int)ErrorCodes.CommentOnSameLineError], wd.checkedLinesThisFile)); } } return; }
public static void Check(string startBlock, Watchdog wd) { if (startBlock.Contains("class ") && startBlock.Contains("public ") && !wd.previousToken.Contains(wd.parsingParameters.startCommentDelimiter + "/") && !wd.previousToken.Contains("</summary>")) { wd.IncreaseCount((int)ErrorCodes.ClassNotDocumentedError); if (wd.woff != null) { wd.woff(string.Format("{0} (line {1})", wd.errorCodeStrings[(int)ErrorCodes.ClassNotDocumentedError], wd.checkedLinesThisFile)); } } return; }
public static void Check(string statement, Watchdog wd) { if (statement.Contains("\t")) { wd.IncreaseCount((int)ErrorCodes.TabError); // TODO: The line report is inaccurate, as several lines may have passed. // HACK: Assuming the next line and using CheckedLinesOfCode + 1. // if (wd.woff != null) { wd.woff(string.Format("{0} (line {1})", wd.errorCodeStrings[(int)ErrorCodes.TabError], wd.checkedLinesThisFile + 1)); } } return; }
public static void Check(string statement, Watchdog wd) { var possibleIdentifier = CamelCaseCSharpWatchdog.GetPossibleIdentifier(statement); // TODO: Use central reserved words list. // if (possibleIdentifier != "" && possibleIdentifier != "if" && possibleIdentifier != "else" && possibleIdentifier != "while" && possibleIdentifier != "foreach" && possibleIdentifier != "for" && !statement.Contains("using") && possibleIdentifier != "get" && possibleIdentifier != "set" && possibleIdentifier != "try" && possibleIdentifier != "catch" && possibleIdentifier != "delegate" && possibleIdentifier != "public" && possibleIdentifier != "switch") { if (statement.Contains("const ") && possibleIdentifier.Length > 2 && char.IsLower(possibleIdentifier, 0)) { wd.IncreaseCount((int)ErrorCodes.PascalCaseError); // TODO: The line report is inaccurate, as several lines may have passed. // HACK: Assuming the next line and using CheckedLinesOfCode + 1. // if (wd.woff != null) { wd.woff(string.Format("{0}: '{1}' (line {2})", wd.errorCodeStrings[(int)ErrorCodes.PascalCaseError], possibleIdentifier, wd.checkedLinesThisFile + 1)); } } } return; }
public static void Check(string startBlock, Watchdog wd) { if (startBlock.Contains("(") && startBlock.Contains(")")) { // Make sure 'public' is before the first brace. // if (startBlock.Split(Char.Parse("("))[0].Contains("public ") && !wd.previousToken.Contains(wd.parsingParameters.startCommentDelimiter + "/") && !wd.previousToken.Contains("</summary>")) { wd.IncreaseCount((int)ErrorCodes.MethodNotDocumentedError); if (wd.woff != null) { wd.woff(string.Format("{0} (line {1})", wd.errorCodeStrings[(int)ErrorCodes.MethodNotDocumentedError], wd.checkedLinesThisFile)); } } } return; }
public static void Check(string comment, string precedingInput, Watchdog wd) { // Also include /// doc comments. // Ignore empty comments. // Ignore comments starting with "--", these are most probably auto-generated decorative lines. // if (!comment.Trim().EndsWith(wd.parsingParameters.startCommentDelimiter) && !(comment.StartsWith(wd.parsingParameters.startCommentDelimiter + " ") || comment.StartsWith(wd.parsingParameters.startCommentDelimiter + "/ ")) && !comment.StartsWith(wd.parsingParameters.startCommentDelimiter + "--")) { wd.IncreaseCount((int)ErrorCodes.CommentNoSpaceError); if (wd.woff != null) { wd.woff(string.Format("{0} (line {1})", wd.errorCodeStrings[(int)ErrorCodes.CommentNoSpaceError], wd.checkedLinesThisFile)); } } return; }
public static Watchdog GetSingleton() { return _singleton ?? (_singleton = new Watchdog()); }
/// <summary> /// Main method runs on startup /// </summary> public static void RealMain() { Debug.EnableGCMessages(true); // START CONFIG var sf800pulseConfig = new PulseConfig() { PulsesPerOunce = PulseConfig.SF800_PULSES_PER_OUNCE, PourStoppedDelay = 250, PulsesPerStoppedExtension = 50, PulsesPerPouring = 250, }; var config = new Config { Connectivity = new ConnectivityConfig { //Wifi = new WifiConfig //{ // Enabled = true, // SSID = "Rightpoint", // Password = "******", // SecurityMode = Toolbox.NETMF.Hardware.WiFlyGSX.AuthMode.MixedWPA1_WPA2 //}, Ethernet = new EthernetConfig { Enabled = true }, BaseUrl = "http://pourcast.labs.rightpoint.com/api/Tap/", HttpLight = Pins.GPIO_PIN_D9 }, Taps = new[] { new TapConfig { Input = Pins.GPIO_PIN_D13, Light = Pins.GPIO_PIN_D11, TapId = "535c61a951aa0405287989ec", PulseConfig = sf800pulseConfig, }, new TapConfig { Input = Pins.GPIO_PIN_D12, Light = Pins.GPIO_PIN_D10, TapId = "537d28db51aa04289027cde5", PulseConfig = sf800pulseConfig, }, }, WatchdogCheckInterval = new TimeSpan(0, 15, 0) }; #if true // a configuration for testing with a local server, buttons, and even the emulator var localButtonConfig = new PulseConfig() { PulsesPerOunce = 0.1, PourStoppedDelay = 1000, PulsesPerStoppedExtension = 1, PulsesPerPouring = 5, }; config = new Config { Connectivity = new ConnectivityConfig { Wifi = new WifiConfig() { Enabled = true, SSID = "XXX", Password = "******", SecurityMode = Toolbox.NETMF.Hardware.WiFlyGSX.AuthMode.MixedWPA1_WPA2, }, BaseUrl = "http://192.168.25.107:23456/api/Tap/", #if true HttpLight = Pins.GPIO_PIN_D9, }, Taps = new[] { new TapConfig { Input = Pins.GPIO_PIN_D13, Light = Pins.GPIO_PIN_D11, TapId = "5396779faa6179467050c33a", PulseConfig = localButtonConfig, }, new TapConfig { Input = Pins.GPIO_PIN_D12, Light = Pins.GPIO_PIN_D10, TapId = "539677a4aa6179467050c33d", PulseConfig = localButtonConfig, }, #else HttpLight = Cpu.Pin.GPIO_Pin6, }, Taps = new[] { new TapConfig { Input = Cpu.Pin.GPIO_Pin2, // emulator up Light = Cpu.Pin.GPIO_Pin1, TapId = "539638b03885a838541b880c", PulseConfig = localButtonConfig, }, new TapConfig { Input = Cpu.Pin.GPIO_Pin4, // emulator down Light = Cpu.Pin.GPIO_Pin3, TapId = "539638bd3885a838541b8810", PulseConfig = localButtonConfig, }, #endif }, WatchdogCheckInterval = new TimeSpan(0, 15, 0) }; #endif // END CONFIG // turn on the tap lights on - they'll turn off as they initialize LightsOn(config.Taps); // turn the HTTP light *off*, it'll go on as it initializes LightOff(config.Connectivity.HttpLight); var sender = BuildMessageSender(config.Connectivity); sender.Initalize(); HttpMessageWriter writer = null; // first watchdog makes sure we send *something* every watchdogCheckInterval. Second reboots us 30s later if the message hasn't been sent yet (ie. if networking dies) // sending *any* message resets both watchdogs var heartbeatWatchdog = new Watchdog(config.WatchdogCheckInterval, () => writer.SendHeartbeatAsync()); var rebootWatchdog = new RebootWatchdog(config.WatchdogCheckInterval + new TimeSpan(0, 0, 30)); writer = new HttpMessageWriter(sender, config.Connectivity.BaseUrl, new OutputPort(config.Connectivity.HttpLight, true), new[] { heartbeatWatchdog, rebootWatchdog }); var sensors = new FlowSensor[config.Taps.Length]; for (var i = 0; i < config.Taps.Length; i++) { var tapConfig = config.Taps[i]; sensors[i] = new FlowSensor( new InterruptPort(tapConfig.Input, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeHigh), new OutputPort(tapConfig.Light, false), writer, tapConfig.TapId, tapConfig.PulseConfig); } heartbeatWatchdog.Start(); rebootWatchdog.Start(); Debug.Print("Starting"); while (true) { Thread.Sleep(Timeout.Infinite); } }
private static bool DoRun(GetOptions options) { Progress progress = null; if (!options.Has("-quiet")) progress = new Progress(options.Has("-verbose")); Watchdog watcher = new Watchdog(options.Has("-verbose")); Error[] errors = null; try { DateTime startTime = DateTime.Now; AnalyzeAssembly analyzer = new AnalyzeAssembly(delegate (string name) { progress.Add(name); watcher.Add(name); }); List<string> excluded = new List<string>(options.Values("-exclude-check")); if (excluded.IndexOf("R1035") < 0) // ValidateArgs2 is disabled by default excluded.Add("R1035"); analyzer.ExcludedChecks = excluded.Except(options.Values("-include-check")); analyzer.ExcludeNames = options.Values("-exclude-name").Except(options.Values("-include-name")); string[] onlyType = options.Values("-only-type"); string[] severities = options.Values("-severity"); Severity severity = (Severity) Enum.Parse(typeof(Severity), severities[severities.Length - 1]); bool ignoreBreaks = options.Has("-ignore-breaking") && !options.Has("-include-breaking"); errors = analyzer.Analyze(options.Operands[0], onlyType, severity, ignoreBreaks); TimeSpan elapsed = DateTime.Now - startTime; string assemblyPath = options.Operands[0]; string outFile = options.Value("-out"); if (options.Has("-xml")) XmlReport.Report(assemblyPath, outFile, errors); else if (options.Has("-html")) HtmlReport.Report(assemblyPath, outFile, errors, analyzer.NumRules, elapsed); else TextReport.Report(assemblyPath, outFile, errors, analyzer.NumRules, elapsed); } finally { if (progress != null) progress.Dispose(); watcher.Dispose(); } int count = errors.Count(x => x.Violation.Severity != Severity.Nitpick); return count == 0; }
private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi) { int now = Environment.TickCount; m_log.ErrorFormat( "[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}", twi.Thread.Name, twi.Thread.ThreadState, now - twi.LastTick, twi.AlarmMethod != null ? string.Format("Data: {0}", twi.AlarmMethod()) : ""); }
private WiFlyGSX SetupModule() { WiFlyGSX workingModule = null; var thread = new Thread(() => { var module = new WiFlyGSX(DebugMode: true); try { module.EnableDHCP(); var isConnected = false; for (var i = 0; i < 3 && !(isConnected = module.JoinNetwork(_ssid, 0, _securityMode, _password)); i++) { Thread.Sleep(1000); } Debug.Print("isConnected: " + isConnected); if (!isConnected) { module.Reboot(); module.Dispose(); return; } for (var i = 0; i < 10 && module.LocalIP == "0.0.0.0"; i++) { Thread.Sleep(1000); } Debug.Print("Local IP: " + module.LocalIP); Debug.Print("MAC address: " + module.MacAddress); if (module.LocalIP == "0.0.0.0") { module.Reboot(); module.Dispose(); return; } } catch(ThreadAbortException) { module.Dispose(); Debug.Print("Our watchdog got fired - sleep a bit and try rebooting the module before we return"); Thread.Sleep(2000); using(module = new WiFlyGSX(DebugMode: true)) { module.Reboot(); } throw; } workingModule = module; }); thread.Start(); var fired = false; using (var setupWatchdog = new Watchdog(new TimeSpan(0, 0, 30), () => { if (!fired) { Debug.Print("Triggering setup watchdog"); thread.Abort(); fired = true; } })) { setupWatchdog.Start(); thread.Join(); } return workingModule; }
public void FetchURL(Uri url) { bool success = false; while (!success) { var module = GetModule(); var thread = new Thread(() => { var httpHost = url.Host; var host = httpHost; var port = (ushort)url.Port; if (host == "pourcast.labs.rightpoint.com") host = "192.168.100.114"; var request = "GET " + url.AbsolutePath + " HTTP/1.1\r\nHost: " + httpHost + "\r\nConnection: Close\r\n\r\n"; SimpleSocket socket = new WiFlySocket(host, port, module); try { // Connects to the socket socket.Connect(); // Does a plain HTTP request socket.Send(request); // Prints all received data to the debug window, until the connection is terminated while (socket.IsConnected) { var line = socket.Receive().Trim(); if (line != "" && line != null) { //Debug.Print(line); } } success = true; } finally { socket.Close(); } }); thread.Start(); using (var fetchWatchdog = new Watchdog(new TimeSpan(0, 0, 5), () => { Debug.Print("Triggering fetch watchdog"); thread.Abort(); Thread.Sleep(500); module.Reboot(); module.Dispose(); _module = null; })) { thread.Join(); } } }