Software apps and online services

Story

This project aims to create a cheap and robust security system which can be configured through the web and can provide detailed reports of the activities.

Security is a great concern in today's world and security of home is of utmost importance. We can utilize the power and convenience of Raspberry Pi and cheap PIR Motion sensor to create an exhaustive security system which is configurable through the web and detailed reporting is available through azure.

The system works as follows:

Whenever the Pi senses any movement it sends events to Azure Cloud Service along with the picture of the scene(optional). The cloud service processes these events and decides whether notification is to be sent to the owner or not (which is configurable) and forwards the data to Microsoft Service Bus Event Hub further forwards it to Microsoft Power BI for reporting. The owner can turn on or turn off notification through the convenience web browser.

The construction is as follows:

Firstly, construct a simple motion detection circuit as shown in the attached picture.

This is a simple circuit in which as soon as it detects some motion a led is lit.

Write the code which will send these motion event details to the cloud service. If any network camera is available we can use that to capture the image and we can send that along with the event.

Create Azure cloud service which will have two end points. One on which the camera would be sending the data, and the other one for configuring the notification service.

The notification service end point would be accepting a parameter which would enable or disable the notification system. The other end point would receive the data and based on notification status send email to the user about the motion sensed. It also forwards the event to Microsoft Service Bus Event Hub.

There is a stream analytics job created to consume the data and send it to Microsoft Power BI.

Comprehensive reports can be generated through Power BI on the data. It would show us details like the peak time for movement and the times whenever motion was sensed in the late hours of the day or whenever the notification system was turned on.

Schematics

Circuit picture

Code

MainPage.xaml

C#

it is the main code file for raspberrypi model b. It includes the code for motion detection using PIR sensor

usingSystem;usingSystem.Diagnostics;usingSystem.Net.Http;usingSystem.Runtime.InteropServices.WindowsRuntime;usingSystem.Text;usingSystem.Threading.Tasks;usingWindows.Devices.Gpio;usingWindows.Storage.Streams;usingWindows.UI.Xaml.Controls;usingWindows.UI.Xaml.Media;usingWindows.UI.Xaml.Media.Imaging;namespacePIRSensorApp{/// <summary>/// An empty page that can be used on its own or navigated to within a Frame./// </summary>publicsealedpartialclassMainPage:Page{privateintcounter=0;privateconstintLED_PIN=5;privateGpioPin_pinLed;privateconstintDISTANCE_PIN=6;privateGpioPin_pinDistance;privateGpioPintestPin;privateconstintTEST_PIN=26;privateboollight=false;privateDateTimelastMotionTime;publicMainPage(){this.InitializeComponent();Initialize();Unloaded+=MainPage_Unloaded;}privatevoidInitialize(){vargpio=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;}TimeSpantimeDiff;privateasyncvoidEventHandler(GpioPinsender,GpioPinValueChangedEventArgsargs){varisOn=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));awaitDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,()=>{MyText.Text="Motion Detected "+counter;});takeImage();}}privateasyncvoidtakeImage(){try{varurl="http://10.0.0.12/image.jpg";HttpClientclient=newHttpClient();varbyteArray=Encoding.UTF8.GetBytes("admin:");client.DefaultRequestHeaders.Authorization=newSystem.Net.Http.Headers.AuthenticationHeaderValue("Basic",Convert.ToBase64String(byteArray));varresult=awaitclient.GetByteArrayAsync(url);ByteToImage(result);}catch(Exceptionex){varmessage=ex.Message;}}publicasyncvoidByteToImage(byte[]imageData){InMemoryRandomAccessStreamrandomAccessStream=newInMemoryRandomAccessStream();varop=randomAccessStream.WriteAsync(imageData.AsBuffer());op.Completed=(info,status)=>{randomAccessStream.Seek(0);Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,()=>{BitmapImagebiImg=newBitmapImage();biImg.SetSource(randomAccessStream);ImageSourceimgSrc=biImgasImageSource;currentImage.Source=imgSrc;});};}privatevoidMainPage_Unloaded(objectsender,objectargs){// 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.

usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Text;usingSystem.Threading.Tasks;namespacePIRSensorApp{publicstaticclassCloudService{publicstaticvoidPushData(stringdateTime,byte[]image,stringcameraId){// Create a new webrequest to the mentioned URL. WebRequestwebRequest=WebRequest.Create("http://www.MYAZURECLOUDSERVICE.com");webRequest.Method="POST";varheaderCollection=newWebHeaderCollection();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.IAsyncResultasyncResult=(IAsyncResult)webRequest.BeginGetResponse(newAsyncCallback(RespCallback),null);// Release the WebResponse resource.}privatestaticvoidRespCallback(IAsyncResultasynchronousResult){//do nothing. We dont want to perform any action with this.}}}