Windows Phone + Micro Framework (using tile push notification and temperature sensor)


In this application on the MicroFramework board will be put a temperature sensor. On the MicroFramework board there is a thread that check a temperature sensor; If the temperature change (above/below) to a predefined range the code on the Micro Framework board send a tile push notification. On the Windows Phone there are a tile that it will be showed as alarm (one tile is green/one tile is red). If you enter in the Windows Phone/Silverlight app you can check the temperature level manually by sending a http rest call to the Micro Framework board; the result will be showed in a label.



using System;
using System.Net;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Collections.ObjectModel;
using System.Windows.Media.Animation;
using System.Windows.Documents;
using System.Windows.Controls;
using System.Windows.Shapes;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;

namespace AppPhone3
{
    public class MainViewModel : BaseViewModel 
    {
        private bool isbusy;
        private ServiceData service;
        private PushNotification channel;
        private object syncs = new object();
        private string _ResponseTemp;
        private string _ResponseMess;
        private RelayCommand _buttonRoomCmd1;
        private bool _visibleRoomCmd1;
        private RelayCommand _buttonRoomCmd2;
        private bool _visibleRoomCmd2;
        private RelayCommand _buttonRoomCmd3;
        private bool _visibleRoomCmd3;

        public MainViewModel()
        {
            isbusy = false;
            ResponseMess = "Init channel";
            service = new ServiceData();
            channel = new PushNotification();
            service.GetDataCompleted += CommandCompleted;
            channel.GetChannelCompleted += ChannelCompleted;
            _visibleRoomCmd1 = true;
            _buttonRoomCmd1 = new RelayCommand(
                () => CommandRoomCmd1(), () => VisibleRoomCmd1
            );
            _visibleRoomCmd2 = true;
            _buttonRoomCmd2 = new RelayCommand(
                () => CommandRoomCmd2(), () => VisibleRoomCmd2
            );
            _visibleRoomCmd3 = true;
            _buttonRoomCmd3 = new RelayCommand(
                () => CommandRoomCmd3(), () => VisibleRoomCmd3
            );
            channel.InitChannel("channel1");
        }   

        public void ChannelCompleted(object sender, PushChannelArgs args)
        {
            string status = args.IsConnected.ToString();
            ResponseMess = "IsConnected:" + status;
            if (args.IsConnected == true)       
                service.RegisterUri(args.UriChannel);
        }

        public void CommandCompleted(object sender, EventResultArgs args)
        {
            ResponseTemp = (string)args.Data2;
            ResponseMess = (string)args.Data1;
            if ( args.Command == "register" )
                service.SendCommand("cmd1");
            isbusy = false;
        }

        public string ResponseTemp
        {
            get { return _ResponseTemp; }
            set
            {
                _ResponseTemp = value;
                RaisePropertyChanged("ResponseTemp");
            }
        }

        public string ResponseMess
        {
            get { return _ResponseMess; }
            set
            {
                _ResponseMess = value;
                RaisePropertyChanged("ResponseMess");
            }
        }

        public RelayCommand ButtonRoomCmd1
        {
            get { return _buttonRoomCmd1; }
        }
        public bool VisibleRoomCmd1
        {
            get { return _visibleRoomCmd1; }
            set { _visibleRoomCmd1 = value; }
        }      
        protected virtual void CommandRoomCmd1()
        {
            if (isbusy == true)
                return;
            isbusy = true;
            ResponseMess = "cmd1";
            SendCommand("cmd1");
        }

        public RelayCommand ButtonRoomCmd2
        {
            get { return _buttonRoomCmd2; }
        }
        public bool VisibleRoomCmd2
        {
            get { return _visibleRoomCmd2; }
            set { _visibleRoomCmd2 = value; }
        }      
        protected virtual void CommandRoomCmd2()
        {
            if (isbusy == true)
                return;
            isbusy = true;
            ResponseMess = "cmd2";
            SendCommand("cmd2");
        }

        public RelayCommand ButtonRoomCmd3
        {
            get { return _buttonRoomCmd3; }
        }
        public bool VisibleRoomCmd3
        {
            get { return _visibleRoomCmd3; }
            set { _visibleRoomCmd3 = value; }
        }
        protected virtual void CommandRoomCmd3()
        {
            if (isbusy == true)
                return;
            isbusy = true;
            ResponseMess = "cmd3";
            SendCommand("cmd3");
        }

        private void SendCommand(string cmd)
        {
            service.SendCommand(cmd);
        }
    }
}


using System;
using System.Net;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.Phone.Notification;
using System.Windows.Media.Animation;
using System.Collections.ObjectModel;
using System.Windows.Documents;
using System.Windows.Controls;
using System.Windows.Shapes;
using System.IO;

namespace AppPhone3
{
    public class PushNotification
    {
        public event EventHandler<PushChannelArgs> GetChannelCompleted;

        public PushNotification()
        {

        }

        public void InitChannel(string channelName)
        {
            HttpNotificationChannel pushChannel;
            pushChannel = HttpNotificationChannel.Find(channelName);
            //
            if (pushChannel == null)
            {
                pushChannel = new HttpNotificationChannel(channelName);
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
                pushChannel.Open();
                if (pushChannel.IsShellTileBound == false)
                   pushChannel.BindToShellTile();
            }
            else
            {
                string uri = pushChannel.ChannelUri.ToString();
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
                if (pushChannel.IsShellTileBound == false)
                   pushChannel.BindToShellTile();
                if (String.IsNullOrEmpty(uri) == false)
                {
                    PushChannelArgs args = new PushChannelArgs(uri, true);
                    GetChannelCompleted(this, args);
                }
            }
        }

        // Event handler for when the Push Channel Uri changes.
        private void PushChannel_ChannelUriUpdated(object sender, 
              NotificationChannelUriEventArgs e)
        {
            string uri = e.ChannelUri.ToString();
            PushChannelArgs args = new PushChannelArgs(uri, true);
            Deployment.Current.Dispatcher.BeginInvoke(
               () => GetChannelCompleted(this, args)
            );
        }

        // Event handler for when a Push Notification error occurs.
        private void PushChannel_ErrorOccurred(object sender, 
             NotificationChannelErrorEventArgs e)
        {
            string uri = "";
            PushChannelArgs args = new PushChannelArgs(uri, false);
            Deployment.Current.Dispatcher.BeginInvoke(
               () => GetChannelCompleted(this, args)
            );
        }
    }
}


using System;
using System.IO;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.FEZ;
using GHIElectronics.NETMF.Hardware;
using System.Collections;
using System.Threading;
using System.Text;

// abilitare se con si e' con scheda reale
using GHIElectronics.NETMF.Net.NetworkInformation;
using GHIElectronics.NETMF.Net;
// abilitare se con si e' con scheda reale

using Socket = System.Net.Sockets.Socket;

namespace FEZ_PandaApplication1
{
    public class PushNotification
    {
        private Hashtable table;
        private IServiceSensor sensor;
        private bool enabled;

        public PushNotification(IServiceSensor value)
        {
            sensor = value;
            table = new Hashtable();
            enabled = false;
        }

        public void Configure(string uri)
        {
            sensor.Beep(2000, 1000);
            if (table.Contains(uri) == false)
               table.Add(uri, uri);
            enabled = true;
        }

        public void SendMessage(int type, double value)
        {
            if (enabled == false)
                return;
            foreach (DictionaryEntry row in table)
            {
                string uri = (string)row.Value;
                string message = CreateMessage(type, value);
                SendHttpRequest(uri, message);
            }
        }

        public void SendMessageTest1(string uri)
        {
            if (enabled == false)
                return;
            string message = CreateMessage(3);
            SendHttpRequest(uri, message);
        }

        public void SendMessageTest2(string uri)
        {
            if (enabled == false)
                return;
            string message = CreateMessage(4);
            SendHttpRequest(uri, message);
        }

        private string CreateMessage(int type)
        {           
            return CreateMessage(type, 0);
        }

        private string CreateMessage(int type, double value)
        {
            // type 3, 4, 11, 12
            string backgroundimage = "";
            string count = "";
            string title = "";
            string backbackgroundimage = "";
            string backtitle = "";
            string backcontent = "";
            if (type == 11)
            {
                string temp = value.ToString();
                backgroundimage = "Tile11.png";
                count = temp;
                title = "Test tile C";
                backbackgroundimage = "TileBack.png";
                backtitle = "Temperature";
                backcontent = "Temperature:" + temp;
            }
            if (type == 12)
            {
                string temp = value.ToString();
                backgroundimage = "Tile12.png";
                count = temp;
                title = "Test tile H";
                backbackgroundimage = "TileBack.png";
                backtitle = "Temperature";
                backcontent = "Temperature:" + temp;
            }
            if (type == 3)
            {
                backgroundimage = "Tile3.png";
                count = "1";
                title = "Test tile 1";
                backbackgroundimage = "TileBack.png";
                backtitle = "sendpush1";
                backcontent = "Test sendpush1";
            }
            if (type == 4)
            {
                backgroundimage = "Tile4.png";
                count = "2";
                title = "Test tile 2";
                backbackgroundimage = "TileBack.png";
                backtitle = "sendpush2";
                backcontent = "Test sendpush2";
            }
            string message = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
              "<wp:Notification xmlns:wp=\"WPNotification\">" +
                 "<wp:Tile>" +
                    "<wp:BackgroundImage>" + backgroundimage + "</wp:BackgroundImage>" +
                    "<wp:Count>" + count + "</wp:Count>" +
                    "<wp:Title>" + title + "</wp:Title>" +
                    "<wp:BackBackgroundImage>" + backbackgroundimage + "</wp:BackBackgroundImage>" +
                    "<wp:BackTitle>" + backtitle + "</wp:BackTitle>" +
                    "<wp:BackContent>" + backcontent + "</wp:BackContent>" +
                 "</wp:Tile> " +
              "</wp:Notification>";
            return message;
        }

        private void SendHttpRequest(string uri, string message)
        {
            HttpWebResponse webres = null;
            HttpWebRequest webreq = null;
            try 
            {
                byte[] buffer = Encoding.UTF8.GetBytes(message);
                webreq = (HttpWebRequest)WebRequest.Create(uri);
                webreq.Method = "POST";
                webreq.ContentType = "text/xml";
                webreq.Headers.Add("X-WindowsPhone-Target", "token");
                webreq.Headers.Add("X-NotificationClass", "1");
                webreq.ContentLength = buffer.Length;
                webreq.Timeout = 10000;
                Stream stin = webreq.GetRequestStream();
                stin.Write(buffer, 0, buffer.Length);
                stin.Close();
                webres = (HttpWebResponse)webreq.GetResponse();
                if (webres.StatusCode == HttpStatusCode.OK)
                {
                    string status1 = webres.Headers[  "X-NotificationStatus"  ];
                    string status2 = webres.Headers[  "X-SubscriptionStatus"  ];
                    string status3 = webres.Headers["X-DeviceConnectionStatus"];
                }
                webres.Close();
                sensor.Beep(8000, 500);
            }
            catch (Exception ex) 
            {
                sensor.Beep(500, 4000);
            }
            finally
            {
                if (  webres != null  )
                    webres.Dispose();
                if (  webreq != null  )
                    webreq.Dispose();
            }           
        }
    }
}


In my example I have used a temperature sensor from GHI connected to a an alogical pin; you can also use a temperature sensor with I2C protocol. On th micro framework board you can find some pin that support this communication standard ( for more details see ).

Windows Phone/Silverlight and MicroFramework (How create a remote control)
Windows Phone/PhoneGap and MicroFramework (How create a remote control)
MicroFramework server side (How create a remote control)
Windows Phone + Micro Framework (using tile push notification)

Last edited Sep 1, 2012 at 11:37 AM by mastefano64, version 22

Comments

No comments yet.