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

Arrow left icon
Profile Icon Peter Waher
Arrow right icon
Can$34.98 Can$49.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (4 Ratings)
eBook Mar 2018 410 pages 1st Edition
eBook
Can$34.98 Can$49.99
Paperback
Can$61.99
Subscription
Free Trial
Arrow left icon
Profile Icon Peter Waher
Arrow right icon
Can$34.98 Can$49.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (4 Ratings)
eBook Mar 2018 410 pages 1st Edition
eBook
Can$34.98 Can$49.99
Paperback
Can$61.99
Subscription
Free Trial
eBook
Can$34.98 Can$49.99
Paperback
Can$61.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781788397438
Vendor :
Raspberry Pi
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 Can$6 each
Feature tick icon Exclusive print discounts
$279.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 Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 158.97
Internet of Things with Raspberry Pi 3
Can$34.99
Mastering Internet of Things
Can$61.99
Internet of Things for Architects
Can$61.99
Total Can$ 158.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.