Ipinder Singh Suri
Published © GPL3+

Sick-urity

Security and monitoring through Microsoft Azure

IntermediateWork in progress1,202
Sick-urity

Things used in this project

Hardware components

Raspberry Pi 2 Model B
Raspberry Pi 2 Model B
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
×1
LED (generic)
LED (generic)
×1
Breadboard (generic)
Breadboard (generic)
×1

Software apps and online services

Windows 10 IoT Core
Microsoft Windows 10 IoT Core

Story

Read more

Schematics

Circuit picture

the sensor is connected to the input pin of Pi. An led indicates the state of motion

Code

MainPage.xaml

C#
it is the main code file for raspberrypi model b. It includes the code for motion detection using PIR sensor
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Gpio;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace PIRSensorApp
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private int counter = 0;

        private const int LED_PIN = 5;
        private GpioPin _pinLed;

        private const int DISTANCE_PIN = 6;
        private GpioPin _pinDistance;

        private GpioPin testPin;
        private const int TEST_PIN = 26;
        private bool light = false;

        private DateTime lastMotionTime;
        public MainPage()
        {
            this.InitializeComponent();
            
            Initialize();
            
            Unloaded += MainPage_Unloaded;
        }

        private void Initialize()
        {
            var gpio = GpioController.GetDefault();

            MyText.Text = "START";
            lastMotionTime = DateTime.Now;


            testPin = gpio.OpenPin(TEST_PIN);
            testPin.Write((light ? GpioPinValue.High : GpioPinValue.Low));
            testPin.SetDriveMode(GpioPinDriveMode.Output);

            _pinLed = gpio.OpenPin(LED_PIN);
            _pinLed.Write(GpioPinValue.High);
            _pinLed.SetDriveMode(GpioPinDriveMode.Output);

            _pinDistance = gpio.OpenPin(DISTANCE_PIN);
            _pinDistance.SetDriveMode(GpioPinDriveMode.Input);
            _pinDistance.ValueChanged += EventHandler;

        }

        TimeSpan timeDiff;
        private async void EventHandler(GpioPin sender, GpioPinValueChangedEventArgs args)
        {
            var isOn = args.Edge == GpioPinEdge.FallingEdge;
            if (isOn)
            {
                Debug.WriteLine("Ready ");
            }
            else
            {
                CloudService.PushData(DateTime.Now.ToString(), null, "Camera1");
                Debug.WriteLine("Motion Detected " + counter++);
                timeDiff = DateTime.Now - lastMotionTime;
                if (timeDiff.Seconds >= 2 || counter == 0)
                {
                    light = (light ? false : true);
                }
                lastMotionTime = DateTime.Now;
                testPin.Write((light ? GpioPinValue.High : GpioPinValue.Low));
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    MyText.Text = "Motion Detected " + counter;
                });
                takeImage();
            }
        }


       


        private async void takeImage()
        {
            try
            {
                var url = "http://10.0.0.12/image.jpg";

                HttpClient client = new HttpClient();
                var byteArray = Encoding.UTF8.GetBytes("admin:");
                client.DefaultRequestHeaders.Authorization =
                    new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
                    Convert.ToBase64String(byteArray));

                var result = await client.GetByteArrayAsync(url);
                ByteToImage(result);
            }
            catch (Exception ex)
            {
                var message = ex.Message;
            }
        }

        public async void ByteToImage(byte[] imageData)
        {

            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            var op = randomAccessStream.WriteAsync(imageData.AsBuffer());
            op.Completed = (info, status) =>
            {

                randomAccessStream.Seek(0);

                Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    BitmapImage biImg = new BitmapImage();
                    biImg.SetSource(randomAccessStream);

                    ImageSource imgSrc = biImg as ImageSource;
                    currentImage.Source = imgSrc;
                });
            };
        }

        private void MainPage_Unloaded(object sender, object args)
        {
            // Cleanup
            _pinLed.Dispose();
            _pinDistance.Dispose();
        }

    }
}

Code for sending events to cloud service

C#
this is the code file for sending the code to azure cloud service. the cloud service would receive the data and act accordingly.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PIRSensorApp
{
    public static class CloudService
    {
        public static void PushData(string dateTime, byte[] image, string cameraId)
        {
            
            // Create a new webrequest to the mentioned URL.   
            WebRequest webRequest = WebRequest.Create("http://www.MYAZURECLOUDSERVICE.com");
            webRequest.Method = "POST";

            var headerCollection = new WebHeaderCollection();

            headerCollection["dateTime"] = dateTime;
            headerCollection["cameraId"] = cameraId;

            webRequest.Headers = headerCollection;

            // Create a new instance of the RequestState.
            // The 'WebRequest' object is associated to the 'RequestState' object.
            // Start the Asynchronous call for response.
            IAsyncResult asyncResult = (IAsyncResult)webRequest.BeginGetResponse(new AsyncCallback(RespCallback), null);
            // Release the WebResponse resource.

        }

        private static void RespCallback(IAsyncResult asynchronousResult)
        {
            //do nothing. We dont want to perform any action with this.
        }
        
        
    }
}

Credits

Ipinder Singh Suri

Ipinder Singh Suri

1 project • 0 followers

Comments