private static void checkHandWash(DistanceSensor distanceSensorEpic) { var handwashDistance = distanceSensorEpic.Distance; if (handwashDistance < Setting.Default.HandwashDistance) { if (!isWashingHands && (lastHandWashEventSent == null || (DateTime.Now - (DateTime)lastHandWashEventSent).TotalSeconds > 10)) { Console.WriteLine("Handwashing being performed"); lastHandWashEventSent = DateTime.Now; isWashingHands = true; SendHandwashingEvent(); Console.WriteLine("Hand wash event sent"); } } else if (isWashingHands) { var timePassed = (DateTime.Now - (DateTime)lastHandWashEventSent).TotalSeconds; isWashingHands = false; Console.WriteLine("Handwash stopped! Lasted " + (int)(timePassed) + " seconds"); if (timePassed > 5) { // SendHandwashingEvent(); // Console.WriteLine("Hand wash event sent"); } } }
public SmartSideSensor(IRobot robot, DistanceSensor distanceSensor, double relativeDirection, int minMapValueForObstacles, int maxDistance) { this.distanceSensor = distanceSensor; this.relativeDirection = relativeDirection; this.minMapValueForObstacles = minMapValueForObstacles; this.maxDistance = maxDistance; robot.OnTick += PollSensorAndFireEventIfNeeded; }
public static bool InitDistanceSensor() { the_only_distance_sensor = new DistanceSensor(); if (!the_only_distance_sensor.InitSensor(ECHO_PIN, GpioController, MAX_DISTANCE_VALUE, AVG_ITTERATIONS)) { return(false); } return(true); }
private void Start() { servo = new RCServo(); servo.Open(); servo.Attach += OnAttachServo; sensorDistance = new DistanceSensor(); sensorDistance.Open(); sensorDistance.Attach += OnAttachDistanceSensor; }
void GetCarComponents() { _carComp = GetComponent <Car>(); _distanceSensorComp = GetComponent <DistanceSensor>(); _followPathComp = GetComponent <FollowPath>(); _brakesComp = GetComponent <Brakes>(); _gasComp = GetComponent <Gas>(); _patienceComp = GetComponent <Patience>(); carData = _carComp.carData; }
public RobotTestBase() { map = new Map(100, 100); env = new DefaultEnvironment(map); var defaultRobot = new RobotBase(env); lineSensor = new LineSensor(defaultRobot); robot = defaultRobot as IRobot; distanceSensor = new DistanceSensor(defaultRobot); robot.Location = new Point(50.0, 50.0); robot.Orientation = 0.0; }
private void OnTriggerEnter(Collider other) { if (other.gameObject.tag == Strings.car) { CarController carController = other. gameObject.GetComponent <CarController>(); carController.isParking = true; DistanceSensor distanceSensor = other. gameObject.GetComponentInChildren <DistanceSensor>(); distanceSensor.gameObject.SetActive(false); } }
public void Start() { float angle = 360 / (float)m_DistanceSensorCount; for (int i = 0; i < m_DistanceSensorCount; i++) { DistanceSensor sensor = Instantiate(m_DistanceSensorPrefab); sensor.transform.position = transform.position; sensor.transform.rotation = Quaternion.Euler(0, 0, angle * i); sensor.transform.parent = transform; } m_Sensors = GetComponentsInChildren <DistanceSensor>(); }
private void CloseConnection() { if (servo != null) { servo.Close(); servo = null; } if (sensorDistance != null) { sensorDistance.Close(); sensorDistance = null; } }
public Robot() { com = new MyCom(this); omniDrive = new OmniDrive(); bumper = new Bumper(); camera = new MyCamera(this); motor = new Motor(); Distance = new DistanceSensor(); omniDrive.setComId(com.id()); motor.setComId(com.id()); bumper.setComId(com.id()); camera.setComId(com.id()); Distance.setComId(com.id()); }
void FixedUpdate() { // Distance Sensors for (int i = 0; i < distanceSensors.Length; ++i) { DistanceSensor sensor = distanceSensors[i]; Vector3 dir = transform.TransformDirection(new Vector3(sensor.direction.x, 0, sensor.direction.z)) * sensor.maxDistance; RaycastHit hit; Vector3 raySrc = transform.position + (transform.right * sensor.origin.x) + (transform.forward * sensor.origin.z) + (transform.up * sensor.origin.y); if (Physics.BoxCast(raySrc, sensor.extents, dir, out hit, Quaternion.identity, sensor.maxDistance, sensor.layerMask)) { data[i * 2] = 1 - (hit.distance / sensor.maxDistance); data[(i * 2) + 1] = ThreatDictionary.ContainsKey(hit.transform.tag) ? ThreatDictionary[hit.transform.tag] : 0; Stats hitStats = hit.transform.GetComponent <Stats>(); if (hitStats != null && Array.IndexOf(stats.Menu, hit.transform.tag) > -1) { data[(i * 2) + 2] = Mathf.Clamp(hitStats.Nutrition / stats.MaxHealth, 0, 1); } else { data[(i * 2) + 2] = 0; } Color col = Color.HSVToRGB((float)data[(i * 2) + 1] * 0.75f, 1f, 0.5f); Debug.DrawRay(raySrc, hit.point - raySrc, col); } else { data[i * 2] = 0; data[(i * 2) + 1] = 0; data[(i * 2) + 2] = 0; } } OnChangeWeights.Invoke(data); }
void Awake() { if (OnChangeWeights == null) { OnChangeWeights = new ChangeWeightsEvent(); } stats = GetComponent <Stats>(); sensorDataLength = (distanceSensors.Length * 3); // (Distance, tag, nutrition) data = new double[sensorDataLength]; threats.ForEach(threat => { ThreatDictionary.Add(threat.tag, threat.level); }); for (int i = 0; i < distanceSensors.Length; ++i) { DistanceSensor sensor = distanceSensors[i]; sensor.layerMask = LayerMask.GetMask(sensor.layers); Quaternion rot = Quaternion.AngleAxis(sensor.angle, Vector3.up); sensor.direction = (rot * Vector3.forward).normalized; } }
private IEnumerator doPark() { //Enable automatic control control.autoParking = true; //Setup sensors sensors = control.sensors; DistanceSensor backPointingRight = sensors[0]; DistanceSensor backMiddlePointingBack1 = sensors[2]; DistanceSensor backMiddlePointingBack2 = sensors[3]; DistanceSensor frontRightAngular = sensors[1]; //Setup other variables float lastDistance1 = 0; float lastDistance2 = 0; float backSensorOffset = 0.1f; float angle = 0; //Drive back without turning control.command = new ControlCar.CommandSet(-1, 0, false); while (backPointingRight.getDistance() != -1) { yield return(null); // until back end of car is aligned with obstacle 1 } StartCoroutine(breaK()); while (doingSubRoutine) { yield return(null); } StartCoroutine(turnRight()); while (doingSubRoutine) { yield return(null); } //Drive back while turning right control.command = new ControlCar.CommandSet(-1, 1, false); while (backMiddlePointingBack1.getDistance() == -1) { yield return(null); //until obstacle two is visible; } while (backMiddlePointingBack1.getDistance() != -1) //and then until it isn't visible again, while keeping track of the last measured value { lastDistance1 = backMiddlePointingBack1.getDistance(); lastDistance2 = backMiddlePointingBack2.getDistance(); yield return(null); } // Calculate angle between alignent of obstacle2(and supposedly object1) and the alignment of the car angle = Mathf.Atan((lastDistance1 - lastDistance2) / backSensorOffset) * Mathf.Rad2Deg; //Set the rotation of the angluar distance sensor to the difference in alignment frontRightAngular.transform.localEulerAngles = new Vector3(0, 180 + angle, 0); StartCoroutine(breaK()); while (doingSubRoutine) { yield return(null); } StartCoroutine(turnMiddle()); while (doingSubRoutine) { yield return(null); } //Drive back without turning control.command = new ControlCar.CommandSet(-1, 0, false); while (frontRightAngular.getDistance() == -1) { yield return(null); //Until front right corner of car clears obstacle 1 } StartCoroutine(breaK()); while (doingSubRoutine) { yield return(null); } StartCoroutine(turnLeft()); while (doingSubRoutine) { yield return(null); } //Drive back while turning left control.command = new ControlCar.CommandSet(-1, -1, false); // until car is aligned with object 2 while (Mathf.Atan((backMiddlePointingBack1.getDistance() - backMiddlePointingBack2.getDistance()) / backSensorOffset) * Mathf.Rad2Deg > 0 || backMiddlePointingBack1.getDistance() == -1) { yield return(null); } ; StartCoroutine(breaK()); while (doingSubRoutine) { yield return(null); } StartCoroutine(turnMiddle()); while (doingSubRoutine) { yield return(null); } //Done - Give back control control.autoParking = false; }
// // Sensor event handlers // private void EnsureSensorsCreated() { IBandSensorManager sensorMgr = Model.Instance.Client.SensorManager; if (accelerometerSensor == null) { accelerometerSensor = sensorMgr.CreateAccelerometerSensor(); accelerometerSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var accelerometerEvent = e.SensorReading; mTextAccX.Text = string.Format("{0:F3}", accelerometerEvent.AccelerationX); mTextAccY.Text = string.Format("{0:F3}", accelerometerEvent.AccelerationY); mTextAccZ.Text = string.Format("{0:F3}", accelerometerEvent.AccelerationZ); }); }; } if (contactSensor == null) { contactSensor = sensorMgr.CreateContactSensor(); contactSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var contactEvent = e.SensorReading; mTextContact.Text = contactEvent.ContactState.ToString(); }); }; } if (distanceSensor == null) { distanceSensor = sensorMgr.CreateDistanceSensor(); distanceSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var distanceEvent = e.SensorReading; mTextTotalDistance.Text = string.Format("{0:D} cm", distanceEvent.TotalDistance); mTextSpeed.Text = string.Format("{0:F2} cm/s", distanceEvent.Speed); mTextPace.Text = string.Format("{0:F2} ms/m", distanceEvent.Pace); mTextPedometerMode.Text = distanceEvent.MotionType.ToString(); }); }; } if (gyroscopeSensor == null) { gyroscopeSensor = sensorMgr.CreateGyroscopeSensor(); gyroscopeSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var gyroscopeEvent = e.SensorReading; mTextGyroAccX.Text = string.Format("{0:F3}", gyroscopeEvent.AccelerationX); mTextGyroAccY.Text = string.Format("{0:F3}", gyroscopeEvent.AccelerationY); mTextGyroAccZ.Text = string.Format("{0:F3}", gyroscopeEvent.AccelerationZ); mTextGyroAngX.Text = string.Format("{0:F2}", gyroscopeEvent.AngularVelocityX); mTextGyroAngY.Text = string.Format("{0:F2}", gyroscopeEvent.AngularVelocityY); mTextGyroAngZ.Text = string.Format("{0:F2}", gyroscopeEvent.AngularVelocityZ); }); }; } if (heartRateSensor == null) { heartRateSensor = sensorMgr.CreateHeartRateSensor(); heartRateSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var heartRateEvent = e.SensorReading; mTextHeartRate.Text = Convert.ToString(heartRateEvent.HeartRate); mTextHeartRateQuality.Text = heartRateEvent.Quality.ToString(); }); }; } if (pedometerSensor == null) { pedometerSensor = sensorMgr.CreatePedometerSensor(); pedometerSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var pedometerEvent = e.SensorReading; mTextTotalSteps.Text = string.Format("{0:D}", pedometerEvent.TotalSteps); }); }; } if (skinTemperatureSensor == null) { skinTemperatureSensor = sensorMgr.CreateSkinTemperatureSensor(); skinTemperatureSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var skinTemperatureEvent = e.SensorReading; mTextSkinTemperature.Text = string.Format("{0:F1}", skinTemperatureEvent.Temperature); }); }; } if (uvSensor == null) { uvSensor = sensorMgr.CreateUVSensor(); uvSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var uvEvent = e.SensorReading; mTextUltraviolet.Text = uvEvent.UVIndexLevel.ToString(); }); }; } }
// // Sensor event handlers // private void EnsureSensorsCreated() { IBandSensorManager sensorMgr = Model.Instance.Client.SensorManager; if (accelerometerSensor == null) { accelerometerSensor = sensorMgr.CreateAccelerometerSensor(); accelerometerSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var accelerometerEvent = e.SensorReading; mTextAccX.Text = string.Format("{0:F3} m/s/s", accelerometerEvent.AccelerationX); mTextAccY.Text = string.Format("{0:F3} m/s/s", accelerometerEvent.AccelerationY); mTextAccZ.Text = string.Format("{0:F3} m/s/s", accelerometerEvent.AccelerationZ); }); }; } if (contactSensor == null) { contactSensor = sensorMgr.CreateContactSensor(); contactSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var contactEvent = e.SensorReading; mTextContact.Text = contactEvent.ContactState.ToString(); }); }; } if (distanceSensor == null) { distanceSensor = sensorMgr.CreateDistanceSensor(); distanceSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var distanceEvent = e.SensorReading; mTextTotalDistance.Text = string.Format("{0:D} cm", distanceEvent.TotalDistance); mTextSpeed.Text = string.Format("{0:F2} cm/s", distanceEvent.Speed); mTextPace.Text = string.Format("{0:F2} ms/m", distanceEvent.Pace); mTextPedometerMode.Text = distanceEvent.MotionType.ToString(); }); }; } if (gyroscopeSensor == null) { gyroscopeSensor = sensorMgr.CreateGyroscopeSensor(); gyroscopeSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var gyroscopeEvent = e.SensorReading; mTextGyroAccX.Text = string.Format("{0:F3} m/s/s", gyroscopeEvent.AccelerationX); mTextGyroAccY.Text = string.Format("{0:F3} m/s/s", gyroscopeEvent.AccelerationY); mTextGyroAccZ.Text = string.Format("{0:F3} m/s/s", gyroscopeEvent.AccelerationZ); mTextGyroAngX.Text = string.Format("{0:F2} deg/s", gyroscopeEvent.AngularVelocityX); mTextGyroAngY.Text = string.Format("{0:F2} deg/s", gyroscopeEvent.AngularVelocityY); mTextGyroAngZ.Text = string.Format("{0:F2} deg/s", gyroscopeEvent.AngularVelocityZ); }); }; } if (heartRateSensor == null) { heartRateSensor = sensorMgr.CreateHeartRateSensor(); heartRateSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var heartRateEvent = e.SensorReading; mTextHeartRate.Text = string.Format("{0:D} beats/min", heartRateEvent.HeartRate); mTextHeartRateQuality.Text = heartRateEvent.Quality.ToString(); }); }; } if (pedometerSensor == null) { pedometerSensor = sensorMgr.CreatePedometerSensor(); pedometerSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var pedometerEvent = e.SensorReading; mTextTotalSteps.Text = string.Format("{0:D} steps", pedometerEvent.TotalSteps); }); }; } if (skinTemperatureSensor == null) { skinTemperatureSensor = sensorMgr.CreateSkinTemperatureSensor(); skinTemperatureSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var skinTemperatureEvent = e.SensorReading; mTextSkinTemperature.Text = string.Format("{0:F1} (C)", skinTemperatureEvent.Temperature); }); }; } if (uvSensor == null) { uvSensor = sensorMgr.CreateUVSensor(); uvSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var uvEvent = e.SensorReading; mTextUltraviolet.Text = uvEvent.UVIndexLevel.ToString(); }); }; } if (altimeterSensor == null) { altimeterSensor = sensorMgr.CreateAltimeterSensor(); altimeterSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var altimeterEvent = e.SensorReading; mTextFlightsAscended.Text = string.Format("{0:D} floors", altimeterEvent.FlightsAscended); mTextFlightsDescended.Text = string.Format("{0:D} floors", altimeterEvent.FlightsDescended); mTextRate.Text = string.Format("{0:F2} cm/s", altimeterEvent.Rate); mTextSteppingGain.Text = string.Format("{0:D} cm", altimeterEvent.SteppingGain); mTextSteppingLoss.Text = string.Format("{0:D} cm", altimeterEvent.SteppingLoss); mTextStepsAscended.Text = string.Format("{0:D} steps", altimeterEvent.StepsAscended); mTextStepsDescended.Text = string.Format("{0:D} steps", altimeterEvent.StepsDescended); mTextTotalGain.Text = string.Format("{0:D} cm", altimeterEvent.TotalGain); mTextTotalLoss.Text = string.Format("{0:D} cm", altimeterEvent.TotalLoss); }); }; } if (ambientLightSensor == null) { ambientLightSensor = sensorMgr.CreateAmbientLightSensor(); ambientLightSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var ambientLightEvent = e.SensorReading; mTextBrightness.Text = string.Format("{0:D} lux", ambientLightEvent.Brightness); }); }; } if (barometerSensor == null) { barometerSensor = sensorMgr.CreateBarometerSensor(); barometerSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var barometerEvent = e.SensorReading; mTextAirPressure.Text = string.Format("{0:D} hPa", barometerEvent.AirPressure); mTextTemperature.Text = string.Format("{0:D} (C)", barometerEvent.Temperature); }); }; } if (caloriesSensor == null) { caloriesSensor = sensorMgr.CreateCaloriesSensor(); caloriesSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var caloriesEvent = e.SensorReading; mTextCalories.Text = string.Format("{0:D} kcals", caloriesEvent.Calories); }); }; } if (gsrSensor == null) { gsrSensor = sensorMgr.CreateGsrSensor(); gsrSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var gsrEvent = e.SensorReading; mTextResistance.Text = string.Format("{0:D} kohms", gsrEvent.Resistance); }); }; } if (rrIntervalSensor == null) { rrIntervalSensor = sensorMgr.CreateRRIntervalSensor(); rrIntervalSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var rrIntervalEvent = e.SensorReading; mTextInterval.Text = string.Format("{0:2F} s", rrIntervalEvent.Interval); }); }; } }
static void Main(string[] args) { var greenButton = new DigitalInput(); greenButton.IsHubPortDevice = true; greenButton.HubPort = 1; var greenLed = new DigitalOutput(); greenLed.IsHubPortDevice = true; greenLed.HubPort = 3; var redButton = new DigitalInput(); redButton.IsHubPortDevice = true; redButton.HubPort = 0; var redLed = new DigitalOutput(); redLed.IsHubPortDevice = true; redLed.HubPort = 2; var sonar = new DistanceSensor(); sonar.HubPort = 4; sonar.Open(1000); redButton.Open(1000); redLed.Open(1000); greenButton.Open(1000); greenLed.Open(1000); greenButton.StateChange += (o, e) => { greenLed.State = e.State; }; redButton.StateChange += (o, e) => { redLed.State = e.State; if (e.State) { var sound = new SoundPlayer(@"C:\windows\media\tada.wav"); sound.Play(); var random = new Random(); Console.WriteLine("The next random number is {0}!", random.Next(0, 10)); } }; sonar.DistanceChange += (o, e) => { if (e.Distance > 100) { greenLed.State = true; redLed.State = false; } else { greenLed.State = false; redLed.State = true; } }; Console.WriteLine("Press enter to exit."); Console.ReadLine(); redButton.Close(); redLed.Close(); greenButton.Close(); greenLed.Close(); }
static void Main() { var distance = new DistanceSensor(Netduino3.GpioPin.D8); //SoundSensor sound = new SoundSensor(Netduino3.AdcChannel.A0); LightSensor light = new LightSensor(Netduino3.AdcChannel.A1); RotaryAngleSensor rotary = new RotaryAngleSensor(Netduino3.AdcChannel.A2); TemperatureSensor temp = new TemperatureSensor(Netduino3.AdcChannel.A3); TouchSensor touch = new TouchSensor(Netduino3.GpioPin.D2); LedSocket led = new LedSocket(Netduino3.GpioPin.D3); Button btn = new Button(Netduino3.GpioPin.D5); Relay rly = new Relay(Netduino3.GpioPin.D6); Buzzer buzz = new Buzzer(Netduino3.GpioPin.D7); //var rgb = new LcdRgbBacklight(); //rgb.EnableDisplay(true); Random rnd = new Random(); int counter = 0; bool Touched = false; while (true) { counter++; Thread.Sleep(100); //rgb.GoHome(); //rgb.SetCursor(0, 0); //rgb.Clear(); //Debug.WriteLine("sound:"+sound.ReadLevel()); Debug.WriteLine("light:" + light.ReadLightLevel()); Debug.WriteLine("rotary:" + rotary.GetAngle()); Debug.WriteLine("temp:" + temp.ReadTemperature()); Debug.WriteLine("distance:" + distance.MeasureInCentimeters() + "cm"); if (touch.IsTouched() && !Touched) { Touched = true; //rgb.Write("turn on light"); led.TurnOn(); } else if (!touch.IsTouched() && Touched) { Touched = false; //rgb.Write("turn off light"); led.TurnOff(); } if (btn.IsPressed()) { rly.TurnOn(); buzz.TurnOn(); } else { buzz.TurnOff(); rly.TurnOff(); } /* * if (counter > 50) * { * rgb.SetBacklightRGB((byte)rnd.Next(255), (byte)rnd.Next(255), (byte)rnd.Next(255)); * counter = 0; * }*/ } }
/// <summary> /// 初始化單一應用程式物件。這是第一行執行之撰寫程式碼, /// 而且其邏輯相當於 main() 或 WinMain()。 /// </summary> public App() { this.InitializeComponent(); DistanceSensor.Init(); this.Suspending += OnSuspending; }
public void InitSensors(TestMeViewModel b) { if (!_client.IsConnected) { return; } _hrSensor = _hrSensor ?? _client.SensorManager.CreateHeartRateSensor(); _gsrSensor = _gsrSensor ?? _client.SensorManager.CreateGsrSensor(); _rrSensor = _rrSensor ?? _client.SensorManager.CreateRRIntervalSensor(); _contactSensor = _contactSensor ?? _client.SensorManager.CreateContactSensor(); _distancerSensor = _distancerSensor ?? _client.SensorManager.CreateDistanceSensor(); if (_contactSensor == null || _hrSensor == null || _gsrSensor == null || _rrSensor == null || _distancerSensor == null) { return; } Activity activity = Droid.MainActivity.instance; //register contact listener _contactSensor.ReadingChanged += (sender, e) => { var contactEvent = e.SensorReading; _bandState = contactEvent.ContactState; }; //register heart rate listener _hrSensor.ReadingChanged += (sender, e) => { activity.RunOnUiThread(() => { var heartRateEvent = e.SensorReading; //_hrReadings.Add(heartRateEvent.HeartRate); if (heartRateEvent.Quality == HeartRateQuality.Locked) { _hrSensor.StopReadings(); _contactSensor.StopReadings(); // if (b != null) { b.HR = _hrReadings[_hrReadings.Count - 1]; } //update ViewModel } if (_bandState != BandContactState.Worn) //user took off the band while reading { _hrSensor.StopReadings(); _contactSensor.StopReadings(); _bandState = null; return; } }); }; //register gsr listener _gsrSensor.ReadingChanged += (sender, e) => { activity.RunOnUiThread(() => { var gsrEvent = e.SensorReading; _gsrReadings.Add(gsrEvent.Resistance); if (b != null) { b.GsrList = gsrEvent.Resistance.ToString(); } if (_gsrDone) { _gsrSensor.StopReadings(); _contactSensor.StopReadings(); return; } }); }; //register RR Intervals listener _rrSensor.ReadingChanged += (sender, e) => { if (_bandState != BandContactState.Worn) //user took off the band while reading { _rrSensor.StopReadings(); _contactSensor.StopReadings(); _bandState = null; b.StressResult = "Error: band is not worn."; return; } var rrEvent = e.SensorReading; _rrIntervalsReadings.Add(rrEvent.Interval); }; _distancerSensor.ReadingChanged += (sender, e) => { currentMotionTyp = e.SensorReading.MotionType; _distancerSensor.StopReadings(); }; }
private static void checkToiletVisit(DistanceSensor distanceSensor0) { if (lastToiletOccupancyReportedTime != null) { var result = (DateTime.Now - lastToiletOccupancyReportedTime).Value.TotalSeconds; //We will not accept more than one toilet visit pr five minutes - should be half an hour - - if this is the case - we should log the incident and continue if (result < 60) { return; } } var distance = distanceSensor0.Distance; //Console.WriteLine("Distance: "+distance); double?duration = null; if (distance < Setting.Default.ToiletDistance) { if (toiletActionStarted == null) { toiletNotOccupiedCounter = 0; //If a new occupancy has started - and this is the first time - sound the alarm Console.WriteLine("Toilet visit started"); toiletActionStarted = DateTime.Now.AddSeconds(-2); System.Media.SystemSounds.Hand.Play(); } // we are on the toilet (maybe just sat down) duration = (int)(DateTime.Now - toiletActionStarted).Value.TotalSeconds - 2; if (duration > 10) { Console.WriteLine("Toilet visit more than {0} seconds in total", duration); } } else { if (toiletActionStarted == null) { return; } toiletNotOccupiedCounter = toiletNotOccupiedCounter + 1; Console.WriteLine("Left toilet for the {0}. time", toiletNotOccupiedCounter); if (toiletNotOccupiedCounter == 2) { var toiletActionEnded = DateTime.Now.AddSeconds(-6); Console.WriteLine(""); Console.WriteLine("Toilet visit lasted from {0} to {1} ", ((DateTime)toiletActionStarted).ToLongTimeString(), ((DateTime)toiletActionEnded).ToLongTimeString()); //now send the toilet occupancy event if ((toiletActionEnded - toiletActionStarted).Value.TotalSeconds > 10) { Console.WriteLine("Toilet event sent!"); SendToiletOccupancyEvent((DateTime)toiletActionStarted, (DateTime)toiletActionEnded, (int)((DateTime)toiletActionEnded - (DateTime)toiletActionStarted).TotalSeconds); } toiletNotOccupiedCounter = 0; toiletActionStarted = null; lastToiletOccupancyReportedTime = DateTime.Now; } } }
static void Main(string[] args) { Log.Enable(LogLevel.Info, "phidgetlog.log"); DistanceSensor distanceSensor0 = new DistanceSensor(); distanceSensor0.HubPort = 3; //distanceSensor0.DistanceChange += DistanceSensor0_DistanceChange; distanceSensor0.Attach += DistanceSensor0_Attach; distanceSensor0.Detach += DistanceSensor0_Detach; distanceSensor0.Error += DistanceSensor0_Error; DistanceSensor distanceSensor1 = new DistanceSensor(); distanceSensor1.HubPort = 4; //distanceSensor0.DistanceChange += DistanceSensor0_DistanceChange; distanceSensor1.Attach += DistanceSensor0_Attach; distanceSensor1.Detach += DistanceSensor0_Detach; distanceSensor1.Error += DistanceSensor0_Error; //VoltageRatioSensorType voltageRatioSensor = new VoltageRatioSensorType(); VoltageRatioInput voltageRatioInput = new VoltageRatioInput(); voltageRatioInput.HubPort = 0; voltageRatioInput.IsHubPortDevice = true; voltageRatioInput.Channel = 0; voltageRatioInput.VoltageRatioChange += VoltageRatioInput_VoltageRatioChange; try { InitizlizeMqttClient(); distanceSensor0.Open(5000); distanceSensor0.DataInterval = 2000; distanceSensor0.SonarQuietMode = false; distanceSensor1.Open(5000); distanceSensor1.DataInterval = 2000; distanceSensor1.SonarQuietMode = false; voltageRatioInput.Open(5000); //voltageRatioInput.SensorType = VoltageRatioSensorType.PN_1129; voltageRatioInput.DataInterval = 100; //Console.ReadLine(); Task.Run(() => { while (true) { Thread.Sleep(2000); checkHandWash(distanceSensor1); checkToiletVisit(distanceSensor0); } }); //Wait until Enter has been pressed before exiting Console.ReadLine(); distanceSensor0.Close(); } catch (PhidgetException ex) { Console.WriteLine(ex.ToString()); Console.WriteLine(""); Console.WriteLine("PhidgetException " + ex.ErrorCode + " (" + ex.Description + "): " + ex.Detail); Console.ReadLine(); } }
// // Sensor event handlers // private void EnsureSensorsCreated() { IBandSensorManager sensorMgr = Model.Instance.Client.SensorManager; if (accelerometerSensor == null) { accelerometerSensor = sensorMgr.CreateAccelerometerSensor(); accelerometerSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var accelerometerEvent = e.SensorReading; mTextAccX.Text = string.Format("{0:F3}", accelerometerEvent.AccelerationX); mTextAccY.Text = string.Format("{0:F3}", accelerometerEvent.AccelerationY); mTextAccZ.Text = string.Format("{0:F3}", accelerometerEvent.AccelerationZ); }); }; } if (contactSensor == null) { contactSensor = sensorMgr.CreateContactSensor(); contactSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var contactEvent = e.SensorReading; mTextContact.Text = contactEvent.ContactStatus.ToString(); }); }; } if (distanceSensor == null) { distanceSensor = sensorMgr.CreateDistanceSensor(); distanceSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var distanceEvent = e.SensorReading; mTextTotalDistance.Text = string.Format("{0:D} cm", distanceEvent.TotalDistance); mTextSpeed.Text = string.Format("{0:F2} cm/s", distanceEvent.Speed); mTextPace.Text = string.Format("{0:F2} ms/m", distanceEvent.Pace); mTextPedometerMode.Text = distanceEvent.PedometerMode.ToString(); }); }; } if (gyroscopeSensor == null) { gyroscopeSensor = sensorMgr.CreateGyroscopeSensor(); gyroscopeSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var gyroscopeEvent = e.SensorReading; mTextGyroAccX.Text = string.Format("{0:F3}", gyroscopeEvent.AccelerationX); mTextGyroAccY.Text = string.Format("{0:F3}", gyroscopeEvent.AccelerationY); mTextGyroAccZ.Text = string.Format("{0:F3}", gyroscopeEvent.AccelerationZ); mTextGyroAngX.Text = string.Format("{0:F2}", gyroscopeEvent.AngularVelocityX); mTextGyroAngY.Text = string.Format("{0:F2}", gyroscopeEvent.AngularVelocityY); mTextGyroAngZ.Text = string.Format("{0:F2}", gyroscopeEvent.AngularVelocityZ); }); }; } if (heartRateSensor == null) { heartRateSensor = sensorMgr.CreateHeartRateSensor(); heartRateSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var heartRateEvent = e.SensorReading; mTextHeartRate.Text = Convert.ToString(heartRateEvent.HeartRate); mTextHeartRateQuality.Text = heartRateEvent.Quality.ToString(); }); }; } if (pedometerSensor == null) { pedometerSensor = sensorMgr.CreatePedometerSensor(); pedometerSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var pedometerEvent = e.SensorReading; mTextTotalSteps.Text = string.Format("{0:D}", pedometerEvent.TotalSteps); }); }; } if (skinTemperatureSensor == null) { skinTemperatureSensor = sensorMgr.CreateSkinTemperatureSensor(); skinTemperatureSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var skinTemperatureEvent = e.SensorReading; mTextSkinTemperature.Text = string.Format("{0:F1}", skinTemperatureEvent.Temperature); }); }; } if (uvSensor == null) { uvSensor = sensorMgr.CreateUVSensor(); uvSensor.ReadingChanged += (sender, e) => { Activity.RunOnUiThread(() => { var uvEvent = e.SensorReading; mTextUltraviolet.Text = uvEvent.UVIndexLevel.ToString(); }); }; } }
void Start() { // Distance Sensors for (int i = 0; i < DistanceSensors.Length; ++i) { DistanceSensor sensor = DistanceSensors[i]; DistanceSensors[i].LayerMask = LayerMask.GetMask(DistanceSensors[i].Layers); Quaternion rot = Quaternion.AngleAxis(DistanceSensors[i].Angle, Vector3.up); DistanceSensors[i].Direction = (rot * Vector3.forward).normalized; } // Telemetry Sensors TelemetrySensor teleSense = new TelemetrySensor() { GetTelemetry = this.getTelemetry, GetTelemetryCount = this.getTelemetryCount }; // Sensor Component Sensors sensors = GetComponent <Sensors>(); sensors.DistanceSensors = DistanceSensors; sensors.TelemetrySensor = teleSense; // Sensor Data Component SensorData sensorData = GetComponent <SensorData>(); sensorData.Data = new double[ sensors.TelemetrySensor.GetTelemetryCount() + (sensors.DistanceSensors.Length * SensorSystem.DATA_POINTS_PER_DISTANCE_SENSOR) ]; for (int i = 0; i < sensorData.Data.Length; ++i) { sensorData.Data[i] = 0; } // Initialize the layers Net net = GetComponent <Net>(); if (InitalNet.LayerSizes != null) { // Debug.Log("INITIALIZING WITH NET"); net.Data = InitalNet; } else { net.Data = new NetData(); net.Data.LayerSizes = new int[HiddenLayerSizes.Length + 2]; net.Data.LayerSizes[0] = sensorData.Data.Length; HiddenLayerSizes.CopyTo(net.Data.LayerSizes, 1); net.Data.LayerSizes[HiddenLayerSizes.Length + 1] = 2; // MotionInputs net.Data.Weights = new double[netSize(net.Data)]; Neural.Mutators.SelfMutate(new NetData[] { net.Data }, new Neural.Options() { { "clone", false }, { "mutationProbability", 1 }, { "mutationFactor", 1 }, { "mutationRange", 10000 }, }); } // Mettabolism Metabolism metabolism = new Metabolism { HealthDecayRate = 1, MealtimeInterval = InitialMealtimeInterval }; gameObjectEntity.EntityManager.AddComponentData <Metabolism>(gameObjectEntity.Entity, metabolism); // Stats Stats stats = new Stats { Tag = gameObject.tag.GetHashCode(), Health = InitialHealth, Age = 0, Generation = 0, Aggression = InitialAggression, Nutrition = InitialNutrition, LastMealTime = DateTime.Now.Ticks, MatingAge = MatingAge, MatingCost = MatingCost, MatingCoolDown = MatingCoolDown }; gameObjectEntity.EntityManager.AddComponentData <Stats>(gameObjectEntity.Entity, stats); }