// see http://code.jonwagner.com/2012/09/06/best-practices-for-c-asyncawait/ // http://www.c-sharpcorner.com/UploadFile/pranayamr/difference-between-await-and-continuewith-keyword-in-C-Sharp/ // http://code.jonwagner.com/2012/09/04/deadlock-asyncawait-is-not-task-wait/ // https://msdn.microsoft.com/en-us/library/ff963550.aspx - Parallel Programming book public override async Task Init(CancellationTokenSource cts, string[] args) { await base.Init(cts, args); // produces hardwareBrick and sets it for communication joystick.joystickEvent += Joystick_joystickEvent; sensorsController = new SensorsControllerShorty(hardwareBrick, loopTimeMs, PIXY_COM_PORT, speaker); await sensorsController.InitSensors(cts); InitDrive(); behaviorFactory = new BehaviorFactory(subsumptionTaskDispatcher, driveGeometry, speaker); // we can set behavior combo now, or allow ControlDeviceCommand to set it later. //behaviorFactory.produce(BehaviorCompositionType.JoystickAndStop); robotState = new RobotState(); robotPose = new RobotPose(); robotState.powerLevelPercent = 100; // can be changed any time. Used by behaviors. robotPose.geoPosition.moveTo(lng, lat, elev); // will be set to GPS coordinates, if available robotPose.direction.heading = headingDegrees; // will be set to Compass Heading, if available robotPose.reset(); robotSlam = new RobotSLAM() { useOdometryHeading = true }; await InitComm(cts); // may throw exceptions // see what kind of timer we have to measure durations: if (Stopwatch.IsHighResolution) { Debug.WriteLine("OK: operations are timed using the system's high-resolution performance counter."); } else { Debug.WriteLine("Warning: operations are timed using the DateTime class."); } stopWatch.Start(); if (isCommError) { speaker.Speak("Shorty cannot see his brick"); } else { speaker.Speak("I am Shorty"); } }
public bool PlayOnePair(WordsPair pair, ICheckIsExit checkIsExit, out bool isExit) { isExit = false; _speaker.Speak($"{pair.First} = {pair.Second}"); _speaker.Speak($"{pair.Second} = {pair.First}"); var input = _listener.Input(); if (checkIsExit.IsExit(input)) { isExit = true; return(true); } return(true); }
public OffendedViewModel(ISpeaker speaker, IShrink shrink) { _speaker = speaker; _shrink = shrink; CheckIfImOffended = new MvxCommand(() => { OffendedState myState = _shrink.AmIOffended(); switch (myState) { case OffendedState.NotOffended: OffendedResultText = "You have absolutely no reason to be offended"; break; case OffendedState.Offended: OffendedResultText = "You should be offended!"; break; case OffendedState.VeryOffended: OffendedResultText = "The level of offended you should be has reached epic!"; break; default: throw new ArgumentOutOfRangeException(); } _speaker.Speak(OffendedResultText); }); }
/// <summary> /// Called when a <see cref="T:System.Windows.Controls.Button"/> is clicked. /// </summary> protected override void OnClick() { base.OnClick(); if (_speech == null) { _speech = ReadingContext.Current.Speaker; } _speech.Speak(Content.ToString()); }
private void lvAnimals_MouseDoubleClick(object sender, MouseButtonEventArgs e) { ISpeaker selectedSpeaker = lvAnimals.SelectedItem as ISpeaker; if (selectedSpeaker != null) { selectedSpeaker.Speak(); } }
public bool PlayOnePair(WordsPair pair, ICheckIsExit checkIsExit, out bool isExit) { var result = true; isExit = false; _speaker.Speak($"{pair.Second} = {pair.First}"); _speaker.Speak("Введите слово:"); var first = _listener.Input(); if (checkIsExit.IsExit(first)) { isExit = true; return(result); } if (first == pair.First.Caption) { _speaker.Speak("Ok!"); result = true; } else { _speaker.Speak($"No. Правильно будет \"{pair.First}\""); result = false; } _speaker.Speak(""); return(result); //_speaker.Speak("Введите второе слово:"); //var second = _listener.Input(); //if (checkIsExit.IsExit(second)) //{ // isExit = true; // return; //} //if (second == pair.Second.Caption) // _speaker.Speak("Ok!"); //else // _speaker.Speak($"No. Правильно {pair.Second}"); }
private void FormInterpretationAlgorithm(Form form) { _currentForm = form; if (form.Field != null) { _speaker.SpeakAsync(form.Field.Prompt.Message); } else { if (form.Id.Equals("GoodEnd")) { CalculateThePrice(); _mainWindow.SetLabels(_order); DatabaseRepository.AddOrder(_order); _speaker.Speak(form.Block.Prompt.Message); Environment.Exit(0); } if (form.Id.Equals("Reset")) { ResetOrder(); } } }
public void BeginTraining() { _speaker.Speak("Time to sweat"); }
public static void DecodeData(IEnumerable <string> fileSystemEntities, IWriter writer = null, ISpeaker speaker = null) { var files = fileSystemEntities .Where(fileSystemEntity => fileSystemEntity.FileOrDirectoryExists() ? File.GetAttributes(fileSystemEntity).HasFlag(FileAttributes.Directory) : false) .Select(folder => Directory.GetFiles(folder)) .SelectMany(file => file) .Union(fileSystemEntities .Where(fileSystemEntity => fileSystemEntity.FileOrDirectoryExists() ? !File.GetAttributes(fileSystemEntity).HasFlag(FileAttributes.Directory) : false)); if (writer == null) { writer = new ConsoleWriter(); } // Can be moved to class - Configurator or so, // but it can be used there, because this configuration was made only for this method. var section = (FormatSection)ConfigurationManager.GetSection("FormatSection"); foreach (var file in files) { var fileInfo = new FileInfo(file); if (!Extensions.Contains(fileInfo.Extension)) { continue; } writer.Write(string.Format(section.File.Format, fileInfo.Name, fileInfo.Extension, fileInfo.Length)); Directory.CreateDirectory($"{fileInfo.DirectoryName}//{Backup}"); try { fileInfo.MoveTo($"{fileInfo.DirectoryName}//{Backup}//{fileInfo.Name}"); } catch (Exception ex) { writer.Write($"File can't be used. Exception: {ex.Message}"); continue; } using (var streamReader = new StreamReader($"{fileInfo.DirectoryName}//{fileInfo.Name}")) { using (var streamWriter = new StreamWriter(file)) { var lineCount = 0; var fileMathchesCount = 0; string line; while ((line = streamReader.ReadLine()) != null) { Regex.Matches(line, RussianLettersPattern).Cast <Match>() .ToList().ForEach(match => { writer.Write(string.Format(section.Substring.Format, lineCount + 1, match.Index, match.Value)); fileMathchesCount++; }); lineCount++; streamWriter.WriteLine(line.Unidecode()); } writer.Write(string.Format(section.Result.Format, fileMathchesCount)); } } if (speaker != null) { speaker.Speak(file); } } }
public void Speak(string text) { speakerEngine.Speak(text); }
/// <summary> /// /// </summary> /// <param name="ddg"></param> /// <param name="speaker"></param> /// <param name="trackFileName">can be null, for a saved track</param> public BehaviorRouteFollowing(IDriveGeometry ddg, ISpeaker speaker, string trackFileName, double powerFactor = 1.0d) : base(ddg) { this.speaker = speaker; this.powerFactor = powerFactor; BehaviorActivateCondition = bd => { return(nextWp != null); }; BehaviorDeactivateCondition = bd => { return(nextWp == null); }; if (String.IsNullOrWhiteSpace(trackFileName)) { //speaker.Speak("Loading saved track"); try { missionTrack = null; // Load stored waypoints: // on the PC, from C:\Users\sergei\AppData\Local\Packages\RobotPluckyPackage_sjh4qacv6p1wm\LocalState\MyTrack.xml // RPi: \\172.16.1.175\c$\Data\Users\DefaultAccount\AppData\Local\Packages\RobotPluckyPackage_sjh4qacv6p1wm\LocalState Track track = SerializableStorage <Track> .Load(savedTrackFileName).Result; if (track != null) { missionTrack = track; //speaker.Speak("Loaded file " + missionTrack.Count + " trackpoints"); } } catch (Exception ex) { speaker.Speak("could not load saved track file"); } if (missionTrack == null) { speaker.Speak("failed to load saved track file"); missionTrack = new Track(); } nextWp = missionTrack.nextTargetWp; stopStartedTime = null; } else { speaker.Speak("Loading file " + trackFileName); missionTrack = new Track(); try { missionTrack.Init(trackFileName); speaker.Speak("Loaded file " + missionTrack.Count + " trackpoints"); nextWp = missionTrack.nextTargetWp; } catch (Exception ex) { speaker.Speak("could not load planned track file"); } } }
// ISpeaker implementation public async void Speak(string whatToSay, int voice = 0) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => speakerImpl.Speak(whatToSay, voice)); }
static void Sample(ISpeaker input) { ISpeaker.Speak(); // this call acts like a control structure }
/// <summary> /// we can create sensors here, but cannot send commands before bridge_CommunicationStarted is called in PluckyTheRobot /// for example, encoder.Clear() will hang. /// </summary> public async Task InitSensors(CancellationTokenSource cts) { // see C:\Projects\Serializer_3_0\ExampleApps\AnalogSensorExample\AnalogSensorExample\Form1.cs // Note: the Element board communicates at 19200 Baud, which is roughly 1.5 kbytes/sec // Comm link is busy with motor commands and has to be responsive to encoders, for odometry to work. // Sensors must carefully adjust their demands by setting UpdateFrequency and Enabled properties. // *********************** infrared rangers: SensorPose spIrLeft = new SensorPose() { XMeters = 0.0d, YMeters = 0.1d, ThetaRadians = Math.PI / 2.0d }; RangerIrLeft = RangerSensorFactory.produceRangerSensor(RangerSensorFactoryProducts.RangerSensorIR10_80, "IrLeft", spIrLeft, hardwareBrick, AnalogPinId.A1, rangersSamplingIntervalMs, rangersSensitivityThresholdCm); RangerIrLeft.distanceChangedEvent += new EventHandler <RangerSensorEventArgs>(RangerDistanceChangedEvent); RangerSensors.Add(RangerIrLeft.Name, RangerIrLeft); SensorPose spIrRight = new SensorPose() { XMeters = 0.0d, YMeters = -0.1d, ThetaRadians = -Math.PI / 2.0d }; RangerIrRight = RangerSensorFactory.produceRangerSensor(RangerSensorFactoryProducts.RangerSensorIR10_80, "IrRight", spIrRight, hardwareBrick, AnalogPinId.A0, rangersSamplingIntervalMs, rangersSensitivityThresholdCm); RangerIrRight.distanceChangedEvent += new EventHandler <RangerSensorEventArgs>(RangerDistanceChangedEvent); RangerSensors.Add(RangerIrRight.Name, RangerIrRight); SensorPose spIrFront = new SensorPose() { XMeters = 0.1d, YMeters = 0.0d, ThetaRadians = 0.0d }; RangerIrFront = RangerSensorFactory.produceRangerSensor(RangerSensorFactoryProducts.RangerSensorIR10_80, "IrFront", spIrFront, hardwareBrick, AnalogPinId.A3, rangersSamplingIntervalMs, rangersSensitivityThresholdCm); RangerIrFront.distanceChangedEvent += new EventHandler <RangerSensorEventArgs>(RangerDistanceChangedEvent); RangerSensors.Add(RangerIrFront.Name, RangerIrFront); SensorPose spIrRear = new SensorPose() { XMeters = -0.1d, YMeters = 0.0d, ThetaRadians = Math.PI }; RangerIrRear = RangerSensorFactory.produceRangerSensor(RangerSensorFactoryProducts.RangerSensorIR10_80, "IrRear", spIrRear, hardwareBrick, AnalogPinId.A2, rangersSamplingIntervalMs, rangersSensitivityThresholdCm); RangerIrRear.distanceChangedEvent += new EventHandler <RangerSensorEventArgs>(RangerDistanceChangedEvent); RangerSensors.Add(RangerIrRear.Name, RangerIrRear); // *********************** ultrasonic rangers: SensorPose spSonarLeft = new SensorPose() { XMeters = 0.1d, YMeters = 0.05d, ThetaRadians = Math.PI / 6.0d }; RangerSonarLeft = RangerSensorFactory.produceRangerSensor(RangerSensorFactoryProducts.RangerSensorSonar, "SonarLeft", spSonarLeft, hardwareBrick, GpioPinId.Pin4, GpioPinId.Pin5, rangersSamplingIntervalMs, rangersSensitivityThresholdCm); RangerSonarLeft.distanceChangedEvent += new EventHandler <RangerSensorEventArgs>(RangerDistanceChangedEvent); RangerSensors.Add(RangerSonarLeft.Name, RangerSonarLeft); SensorPose spSonarRight = new SensorPose() { XMeters = 0.1d, YMeters = -0.05d, ThetaRadians = -Math.PI / 6.0d }; RangerSonarRight = RangerSensorFactory.produceRangerSensor(RangerSensorFactoryProducts.RangerSensorSonar, "SonarRight", spSonarRight, hardwareBrick, GpioPinId.Pin2, GpioPinId.Pin3, rangersSamplingIntervalMs, rangersSensitivityThresholdCm); RangerSonarRight.distanceChangedEvent += new EventHandler <RangerSensorEventArgs>(RangerDistanceChangedEvent); RangerSensors.Add(RangerSonarRight.Name, RangerSonarRight); // *********************** wheel encoders - roughly 500 ticks per wheel revolution, 1200 ticks per meter. encoderLeft = CreateWheelEncoder(hardwareBrick, WheelEncoderId.Encoder2, (int)mainLoopCycleMs, encodersSensitivityThresholdTicks); encoderRight = CreateWheelEncoder(hardwareBrick, WheelEncoderId.Encoder1, (int)mainLoopCycleMs, encodersSensitivityThresholdTicks); Compass = hardwareBrick.produceCompassCMPS03(0x60, CompassSamplingIntervalMs, CompassSensitivityThreshold); Compass.HeadingChanged += new HardwareComponentEventHandler(Compass_HeadingChanged); // arduino based AHRS - PWM DAC to pin 4: Ahrs = hardwareBrick.produceAnalogSensor(AnalogPinId.A4, CompassSamplingIntervalMs, CompassSensitivityThreshold); Ahrs.AnalogValueChanged += new HardwareComponentEventHandler(Ahrs_ValueChanged); // arduino based AHRS - I2C does not connect: //Ahrs = new I2CDevice(hardwareBrick); //Ahrs.I2CAddress = 173; // The Wire library uses 7 bit addresses throughout. // // If you have a datasheet or sample code that uses 8 bit address, you'll want to drop the low bit (i.e. shift the value one bit to the right), // // yielding an address between 0 and 127. However the addresses from 0 to 7 are not used because are reserved so the first address that can be used is 8. //Ahrs.WriteCommand = "234"; //Ahrs.ReadCommand = "6"; if (PixyCameraSensor != null) { try { await PixyCameraSensor.Open(cts); PixyCameraSensor.TargetingCameraTargetsChanged += PixyCameraSensor_PixyCameraBlocksChanged; } catch (Exception exc) { speaker.Speak("Could not open Pixy Camera at " + PixyCameraSensor.ComPortName); PixyCameraSensor = null; } } batteryVoltage = CreateBatteryVoltageMeter(hardwareBrick, batterySamplingIntervalMs, batterySensitivityThresholdVolts); batteryVoltage.Enabled = true; // slow update rate, leave it turned on IrRangersEnabled = true; // if false, do not sample or update SonarsEnabled = false; // will enable sonars with an interval 50ms to avoid interference EncodersEnabled = true; //CompassEnabled = true; // compass no good inside concrete buildings, use gyro instead CompassEnabled = false; Ahrs.Enabled = true; if (PixyCameraSensor != null) { PixyCameraSensor.Enabled = true; } currentSensorsData = new SensorsDataShorty() { RangerSensors = this.RangerSensors }; }
/// <summary> /// /// </summary> /// <param name="ddg"></param> /// <param name="speaker"></param> /// <param name="trackFileName">can be null, for a saved track</param> public BehaviorRouteFollowing(IDriveGeometry ddg, ISpeaker speaker, string trackFileName) : base(ddg) { this.speaker = speaker; BehaviorActivateCondition = bd => { return nextWp != null; }; BehaviorDeactivateCondition = bd => { return nextWp == null; }; if (String.IsNullOrWhiteSpace(trackFileName)) { speaker.Speak("Loading saved track"); try { missionTrack = null; // Load stored waypoints: // on the PC, from C:\Users\sergei\AppData\Local\Packages\RobotPluckyPackage_sjh4qacv6p1wm\LocalState\MyTrack.xml // RPi: \\172.16.1.175\c$\Data\Users\DefaultAccount\AppData\Local\Packages\RobotPluckyPackage_sjh4qacv6p1wm\LocalState Track track = SerializableStorage<Track>.Load(savedTrackFileName).Result; if (track != null) { missionTrack = track; speaker.Speak("Loaded file " + missionTrack.Count + " trackpoints"); } } catch (Exception ex) { speaker.Speak("could not load saved track file"); } if(missionTrack == null) { speaker.Speak("failed to load saved track file"); missionTrack = new Track(); } nextWp = missionTrack.nextTargetWp; } else { speaker.Speak("Loading file " + trackFileName); missionTrack = new Track(); try { missionTrack.Init(trackFileName); speaker.Speak("Loaded file " + missionTrack.Count + " trackpoints"); nextWp = missionTrack.nextTargetWp; } catch (Exception ex) { speaker.Speak("could not load planned track file"); } } }