Code Monkey home page Code Monkey logo

particle-windows-sdk's Introduction

Particle

Particle Windows Cloud SDK

license NuGet Version

Introduction

Particle Windows Cloud SDK enables Windows apps to interact with Particle-powered connected products via the Particle Cloud. It's an easy-to-use wrapper for Particle REST API. The Cloud SDK will allow you to:

  • Manage user sessions for the Particle Cloud (access tokens, encrypted session management)
  • Claim/Unclaim devices for a user account
  • Get a list of instances of user's Particle devices
  • Read variables from devices
  • Invoke functions on devices
  • Publish events and subscribe to events coming from devices

All cloud operations take place asynchronously and return a System.Threading.Tasks.Task allowing you to build beautiful responsive apps for your Particle products and projects. Windows Cloud SDK is implemented as an open-source .NET Portable Class Library. See Installation section for more details. It works well for both C# and VB projects.

Beta notice

This SDK is still under development and is currently released as Beta and over the next few months may go under considerable changes. Although tested, bugs and issues may be present. Some code might require cleanup. In addition, until version 1.0 is released, we cannot guarantee that API calls will not break from one Cloud SDK version to the next. Be sure to consult the Change Log for any breaking changes / additions to the SDK.

Getting started

  • Perform the installation step described under the Installation section below for integrating in your own project
  • Be sure to check Usage before you begin for some code examples

Usage

Cloud SDK usage involves two basic classes: first is ParticleCloud which is an object that enables all basic cloud operations such as user authentication, device listing, claiming etc. Second class is ParticleDevice which is an instance representing a claimed device in the current user session. Each object enables device-specific operation such as: getting its info, invoking functions and reading variables from it.

SDK calls from the UI thread

Some calls from the SDK can both update properties or run callbacks on a non UI thread (e.g. Events). If your application has a UI thread make sure to set the SynchronizationContext.

ParticleCloud.SharedCloud.SynchronizationContext = System.Threading.SynchronizationContext.Current;

Common tasks

Here are few examples for the most common use cases to get your started:

Log in to Particle Cloud

You don't need to worry about access tokens and session expiry, SDK takes care of that for you.

var success = await ParticleCloud.SharedCloud.LoginAsync("[email protected]", "myl33tp4ssw0rd");

Log in to Particle Cloud with a token and validate

var success = await ParticleCloud.SharedCloud.TokenLoginAsync("d4f69e3a357f78316d50e76dbf10fe92364154bf");

Injecting an access token (app utilizes two legged authentication)

var success = await ParticleCloud.SharedCloud.SetAuthentication("d4f69e3a357f78316d50e76dbf10fe92364154bf");

Get a list of all devices

List the devices that belong to currently logged in user and find a specific device by name:

ParticleDevice myDevice = null;
List<ParticleDevice> devices = ParticleCloud.SharedCloud.GetDevicesAsync();
foreach (ParticleDevice device in devices)
{
  if (device.Name().equals("myDeviceName"))
    myDevice = device;
}

Get device instance by its ID or name

ParticleDevice device = ParticleCloud.SharedCloud.GetDeviceAsync("e9eb56e90e703f602d67ceb3");

Read a variable from a Particle device

Assuming here that myDevice is an active instance of ParticleDevice class which represents a device claimed to current user.

var variableResponse = myDevice.GetVariableAsync("temperature");
int temperatureReading = (int)variableResponse.Result;

Call a function on a Particle device

Invoke a function on the device and pass a parameter to it, the returning ParticleFunctionResponse will represent the returned result data of the function on the device.

int functionResponse = myDevice.RunFunctionAsync("digitalwrite", "D7 HIGH"));
int result = functionResponse.ReturnValue;

List device exposed functions and variables

ParticleDevice.Functions returns a list of function names. ParticleDevice.Variables returns a dictionary of variable names to types.

foreach (string functionName in myDevice.Functions)
  Debug.WriteLine($"Device has function: {functionName}");

foreach (varvariable in myDevice.Variables)
  Debug.WriteLine($"Device has variable: '{variable.Key}' of type '{variable.Value}'");

Rename a device

Set a new name for a claimed device:

myDevice.RenameAsync("myDeviceNew");

Refresh a device

Refreshes all the locally stored properties from the cloud and physical device (if online):

myDevice.RefreshAsync();

Signal a device

Send a signal to the device to shout rainbows:

myDevice.SignalAsync(true);

Log out

Log out the user, clearing their session and access token:

ParticleCloud.SharedCloud.LogOut();

Events sub-system

You can make an API call that will open a stream of Server-Sent Events (SSEs). You will make one API call that opens a connection to the Particle Cloud. That connection will stay open, unlike normal HTTP calls which end quickly. Very little data will come to you across the connection unless your Particle device publishes an event, at which point you will be immediately notified. In each case, the event name filter is eventNamePrefix and is optional. When specifying an event name filter, published events will be limited to those events with names that begin with the specified string. For example, specifying an event name filter of 'temp' will return events with names 'temp' and 'temperature'.

Subscribe to events

Subscribe to the firehose of public events, plus private events published by devices one owns:

private void onEvent(object sender, ParticleEventResponse particeEvent)
{
  Debug.WriteLine($"Got Event {particeEvent.Name} with data {particeEvent.Data}");
}

Guid eventListenerID = ParticleCloud.SharedCloud.SubscribeToAllEventsWithPrefixAsync(onEvent, "temp");

Note: specifying null or empty string in the eventNamePrefix parameter will subscribe to ALL events (lots of data!) You can have multiple handlers per event name and/or same handler per multiple events names.

Subscribe to all events, public and private, published by devices the user owns:

Guid eventListenerID = ParticleCloud.SharedCloud.SubscribeToDevicesEventsWithPrefixAsync(handler, "temp");

Subscribe to events from one specific device. Pass a PaticleDevice or deviceId string as a second parameter. If the API user owns the device, then all events, public and private, published by that device will be received. If the API user does not own the device only public events will be received.

Guid eventListenerID = ParticleCloud.SharedCloud.SubscribeToDeviceEventsWithPrefixAsync(handler, myDevice);
Guid eventListenerID = ParticleCloud.SharedCloud.SubscribeToDeviceEventsWithPrefixAsync(handler, "e9eb56e90e703f602d67ceb3");

The method SubscribeToDeviceEventsWithPrefixAsync can also be called on a ParticleDevice instance, guaranteeing that private events will be received since having access device instance in your app signifies that the user has this device claimed.

Guid eventListenerID = myDevice.SubscribeToDeviceEventsWithPrefixAsync(handler, "temp");

Unsubscribing from events

Very straightforward. Keep the id object the subscribe method returned and use it as parameter to call the unsubscribe method:

ParticleCloud.SharedCloud.UnsubscribeFromEvent(eventListenerID);

or via the ParticleDevice instance (if applicable):

myDevice.UnsubscribeFromEvent(eventListenerID);

Publishing an event

You can also publish an event from your app to the Particle Cloud:

ParticleCloud.SharedCloud.PublishEventAsync("event_from_app", "event_payload", true, 60);

OAuth client configuration

If you're creating an app you're required to provide the ParticleCloud class with OAuth clientId and secret. Those are used to identify users coming from your specific app to the Particle Cloud. Please follow the procedure described in our guide to create those strings.

Once you've created your OAuth credentials, you can supply them to the SDK by providing them as string resources in a string resource file called "OAuthClient.resw", using the names OAuthClientID and OAuthClientSecret and they'll be picked up by the SDK automatically:

<data name="OAuthClientID" xml:space="preserve">
  <value>(client ID string goes here)</value>
</data>
<data name="OAuthClientSecret" xml:space="preserve">
  <value>(client secret 40-char hex string goes here)</value>
</data>

If you aren't creating a Windows Store app and/or not using string resources you can manually set the values. Make sure you do this before calling any other functions.

ParticleCloud.SharedCloud.OAuthClientId  = "(client ID string goes here)";
ParticleCloud.SharedCloud.OAuthClientSecret  = "(client secret 40-char hex string goes here)";

Installation

  • There are two versions of the library:
  • portable46-win81+wpa81: Portable .NET Framework 4.6 for use in Windows Runtime (WinRT) applications (Windows 8.1+ and Windows Phone 8.1+)
  • net452: .NET 4.5.2 Framework for use in Windows Console, ASP.NET and Windows Forms Applications
  • Any edition of Microsoft Visual Studio 2015 (Other build systems may also work, but are not officially supported.)
  • You can use either C# or VB

You can either download Particle Windows Cloud SDK or install using NuGet

PM> Install-Package Particle.SDK

Communication

  • If you need help, use Our community website, use the Mobile category for discussion/troubleshooting Windows apps using the Particle Windows Cloud SDK.
  • If you are certain you found a bug, and can provide steps to reliably reproduce it, open an issue on GitHub.
  • If you have a feature request, open an issue on GitHub.
  • If you want to contribute, submit a pull request, be sure to check out spark.github.io for our contribution guidelines, and please sign the CLA.

Maintainers

License

Particle Windows Cloud SDK is available under the Apache License 2.0. See the LICENSE file for more info.

particle-windows-sdk's People

Contributors

justmobilize avatar idokleinman avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.