Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Mastering Internet of Things
Mastering Internet of Things

Mastering Internet of Things: Design and create your own IoT applications using Raspberry Pi 3

eBook
£20.98 £29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Mastering Internet of Things

Creating a Sensor to Measure Ambient Light

In the previous chapter, you learned how to create a Universal Windows Platform application and execute it on the Raspberry Pi. You also learned how to do basic I/O with your Arduino board and connected peripherals.

In this chapter, we'll focus more on how to build a real sensor firmware, and prepare it for use in the Internet of Things. The chapter covers:

  • Sampling
  • Error correction
  • Physical quantities
  • Basic statistics
  • Data persistence

Preparing our project

Following the same steps as outlined in the previous chapter, we will create a new Universal Windows Platform application project. This time, we call it Sensor. We can use the same hardware setup as in the previous chapter, even though we will only use the light sensor and motion detector (PIR sensor) in this project. We will also add the latest version of a new NuGet package, the Waher.Persistence.FilesLW package. This package will help us with data persistence. It takes our objects and stores them in a local object database. We can later load the objects back into the memory and search for them. This is all done by analyzing the metadata available in the class definitions, so there's no need to do any database programming. Go ahead and install the package in your new project.

The Waher.Persistence.Files package contains similar functionality, but it...

Sampling raw sensor data

After the database provider has been successfully registered, the persistence layer is ready to be used. We now continue with the first step in acquiring the sensor data: sampling. Sampling is normally done using a short regular time interval. Since we use the Arduino, we get values as they change. While such values can be an excellent source for event-based algorithms, they are difficult to use in certain kinds of statistical calculations and error-correction algorithms. To set up the regular sampling of values, we begin by creating a Timer object from the System.Threading namespace, after the successful initialization of the Arduino:

this.sampleTimer = new Timer(this.SampleValues,  
   null, 1000 - DateTime.Now.Millisecond, 1000);

This timer will call the SampleValues method every thousand milliseconds, starting the next second. The second parameter...

Performing basic error correction

Values we sample may include different types of errors, some of which we can eliminate in the code to various degrees. There are systematic errors and random errors. Systematic errors are most often caused by the way we've constructed our device, how we sample, how the circuit is designed, how the sensors are situated, how they interact with the physical medium and our underlying mathematical model, or how we convert the sampled value into a physical quantity. Reducing systematic errors requires a deeper analysis that goes beyond the scope of this book.

Random errors are errors that are induced stochastically and are often unbiased. They can be induced due to a lack of resolution or precision, by background noise, or through random events in the physical world. While background noise and the lack of resolution or precision in our electronics...

Converting to a physical quantity

It is not sufficient for a sensor to have a numerical raw value of the measured quantity. It only tells us something if we know something more about the raw value. We must therefore convert it to a known physical unit. We must also provide an estimate of the precision (or error) the value has.

A sensor measuring a physical quantity should report a numerical value, its physical unit, and the corresponding precision, or error of the estimate.

To avoid creating a complex mathematical model that converts our measured light intensity into a known physical unit, which would go beyond the scope of this book, we convert it to a percentage value. Since we've gained a factor of five of precision using our averaging calculation, we can report two decimals of precision, even though the input value is only 1,024 bits, and only contains one decimal...

Illustrating measurement results

Following image shows how our measured quantity behaves. The light sensor is placed in broad daylight on a sunny day, so it's saturated. Things move in front of the sensor, creating short dips. The thin blue line is a scaled version of our raw input A0. Since this value is event based, it is being reported more often than once a second. Our red curve is our measured, and corrected, ambient light value, in percent. The dots correspond to our second values. Notice that the first two spikes are removed and don't affect the measurement, which remains close to 100%. Only the larger dips affect the measurement. Also, notice the small delay inherent in our algorithm. It is most noticeable if there are abrupt changes:

Removal of spikes

If we, on the other hand, have a very noisy input, our averaging algorithm helps our measured value to stay...

Calculating basic statistics

A sensor normally reports more than the measured momentary value. It also calculates basic statistics on the measured input, such as peak values. It also makes sure to store measured values regularly, to allow its users to view historical measurements. We begin by defining variables to keep track of our peak values:

private int? lastMinute = null; 
private double? minLight = null; 
private double? maxLight = null; 
private DateTime minLightAt = DateTime.MinValue; 
private DateTime maxLightAt = DateTime.MinValue; 

We then make sure to update these after having calculated a new measurement:

DateTime Timestamp = DateTime.Now; 
 
if (!this.minLight.HasValue || Light < this.minLight.Value) 
{ 
   this.minLight = Light; 
   this.minLightAt = Timestamp; 
} 
 
if (!this.maxLight.HasValue || Light > this.maxLight.Value) 
{ 
   this.maxLight = Light; ...

Defining data persistence

The last step in this chapter is to store our values regularly. In later chapters, when we present different communication protocols, we will show how to make these values available to users. Since we will use an object database to store our data, we need to create a class that defines what to store. We start with the class definition:

[TypeName(TypeNameSerialization.None)] 
[CollectionName("MinuteValues")] 
[Index("Timestamp")] 
public class LastMinute 
{ 
   [ObjectId] 
   public string ObjectId = null; 
}

The class is decorated with a couple of attributes from the Waher.Persistence.Attributes namespace. The CollectionName attribute defines the collection in which objects of this class will be stored. The TypeName attribute defines if we want the type name to be stored with the data. This is useful, if you mix different types of...

Storing measured data

We are now ready to store our measured data. We use the lastMinute field defined earlier to know when we pass into a new minute. We use that opportunity to store the most recent value, together with the basic statistics we've calculated:

if (!this.lastMinute.HasValue) 
   this.lastMinute = Timestamp.Minute; 
else if (this.lastMinute.Value != Timestamp.Minute) 
{ 
   this.lastMinute = Timestamp.Minute; 

We begin by creating an instance of the LastMinute class defined earlier:

LastMinute Rec = new LastMinute() 
{ 
   Timestamp = Timestamp, 
   Light = Light, 
   Motion= D8, 
   MinLight = this.minLight, 
   MinLightAt = this.minLightAt, 
   MaxLight = this.maxLight, 
   MaxLightAt = this.maxLightAt 
}; 

Storing this object is very easy. The call is asynchronous and can be executed in parallel, if desired. We choose to wait for it to complete, since we...

Removing old data

We cannot continue storing new values without also having a plan for removing old ones. Doing so is easy. We choose to delete all records older than 100 minutes. This is done by first performing a search, and then deleting objects that are found in this search. The search is defined by using filters from the Waher.Persistence.Filters namespace:

foreach (LastMinute Rec2 in await Database.Find<LastMinute>( 
   new FilterFieldLesserThan("Timestamp",  
   Timestamp.AddMinutes(-100)))) 
{ 
   await Database.Delete(Rec2); 
} 

You can now execute the application, and monitor how the MinuteValues collection is being filled.

Summary

In this chapter, you've been shown how to create a simple sensor app for the Raspberry Pi using C#. You've learned how to sample data, correct for common sampling errors, work with physical quantities, and calculate basic statistics. You've also learned how to use a local object database for persisting this data, and delete it when it's considered old. In the next chapter, you will learn the basics of creating a working actuator.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Design and implement state-of-the-art solutions for the Internet of Things
  • • Build complex projects using motions detectors, controllers, sensors, and Raspberry Pi 3
  • • A hands-on guide that provides interoperable solutions for sensors, actuators, and controllers

Description

The Internet of Things (IoT) is the fastest growing technology market. Industries are embracing IoT technologies to improve operational expenses, product life, and people's well-being. Mastering Internet of Things starts by presenting IoT fundamentals and the smart city. You will learn the important technologies and protocols that are used for the Internet of Things, their features, corresponding security implications, and practical examples on how to use them. This book focuses on creating applications and services for the Internet of Things. Further, you will learn to create applications and services for the Internet of Things. You will be discover various interesting projects and understand how to publish sensor data, control devices, and react to asynchronous events using the XMPP protocol. The book also introduces chat, to interact with your devices. You will learn how to automate your tasks by using Internet of Things Service Platforms as the base for an application. You will understand the subject of privacy, requirements they should be familiar with, and how to avoid violating any of the important new regulations being introduced. At the end of the book, you will have mastered creating open, interoperable and secure networks of things, protecting the privacy and integrity of your users and their information.

Who is this book for?

If you're a developer or electronic engineer and are curious about the Internet of Things, this is the book for you. With only a rudimentary understanding of electronics and Raspberry Pi 3, and some programming experience using managed code, such as C# or Java, you will be taught to develop state-of-the-art solutions for the Internet of Things.

What you will learn

  • • Create your own project, run and debug it
  • • Master different communication patterns using the MQTT, HTTP, CoAP, LWM2M and XMPP protocols
  • • Build trust-based as hoc networks for open, secure and interoperable communication
  • • Explore the IoT Service Platform
  • • Manage the entire product life cycle of devices
  • • Understand and set up the security and privacy features required for your system
  • • Master interoperability, and how it is solved in the realms of HTTP,CoAP, LWM2M and XMPP

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 28, 2018
Length: 410 pages
Edition : 1st
Language : English
ISBN-13 : 9781788397483
Vendor :
Raspberry Pi
Category :
Concepts :

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Mar 28, 2018
Length: 410 pages
Edition : 1st
Language : English
ISBN-13 : 9781788397483
Vendor :
Raspberry Pi
Category :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£169.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£234.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 94.97
Internet of Things with Raspberry Pi 3
£20.99
Mastering Internet of Things
£36.99
Internet of Things for Architects
£36.99
Total £ 94.97 Stars icon
Banner background image

Table of Contents

17 Chapters
Preparing Our First Raspberry Pi Project Chevron down icon Chevron up icon
Creating a Sensor to Measure Ambient Light Chevron down icon Chevron up icon
Creating an Actuator for Controlling Illumination Chevron down icon Chevron up icon
Publishing Information Using MQTT Chevron down icon Chevron up icon
Publishing Data Using HTTP Chevron down icon Chevron up icon
Creating Web Pages for Your Devices Chevron down icon Chevron up icon
Communicating More Efficiently Using CoAP Chevron down icon Chevron up icon
Interoperability Chevron down icon Chevron up icon
Social Interaction with Your Devices Using XMPP Chevron down icon Chevron up icon
The Controller Chevron down icon Chevron up icon
Product Life Cycle Chevron down icon Chevron up icon
Concentrators and Bridges Chevron down icon Chevron up icon
Using an Internet of Things Service Platform Chevron down icon Chevron up icon
IoT Harmonization Chevron down icon Chevron up icon
Security for the Internet of Things Chevron down icon Chevron up icon
Privacy Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(4 Ratings)
5 star 75%
4 star 0%
3 star 0%
2 star 0%
1 star 25%
William J. Miller Jul 27, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Mastering Internet of Things - provides a broad overview of IoT from a protocol prospective and helps an owner of a Rayberry PI 3 B+ be able to utilize Microsoft 10 IoT Core Operating System. It also helps the user to learn more about device provisioning and how to read data using XEP SensorData and to perform control actions using XEP Control. Many of the aspects discussed can be found in the IEEE Open Source Repository as new standard for IoT developed by IEEE SA..
Amazon Verified review Amazon
Wilson Apr 17, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As I'm writing this, a judge ruled that Oracle my collect billions from Google for its use of Java on Android. So this book enabling you to leverage your C# skills on Windows rather than just Java is prescient. Additionally, this book covers the XMPP protocol which is more secure and "free" than those more widely supported by vendors. This means that by following the book's step-by-step instructions you'll end up with real security, end-to-end on a peer network that that doesn't require payment to a cloud vendor.
Amazon Verified review Amazon
Naveen Nov 03, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is very helpful
Amazon Verified review Amazon
Brennan Jan 05, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I'm not sure who that target audience of this book is supposed to be. I've done a little bit of tinkering with Arduino, electronics, and am fluent with programming. This book has almost no value to me. At best, it gave a tiny bit of teaser for a few protocols I can Google to find out more about.It is extremely specific and only has value if you are planning on installing Windows 10 IoT on your Raspberry Pi and programming it in C#. The vast majority of people working with the Pi and Arduino are not using C#. It really applies more to the corporate enterprise employee that runs a .NET stack. It's too targeted to that; there's very little information here that can be applied to other platforms.It's not for novices to electronics because it has you building things with mains AC with only half a page of explanation of what is being built and a single sentence that says "Be sure to follow appropriate safety regulations when working with electricity". If you are going to have people splicing wires into live household AC then I think a little bit more precaution and explanation is needed for readers who don't know what they are doing. The book assumes you already know to build circuits and read schematics.At the same time, it's not for people experienced with electronics either because it wastes time describing what a relay is, how to light an LED with a resistor using Ohm's Law.It's not for programmers, because it dedicates an ENTIRE chapter going into the basics of what HTTP is. The book assumes you are already fluent with C# so not sure how you can get to that point without knowing what HTTP and a URL is.It's doesn't give a wide view of the IoT landscape and what other vendors and platforms are available out there. I was disappointed that there was no talk about hardware platforms that are more suitable for IoT like the ESP8266 or Photon. Not a single mention of other IoT platforms like those from AWS or Google.This book really needs to cut out all the code, just be an overview book, go into more detail, and add more topics—it's of no value if you aren't intending to install Windows on your Pi. Or it needs to make it clearer and be called something like IoT with Windows and C#.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.