Skip to content
This repository has been archived by the owner on Nov 16, 2023. It is now read-only.

Commit

Permalink
Merge pull request #393 from microsoft/saraclay-patch-1
Browse files Browse the repository at this point in the history
Update README.md
  • Loading branch information
saraclay authored Aug 16, 2019
2 parents bf8bfcc + 0d7b4c5 commit 5703a52
Show file tree
Hide file tree
Showing 17 changed files with 558 additions and 148 deletions.
8 changes: 8 additions & 0 deletions Samples/WeatherStation/CS/App.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Application
x:Class="WeatherDataReporter.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WeatherDataReporter"
RequestedTheme="Light">

</Application>
97 changes: 97 additions & 0 deletions Samples/WeatherStation/CS/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace WeatherDataReporter
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}

/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;

// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();

rootFrame.NavigationFailed += OnNavigationFailed;

if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}

// Place the frame in the current Window
Window.Current.Content = rootFrame;
}

if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}

/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}

/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
11 changes: 11 additions & 0 deletions Samples/WeatherStation/CS/ConnectionStrings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Windows.UI.Xaml.Controls;

namespace WeatherDataReporter
{
public sealed partial class MainPage : Page
{
static string iotHubUri = "{replace}";
static string deviceKey = "{replace}";
static string deviceId = "{replace}";
}
}
14 changes: 14 additions & 0 deletions Samples/WeatherStation/CS/IWeatherDataProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WeatherDataReporter
{
interface IWeatherDataProvider
{
double GetTemperature();
double GetHumidity();
}
}
16 changes: 16 additions & 0 deletions Samples/WeatherStation/CS/MainPage.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Page
x:Class="WeatherDataReporter.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WeatherDataReporter"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid>
<Grid.Background>
<SolidColorBrush Color="{ThemeResource SystemBaseMediumHighColor}"/>
</Grid.Background>
<ListView x:Name="listView" Margin="20" SelectionMode="None" FontSize="18.667" Foreground="White" BorderThickness="1" HorizontalContentAlignment="Left" Background="#FFD0D0D0"/>
</Grid>
</Page>
55 changes: 55 additions & 0 deletions Samples/WeatherStation/CS/MainPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using Windows.UI.Xaml.Controls;

namespace WeatherDataReporter
{
public sealed partial class MainPage : Page
{
static DeviceClient deviceClient;

public MainPage()
{
this.InitializeComponent();

deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1);

SendDeviceToCloudMessagesAsync();
}

private async void SendDeviceToCloudMessagesAsync()
{
//var weatherDataprovider = await WeatherDataProvider.Create();

// Use this if you don't have a real sensor:
var weatherDataprovider = await SimulatedWeatherDataProvider.Create();

while (true)
{
double currentHumidity = weatherDataprovider.GetHumidity();
double currentTemperature = weatherDataprovider.GetTemperature();

var telemetryDataPoint = new
{
time = DateTime.Now.ToString(),
deviceId = deviceId,
currentHumidity = currentHumidity,
currentTemperature = currentTemperature
};
var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
var message = new Message(Encoding.ASCII.GetBytes(messageString));

await deviceClient.SendEventAsync(message);
Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);

this.listView.Items.Insert(0, messageString);

await Task.Delay(1000);
}
}
}
}
30 changes: 12 additions & 18 deletions Samples/WeatherStation/CS/Package.appxmanifest
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>

<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10"
IgnorableNamespaces="uap mp iot">
IgnorableNamespaces="uap mp">

<Identity
Name="WeatherStation-uwp"
Name="47d77310-4819-4b33-aabc-2324f2167015"
Publisher="CN=MSFT"
Version="1.0.0.0" />

<mp:PhoneIdentity PhoneProductId="891bba20-d8f1-4138-baf5-a3d07e9fe96e" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<mp:PhoneIdentity PhoneProductId="47d77310-4819-4b33-aabc-2324f2167015" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>

<Properties>
<DisplayName>WeatherStation</DisplayName>
<DisplayName>WeatherDataReporter</DisplayName>
<PublisherDisplayName>MSFT</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
Expand All @@ -29,23 +28,18 @@
</Resources>

<Applications>
<Application Id="App">
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="WeatherDataReporter.App">
<uap:VisualElements
DisplayName="WeatherStation"
DisplayName="WeatherDataReporter"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png"
Description="WeatherStation"
BackgroundColor="transparent"
AppListEntry="none">
Description="WeatherDataReporter"
BackgroundColor="transparent">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="WeatherStation.StartupTask">
<BackgroundTasks>
<iot:Task Type="startup" />
</BackgroundTasks>
</Extension>
</Extensions>
</Application>
</Applications>

Expand Down
11 changes: 4 additions & 7 deletions Samples/WeatherStation/CS/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
// Copyright (c) Microsoft. All rights reserved.


using System.Reflection;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WeatherStation")]
[assembly: AssemblyTitle("WeatherDataReporter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WeatherStation")]
[assembly: AssemblyProduct("WeatherDataReporter")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
Expand All @@ -29,4 +26,4 @@
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]
[assembly: ComVisible(false)]
82 changes: 75 additions & 7 deletions Samples/WeatherStation/CS/README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,81 @@
# Weather Station
# Azure Weather Station

Communicate with an I2C/SPI based temperature and pressure sensor
## Adapted from [here](https://blogs.msdn.microsoft.com/iot/2016/01/26/using-power-bi-to-visualize-sensor-data-from-windows-10-iot-core/).

Upon executing this sample, you'll have learned how to measure temperature and pressure using I2C/SPI!
## Introduction
Building a weather station is the rite of passage for beginning IoT enthusiasts. It's easy to put together from inexpensive components and provides immediate gratification. For example, you can blow air on your sensor and watch the temperature graph spike up or down. You can leave the weather station in your home and monitor humidity and temperature remotely. The list goes on.

[Each pin on this map](https://adafruitsample.azurewebsites.net/cardViewer?lesson=203) is another maker that has run this sample. Zoom around to see where they are and deploy the sample to put your pin on the map!
At the same time, the project presents some unique challenges. How do you send the data from your device to the cloud? How do you visualize it in interesting ways? Finally -- how do you make sure you're looking at your data? In other words, how do you reliably authenticate your device?

![weather-station](../../../Resources/images/AdafruitStarterPack/WeatherStation.jpg)
## Authenticating a Headless Device
In a typical OAuth 2.0 authorization flow, the user is presented with a browser window where they can enter their credentials. The application then obtains an access token that is used to communicate with the desired cloud service. Alas, this approach is not suitable for headless IoT devices without the mouse and keyboard attached, or devices that only offer console I/O.

### Click [here](https://www.hackster.io/windows-iot/weather-station) to get started!
This problem is solved with the latest version of the Active Directory Authentication Library (still in preview) that introduces a new authentication flow tailored for headless devices. The approach goes like this: when a user authentication is required, instead of bringing up a browser window, the app asks the user to use another device to navigate to [https://aka.ms/devicelogin](https://aka.ms/devicelogin) and enter a specific code. Once the code is provided, the web page will lead the user through a normal authentication experience, including consent prompts and multi factor authentication if necessary. Upon successful authentication, the app will receive the required access tokens through a back channel and use it to access the desired cloud service.

### If you have v2 of the kit with a BME280 Click [here](https://www.hackster.io/windows-iot/weather-station-v-2-0-8abe16?auth_token=80b912d8d81919969ccab0080ddd8e2f) to get started!
## Hardware Setup
For this example, we will use a humidity and temperature sensor, such as the HTU21D, which is available from a number of vendors (e.g., Sparkfun, Amazon).

The sensor connects to your device via I²C bus, as shown on the following wiring diagram (the location of the pins might be slightly different if you're using a device other than Raspberry Pi 2):

![Humidity and temperature sensor](https://msdnshared.blob.core.windows.net/media/2016/01/humidity-htu21d_bb.png)

## Software Setup
The software setup will require several steps. First, we'll need to register an application in the Azure Active Directory. Then, we'll copy the client ID from the application and use it in our UWP app running on the device. Finally, we'll create a dashboard in Power BI to visualize data coming from our device.

### Registering an Application in Azure
This step assumes that your organization already has an Azure Active Directory set up. If not, you can get started here.

You can register your application from the Azure Portal, however it's easier to do it from the dedicated Power BI application registration page [here](https://dev.powerbi.com/apps).

Navigate to the above page, log in with your Power BI credentials and fill out the information about your app:

![Power Bi app information](https://msdnshared.blob.core.windows.net/media/2016/01/Register_app_step2.png)

Note that I used a dummy URL for the redirect -- our app will not need this information but we cannot leave this field empty.

In the next step, enable the "Read All Datasets" and "Read and Write All Datasets" APIs and click "Register App".

Once this is done, click "Register App". The web page will generate the Client ID, which looks like this:

![Register your app](https://msdnshared.blob.core.windows.net/media/2016/01/Register_app_step4.png)

Leave the browser page open -- we will need to copy the Client ID and paste it into our C# app.

## Build the App
The C# app UWP that we're going to use combines the Power BI REST APIs with the use of headless device flow from the Azure Active Directory Library described [here](https://github.com/Azure-Samples/active-directory-dotnet-deviceprofile/).

The full source of the app is available on our GitHub repository [here](https://github.com/ms-iot/samples/tree/develop/Azure/WeatherStation.PowerBI).

To run your application on your device, you need to get the source code and find the clientID constant in PBIClient.cs:

```
// WeatherPBIApp: replace with the actual Client ID from the Azure Application:
private const string clientID = "<replace>";
```

Replace the value with the string obtained from the registered Azure Application at the previous step and compile the app for ARM architecture. For this app, you will need to connect your Raspberry Pi to a monitor (keyboard and mouse are not required) to display the user code from the device. While this means that the device is no longer completely headless, you might imagine a slightly more advanced version of the app where the user code is communicated via an SMS message, an HTTP POST request, or is displayed on an [LED matrix](https://www.raspberrypi.org/products/sense-hat/).

Deploy the app to your Raspberry Pi. If all goes well, you should see the following:

![Running Raspberry Pi app](https://msdnshared.blob.core.windows.net/media/2016/01/App_running.png)

Now switch to another device -- either a desktop PC or a phone and navigate to the specified URL. Type in the specified user code and press Continue:

![Signing into application](https://msdnshared.blob.core.windows.net/media/2016/01/signin1.png)

Once the user code is accepted, the application will receive the access code and start sending data to Power BI.

### Configure Power BI Dashboard
Login to your [Power BI account](https://powerbi.microsoft.com/en-us/) and look for the "WeatherReport" dataset in the navigation bar on the left. In the Visualization pane create a "Temperature by Time" line chart:

![Temperature by Time line chart](https://msdnshared.blob.core.windows.net/media/2016/01/TemperaturexTime.png)

You can then create a "Humidity by Time" chart in a similar way. Alternatively, you can plot both temperature and humidity on the same axis.

Now save your report and pin it to the dashboard. You should see something that looks like this:

![Temperature and humidity charts](https://msdnshared.blob.core.windows.net/media/2016/01/dashboard.png)

That's it! Enjoy your weather station!

Want to learn more about using Power BI to visualize sensor data from IoT Core? Read the blog post [here](https://blogs.msdn.microsoft.com/iot/2016/01/26/using-power-bi-to-visualize-sensor-data-from-windows-10-iot-core/).
Loading

0 comments on commit 5703a52

Please sign in to comment.