Filter results by

Azimut’s Cricket Teaches SAMI About Clean Air

Here at Azimut Monitoring, we have been developing devices that enable customers to monitor and get reports on different environmental measures (e.g., noise, pollution, weather). Today we’re working with Samsung to bring our products into the SAMI environment in order to interact with other connected devices and develop future uses.

Azimut logo

Cricket© is a compact, low-power device targeting indoor air quality. It allows the user to wirelessly monitor various metrics in the room by viewing the data collected on our central servers, therefore requiring very little equipment on premise—depending on the location’s constraints, it can work either with a local ZigBee/WiFi gateway or with cellular networks (GPRS, SIGFOX, LoRa).

Our architecture

Most of the work in our architecture happens on our back end in charge of processing and analyzing the data. It has been designed to allow for different types of data sources (e.g., web service push, external files, custom protocol) in order to be compatible with a wide range of devices. Most of our own devices communicate via a protocol with a very small footprint on embedded software and hardware. This enables them to keep power usage low while communicating, making them autonomous for up to 3 years, depending on the setup and sensors.

Our servers process thousands of payloads a day to feed our databases. Here, device data are stored and then either made viewable via our business-specific Web portals, pushed in various formats to our customers or summarized in subscribed reports. We also provide management tools to remotely configure the devices according to needs.

Integrating with SAMI

Integrating our existing architecture with SAMI was more simply done through our central servers than directly from the devices. This has allowed us to control the data before it is published and to keep our general workflow. We decided to push the device data to SAMI as part of our data integration process while keeping it in our systems as well. No change whatsoever was therefore required on our devices’ firmware.

We use Microsoft .NET on the server side, so we have access to all the required high-level libraries to leverage the REST API with ease. The code samples here use the HttpClient class found in namespace System.Net.Http.

var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://api.samsungsami.io/v1.1/");

Data submission is done using an OAuth token produced after users register each device on their SAMI account, therefore ensuring they agree to have their data shared with Samsung’s servers, and enabling them to revoke access at any time.

Azimut management website

These tokens, along with the device IDs, are manually entered as metadata in Azimut’s management website during setup; they can then be included in the HTTP headers for authentication in all related API calls.

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", samiToken);

Alternatively, this could have been achieved with WebSockets, probably requiring a bit more code but potentially faster for bulk uploads. For more information you can check out the SAMI documentation for the API specification and OAuth authentication process.
Depending on the device setup, data submission can happen in real-time (device sends its data as soon as it collects it) or in batch to save power (data is collected but sent only at a determined frequency). Either way, as soon as our servers receive the data, we forward it to SAMI using the same API method which at the time of writing takes only one publication at a time, meaning it needs to be called multiple times for batch mode.

// Formatting JSON message
    var samiMessage = new
    {
        sdid = samiDeviceId,
        ts = ConvertToUnixTimeStamp(DateTime.UtcNow), // date is is UTC Unix timestamp format 
        type = "message",
        data = GetPayload() // Payload can be any serializable type, as described in the manifest
    };

    var httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("https://api.samsungsami.io/v1.1/");
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", samiToken);
    var httpResponse = httpClient.PostAsJsonAsync("messages", samiMessage, CancellationToken.None).Result;

This works really well as long as we keep track of the quota restrictions in place when pushing lots of payloads in a given time frame. SAMI’s rate limits apply per device and user on minute and daily time windows, and we can check how many allowed calls are left by extracting the remaining quotas provided in the HTTP response after each call, and briefly holding off before continuing once limits are reached.

// Testing quotas in the response headers
    var quotasRemaining = httpResponse.Headers.GetValues("X-Rate-Limit-Remaining").SingleOrDefault();
    if (!String.IsNullOrEmpty(quotasRemaining))
    {
        var restQuota = Int32.Parse(quotasRemaining.Split('/')[0]);
        if (restQuota <= 5)
        {
            //SAMI remaing quotas is low, waiting for a minute before next upload...
            Thread.Sleep(60000);
        }
    }

We also wanted to handle possible errors in the communication between our servers and SAMI. To do this we look at the HTTP response codes and resend data as appropriate.

if (httpResponse == null)
        throw new Exception("No response was found");
    httpResponse.EnsureSuccessStatusCode();

In our case, we just keep a log of our exports and are able to re-submit the missing data when needed, since we still store it in our own database:

Exports log

Once the data is in SAMI, users can obviously view them in the dynamic charts in the SAMI User Portal.

Azimut in SAMI User Portal

Having the data in SAMI also opens up lots of possibilities for new applications around it, such as analysis with data aggregated from other sources to provide more context to the measures (local weather, geolocation, etc.), or even home automation to improve the indoor environment (windows/fans to control air flow and temperature, power plugs to disable sources of noise, etc.).

We are looking forward to see what else can be built around our data, thanks to SAMI!

Full code sample

// Formatting JSON message
    var samiMessage = new
    {
        sdid = samiDeviceId,
        ts = ConvertToUnixTimeStamp(DateTime.UtcNow), // date is is UTC Unix timestamp format 
        type = "message",
        data = GetPayload() // Payload can be any serializable type, as described in the manifest
    };

    var httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("https://api.samsungsami.io/v1.1/");
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", samiToken);
    var httpResponse = httpClient.PostAsJsonAsync("messages", samiMessage, CancellationToken.None).Result;

    if (httpResponse == null)
        throw new Exception("No response was found");
    httpResponse.EnsureSuccessStatusCode();

    // Testing quotas in the response headers
    var quotasRemaining = httpResponse.Headers.GetValues("X-Rate-Limit-Remaining").SingleOrDefault();
    if (!String.IsNullOrEmpty(quotasRemaining))
    {
        var restQuota = Int32.Parse(quotasRemaining.Split('/')[0]);
        if (restQuota <= 5)
        {
            //SAMI remaing quotas is low, waiting for a minute before next upload...
            Thread.Sleep(60000);
        }
    }

This is a guest post from Thomas Rabiller, Senior Software Developer at Azimut Monitoring.

Get the ARTIK Newsletter

You like your news fresh! Sign up now and you will be the first to know about our latest software releases, coding tips, upcoming events, blog posts, datasheet updates, and more.

* By checking either box, you may receive notifications by phone, email, text, and/or other electronic means from Samsung Semiconductor, Inc. and its affiliates. If you choose to receive partner notifications, we may forward your contact information to our partners. You may unsubscribe from these services at any time by clicking on the unsubscribe link in our communications or by submitting a request here. Please see our Privacy Policy and Terms of Use for more information about how your data is stored and used.