Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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
€29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
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
Estimated delivery fee Deliver to Belgium

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to Belgium

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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
€18.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
€189.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
€264.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

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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela