Monday, 9 May 2016

Minimal MQTT: Building a Broker

In this short series, we’re going to get you set up with a completely DIY home automation system using MQTT. Why? Because it’s just about the easiest thing under the sun, and it’s something that many of you out there will be able to do with material on-hand: a Raspberry Pi as a server and an ESP8266 node as a sensor client. Expanding out to something more complicated is left as an exercise to the motivated reader, or can be simply left to mission creep.

We’ll do this in four baby steps. Each one should take you only fifteen minutes and is completely self-contained. There’s a bunch more that you can learn and explore, but we’re going to get you a taste of the power with the absolute minimal hassle.

In this installment, we’re going to build a broker on a Raspberry Pi, which is the hub of your MQTT network. Next time, we’ll get an ESP8266 up and running and start logging some data. After that, we’ll do some back-end scripting in Python to make the data speak, and in the last installment, we’ll explore some of the useful frills and fancy bits. Let’s get started!

Overview

MQTT is a pub-sub, store-and-forward, IoT-enabled, machine-to-machine connectivity protocol juggernaut. As you can see, it’s fully buzzword-compliant. That doesn’t necessarily mean that it’s super complicated, though. You can read up on MQTT until you’re blue in the face. Here’s the bare minimum you need to know to be comfortable.

The network has clients (called “clients”) and servers (called “brokers”). Clients, whether it’s your temperature sensor node or the graphing application that’s going to use the data, use the broker as a central hub. Data are arranged in “topics”, which use a directory-like structure. So the temperature node in my bedroom is called “home/bedroom/temp”. When I add a light sensor to my bedroom node, I’ll set up a topic called “home/bedroom/light” and so on.

When a client gets some new data, it “publishes” it to the topic — sends the data to the server. The server then forwards the data along to all of the other clients that have “subscribed” to the topic. In my example, the bedroom node publishes to “home/bedroom/temp” and then a databasing program which is a subscriber to “home/bedroom/temp” automatically receives it. And so does any other client that’s subscribed to the topic.
Often a given physical device will subscribe to some topics and publish to others.  My heating controller will want to act on the temperature sensors, and display its status on an LED in the bedroom, for instance. There’s naturally more to say, but let’s get our broker up and running first and explore the details later.

Build a Broker

attachment_69370628OK, “build” is a little bit overstated. We’re just going to download mosquitto, which is the most widely-used broker. If you’ve got a Raspberry Pi (or other spare computer) lying around, you’ve got an MQTT broker-in-waiting. Unfortunately, Raspbian comes with an old version of mosquitto by default, so we’ll have to do a tiny bit more typing to get the most recent version. Here’s how I set up a fully-featured MQTT broker on a brand-new Raspberry Pi (Jessie Lite):

curl -O http://ift.tt/1Jo2xYJ
sudo apt-key add mosquitto-repo.gpg.key
rm mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo curl -O http://ift.tt/20kE7aR
sudo apt-get update
sudo apt-get install mosquitto mosquitto-clients

Et voilĂ . Later, when we need to access the broker from the outside world, we’ll need to know the Raspberry Pi’s IP address, but that’s it. You’re up and running. If you’re using an older version of Raspbian, substitute “wheezy” for “jessie” in the fifth line. If you’re using anything other than a Raspberry Pi, you can probably find what you need, including Windows binaries, here. (I haven’t tested Windows or Mac.)

Playing Around

Now that our broker is set, let’s do some quick experiments to get a taste of how MQTT works in practice. The astute among you noticed that I also installed mosquitto-clients. Let’s try them out.

Open up a window and type mosquitto_sub -h localhost -t "test/topic". Congratulations, you’ve just subscribed a client to the “test/topic” topic. -h localhost connects you to an MQTT server on the local machine, rather than on the broader Internet. If we weren’t setting up our own server, I’d have you point to the MQTT test servers. As it is, I’ll just let you know that they’re out there when you need them.

OK, let’s publish our first data. Open up another window and type mosquitto_pub -h localhost -t "test/topic" -m "hello!" Same server, same topic, but now we’re sending a message. You should see the message pop up instantly in the subscribed window.

Try opening up multiple subscriber windows, subscribed to the same topic. You’ll see that they all get the message. Try sending messages to topics that don’t exist yet. What happens?

One last stupid MQTT trick before we get to the important stuff. MQTT can use two different types of wildcards in the topic names. So my network has “home/bedroom/temp” and “home/cellar/temp” topics. I can read all the temperatures by subscribing to “home/+/temp” and get all the values from my bedroom node from “home/bedroom/#”. (“+” matches one hierarchical level, while “#” stands for everything deeper in the tree.) Once you start using wildcards, you’ll want to know which topic is reporting, so try subscribing in verbose mode mosquitto_sub -h localhost -v -t "test/#" and send yourself some test messages to different topics.

Quality of Service

Here is MQTT’s killer feature for a low-power home automation sensor network: it’s a “store and forward” protocol with a couple levels of quality of service (QOS) guarantees. If your node has already registered with the broker and it’s offline when a new message comes in, the broker can take care of delivering that message to the node as soon as it reconnects. This means that your nodes can spend most of their lives in a deep sleep, conserving battery power, and when they do finally connect, they haven’t missed anything.

Three things are needed for the QOS feature: the subscribing clients need to be previously registered by ID with the server, and they need to disable the (default) clean-slate behavior otherwise all stored messages are erased when you log back in. Both the subscriber and the publisher need to be using quality-of-service level one or two so that the server knows it’s a stored message. (QOS level one usually suffices, but feel free to read up.)

Here’s an example:

subscriber:  
    mosquitto_sub -h localhost -v -t "test/#" -c -q 1 -i "james bond"
publisher:
    mosquitto_pub -h localhost -t "test/topic" -m "wowie" -q 1
    mosquitto_pub -h localhost -t "test/topic" -m "zowie"

To demonstrate what QOS does, run the subscriber’s command in one window and send the other two messages to it. You’ll get them both. Now stop the subscriber with ctrl-c and resend both messages. Now, when you subscribe again, you’ll only get “wowie” because it was the message sent with QOS enabled.

One gotcha with IDs is that you’ll only get whatever has happened between IDed logins. You have to be previously registered with the server so that it saves messages for you. You can’t just walk in, give it a new ID, and say “what have I missed?” because it doesn’t know you yet.

Also note that the subscriber must do three things to enable receiving messages with QOS. The ID and QOS levels are obvious. The one I always forget is to disable clean-slate logins with the -c flag. Don’t forget.

Retained Messages

If you don’t need to get the full history of messages since your node was last online, consider the “retain” flag. When messages are sent as retained, the last such message gets automatically transmitted to any client that subscribes to the topic. Retained messages are great for things like status reports. Any time that you want to log in and see just the last value without having to wait for an update, you’ll wish you had retain set. And note that retained messages and QOS aren’t exclusive — just be careful because you’ll get one message (the most recent one) delivered twice.

More??

This was just a taste of the power of having your own MQTT server running. Next, we’ll connect some small devices to the network, and then we’ll build up some back-end processing. If you’ve gotten this far and just can’t wait, try playing around with mosquitto_sub -h test.mosquitto.org -t "hackaday/new_articles" -c -q 1 -i "your_name_here". The stream is published with QOS=1 and retains the last message. Feel free to play around and show us what you build in the comments.


Filed under: Engineering, Hackaday Columns, Network Hacks, Original Art

from raspberry pi – Hackaday http://ift.tt/1XhnMWl
via Hack a Day

Sunday, 8 May 2016

Raspberry Pi Balloon Goes Too High, Goes Boom, But Survives

Some people like to get high on a Wednesday afternoon. [Kevin Hubbard] of Black Mesa Labs likes to get really high. Even higher than intended: last month, he flew a helium balloon powered by a Raspberry Pi to 103,000 feet. It was only supposed to go to 90,000, but a fault in the code for the controller meant that it went higher, burst and plunged to the ground. All thanks to an extra hash mark in his code.

[Kevin] was part of a team called the Balloongineers who are competing in the Global Space Balloon Challenge, a project to simultaneously fly balloons from multiple locations. The Balloongineers entry was called HAB1, built around a Raspberry Pi, an FPGA watchdog system, a uBlox GPS and an Iridium satellite modem. The idea was that their balloon would zoom up to 90,000 feet, where it would release some helium gas, hover, and move eastwards with the prevailing winds. reporting back via satellite as it went. Unfortunately, something went wrong. The balloon didn’t report back properly, and kept on rising, eventually reaching over 100,000 feet, where it burst and fell to earth.

[Kevin] thought all was lost, including the expensive satellite modem that HAB1 used. But the next day, his balloon sent him an email, reporting that it was hale and hearty at an altitude of 300 feet. After recovery, he analyzed HAB1, and figured out what had happened: a single mistyped hash mark had caused the system to lock up when it tried to open the vent to release the gas.

What saved the rig was the foresight [Kevin] had in building it. Although the system didn’t work fully as planned, the FPGA watchdog (nicknamed the Lizard Brain) eventually noticed that the main computer was locked up, and rebooted it, enabling the system to report back to [Kevin]. An additional recovery mode woke the system once an hour sent a location and went back to sleep, which allowed the small battery to keep powering the system until it could get a signal out the morning after. That’s a smart piece of design in a system that allowed them to recover the hardware, even though the main objective of hovering at 90,000 feet wasn’t achieved.

[Kevin] ends his writeup of the flight with a few notes that any engineer would be wise to consider. Primary among these is his decision to have the system check very rarely for manual overrides over the satellite connection. He decided to do this to save money: checking for messages on Iridium costs a certain amount each time you do it. If he had checked more frequently, he might have been able to fix the problem earlier by venting the helium manually, leading to a more controlled descent and recovery. In any project, a failure can only be useful if you can figure out what the problem was, gathering as much information as possible to help you avoid it next time.


Filed under: Raspberry Pi

from raspberry pi – Hackaday http://ift.tt/273UZZM
via Hack a Day

Saturday, 7 May 2016

Chess Computers Improve Since 90s

The AlphaGo computer has been in the news recently for beating the top Go player in the world in four out of five games. This evolution in computing is a giant leap from the 90s when computers were still struggling to beat humans at chess. The landscape has indeed changed, as [Folkert] shows us with his chess computer based on a Raspberry Pi 3 and (by his own admission) too many LEDs.

The entire build is housed inside a chess board with real pieces (presumably to aid the human player) and an LED on every square. When the human makes a move, he or she inputs it into the computer via a small touch screen display. After that, the computer makes a move, indicated by lighting up the LEDs on the board and printing the move on the display. The Raspberry Pi is running the embla chess program, which has an Elo strength of about 1600.

While the computer isn’t quite powerful enough to beat Magnus Carlsen, we can only imagine how much better computers will be in the future. After all, this credit-card sized computer is doing what supercomputers did only a few decades ago. With enough Raspberry Pis, you might even be able to beat a grandmaster with your chess computer. Computer power aside, think of the advancements in fabrication technology (and access to it) which would have made this mechanical build a wonder back in the 90s too.

 


Filed under: Raspberry Pi

from raspberry pi – Hackaday http://ift.tt/1WQ9WtH
via Hack a Day

K.I.S.S. Pi Sprinkler – Just Keep the Plants Alive

A good first step in a project is knowing what you want to do. [Ben Fino] made it clear that his Raspberry Pi Sprinkler control system for his wife’s garden had one goal: keep the plants alive. The resulting project is doing just that and no more.

The circuitry, and plumbing, is straightforward and explained well in the Instructable. All the electronics consists of is the Pi and a MOSFET to take the 3.3v GPIO to 5v to control a relay. The valve controlling the water requires 28v AC which necessitated the relay to control it. There are also three LEDs: one is for power, one to indicate when the valve is opened, and one is an extra for some future purpose.

FC9RPDAIN4P8QU2.LARGE FIAWKVIIN4P8PZN.LARGE

The intriguing part is the use of weather data from the web to determine if it’s rained recently. Python scripts provided by [Ben’s] friend [Mark Veillette] use a weather site API to get the rainfall data. The main script is set to run once every 24 hours. [Ben] set his system to water unless the previous day had sufficient rain. How much rain and the number of look-back days is programmable.

What a great application of the KISS principle: keep it simple, stupid – except for that third LED without a purpose.


Filed under: internet hacks, Raspberry Pi

from raspberry pi – Hackaday http://ift.tt/1s1G2HI
via Hack a Day

Friday, 6 May 2016

Don’t Take Photos of Your Arduino 101 Either, Its Light Sensitive

Wafer level chips are cheap and very tiny, but as [Kevin Darrah] shows, vulnerable to bright light without the protective plastic casings standard on other chip packages.

We covered a similar phenomenon when the Raspberry Pi 2 came out. A user was taking photos of his Pi to document a project. Whenever his camera flash went off, it would reset the board.

[Kevin] got a new Arduino 101 board into his lab. The board has a processor from Intel, an accelerometer, and Bluetooth Low Energy out of the box while staying within the same relative price bracket as the Atmel versions. He was admiring the board, when he noticed that one of the components glittered under the light. Curious, he pulled open the schematic for the board, and found that it was the chip that switched power between the barrel jack and the USB. Not only that, it was a wafer level package.

So, he got out his camera and a laser. Sure enough, both would cause the power to drop off for as long as the package was exposed to the strong light. The Raspberry Pi foundation later wrote about this phenomenon in more detail. They say it won’t affect normal use, but if you’re going to expose your device to high energy light, simply put it inside a case or cover the chip with tape, Sugru, or a non-conductive paint to shield it.


Filed under: Arduino Hacks

from raspberry pi – Hackaday http://ift.tt/1XbcbYY
via Hack a Day

Thursday, 5 May 2016

Issue 165 is out now

LU&D #165

Issue 165 of Linux User And Developer is now available from all good newsagents, our online store, or as a digital magazine. Not in your local store yet? Subscribe to make sure you get it before they do!

In this issue we take an in-depth look at the latest version of Ubuntu, complete with insights from the developers on its new features and how it can converge across your devices – it even comes complete with the 32-bit, 64-bit and Server editions to live boot from the free disc.

We also take our first look at the BBC micro:bit, get started with programming in Go, and look at some useful techniques for virtualisation, data recovery and more. Plus there’s a wealth of Raspberry Pi content to inspire you and help you build and code your own projects.

 



from Linux User & Developer – the Linux and FOSS mag for a GNU generation http://ift.tt/24ty8YO
via IFTTT

Wednesday, 4 May 2016

An Open Source Lead Tester

If you’ve ever needed an example of colossal failure of government actors, you need only to look at Flint, Michigan’s water crisis. After the city of Flint changed water supplies from Detroit to the Flint river, city officials failed to add the correct corrosion inhibitors. This meant that lead dissolved into the water, thousands of children were exposed to lead in drinking water, a government coverup ensued, [Erin Brockovich] showed up, the foreman of the Flint water plant was found dead, and the City Hall office containing the water records was broken into.

Perhaps inspired by Flint, [Matthew] is working on an Open Source Lead Tester for his entry into the 2016 Hackaday Prize.

[Matthew]’s lead tester doesn’t test the water directly. Instead, it uses a photodiode and RGB LED to look at the color of a lead test strip. These results are recorded, and with a bit of a software backend, an entire city can be mapped for lead contamination in a few days with just a few of these devices.

One problem [Matthew] has run into is the fact the Pi does not have analog to digital conversion, making reading a photodiode a little harder than just plugging a single part into a pin header and watching an analog value rise and fall. That really shouldn’t be a problem – ADCs are cheap, especially if you only need a single channel of analog input with low resolution. [Matthew] is also looking into using the Pi webcam for measuring the lead test strip. There are a lot of decisions to make, but any functional device that comes out of this project will be very useful in normal, functioning governments. And hopefully in Flint, Michigan too.

The HackadayPrize2016 is Sponsored by:

Filed under: Raspberry Pi, The Hackaday Prize

from raspberry pi – Hackaday http://ift.tt/1Y7bb6t
via Hack a Day

Amazon

Donate

Donate Towards More Raspberry PI's for Projects