Things used in this project

Custom parts and enclosures

Touch screen assembly instructions

Code

ServiceStartupTask.csC#
The service class reading sensor data.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.AppService;
using Windows.Foundation.Collections;

// The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409

namespace DataCollector
{
    public sealed class ServiceStartupTask : IBackgroundTask
    {
        private AppServiceConnection _connection;
        private BackgroundTaskDeferral _deferral;
        private volatile static SensorHatProxy _proxy = null;
        private bool? _state;

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            if (_proxy == null)
            {
                _proxy = new SensorHatProxy();
                _proxy.Init();
            }
           
            var res = _proxy.ReadSensorData();

            _deferral = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            if (triggerDetails != null)
            {

                _connection = triggerDetails.AppServiceConnection;
                _connection.RequestReceived += Connection_RequestReceived;
            }

            
        }

        private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            // if you are doing anything awaitable, you need to get a deferral
            var requestDeferral = args.GetDeferral();
            var returnMessage = new ValueSet();
            try
            {
                //obtain and react to the command passed in by the client
                var message = args.Request.Message["Request"] as string;
                switch (message)
                {
                    case "SensorData":

                        CrossCuttingRT.Dto.SensorsDataDto sd = _proxy.ReadSensorData();

                        returnMessage.Add("Temperature", sd.Temperature);
                        returnMessage.Add("LightLevel", sd.LightLevel);
                        break;
                }
                returnMessage.Add("Response", "OK");
            }
            catch (Exception ex)
            {
                returnMessage.Add("Response", "Failed: " + ex.Message);
            }

            await args.Request.SendResponseAsync(returnMessage);

            //let the OS know that the action is complete
            requestDeferral.Complete();
        }

        private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            if (_deferral != null)
            {
                _deferral.Complete();
                _deferral = null;
            }
        }
    }
}
SensorDataServicePoll.csC#
Class responsible for polling data from background service.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.AppService;
using Windows.Foundation.Collections;
using Windows.System.Threading;

namespace BLL
{
    public class SensorDataServicePoll
    {
        private ThreadPoolTimer _timer;

        private static volatile bool _running;

        public CrossCuttingRT.Dto.SensorsDataDto SensorData { get; set; }

        public SensorDataServicePoll()
        {
            _timer = ThreadPoolTimer.CreatePeriodicTimer(_timerElapsed, TimeSpan.FromSeconds(1));
        }

        private async void _timerElapsed(ThreadPoolTimer timer)
        {
            if (_running) return;
            _running = true;
            try
            {
                var data = await PollData();
                if (data != null)
                {
                    SensorData = data;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
            finally
            {
                _running = false;
            }
        }

        private async Task<CrossCuttingRT.Dto.SensorsDataDto> PollData()
        {
            CrossCuttingRT.Dto.SensorsDataDto result = null;

            using (var dataService = new AppServiceConnection())
            {
                var listing = await AppServiceCatalog.FindAppServiceProvidersAsync("DataCollectorInterface");
                var packageName = "";

                // there may be cases where other applications could expose the same App Service Name, in our case
                // we only have the one
                if (listing.Count == 1)
                {
                    packageName = listing[0].PackageFamilyName;
                }

                dataService.AppServiceName = "DataCollectorInterface";
                dataService.PackageFamilyName = packageName;
                var status = await dataService.OpenAsync();

                if (status == AppServiceConnectionStatus.Success)
                {
                    var msg = new ValueSet();
                    msg.Add("Request", "SensorData");
                    AppServiceResponse request = await dataService.SendMessageAsync(msg);

                    if (request.Status == AppServiceResponseStatus.Success)
                    {
                        CrossCuttingRT.Dto.SensorsDataDto data = new CrossCuttingRT.Dto.SensorsDataDto();

                        data.Temperature = request.Message["Temperature"] as double?;
                        data.LightLevel = request.Message["LightLevel"] as double?;
                        result = data;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Request Response Status: " + status.ToString());
                    }
                }
            }

            return result;
        }

    }
}
Public Pi Imageframe Repository
PiImageFrame link contains this project

Credits

944886 10207332723049051 1010476743701632688 n wxrlaregcv
Patricia

A c# developer. As child i used to play with electronics and this source of fun is living up again in me, as we enter the age of IoT.

Contact

Replications

Did you replicate this project? Share it!

I made one

Love this project? Think it could be improved? Tell us what you think!

Give feedback

Comments

Similar projects you might like

Hey Mycroft, Where Is the International Space Station?
Easy
  • 1,823
  • 37

Full instructions

Developing my first skill with the Mycroft.ai open source voice assistant on a Raspberry Pi 3 - aka Picroft!

Setup SQL Anywhere on Raspberry Pi
Easy
  • 182
  • 3

Protip

Setup of SQL Anywhere on Raspberry Pi to allow collecting and processing sensor data offline on the edge, plus synchronizing when online.

Sound Detector with Visual Alerts
Easy
  • 2,057
  • 3

Full instructions

Create a WiFi-enabled sound detector that sends your phone notifications using Prowl and Python!

Measure Plant Growth
Easy
  • 1,124
  • 16

Find out how much plants grow without killing the plant.

How to Add Alexa to a Raspberry Pi
Easy
  • 2,425
  • 21

Full instructions

Solution that allows turning any Linux-based device into an Amazon Echo.

Shoe Box RetroPie Console
Easy
  • 697
  • 10

Full instructions

A RetroPie install on a Raspberry Pi Zero W with an Arcade Bonnet from Adafruit all packed in a shoe box decorated with neon duct tape.

ProjectsCommunitiesTopicsContestsLiveAppsBetaFree StoreBlogAdd projectSign up / Login