IoT in .NET with a Raspberry Pi, Azure IoT Hub, and Xamarin
An IoT Home Security Project
Back in November 2017 I blogged about a small home IoT project, wiring up garden lights and my garage to the internet through a Spark Core IoT device, accessed via a Xamarin app. That was so fun, I got more ideas and thought I’d do it again with a much more ambitious project. A fully automated and autonomous, IoT home security system.
I wasn’t going to get in to the nitty gritty details of exactly what my home security system build consisted of, but rather hoped to broadly explain how I went about building this. However, there was some interest in the security system aspect of this, so this blog is a little, actually a lot, longer now, with discussion of what I achieved and how.
However if all you want is to check out the Raspberry Pi .NET Core code and the Xamarin Forms app, and how you can get a head start with a .NET IoT project yourself, just go straight to my GitHub sample code.
Overview of my Home IoT Security System build
My goals were to replace my previous IoT project with this new one, wire up my other existing garden/deck lighting, and more importantly, build that automated and autonomous home security alarm system.
This is basically what I set out to achieve:
- Have this system connected securely to the internet 24/7, including apps for me and my wife. (I am lucky enough to have a super fast, super reliable, fibre to the premise internet connection that hardly ever goes down)
- Security as number 1 priority, so all sensors to be physically wired, no wireless Zigbee/Z-Wave, etc
- Indoor and outdoor motion sensors
- Know when me or my wife are home to arm and disarm automatically
- Arm the outdoor motion sensors automatically at night, even if we are home
- Disarm the outdoor motion sensors automatically via beacons if we step outside at night
- Arm the indoor sensors while we are sleeping via beacons sitting near our phone chargers, and also auto disarm if we decide to make a trip to the kitchen for water
- Send us rich push notifications whenever sensors were tripped, including a security camera snapshot of the outdoor area tripped
- Send push notifications whenever the alarm is tripped, and turn all Hue lights to red colour when this happens
- Poll the front door Ring Video Doorbell for motion/ding, and send a rich push notification with a security camera snapshot
- Get push notifications if someone left home and forgot to close the garage door, or went to bed without closing the garage door
- Some other niceties like waking my home PC via the app, temperature sensor to turn the network cabinet fan on or off, disable the Pi-Hole for 30s or 5 minutes
- Decommission my November 2017 IoT garden/garage project and roll it in to this one
- Add my existing backyard garden lights and deck lights to this new system, as well as turning the office desk LED strip light on/off
- Wire this up myself, it’s an all low voltage 12v system
That’s a bit of a list, but after over 3 months working on this in my spare time, my new IoT project is finally all set up and operational!
In this blog I’ll detail some of my decisions in how I achieved this, while also providing most of the source code so you can quickly get started doing something similar yourself, all in .NET! If you’re not into .NET you can most definitely use Azure IoT Hub with Java, Node.js or Python on a Raspberry Pi.
And just a quick word about electronics and power, only ever work with safe low voltages, but even then, it can still be dangerous so always take extreme caution and get help from an electrician if your project requires it.
IoT Hardware and Platform
If you’ve read my previous blog you’ll know I used a Spark Core, which I bought many years back via a kickstarter campaign. They have a newer version called the Photon, and since I loved working with the Spark Core and Particle Cloud, I bought the new Photon with a relay shield. The Particle Cloud can connect to Azure IoT Hub, so via events I was going to build a microservice to listen to these for any required actions.
After getting a good way through this build, I changed my mind in a big way. I moved from the Particle with Relay Shield, to a Raspberry Pi 3 and Arduino compatible relay boards. Not that I didn’t like the Photon, but I had a realisation I can run .NET Core on Linux on these Pi’s! This will effectively allow me to build a “monolith” application, and not rely on additional services or serverless computing. All I needed in the cloud was Azure IoT Hub and a push notification service.
Why not a Netduino? Netduino has recently garnered some attention, especially in the Xamarin community since it appeared on a The Xamarin Show episode with James Montemagno. I looked into it and the .NET MicroFramework looked limiting to me, no support for Azure IoT Hub or other Nuget packages that I could see, and you have to interface with it by calling an endpoint on the Netduino directly via IP address?
An Azure IoT Hub device can live safely behind your home internet firewall without opening any ports.
Running a .NET app on a Raspberry Pi
Why .NET? I’m a .NET developer! But more importantly:
- There are various libraries on Nuget for driving the GPIO (general purpose input/output) pins of a Raspberry Pi, including official Azure IoT Hub libraries
- I can use .NET Core to run .NET apps in a Linux environment
- You can install Windows 10 IoT Core on a Raspberry Pi 2/3 and run .NET apps there too
- I can reuse code between the device and the Xamarin app
.NET Apps on Windows 10 IoT Core
I tried writing a UWP app interfacing with the GPIO pins and running it as a service on Windows 10 IoT Core via the task scheduler, but writing a UWP app seemed daunting to me as I found it quite different to other .NET/Xamarin apps. However the debugging experience, pressing play in Visual Studio, and interacting with your code directly hooked up to the GPIO pins, was great! I miss that, but I ultimately decided not to pursue this further.
.NET Apps on Linux on the Raspberry Pi
I’ve been using .NET Core in Linux Docker containers for a while, so my decision to write this in .NET Core 2 in C# was easy. Especially since I could run the app on the officially supported OS for the Raspberry Pi, which is Raspbian Linux in headless mode, as I felt stability would also be much higher there.
Interacting with the physical world
Interacting with the physical world and designing the hardware was probably the easy part. However climbing in and out of my roof, drilling holes and wiring everything up is not for everyone. So please get help if you need to do and aren’t comfortable with it.
Your IoT project most possibly will be completely different to mine, however as I’ve had interest from some people that they would like to know about my particular build, I’ll talk about it here. Hopefully it gives you some insights in to what went in to getting the hardware side of things all wired up, and how it might translate to your project.
My project consisted of:
- Raspberry Pi 3 Model B
- 5.1V DC 2.5A Micro USB Raspberry Pi Official Power Supply, supplying the recommended power to power the Pi including any attached 3.3v/5v components you might require
- 12v 8 Channel Relay Board, used to wire up the garden/deck lights, strobe and sirens, and a network cabinet fan. The good thing about these 4 or 8 channel boards is that they have optical isolation. That means that there is isolation between the Raspberry Pi and the relays, their switching transistors and power supply, more info here.
- Single Relay Board, this was used to wire up to the garage door remote button to simulate presses (see my previous blog here)
- Outdoor Dual Passive Infra Red & Microwave Motion Detectors, these are great but quite bulky, however required to reduce false alarms to a minimum in an outdoor environment. The 2 PIR’s and the microwave sensor have to all be tripped together to activate the alarm. Strong sunlight changes through clouds did trip the sensors though, so I set the sensitive of these to LOW. And they still get tripped :( I might have to further reduce the sensitivity.
- Indoor Passive Infra Red (PIR) Detectors, for the indoor motion sensors
- Roller shutter garage door reed switch, (detect if garage door is open or closed)
- 2x Outdoor Siren/Strobe, one at the front, and one at the back of the house
- Touch Button with LED light, for replacing the wallplate garage remote with this button, which when pressed will trigger the single relay to simulate the garage door button been pressed (the wallplate garage remote will still be in use to activate the garage, just live elsewhere)
- AM2302 (wired DHT22) temperature-humidity sensor, I use this to automatically turn the network cabinet fan on and off depending on the temperature
- 10mm Blue LED, as a blinking heartbeat monitor
- 12V DC Powerpack, to provide power for the components which are all 12V, including the 8 channel relay board, the motion detectors, strobe and sirens, network cabinet fan and touch button
- Ring Video Doorbell, with a 24v AC Power Supply and resistor, it’s a good idea to wire this up to power instead of needing to recharge it all the time, and via an unofficial API I can detect motion at my front door
- Various bits and pieces to house and connect everything up
- Ubiquiti UniFi Security Cameras and NVR which I’ve already had installed. The good thing about this UniFi system is that they provide an API to interface with and get live video camera snapshots, not to mention the great native app they offer
- Garden Light Transformer and wiring to power the front and back yard garden lights
- Various 12v Garden Lights (which I already had)
- 12v Deck Lights (which I already had, similar to these)
Depending on your project, installing and wiring things up might require you to get an electrician.
I was initially going to put an outdoor motion sensor at my front door, however as stated above I had a realisation that I could instead buy a Ring internet connected Video Doorbell, and poll it’s (unofficial) API for motion. I got the idea thanks to this blog post, and I think a Ring Video Doorbell looks much more nicer than a motion sensor on the roof there somewhere :) However contrary to that blog, it should poll the Ring API every 5 seconds, not 15 as you might miss events. I also disabled motion alerts on the Ring app as they got replaced by the rich push notifications in this IoT project.
Another benefit was that, we didn’t want to receive motion alerts when we walked passed the front door. So via Estimote Beacons, if me or my wife walked past the front door, no motion notifications would get sent, as the system knows it was one of us. If you require this functionality, this code is included in my IoT Getting Started GitHub repo.
Planning the PIN connections and housing the Pi and components
I planned all the hardware setup and PIN connections via spreadsheets and plain old paper + photos, so it was basically just a matter of placing everything in the housing enclosure, drilling holes for various length nylon spacers to screw the boards in place, creating the connection board, screwing in and soldering everything up.
I also hard wired the pull-up/pull-down 10K resisters on the board for each sensor (same schematic as my previous IoT project). To understand more about pull-up/pull-down resistors, and why it’s required, take a look at this Arduino guide (note my circuit is flipped around, sensors/buttons are attached to ground not to 3.3v/5v). You can also enable pull-up and pull-down resistors via software, as most hardware boards have these installed by the manufacturer, but I think it’s worthwhile adding these in your own hardware circuit boards.
An issue I realised after I wired the 2 backyard sensors, is that I wanted to combine the 2 tamper and 2 mask outputs to a single tamper and mask output. They are in the same area, and I have a camera pointed in that direction, so there was no point having them separate as I could also save 2 GPIO pins on the Raspberry Pi. Since I had already installed the backyard sensors and soldered all the cabling already, I didn’t want to rewire this. Enter a transistor AND gate. This is basically the same as programming an AND statement, in the physical world! Thanks to iCircuit I could simulate my AND gate before I bought the transistors and 4.7K and 10K resistors and soldered them on to my sensor board.
So now I could feel confident, using 3 PNP transistors (not NPN because my sensor connections are connected to ground), I could build an AND gate so that even if 1 of the 2 tamper/mask sensors are tripped, the alarm will activate.
Below is my completed hardware in its housing enclosure.
Software — Raspberry Pi Appliance
Let’s start on the software side of things now, the brain of the IoT system.
The goals of my software appliance were to:
- Use Raspbian as the Linux operating system for the Raspberry Pi, as I believe this will be the most reliable OS
- Use .NET Core 2 with Azure IoT Hub to connect the physical world to the internet
- Use AWS SNS Mobile Notifications to send push notifications (you can use Azure but I am already familiar with AWS SNS)
- Use Unosquare.Raspberry.IO to interface with the Raspberry Pi’s hardware modules. Note that I didn’t use the Nuget package as it was out of date, but instead built the DLL from the source for my project
- Use systemd to manage the .NET Core service in Raspbian, automatically start it on boot, and keep it alive, restarting it if anything goes wrong
Below are the steps involved for installing everything required on a Raspberry Pi and your development machine, and simply running
build.sh to deploy your app to the Raspberry Pi. Clone my repo, set up Azure IoT Hub, attach some components, and you’ll be quickly up and running with an IoT project! Note that you can also simply just press F5 in Visual Studio to get a simulation up and running if you don’t yet have a Raspberry Pi and components yet. I also want to thank Jeremy Lindsay for blogging about this kind of stuff already, which really helped me get started.
Setting up the Raspberry Pi
Install Raspbian onto an SD card, enable SSH, and insert into your Raspberry Pi. Instructions are on Jeremy’s blog so I won’t repeat here. Remember to add a blank file called
ssh in to the root of the SD card so you can SSH in. Attach a network cable to your Raspberry Pi, wait a bit for it to boot and to get an IP address, and then you should be able to SSH in to it by executing this command in bash
ssh pi@raspberrypi with password
Update Raspbian and ensure all the latest updates and packages have been applied:
sudo apt-get update -y && sudo apt-get dist-upgrade -y && sudo apt-get upgrade -y
Ensure the latest Raspberry Pi firmware has been applied:
sudo apt-get install rpi-update && echo Y | sudo rpi-update
Install .NET Core 2 on the Raspberry Pi (thanks to this blog):
NOTE: This is not needed if you can make your .NET Core app self contained.
To get access to the GPIO pins via
Unosquare.Raspberry.IO, I had to install wiringpi.
sudo apt-get install wiringpi
I then went in to the Raspberry Pi config
sudo raspi-config and updated my locale and timezone settings. Once all done, then
Once you SSH back in, you should be able to run
dotnet --info and confirm .NET Core is successfully installed. You can then keep following Jeremy’s blog and create a .NET Core app from his template, or you can clone my getting started repo and start from there. https://github.com/michaeldimoudis/raspberrypi-xamarin-iot
My getting started repo has complete working code, and the architecture I used for my Raspberry Pi home security application, as well as a demo Xamarin Forms app which I’ll talk about briefly later.
Remember to add the credentials for your Azure IoT Hub in
Config.cs. If you don’t yet have a Raspberry Pi or any components attached to it, just press play in Visual Studio in debug mode and you’ll be able to play with Azure IoT Hub, see the led blinking in the console, as well as call direct methods from Azure IoT Hub in a simulated console environment.
Building and deploying the app to a Raspberry Pi is made very simple with Cake build. Once again this is thanks to Jeremy’s blog, and made the build and deploy also work on a Mac. Update the
build.cake file with you Raspberry Pi’s IP address and password, as well as the destination directory (you need to create this on your Raspberry Pi), run
build.ps1 on Windows in Powershell, or
chmod +x build.sh) on a Mac, and this will build and deploy the app straight to the Raspberry Pi.
Via SSH go into your app’s folder, and run the console application by issuing command
Interfacing with the GPIO Pins
My sample project has a few already configured components to interface with, including a blinking LED, 4 channel relay board, a button and an AM2302 temperature/humidity sensor.
In the sample code, the 4 channel relay board connects to WiringPi pins set in the Enums, with COM attached to GND on the Pi, an LED, a button, and an AM2302 thermometer. Add your Azure IoT Hub Device connection string, and you should be able to build and deploy to a Raspberry Pi, see the LED start blinking, push the button to see a relay turn on and off, and go in to the “Direct Method” Azure IoT Hub device blade, “Invoke Method” for method name “ToggleGardenLights”, and you should the see a different relay toggle. Exciting!
If you have some or all these components, getting started is easy.
Note that the standard GPIO pin numbers are completely different to the WiringPi pin numbers. A lot more information on the Pi hardware access from .NET is available at the RaspberryIO GitHub, but below is a short cut down version. Not you must use the wPi pin numbers.
Setting up Azure IoT Hub
The heart of the integration is done with Azure IoT Hub which is quite awesome, and free for simple/test projects. At a high level, in Azure, you create an IoT Hub, add a Device, get the connection string, and you’re basically up and running.
When using the Azure IoT Hub Devices Client SDK, be sure to use the MQTT protocol. This is for per-device authentication, so 1 device with 1 connection string. You can then be sure you are communicating with that device, and check if that device is connected by querying its Device Twin.
Simply put, a device twin is device metadata and state information where you can query, store and synchronise data with a device. In my case I mainly use the reported and desired properties.
Whenever something like a relay state changes, or whenever the home state of me or my wife changes (at home, sleeping, at the backyard or front door etc), they are reported states, and we can have an accurate state representation in the app. I paired this with a silent push notification to update the app on our devices for immediate updates.
I update desired properties, via the mobile app, when an occupant state changes, such as arriving or leaving home, entered the bedroom or front door area, etc. Once this desired property is updated, a callback event is immediately issued on the Raspberry Pi device via the
SetDesiredPropertyUpdateCallbackAsync method. That means the device appliance can arm or disarm the home or certain zones immediately. For example, when we are sleeping (inside the bedroom beacon zone), the indoor sensors are armed. If I grab my phone and walk out to the kitchen for a glass of water, I’m very confident the beacon exited event will fire in the app, update the desired property, and call in to the Raspberry Pi disarming my indoor sensors. This happens very quickly and works great.
Most of the in-app interactions are done via direct methods. From the docs, “Direct methods represent a request-reply interaction with a device similar to an HTTP call in that they succeed or fail immediately”. For example, if I toggle a garden light, I receive an immediate response back if that light is now on or off. This is blazingly fast too! I’m in Melbourne Australia, and talking to the Azure Data Centre in Melbourne, I could toggle relays (with a response back with the new state of the relay) in 20 milliseconds!! However it’s more common to be around the 70–80ms range, especially on 4G. Check out this below tweet that went viral (for my standards).
In the Azure Portal you can select a storage container for your IoT Hub and upload blobs directly to that container via the Microsoft Azure IoT Device Client SDK. You can see how simple this code is in the
SendRichPushNotificationHandler where I get a camera snapshot stream and upload it to an Azure Storage Account via
Message to Device
There’s also the ability of sending a message to a device, however I didn’t find that I needed this in my IoT project.
A Timer Service
Usually with IoT, you might want some kind of timed events. For example, turn lights on at sunset, or turn them off at sunrise. Or, if motion has been detected, sound the siren for 2 minutes, however keep the strobe on for 20 minutes. In the sample code, I have implemented a
TimerService where you can add, enable or disable
TimedEvents in a
TimerService ticks every second and checks if any events are set to trigger for that second.
It works great for me, and I’m using a
TimerClock provided by Nima Ara in a library called Easy.Common. The TimerClock raises the
Easy.Common.TimerClock.Tick event every second (in my case), and it’s so much more elegant then a for loop with
Task.Delay(1000), let alone more accurate. Check out
Easy.Common, it’s a pretty awesome library and I’m using a few of its other awesome features, such as
The Mediator Design Pattern and Mediatr
If you haven’t heard about the mediator design pattern in software engineering, you might be interested to look in to it. To make this design pattern even easier to implement, there’s an awesome simple mediator implementation in .NET by Jimmy Bogard called Mediatr. It’s great, and can be a blog post on its own, as this one by Steve Gordon is. Simply put, this allows .NET objects to no longer communicate directly with each other, but instead communicate through Mediatr via simply injecting the
IMediator interface in the constructor. The benefits are that it will make the code more decoupled, just send a command via Mediatr and its in-process messaging handler will pick it up. This also makes code easier to unit test and debug.
I’ve used Mediatr quite extensively to pass commands and notifications around when actions occur. Such as when a sensor in the sensor board gets tripped, a command to send a push notification, toggle a relay, or update a device twin reported property, is fired.
Once you have everything set up and ready for production, you’ll want to start the .NET Core service whenever your Raspberry Pi boots up, and to also restart the service if the .NET Core service happens to fault or terminate. Here is where systemd comes in to play.
Basically, you need to define a service to run your app via a service definition file in the
/lib/systemd/system/ folder. For the sample device Appliance app, we’ll create an Appliance service.
sudo nano /lib/systemd/system/Appliance.service
Next, you’ll need to define that service. Here’s what works for me:
Note that I require the service to have a network connection before it’s attempted to be started, as it will crash out trying to access Azure IoT Hub and Azure KeyVault. I’ve also add Watchdog StartLimit* parameters to reboot the Raspberry Pi if a burst of fatal crashes occur. This makes the system a little bit more robust and resilient to various issues that might happen.
You’ll need to set the appropriate permissions on that file, and most importantly, when you add or modify a service, you need to reload the daemon.
sudo chmod 644 /lib/systemd/system/Appliance.service
sudo systemctl daemon-reload
Then you can enable the service:
sudo systemctl enable Appliance.service
Start the service:
sudo systemctl start Appliance.service
Check its status:
sudo systemctl status Appliance.service
sudo systemctl stop Appliance.service
sudo systemctl disable Appliance.service
And check the service’s log:
sudo journalctl -f -u Appliance.service
sudo journalctl -u Appliance.service
That’s basically it for running your .NET Core app as a service on a Raspberry Pi. systemd has never failed me, ̶a̶n̶d̶ ̶I̶ ̶d̶o̶n̶’̶t̶ ̶b̶e̶l̶i̶e̶v̶e̶ ̶I̶’̶v̶e̶ ̶e̶v̶e̶r̶ ̶s̶e̶e̶n̶ ̶t̶h̶e̶ ̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶ ̶r̶e̶s̶t̶a̶r̶t̶ ̶d̶u̶e̶ ̶t̶o̶ ̶a̶ ̶n̶o̶n̶ ̶f̶o̶r̶c̶e̶d̶ ̶i̶n̶d̶u̶c̶e̶d̶ ̶f̶a̶u̶l̶t̶. A well set out guide on understanding systemd can be found here.
September 2018 Update: The application has in fact faulted a few times since I initially published this article. Most faults have occurred after the .NET Core 2.1 update, including this issue occasionally happening https://github.com/dotnet/coreclr/issues/18486. Also AWS SDK and Azure Application Insights were not using reusing HttpClient (which they have since fixed), causing issues with the new 2.1 HttpClient. So below I will detail some additional stability improvements you can make for the Raspberry Pi.
Increase Raspberry Pi Stability
Activate watchdog (for RPI 2 and more recent) by editing:
sudo nano /etc/systemd/system.conf
Prevent SD card corruption
Disable Swap mechanism to increase the life of the SD card.
sudo systemctl stop dphys-swapfile
sudo systemctl disable dphys-swapfile
sudo apt-get purge dphys-swapfile
Enable OverlayFS makes the SD card read only. This will help prevent the file system from getting corrupted if the Raspberry Pi is not shut down properly.
sudo wget https://github.com/ppisa/rpi-utils/raw/master/init-overlay/sbin/init-overlay
sudo wget https://github.com/ppisa/rpi-utils/raw/master/init-overlay/sbin/overlayctl
sudo chmod +x init-overlay overlayctl
sudo mkdir /overlay
sudo overlayctl install
Get the status of OverlayFS by entering
sudo overlayctl status, enable it with
sudo overlayctl enable, and disable it with
sudo overlayctl disable. Note you need to reboot for the changes to take affect
In conclusion, long-running .NET Core apps run ̶v̶e̶r̶y̶ well on a Raspberry Pi in Linux. You will need to monitor them though, and you can get memory/cpu by running
htop. I also used to run UniFi Controller and Pi-Hole on the same Raspberry Pi, I’ve since moved those off my Home Security Raspberry Pi, and this Pi is only dedicated for my Home Security app. This also increased stability.
Next up, controlling your IoT project with an app!
Xamarin Forms App
The final piece of the puzzle is a Mobile App to control your IoT project, in my case it’s controlling my home security system. For example arming and disarming the system via Geo Location services and beacons, turning garden/deck lights on or off, etc.
In my sample GitHub repo I have provided a simple Xamarin Forms iOS app that connects to Azure IoT Hub and controls some relays. If you need Geo Location or Estimote Beacon examples, they are there too. I did not build an Android version, however it’s in Xamarin Forms so most of the app will work with Android too. You’ll need to write your own Geo Location/Beacon code if you need this on Android.
Azure IoT Hub integration
Installing the Microsoft.Azure.Devices Nuget package allows the app to talk directly to Azure via MQTT. As discussed above in the Azure IoT Hub section, this gives you the ability to securely query the twin, update the twin, and invoke methods on the device.
Note that the credentials for the app side is via the “Shared access policies” for the IoT Hub, and not the device connection string.
Arm and Disarm the Raspberry Pi Home Security Appliance via Geo Location services
I initially had some trouble with the responsiveness of the Geo Location updates. My wife especially did, setting off the alarm whenever she got home opening the garage door (setting off alarm 1) and then walking in to the house (setting off alarm 2), and sending us push notifications that there’s been an intruder, not mentioning probably concerning the neighbours too with sirens going off. Hey at least the system works! Reading up more about iOS Geo Location, Apple documentation, and especially this blog, with some updates to the iOS code, the Geo Location updates became very responsive. No more (well many) false alarms! After fixing this bug, and tweaking the outdoor sensor sensitivity, I then informed my neighbours that now any time the alarm goes off, IT’S FOR REALS!
On location change, the Azure Device Twin Desired Properties are updated, immediately updating the Raspberry Pi Appliance via the
SetDesiredPropertyUpdateCallbackAsync registration, arming/disarming the security system. The same occurs for the beacons, more below.
Your IoT project might benefit from Geo Location services, so hopefully this brief insight helps.
Estimote Proximity Beacons
Geo Location services to know when you are at a certain place, like home or not, and automatically arming/disarming a home security system is a great first step. But I wanted to go a bit further with Beacon technology. I bought Estimote Beacons 2 years ago to play with them but have never used them for something real, now was that chance. I went off and bought 6 brand new Proximity Beacons, as these newer ones are compatible with Estimote Monitoring 2.0, and they’re great!
If you aren’t aware, the standard iOS CoreBluetooth and CoreLocation API’s are good, but they don’t offer much in security or immediate enter/exit events. With Estimote Secure Beacons I could apply security around my beacon installation, and with Estimote Monitoring 2.0 I could install Estimote Proximity Beacons around my home and know that I can get fast enter/exit events.
For example, I have placed a beacon in the master bedroom where we charge our phones while sleeping. If the phones are there at night, it likely means we are sleeping and the indoor motion sensors arm. If someone evades the outdoor sensors and breaks in while we are sleeping, the alarm will go off. However, if we wake up in the middle of the night and need to go in to the kitchen for a drink, we can just take a phone, and know that by the time we are at the bedroom door, the indoor motion sensors would have disarmed.
If you plan on using Estimote beacons, it’s best to use their SDK in your app. For Xamarin developers there is a slight problem though. The Xamarin.Estimote.iOS and Xamarin.Estimote.Android Nuget libraries are old, and Estimote does not provide native Xamarin bindings. Secure beacons are supported in the current Xamarin.Estimote.iOS Nuget package, but not Estimote Monitoring 2.0. I set out to create an iOS binding for the latest Estimote SDK, and got quite far, basically completing it. When I attempted to send a PR I saw that someone else has done the exact same thing. So I’m using that version in the PR in my app, but it’s unfortunate that it hasn’t been merged and uploaded to Nuget so others can use too.
The updated Xamarin.Estimote.iOS PR is in my sample project as a standalone DLL so you can take it from there if you need to. You’ll need to get an Estimote AppID and AppToken via the Estimote Cloud to utilise Secure Beacons and Monitoring V2 Manager.
The sample Xamarin Forms app on GitHub
The sample Xamarin Forms App source code has integration with Azure IoT Hub, Geo Location and Estimote Beacon sample code, as well as the basics of toggling relays via the app. Once again hopefully this will get you up and running quickly.
I’ve been asked about security of IoT in general and that anything connected to the Internet is potentially vulnerable. Which is true, however the bad rep has come from bad manufacturers and their ridiculously lax security. Since my IoT project is a security system, I’ve obviously received more scrutiny from peers :)
I trust Microsoft’s Azure security protocols for the IoT Hub integration, not needing to open any port on my home firewall, an updated Linux distro on a Raspberry Pi that’s not vulnerable to Spectre or Meltdown, using a custom built app not in the App Store, paired together with Secure Beacons by Estimate. I think that’s fairly safe so you shouldn’t be worried about your own IoT project.
Reliable and fast internet connection is probably also a security concern, as well as an uninterruptable power supply attached to this.
Why did I do this instead of buying an off the shelf security system?
- That’s no fun
- Have you seen the apps these companies make? yuck! How is their security? Not as great as Microsoft’s I think…?
- A fully custom built solution, tailored precisely to my needs, is always more rewarding…
- Not to mention how much I’ve learnt :)
This was a really fun, albeit very long and time-consuming project in my spare time. Some parts of the code are a tad sloppy and could do with more refactoring, and especially unit testing. But hopefully this blog has got your IoT creative juices flowing, with a bunch of code to get you up and running quickly. If you have any questions just send them through.
I’ll also be presenting this at the next Melbourne Xamarin Meetup, so if you’re in Melbourne come down on April 15, 2018.
Now go and IoT away!!!