# data[].attributes.attachment_link.title
Securing your Raspberry Pi - Raspberry Pi Documentation

# data[].attributes.attachment_link.description
Documentation in this section includes basic guides to configuring your Raspberry Pi.

# data[].attributes.body
Read the comments too

# data[].attributes.attachment_link.title
Logging in via Putty and Secure Keys - Raspberry Pi Forums

# data[].attributes.attachment_link.title
Using PuTTYgen on Windows to generate SSH key pairs | SSH.COM

# data[].attributes.attachment_link.description
How to install and use puttygen to create new key pairs and change passphrases. Installing keys on server, managing SSH keys.

# data[].attributes.attachment_link.title
PIR Motion Sensor using something other than delay() - Millis?

# data[].attributes.attachment_link.description
PIR Motion Sensor using something other than delay() - Millis?

# data[].attributes.attachment_link.readable_text
Overview

Want to receive a text if there's a bump in the night? Want an SMS if your cat is drinking from the toilet again? Want to get a text if a snooping parent or sibling comes in your room? This is a project for you!

We're going to use an ESP8266 based WiFi prototyping development board - the Adafruit Feather HUZZAH and IoT platform Losant to send an SMS when an intruder is detected.

If you're not familiar with Losant, Losant provides a simple way for generating visualization of all your data from all of your Internet of Things devices in customizable dashboards. Losant also allows you to respond to events coming from your devices like sending you an email when one of your devices measures a low moisture reading for one of your plants. Or even better, when your moisture sensing device measures low moisture, Losant can send a command to the watering device to start the watering cycle. The great thing is that you can modify the logic of the interaction between the devices in the Losant web app without modifying a line of code on any of your devices. This can all be done through an intuitive UI. You'll see that in action in this project.

Bill of Materials

You'll need the following components for this project.

Services Used

Wiring

A Passive Infrared (PIR) sensor works by detecting the infrared radiation from an object - like a human or animal.

Each PIR sensor can have different pin outs. I'm using the Parallax 555-28027 PIR Sensor. If you face the sensor toward you the pins from left to right are, out to signal, power and ground. OUT will send a HIGH signal once an infrared body is detected by the sensor. Here's a illustration of the sensor and pin out.

Here's what the Adafruit Feather HUZZAH looks like - big style!

Wire up the VCC on the PIR sensor to 3V on the HUZZAH, the GND pin on the PIR sensor to the GND on the HUZZAH. The sensor should be working now. There's a red LED that comes on when the sensor detects a body. Finally connect the OUT from the PIR sensor to any digital pin on the HUZZAH. I picked 12.

Here's how it looks IRL.

For further reading on the PIR sensor visit the Parallex Website or Adafruit's Learning System for the Feather HUZZAH.

Arduino Code

The Adafruit Feather HUZZAH is Arduino compatible, so we'll be using the Arduino IDE. If you're new to Arduino you should check out The Absolute Beginner's Guide to Arduino.

The Arduino IDE doesn't come working "out-of-the-box" with the Feather HUZZAH. To get it up and running take a quick detour to Adafruit's Learning Guide. When the IDE has been set up, let's get ready to code.

Our Arduino code needs to do the following things:

1. Connect and reconnect to WiFi (connect() and reconnect())

2. Connect and reconnect to the Losant IoT platform (connect() and reconnect())

3. Read the PIR sensor (int currentRead = digitalRead(MOTION_PIN);)

4. Send a message to Losant when motion of an infrared body has been detected (motionDetected())

The Arduino code is below and requires the Losant mqtt library for Arduino. See the README.md for other dependencies.

Fill in your SSID for WIFI_SSID and WiFi password for WIFI_PASS.

This only leaves the Losant credentials.

Setting up Losant

To connect to Losant you require 3 things:

1. A Device ID to identify the device from another device (LOSANT_DEVICE_ID)

2. An access key (LOSANT_ACCESS_KEY)

3. An access secret (LOSANT_ACCESS_SECRET)

If you haven't signed up to Losant yet, do that now at Losant.com - it's free for our use case.

First we need to create an application by going to Applications > + Create Application from the drop down menus.

I'm calling mine Security System.

Now we can create an Access Key. Visit the Access Keys link, then + Add Access Key.

Then, simply press Create Access Key for All Devices. You'll be presented with an Access Key and Access Secret. These will be LOSANT_ACCESS_KEY and LOSANT_ACCESS_SECRET respectively in your Arduino code. Keep your secret safe. If you loose it you have to regenerate it and update all your devices with the new secret.

Now we need to create a device to get a Device ID to put in to our Aruino code to assign to the LOSANT_DEVICE_ID constant.

Then click on Create Blank Device.

Then we can create a new device. Let's give the device a Name of Bedroom since this is going to be where the device will be. Then keep the Device Type set to Standalone, since it connects directly to Losant.

Then you can specify the Device Attributes that the device will send to Losant. In our case it's a boolean value of motion. You can have as many device attributes as you'd like, like a temperature reading or humidity reading. Device attributes are contained in the JSON that we send from the device in the motionDetected() function to Losant.

Then click Create Device. You'll now get a Device ID. You can copy and paste that for your LOSANT_DEVICE_ID.

Awesome, we have all the required strings for the Arduino Skecth. Update the values for LOSANT_DEVICE_ID, LOSANT_ACCESS_KEY and LOSANT_ACCESS_SECRET and Upload your Arduino Sketch to the Adafruit Feather HUZZAH.

The final step is to get Losant to send us a text message when the motion state is true. To do this we need to create a Workflow. A Workflow is work triggered by your device's states. In our case we want Losant to send an SMS message (the work) when the motion event occurs and is the value of true.

Create a Workflow from the drop down menus.

Enter in a Workflow Name like Send Notification or Send SMS and press Save Workflow.

You are now presented with a simple drag and drop interface to create your workflow. First drag Device from Triggers in to the grid in the center of the screen.

Then drag Conditional from the Logic panel.

We then want to add the expression of...

{{ data.motion }} == true

...in the Expression section of the Conditional panel.

Now let's drag SMS from the Output section and type in your cell phone number in the Phone Number Template.

Then connect the nodes of the workflow together. Be sure to connect the green connection point on the Conditional to the SMS node. This means the condition has evaluated to true.

Oh, let's not forget to include a Message Template of Motion Detected!.

Finally, we Deploy Workflow, meaning it's ready to work when events come in.

Unplug your device and set it up where you want to have it.

Now it's time to see if it works!

And it does! Awesome!

Conclusion

Losant limits the SMS service to 1 per minute, which is fine for our purposes, but you can integrate with third party services such as telecom API provider Twilio which doesn't have that restriction.

Taking the project further, you may want to add a button to "Arm" the device, with an LED indicator, so it doesn't send the motion detection JSON when you're expecting movement.

If you like this project why not give it some Respect on Hackster.io?

# data[].attributes.attachment_link.description
OverviewWant to receive a text if there's a bump in the night? Want an SMS if your cat is drinking from the toilet again? Want to get a text if a snooping parent or sibling comes in your room? This is

# data[].attributes.attachment_link.title
Problem getting PIR sensor working using interrupts

# data[].attributes.attachment_link.description
Problem getting PIR sensor working using interrupts

# data[].attributes.attachment_link.title
Access your Raspberry Pi over the internet - Raspberry Pi Documentation

# data[].attributes.attachment_link.description
Need to access a Raspberry Pi, but don't have a monitor spare? This section provides basic instructions for setting up remote access.

# data[].attributes.attachment_link.title
VNC (Virtual Network Computing) - Raspberry Pi Documentation

# data[].attributes.attachment_link.description
Need to access a Raspberry Pi, but don't have a monitor spare? This section provides basic instructions for setting up remote access.

# data[].attributes.attachment_link.readable_text
Learn what a JSON feed is, and how to extract its data with PHP, JavaScript, or jQuery.

JSON is used to transmit data between a server and a browser. Here is a basic example of what might be in a .json string.

{ "name": "Tania", "title": "Web Developer", "website": "https://www.taniarascia.com" }

As you can see, it's a human readable format of data that might traditionally be stored in a table. Some companies might have public .json files located that you can access and extract data from (an API you can connect to). You might also save a .json file somewhere in your project that you want to extract data from.

Goals

JSON data can be accessed and utilized with many programming languages. In this tutorial, we'll learn how to access JSON with PHP and JavaScript.

Prerequisites

What is JSON?

JSON stands for Java Script Object Notation. It is data saved in a .json file, and consists of a series of key/value pairs.

The value of any JSON key can be a string, Boolean, number, null, array, or object. Comments are not allowed in JSON.

Although JSON resembles an object or an array, JSON is a string. A serialized string, which means it can later be parsed and decoded into data types.

Using data from JSON with PHP

First, to drill in that JSON is simply a string, we're going to write JSON into a PHP string and apply it to a variable called $data.

$data = '{ "name": "Aragorn", "race": "Human" }';

Then we'll use the json_decode() function to convert the JSON string into a PHP object.

$character = json_decode($data);

Now we can access it as a PHP object.

echo $character->name;

Here's the whole file.

<?php $data = '{ "name": "Aragorn", "race": "Human" }'; $character = json_decode($data); echo $character->name;

Here is the output.

Accessing a JSON feed from a URL

From here out, we'll put all JSON data into its own .json file. This way, we can retrieve the contents of the file instead of keeping it as a PHP string.

Here's what data.json will look like.

[ { "name": "Aragorn", "race": "Human" }, { "name": "Legolas", "race": "Elf" }, { "name": "Gimli", "race": "Dwarf" } ]

And here's how we'll extract that data in PHP.

$url = 'data.json'; // path to your JSON file $data = file_get_contents($url); // put the contents of the file into a variable $characters = json_decode($data); // decode the JSON feed

In order to get one entry, we'll have to access the appropriate array number. Remember, counting begins with 0 in programming.

echo $characters[0]->name;

I can access all the data in the array with a foreach loop.

foreach ($characters as $character) { echo $character->name . '<br>'; }

Here is the full PHP file.

<?php $url = 'data.json'; // path to your JSON file $data = file_get_contents($url); // put the contents of the file into a variable $characters = json_decode($data); // decode the JSON feed echo $characters[0]->name; foreach ($characters as $character) { echo $character->name . '<br>'; }

We can display the data in a table, for an example.

<table> <tbody> <tr> <th>Name</th> <th>Race</th> </tr> <?php foreach ($characters as $character) : ?> <tr> <td> <?php echo $character->name; ?> </td> <td> <?php echo $character->race; ?> </td> </tr> <?php endforeach; ?> </tbody> </table>

In this example, I'm using the alternate syntax for foreach, which looks like foreach() : /* loop */ endforeach; instead of foreach() { /* loop */ }. This is often preferable when outputting HTML.

Using associative arrays

There's another way we can access the data in PHP. If you pass true as the argument in json_decode(), the data becomes an associative array instead of an object. This means we'll be using square bracket notation[] instead of the skinny arrow->.

$characters = json_decode($data, true); // decode the JSON feed and make an associative array

Instead of ->race, we will access the value with ['race'].

echo $characters[0]['race'];

And here's how to access the loop.

foreach ($characters as $character) { echo $character['race'] . "\n"; }

Getting data from nested arrays

So far, we've only used JSON feeds with key/value pairs, but it's common to encounter nesting. Here's another nerdy example, which we can save in a new file called wizards.json.

[ { "name": "Harry Potter", "wand": [ { "core": "phoenix feather", "length": "11 inches", "wood": "holly" } ] }, { "name": "Hermione Granger", "wand": [ { "core": "dragon heartstring", "length": "10 and 3/4 inches", "wood": "vine" } ] } ]

Decoding the feed.

$url = 'wizards.json'; $data = file_get_contents($url); $wizards = json_decode($data, true);

We'll be able to access the nested array using $wizard['key'][0]['key'] in a loop, or whatever number corresponds correctly if you only want to print one.

foreach ($wizards as $wizard) { echo $wizard['name'] . '\'s wand is ' . $wizard['wand'][0]['wood'] . ', ' . $wizard['wand'][0]['length'] . ', with a ' . $wizard['wand'][0]['core'] . ' core. <br>' ; }

Harry Potter's wand is holly, 11 inches, with a phoenix feather core. Hermione Granger's wand is vine, 10 and 3/4 inches, with a dragon heartstring core.

Converting a PHP object or array into JSON

Just as you use json_decode() to turn JSON into PHP, you can turn PHP into JSON with json_encode().

$data = [ 'name' => 'Aragorn', 'race' => 'Human' ]; echo json_encode($data);

We made a PHP array and encoded it. Here's the output:

{"name":"Aragorn","race":"Human"}


Using data from JSON with JavaScript


We're going to create a JavaScript variable called data and apply the JSON string.


var data = '[ { "name": "Aragorn", "race": "Human" }, { "name": "Gimli", "race": "Dwarf" } ]';


Now we'll use JavaScript built in JSON.parse() function to decode the string.


data = JSON.parse(data);


From here we can access the data like a regular JavaScript object.


console.log(data[1].name);


And we can loop through each iteration with a for loop.


for (var i = 0; i < data.length; i++) { console.log(data[i].name + ' is a ' + data[i].race + '.'); }




Aragorn is a Human. Gimli is a Dwarf.


That was easy! Now, we'll probably need to access JSON from a URL. There's an extra step involved, where we have to make a request to the file. Let's just take the above JSON string and put it in data.json.


[ { "name": "Aragorn", "race": "Human" }, { "name": "Gimli", "race": "Dwarf" } ]


Now we'll make an XMLHttpRequest().


var request = new XMLHttpRequest();


We'll open the file ( data.json) via GET (URL) request.


request.open('GET', 'data.json', true);


From here, we'll parse and work with all our JSON data within the onload function.


request.onload = function () { // begin accessing JSON data here }


Then finally, submit the request.


request.send();


Here's the final code.


var request = new XMLHttpRequest(); request.open('GET', 'data.json', true); request.onload = function () { // begin accessing JSON data here var data = JSON.parse(this.response); for (var i = 0; i < data.length; i++) { console.log(data[i].name + ' is a ' + data[i].race + '.'); } } request.send();


And the output.




Aragorn is a Human. Gimli is a Dwarf.


Using Fetch


Now you can also use the Fetch API to do the same thing. Read How to Use the JavaScript Fetch API to Get JSON Data for an easier method to get this data.


// Replace ./data.json with your JSON feed fetch('./data.json').then(response => { return response.json(); }).then(data => { // Work with JSON data here console.log(data); }).catch(err => { // Do something for an error here });


Using jQuery


As you can see, it's not too difficult to retrieve a JSON feed with plain JavaScript. However, it's even easier with jQuery, using the getJSON() function. If you don't know how jQuery works, you'll need to load the jQuery JavaScript library before any of this custom code.


$(document).ready(function () { $.getJSON('data.json', function (data) { // begin accessing JSON data here console.log(data[0].name); }); });


You might also see jQuery access JSON via an AJAX request, which is a little more verbose.


	$(document).ready(function () { var data; $.ajax({ dataType: "json", url: 'data.json', data: data, success: function (data) { // begin accessing JSON data here console.log(data[0].name); } }); });


Both will have the same output.


Conclusion


Hopefully this article has taught you a bit about what JSON is and does, and how to access JSON data with PHP, JavaScript, or jQuery.




Email List


Get friendly updates, infrequently.









Tania Rascia


Hiya. I'm Tania, a web developer from Chicago. Hope you enjoyed my ad-free, bullshit-free site. If you liked it, tell someone about it!  GitHub  Twitter

# data[].attributes.attachment_link.title
How to Use JSON Data with PHP or JavaScript

# data[].attributes.attachment_link.description
Learn what a JSON feed is, and how to extract its data with PHP, JavaScript, or jQuery. JSON is used to transmit data between a server and a browser. Here is a basic example of what might be in a .json string.

# data[].attributes.attachment_link.readable_text
Nothing on the web happens instantly. The only difference is in the time it takes for a process to complete. Some processes can happen in a few milliseconds, while others can take up to several seconds or minutes. For example, you might be editing a very large image uploaded by your users, and this process can take some time. In such cases, it is a good idea to let the visitors know that the website is not stuck somewhere but it is actually working on your image and making some progress.

One of the most common ways to show readers how much a process has progressed is to use progress bars. In this tutorial, you will learn how to use the ProgressBar.js library to create different progress bars with simple and complex shapes.

Creating a Basic Progress Bar

Once you have included the library in your project, creating a progress bar using this library is easy. ProgressBar.js is supported in all major browsers, including IE9+, which means that you can use it in any website you are creating with confidence. You can get the latest version of the library from GitHub or directly use a CDN link to add it in your project.

To avoid any unexpected behavior, please make sure that the container of the progress bar has the same aspect ratio as the progress bar. In the case of a circle, the aspect ratio of the container should be 1:1 because the width will be equal to the height. In the case of a semicircle, the aspect ratio of the container should be 2:1 because the width will be double the height. Similarly, in the case of a simple line, the container should have an aspect ratio of 100:strokeWidth for the line.

You can specify the color of the progress bar using the color property. Any progress bar that you create will have a dark gray color by default. The thickness of the progress bar can be specified using the strokeWidth property. You should keep in mind that the width here is not in pixels but in terms of a percentage of the canvas size. For instance, if the canvas is 200px wide, a strokeWidth value of 5 will create a line which is 10px thick.

Besides the main progress bar, the library also allows you to draw a trailing line which will show readers the path on which the progress bar will move. The color of the trail line can be specified using the trailColor property, and its width can be specified using the trailWidth property. Just like strokeWidth, the trailWidth property also computes the width in percentage terms.

The total time taken by the progress bar to go from its initial state to its final state can be specified using the duration property. By default, a progress bar will complete its animation in 800 milliseconds.

After specifying the initial parameter values, you can animate the progress bars using the animate() method. This parameter accepts three parameters. The first parameter is the amount up to which you want to animate the progress line. The two other parameters are optional. The second parameter can be used to override any animation property values that you set during initialization. The third parameter is a callback function to do something else once the animation ends.

In the following example, I have created three different progress bars using all the properties we have discussed so far.

var lineBar = new ProgressBar.Line('#line-container', {
    color: 'orange',
    strokeWidth: 2,
    trailWidth: 0.5
});

lineBar.animate(1, {
    duration: 1000
});

var circleBar = new ProgressBar.Circle('#circle-container', {
    color: 'white',
    strokeWidth: 2,
    trailWidth: 10,
    trailColor: 'black',
    easing: 'easeInOut'
});

circleBar.animate(0.75, {
    duration: 1500
});

var semiBar = new ProgressBar.SemiCircle('#semi-container', {
    color: 'violet',
    strokeWidth: 2,
    trailWidth: 0.5,
    easing: 'bounce'
});

semiBar.animate(1, {
    duration: 3000
});

Animating Text Values With the Progress Bar

The only thing that changes with the animation of the progress bars in the above example is their length. However, ProgressBar.js also allows you to change other physical attributes like the width and color of the stroking line. In such cases, you will have to specify the initial values for the progress bar inside the from parameter and the final values inside the to parameter when initializing the progress bars.

You can also tell the library to create an accompanying text element with the progress bar to show some textual information to your users. The text can be anything from a static value to a numerical value indicating the progress of the animation. The text parameter will accept an object as its value.

The value inside the text element will stay the same during the whole animation if you don't update it yourself. Luckily, ProgressBar.js also provides a step parameter which can be used to define a function to be called with each animation step. Since this function will be called multiple times each second, you need to be careful with its use and keep the calculations inside it simple.

var lineBar = new ProgressBar.Line("#line-container", {
  strokeWidth: 4,
  trailWidth: 0.5,
  from: { color: "#FF9900" },
  to: { color: "#00FF99" },
  text: {
    value: '0',
    className: 'progress-text',
    style: {
      color: 'black',
      position: 'absolute',
      top: '-30px',
      padding: 0,
      margin: 0,
      transform: null
    }
  },
  step: (state, shape) => {
    shape.path.setAttribute("stroke", state.color);
    shape.setText(Math.round(shape.value() * 100) + ' %');
  }
});

lineBar.animate(1, {
  duration: 4000
});

var circleBar = new ProgressBar.Circle("#circle-container", {
  color: "white",
  strokeWidth: 2,
  trailWidth: 25,
  trailColor: "black",
  easing: "easeInOut",
  from: { color: "#FF9900", width: 1 },
  to: { color: "#FF0099", width: 25 },
  text: {
    value: '0',
    className: 'progress-text',
    style: {
      color: 'black',
      position: 'absolute',
      top: '45%',
      left: '42%',
      padding: 0,
      margin: 0,
      transform: null
    }
  },
  step: (state, shape) => {
    shape.path.setAttribute("stroke", state.color);
    shape.path.setAttribute("stroke-width", state.width);
    shape.setText(Math.round(shape.value() * 100) + ' %');
  }
});

circleBar.animate(0.75, {
  duration: 1500
});

var semiBar = new ProgressBar.SemiCircle("#semi-container", {
  color: "violet",
  strokeWidth: 2,
  trailWidth: 8,
  trailColor: "black",
  easing: "bounce",
  from: { color: "#FF0099", width: 1 },
  to: { color: "#FF9900", width: 2 },
  text: {
    value: '0',
    className: 'progress-text',
    style: {
      color: 'black',
      position: 'absolute',
      top: '45%',
      left: '50%',
      padding: 0,
      margin: 0,
      transform: null
    }
  },
  step: (state, shape) => {
    shape.path.setAttribute("stroke", state.color);
    shape.path.setAttribute("stroke-width", state.width);
    shape.setText(Math.round(shape.value() * 100) + ' %');
  }
});

semiBar.animate(0.75, {
  duration: 2000
});

Creating Progress Bars With Custom Shapes

The library does not provide any way to draw a trail for the custom path, as it did for simple lines and circles. However, you can create the trail yourself fairly easily. In the following example, I have created a triangular progress bar using the Path() method.

Before writing the JavaScript code, we will have to define our custom SVG path in HTML. Here is the code I used to create a simple triangle:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" width="300" height="300" viewBox="0 0 300 300">
  <path d="M 50 50 L 200 100 L 200 300 z" fill="none" stroke="#ddd" stroke-width="1"/>
  <path id="triangle" d="M 50 50 L 200 100 L 200 300 z" fill="none" stroke="blue" stroke-width="5"/>
</svg>

You might have noticed that I created two different path elements. The first path has a light gray color which acts like the trail we saw with simple progress bars in the previous section. The second path is the one that we animate with our code. We have given it an id which is used to identify it in the JavaScript code below.

var path = new ProgressBar.Path("#triangle", {
  duration: 6000,
  from: {
    color: "#ff0000",
    width: 2
  },
  to: {
    color: "#0099ff",
    width: 10
  },
  strokeWidth: 4,
  easing: "easeInOut",
  step: (state, shape) => {
    shape.path.setAttribute("stroke", state.color);
    shape.path.setAttribute("stroke-width", state.width);
  }
});

path.animate(1);

Final Thoughts

As you saw in this tutorial, ProgressBar.js allows you to easily create different kinds of progress bars with ease. It also gives you the option to animate different attributes of the progress bar like its width and color.

Not only that, but you can also use this library to change the value of an accompanying text element in order to show the progress in textual form. This tutorial covers everything that you need to know to create simple progress bars. However, you can go through the documentation to learn more about the library.

If there is anything that you would like me to clarify in this tutorial, feel free to let me know in the comments.

# data[].attributes.attachment_link.title
Creating Stylish and Responsive Progress Bars Using ProgressBar.js

# data[].attributes.attachment_link.description
Nothing on the web happens instantly. The only difference is in the time it takes for a process to complete. Some processes can happen in a few milliseconds, while others can take up to several seconds or minutes. For example, you might be editing a very large image uploaded by your users, and this process can take some time.