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

Distance Calculation with Ultrasonic Sensor
Easy
  • 250
  • 8

Full instructions

Ultrasonic distance sensors are designed to measure distance between the source and target using ultrasonic waves.

Controlling Raspberry Pi's Terminal Using Android Phone
Easy
  • 710
  • 9

Full instructions

Controlling the terminal window of the Raspberry Pi 3 using Android Phone via SSH.

Cheapest Smart Home for $38
Easy
  • 748
  • 4

Full instructions

Use Raspberry Pi Zero W to make the cheapest and easiest yet very useful smart home automation for $38 only and no skills needed!

PIR Motion Sensor with Raspberry Pi
Easy
  • 574
  • 11

Protip

Quick project to interface PIR sensor to Raspberry Pi.

Using Android Phone as Raspberry Pi's Display
Easy
  • 528
  • 6

Full instructions

Project using Android Phone as Raspberry Pi's display via SSH through VNC Viewer.

Getting Started with BBC Micro:Bit
Easy
  • 314
  • 8

Full instructions

This tutorial will show you the basics to get started with BBC micro bit.

ProjectsCommunitiesTopicsContestsLiveAppsBetaFree StoreBlogAdd projectSign up / Login
Feedback