async void Publish() { if (dht11 == null || deviceClient == null) { return; } double temperature, humidity; try { publishLed.ChangeState(SensorStatus.On); dht11.Measure(); temperature = dht11.TemperatureInCelsius; humidity = dht11.Humidity; if (double.IsNaN(temperature) || double.IsNaN(humidity)) { return; } var content = new Message(telemetry.ToJson(temperature, light.SensorValue() * 100 / 1023, 0, humidity)); await deviceClient.SendEventAsync(content); } catch { telemetry.Exceptions++; } publishLed.ChangeState(SensorStatus.Off); }
/* * // Method called every time the app timer interval occurs. It toggles the on/off * // state of the LED as well as updating the color of the circular representation * // of the LED on the UI to match */ private void Timer_Tick(object sender, object e) { if (ledOff) { try { led.ChangeState(SensorStatus.On); LED.Fill = redBrush; ledOff = false; } catch (Exception) { throw; } } else { try { led.ChangeState(SensorStatus.Off); LED.Fill = grayBrush; ledOff = true; } catch (Exception) { throw; } } }
private void TimerCallBack(object state) { try { int value = getLightSensor(); System.Diagnostics.Debug.WriteLine("Light sensor: " + value.ToString()); if (value < darkLevel) { led.ChangeState(SensorStatus.On); } else if (value > lightLevel) { led.ChangeState(SensorStatus.Off); } /* UI updates must be invoked on the UI thread */ var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Text_lightSensor.Text = "Light Sensor: " + value.ToString(); }); } catch (Exception ex) { // If you want to see the exceptions uncomment the following: System.Diagnostics.Debug.WriteLine(ex.ToString()); } }
private void Timer_Tick(ThreadPoolTimer timer) { if (led.CurrentState == SensorStatus.Off) { led.ChangeState(SensorStatus.On); } else { led.ChangeState(SensorStatus.Off); } }
private async void MainPage_Loaded(object sender, RoutedEventArgs e) { sendingPhoto = false; panicLed = DeviceFactory.Build.Led(Pin.DigitalPin2); infoLed = DeviceFactory.Build.Led(Pin.DigitalPin4); ranger = DeviceFactory.Build.UltraSonicSensor(Pin.DigitalPin3); screen = DeviceFactory.Build.RgbLcdDisplay(); screen.SetText("setting up..."); screen.SetBacklightRgb(0, 0, 200); // init mode -> Both Led's are on panicLed.ChangeState(SensorStatus.On); infoLed.ChangeState(SensorStatus.On); // init camera camera = new UsbCamera(); var initWorked = await camera.InitializeAsync(); // Something went wrong if (!initWorked || ranger.MeasureInCentimeters() == -1) { infoLed.ChangeState(SensorStatus.Off); screen.SetText("Camera or Sensor not connected!"); screen.SetBacklightRgb(200, 0, 0); blink(panicLed); return; } // init photobackend Microsoft.WindowsAzure.Storage.Auth.StorageCredentials credentials = new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(accountName, accountKey); //credentials.UpdateSASToken("?sv=2015-04-05&ss=b&srt=sco&sp=rwlac&se=2016-11-20T04:05:54Z&st=2016-11-12T20:05:54Z&spr=https,http&sig=B0zDabRXoO7LfWy5iACsn0sHOnWzvmmrDv8fAqITPgI%3D"); CloudStorageAccount acc = new CloudStorageAccount(credentials, true); CloudBlobClient client = acc.CreateCloudBlobClient(); container = client.GetContainerReference("picture-storage"); previewElement.Source = camera.MediaCaptureInstance; await camera.StartCameraPreview(); // init finished - turn off panic Led infoLed.ChangeState(SensorStatus.Off); panicLed.ChangeState(SensorStatus.Off); screen.SetText(""); screen.SetBacklightRgb(0, 0, 0); DispatcherTimer mainThread = new DispatcherTimer(); mainThread.Interval = TimeSpan.FromSeconds(0.5); mainThread.Tick += run; mainThread.Start(); }
public void GetButton() { while (true) { string buttonState = button.CurrentState.ToString(); if (buttonState.Equals("On")) { Debug.WriteLine("Button is required"); ledRed.ChangeState(SensorStatus.On); Sleep(200); ledRed.ChangeState(SensorStatus.Off); Sleep(200); } } }
private void run(object sender, object e) { if (userInRange()) { if (infoLed.CurrentState == SensorStatus.Off && !sendingPhoto) { infoLed.ChangeState(SensorStatus.On); sendPhoto(); } } else { infoLed.ChangeState(SensorStatus.Off); } }
private void Timer_Tick(ThreadPoolTimer timer) { try { if (button.CurrentState != buttonState) { buttonState = button.CurrentState; blueLed.ChangeState(buttonState); buzzer.ChangeState(buttonState); } actualAmbientLight = lightSensor.SensorValue(); if (actualAmbientLight < ambientLightThreshold) { brightness = Map(ambientLightThreshold - actualAmbientLight, 0, ambientLightThreshold, 0, 255); } else { brightness = 0; } redLed.AnalogWrite(Convert.ToByte(brightness)); byte rgbVal = Convert.ToByte(brightness); display.SetBacklightRgb(rgbVal, rgbVal, 255); display.SetText(String.Format("Thingy\nLight: {0}", actualAmbientLight)); } catch (Exception ex) { System.Diagnostics.Debug.Write("Something happened: " + ex.ToString()); throw; } }
//Process Ultrasonic Sensor readings and calculate people public void ProcessDistanceReadings() { if (_distAValue < 0 || _distBValue < 0) { return; } if (_distAValue < 30) { _distATriggered = DateTime.Now; _greenLed.ChangeState(SensorStatus.On); if (_distBTriggered > DateTime.Now.AddSeconds(-2) && !_peoplePresent) { _currentUsers++; _totalUsers++; _peoplePresent = true; _distATriggered = DateTime.Now.AddDays(-1); _distBTriggered = DateTime.Now.AddDays(-1); } } else { _greenLed.ChangeState(SensorStatus.Off); _peoplePresent = false; } if (_distBValue < 30) { _distBTriggered = DateTime.Now; _redLed.ChangeState(SensorStatus.On); if (_distATriggered > DateTime.Now.AddSeconds(-2) && !_peoplePresent) { _peoplePresent = true; if (_currentUsers > 0) { _currentUsers--; } _distATriggered = DateTime.Now.AddDays(-1); _distBTriggered = DateTime.Now.AddDays(-1); } } else { _redLed.ChangeState(SensorStatus.Off); _peoplePresent = false; } }
private void blink(ILed led) { DispatcherTimer t = new DispatcherTimer(); t.Interval = TimeSpan.FromSeconds(1); t.Tick += (s, e) => { led.ChangeState(led.CurrentState == SensorStatus.On ? SensorStatus.Off : SensorStatus.On); }; t.Start(); }
public void Run(IBackgroundTaskInstance taskInstance) { while (true) { Sleep(300); if (ledRed.CurrentState == SensorStatus.Off) { ledRed.ChangeState(SensorStatus.On); Debug.WriteLine("Turning ON LED"); } else { ledRed.ChangeState(SensorStatus.Off); Debug.WriteLine("Turning OFF LED"); } } }
private void ParseCommand(GoPiGoCommand command, int value) { var motorController = _goPiGo.MotorController(); switch (command) { case GoPiGoCommand.Stop: motorController.Stop(); break; case GoPiGoCommand.Backward: motorController.MoveBackward(); break; case GoPiGoCommand.Forward: motorController.MoveForward(); break; case GoPiGoCommand.Left: motorController.MoveLeft(); break; case GoPiGoCommand.Right: motorController.MoveRight(); break; case GoPiGoCommand.RotateLeft: motorController.RotateLeft(); break; case GoPiGoCommand.RotateRight: motorController.RotateRight(); break; case GoPiGoCommand.SetLeftMotorSpeed: motorController.SetLeftMotorSpeed(value); break; case GoPiGoCommand.SetRightMotorSpeed: motorController.SetRightMotorSpeed(value); break; case GoPiGoCommand.SwitchLeftLed: _leftLed.ChangeState((SensorStatus)value); break; case GoPiGoCommand.SwitchRightled: _rightLed.ChangeState((SensorStatus)value); break; case GoPiGoCommand.SetServoAngle: motorController.RotateServo(value); break; } }
private void Timer_Tick(ThreadPoolTimer timer) { try { led.ChangeState((led.CurrentState == SensorStatus.Off) ? SensorStatus.On : SensorStatus.Off); } catch (Exception) { System.Diagnostics.Debug.Write("Something happened"); throw; } }
private async void sendPhoto() { sendingPhoto = true; panicLed.ChangeState(SensorStatus.On); Windows.Storage.StorageFile photo = await camera.CapturePhoto(); // Retrieve reference to a blob named "myblob". string fileName = DateTime.Now.ToString("yyyy_MM_dd_h_mm_ss") + ".jpg"; CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName); // Create or overwrite the "myblob" blob with contents from a local file. await blockBlob.UploadFromFileAsync(photo); string httpAddressOfPhoto = "https://" + accountName + ".blob.core.windows.net/" + containerName + "/" + fileName; sendPost(httpAddressOfPhoto); sendingPhoto = false; panicLed.ChangeState(SensorStatus.Off); }
/// <summary> /// Reads current sensor values and takes any action needed /// </summary> /// <param name="source"></param> private void ReadSensors(ThreadPoolTimer source) { bool buttonPressed = _button.CurrentState == SensorStatus.On; _state.Led = _blueLED.CurrentState == SensorStatus.On; _state.LightLevel = _lightSensor.SensorValue() < 1000 ? _lightSensor.SensorValue() : _state.LightLevel; // Update the LCD backlight based on light level _groveLCD.SetBacklightRgb(Linear(0xff, 0x4b, _state.LightLevel, 0xff), Linear(0x00, 0x00, _state.LightLevel, 0xff), Linear(0x00, 0x82, _state.LightLevel, 0xff)); // If the button was pressed toggle the LED and set the text to a new value // This simulates something going "wrong" on the device requirnig the backend // to react if (buttonPressed) { _blueLED.ChangeState(_state.Led ? SensorStatus.Off : SensorStatus.On); _state.LcdText = "ERROR"; } }
private async Task startDistanceMonitoring() { while (true) { await Distance(); if (distance >= 100) { ledGreen.ChangeState(SensorStatus.On); ledRed.ChangeState(SensorStatus.Off); await sendtoapi(); Sleep(5000); } else if (distance < 50) { ledRed.ChangeState(SensorStatus.On); ledGreen.ChangeState(SensorStatus.Off); await sendtoapi1(); Sleep(10000); } else { ledGreen.ChangeState(SensorStatus.On); ledRed.ChangeState(SensorStatus.Off); ledGreen.ChangeState(SensorStatus.On); ledRed.ChangeState(SensorStatus.Off); await sendtoapi2(); Sleep(5000); } Sleep(5000); } }
public async void Run(IBackgroundTaskInstance taskInstance) { // Initiate the LED on Digital Pin 2. (D2). led = DeviceFactory.Build.Led(Pin.DigitalPin2); while (true) { Task.Delay(1000).Wait(); //Delay 1 second try { // If the LED is on, turn it off. If the LED is off, turn it on. led.ChangeState((led.CurrentState == SensorStatus.Off) ? SensorStatus.On : SensorStatus.Off); } catch (Exception ex) { // Do Nothing if there's an exception. } } }
private void Timer_Tick(ThreadPoolTimer timer) { try { // Capture the current ambient noise level soundLevel = soundSensor.SensorValue(); // Check the button state if (button.CurrentState == SensorStatus.On) { // If the button is depressed, turn on the blue LED // and activate the buzzer buzzer.ChangeState(SensorStatus.On); blueLed.ChangeState(SensorStatus.On); // For debugging purposes, log a console message System.Diagnostics.Debug.WriteLine("**** BUTTON ON ****"); } else if (buzzer.CurrentState == SensorStatus.On || blueLed.CurrentState == SensorStatus.On) { // Turn the buzzer and LED off buzzer.ChangeState(SensorStatus.Off); blueLed.ChangeState(SensorStatus.Off); } // Capture the current value from the Light Sensor actualAmbientLight = lightSensor.SensorValue(); // If the actual light measurement is lower than the defined threshold // then define the LED brightness based on the delta between the actual // ambient light and the threshold value if (actualAmbientLight < ambientLightThreshold) { // Use a range mapping method to conver the difference between the // actual ambient light and the threshold to a value between 0 and 255 // (the 8-bit range of the LED on D6 - a PWM pin). // If actual ambient light is low, the differnce between it and the threshold will be // high resulting in a high brightness value. brightness = Map(ambientLightThreshold - actualAmbientLight, 0, ambientLightThreshold, 0, 255); } else { // If the actual ambient light value is above the threshold then // the LED should be completely off. Set the brightness to 0 brightness = 0; } // AnalogWrite uses Pulse Width Modulation (PWM) to // control the brightness of the digital LED on pin D6. redLed.AnalogWrite(Convert.ToByte(brightness)); // Use the brightness value to control the brightness of the RGB LCD backlight byte rgbVal = Convert.ToByte(brightness); display.SetBacklightRgb(rgbVal, rgbVal, rgbVal); // Updae the RGB LCD with the light and sound levels display.SetText(String.Format("Thingy\nL:{0} S:{1}", actualAmbientLight, soundLevel)); } catch (Exception ex) { // NOTE: There are frequent exceptions of the following: // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '. // This appears to be caused by the rapid frequency of writes to the GPIO // These are being swallowed here // If you want to see the exceptions uncomment the following: // System.Diagnostics.Debug.WriteLine(ex.ToString()); } }
private void ChangeLedState(ILed led, SensorStatus targetState) { sm.WaitOne(); led.ChangeState(targetState); sm.Release(); }
public void Run(IBackgroundTaskInstance taskInstance) { // LCD - This screen is I2C IRgbLcdDisplay LCD = DeviceFactory.Build.RgbLcdDisplay(); LCD.SetBacklightRgb(255, 255, 255); LCD.SetText("Hello world!"); // Not sure what colour this will show up in // LEDs ILed red = DeviceFactory.Build.Led(Pin.DigitalPin2); ILed blue = DeviceFactory.Build.Led(Pin.DigitalPin3); // Ultrasonic IUltrasonicRangerSensor Ultrasonic = DeviceFactory.Build.UltraSonicSensor(Pin.DigitalPin4); // Temperature and Humidity // TODO: Double check Sensor model number. Assumed DHT11 from the GrovePi+ Starter Kit IDHTTemperatureAndHumiditySensor tempHumidity = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin5, DHTModel.Dht11); // Sound sensor ISoundSensor Sound = DeviceFactory.Build.SoundSensor(Pin.AnalogPin0); // LDR IRotaryAngleSensor LDR = DeviceFactory.Build.RotaryAngleSensor(Pin.AnalogPin1); while (true) { Task.Delay(100).Wait(); try { // Ultrasonic sensor int distance = Ultrasonic.MeasureInCentimeters(); Debug.WriteLine("Distance: " + distance.ToString()); // TODO - tune to distance of door //if(distance < 50) // LDR int lightLevel = LDR.SensorValue(); Debug.WriteLine("Light Level: " + lightLevel.ToString()); // LEDs red.ChangeState(SensorStatus.On); blue.ChangeState(SensorStatus.On); // Temperature Humidity tempHumidity.Measure(); double temp_degC = tempHumidity.TemperatureInCelsius; double humidity = tempHumidity.Humidity; Debug.WriteLine("Temperature: " + temp_degC + "\tHumidity: " + humidity); // Sound sensor int soundLevel = Sound.SensorValue(); Debug.WriteLine("Sound Level: " + soundLevel); // TODO: Send data to Azure } catch (Exception ex) { Debug.WriteLine(ex.Message); } } }
private void Timer_Tick(ThreadPoolTimer timer) { led.ChangeState((led.CurrentState == SensorStatus.Off) ? SensorStatus.On : SensorStatus.Off); }
//// Create a file StartupTask.Secrets.cs with a partial class for this class and add following declaration with the value for the deviceid and the connection string. //private const string DeviceId = ""; //private readonly static string ConnectionString = ""; //private static DeviceClient s_deviceClient; //private readonly static string s_connectionString = ""; public void Run(IBackgroundTaskInstance taskInstance) { redLed = DeviceFactory.Build.Led(Pin.DigitalPin2); greenLed = DeviceFactory.Build.Led(Pin.DigitalPin3); angleSensor = DeviceFactory.Build.RotaryAngleSensor(Pin.AnalogPin2); temperatureSensor = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin1); _deviceClient = DeviceClient.CreateFromConnectionString(ConnectionString, TransportType.Mqtt); //// Initial telemetry values //double minTemperature = 20; //double minHumidity = 60; //Random rand = new Random(); //s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt); // Loop endlessly while (true) { try { var angleValue = angleSensor.SensorValue(); var desiredTemperature = MinDesiredTemperature + ((MaxDesiredTemperature - MinDesiredTemperature) * angleValue / 1024); var currentTemperature = temperatureSensor.TemperatureInCelsius(); System.Diagnostics.Debug.WriteLine("temperature is :" + currentTemperature + ", desired is: " + desiredTemperature); if (currentTemperature < desiredTemperature) { redLed.ChangeState(SensorStatus.On); greenLed.ChangeState(SensorStatus.Off); } else { redLed.ChangeState(SensorStatus.Off); greenLed.ChangeState(SensorStatus.On); } var telemetryDataPoint = new { messageId = _messageId++, //deviceId = DeviceId, temperature = currentTemperature, }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Message(System.Text.Encoding.ASCII.GetBytes(messageString)); _deviceClient.SendEventAsync(message).Wait(); //double currentTemperature = minTemperature + rand.NextDouble() * 15; //double currentHumidity = minHumidity + rand.NextDouble() * 20; //// Create JSON message //var telemetryDataPoint = new //{ // temperature = currentTemperature, // humidity = currentHumidity //}; //var messageString = JsonConvert.SerializeObject(telemetryDataPoint); //var message = new Message(Encoding.ASCII.GetBytes(messageString)); //// Add a custom application property to the message. //// An IoT hub can filter on these properties without access to the message body. //message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); //// Send the tlemetry message //s_deviceClient.SendEventAsync(message).Wait(); //Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); Task.Delay(1000).Wait(); } catch (Exception ex) { // NOTE: There are frequent exceptions of the following: // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '. // This appears to be caused by the rapid frequency of writes to the GPIO // These are being swallowed here/ // If you want to see the exceptions uncomment the following: System.Diagnostics.Debug.WriteLine(ex.ToString()); } } }
public void SetLed(bool isOn) { _led.ChangeState(isOn ? SensorStatus.On : SensorStatus.Off); }