• No results found

TRACK YOUR ATMOSPHERE

N/A
N/A
Protected

Academic year: 2021

Share "TRACK YOUR ATMOSPHERE"

Copied!
35
0
0

Loading.... (view fulltext now)

Full text

(1)

TRACK YOUR ATMOSPHERE

Intellectual Output IO4

Software – Hardware Weather Station Interface

GNSS = Global Navigation Satellite Systems

Erasmus+ Projekt 2017-1-DE02-KA202-004229 Version 04/20FR

(2)

List of contents

A. Preface...5

B. Human Machine Interface...5

I. Introduction...5

II. HTML...5

1. Definition...5

2. Example...5

3. Client-server operation...6

4. Exercises...6

a. Direct read HTML file...6

b. File deposited on a WEB server...7

III. Javascript...7

1. First steps in Javascript...7

2. Libraries...8

a. Personal Library...8

b. Outdoor Libraries...8

Example of using an external graphics library...9

Example of a period picker...10

IV. The PHP...12

1. Client-server operation...12

a. Principle...12

b. Example...12

2. Applications...13

a. Reception of data entered in JavaScript...13

JavaScript pre-processing...13

PHP post-processing...14

b. Accessing data stored on a MySql server...15

Timestamp...15

Access to the Mysql database...15

Reading Wind Data...16

c. Displaying Weather Statistics...17

C. Hardware Interruption...18

I. Prerequisite...18

II. Hardware...18

III. Final assembly...18

IV. Target...19

V. Principle of interruption...19

VI. Assembly...19

VII. Mounting with the anemometer...19

VIII. Using the clock...20

IX. Mounting with the windvane...20

D. I2C Bus...20

I. Prerequisite...20

II. Hardware...21

III. Assembly...21

IV. Target...21

V. I2C device detection...21

(3)

VI. Reading the measured values...22

E. Weather Station Data sending...24

I. Principe...24

II. Arduino Code...25

III. Python Code on the Raspberry...27

F. Internet Of Things...29

I. Sigfox...29

1. Description...29

2. Sigfox weather station configuration...30

3. Data Frame...30

II. Data storage...31

1. Sigfox Callbacks...31

2. On the TRYAT server...32

a. PHP/CSV method...32

b. PHP / Mysql method...34

3. API REST...34

a. API account Configuration...34

b. Advanced Rest Client...34

c. Another example : location covering...35

The European Commission's support for the production of this publication does not constitute an endorsement of the contents, which reflect the views only of the authors, and the Commission cannot be held responsible for any use which may be made of the information contained therein.

(4)

GNSS Antena and Weather Station on the roof from the Lycée Saint-Cricq

(5)

A. Preface

In the Intellectual Output 4, we will develop an interactive learning unit (“learning environment”) with focus on elements of innovation, expected informatics and electronics. While in O2 the hardware (Arduino and sensors) and the server structure is readily given to the student (which makes it easier to try and modify the starter kit and data collecting) here the students are given just a problem, namely the collecting of environmental data. This problem is given to them in the form of an order from industry “Monitoring of renewable energy plant – measuring wind and sun strength as well as the electrical power”.

This document presents the software needs to produce and use the weather station data.

B. Human Machine Interface

I. I. IntroductionIntroduction

In this chapter we will see how to create a web interface for a data processing application.

Several languages will be implemented: HTML, JavaScript, PHP, the aim of this course is not to study these languages in depth but to understand their use through examples.

Students have computer sciences development bases : basic algorithmic ; basic structured language knowledge.

It will better to use a computer with a Linux operating system, but all those programs can be launch on another operating system with web services and python3.x

II. II. HTMLHTML

1.

1. DefinitionDefinition

"Hypertext Markup Language, usually abbreviated to HTML, is the markup language designed to represent web pages. It is a language for writing hypertext, hence its name. HTML also enables the semantic and logical structuring and formatting of page content, and the inclusion of multimedia resources including images, input forms and computer programs. It enables the creation of documents that are interoperable with a wide variety of equipment in a way that complies with web accessibility requirements. "(source: Wikipedia)

2. 2. ExampleExample

<DOCTYPE html>

<html lang="fr">

<Head.

<meta charset="utf-8" />

<title>Page title displayed in the title bar</title>

<meta name="generator" content="Geany 1.32" />

</Head.

(6)

<Body.

This is the body of the page, this text is displayed when the file is read by the <b> web browser</

b>

<Brr!

<img src="./nsi.png" alt="ImageNsi" width="500", height="500">

<Brr!

<a href="http://www. tryat.eu">Link to the Erasmus - Tryat"</a> website.

</Body.

</html>

 The page is composed between two tags <head> and </head>.

 Tags <meta> give additional information about the page, for example the author or keywords that will be read by search engines to reference the page.

 The content of the page that will be displayed must be placed between the <body> and </body>

tags.

 The <img> tag allows you to display an image whose file location must be sounded, you can change its size and give information that will be displayed/read instead of the image if the browser is so configured (for blind people for example).

3. 3. Client-server operationClient-server operation

4. 4. ExercisesExercises

a. Direct read HTML file

 Write an HTML file that introduces you (name, first name, class, photo), you can use the text editor " Geany " (free software editor) and ask it to generate a new file according to the template " file.html ".

(7)

 Make a link to the site " www.elektronslibres.fr ",

 Open the page with your web browser,

 Right click on the page and look at the source code

b. File deposited on a WEB server

 Install an "Apache" server on your computer with the command "sudo apt-get install apache2"

(Linux), or install WAMP on a Windows OS.

 Place a web page at the root of this site with the name "index.html" with the command "sudo cp file_name /var/www/html",

 Modify your web page to make links to your classmates.

III.

III. JavaScriptJavaScript

The HTML language allows very little interaction between the user and the web page, that's why very quickly another language was developed, included in the web pages that offers more advanced functionalities.

This language JavaScript, uses the same client-server mechanism as HTML, it is directly written in the web page and interpreted by the browser.

"JavaScript is a scripting language mainly used in interactive web pages but also for servers2 with the use (for example) of Node.js3.

Along with HTML and CSS, JavaScript is sometimes considered one of the core technologies of the World Wide Web5. The JavaScript language allows interactive web pages, and as such is an essential part of web applications. A large majority of websites use it6 , and most web browsers have a dedicated JavaScript engine to interpret it, regardless of any security considerations that may arise. "

(source: Wikipedia)

In recent years, it has grown significantly and now provides a large number of libraries of tools to facilitate the development of interactive web pages.

1. 1. First steps in JavaScriptFirst steps in JavaScript

Modify your web page by adding this portion of code in the <body> section:

<script type= "text/javascript" >

>

alert('Welcome to Tryat's Weather page');

</Scripting.

To add an interaction modify the code as follows:

<script type= "text/javascript" >

>

var FirstNameName;

FirstnameLastname=prompt("Give your first and last name");

alert("Hello"+FirstnameName);

</Scripting.

You notice that in JavaScript, it is necessary to declare the variables.

(8)

It is also possible to make :

function invite(FirstNameName) {

alert("Hello"+FirstnameName);

}

var FirstNameName;

FirstnameLastname=prompt("Give your first and last name");

invite(FirstnameName);

2. 2. LibrariesLibraries

a. Personal Library

 save the function that you have done in a file " myScripts.js ".

 call it by modifying the main file as follows:

<DOCTYPE html>

<html lang="fr">

<Head.

<meta charset="utf-8" />

<title>Page title displayed in the title bar</title>

<meta name="generator" content="Geany 1.32" />

</Head.

<script type= "text/javascript" src="./mesScripts.js"></script>

<Body.

This is the body of the page, this text is displayed when the file is read by the <b> web browser</

b>

<Brr!

<img src="./nsi.png" alt="ImageNsi" width="500", height="500">

<Brr!

<script type= "text/javascript">

var FirstNameName;

FirstnameLastname=prompt("Give your first and last name");

invite(FirstnameName);

</Scripting.

<a href="http://www.w3.org">Link to the W3 web standardization site"</a>

</Body.

</html>

b. Outdoor Libraries

javascript can use libraries located on other sites, for example :

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js" integrity="sha256- arMsf+3JJK2LoTGqxfnuJPFTU4hAK57MtIPdFpiHXOU=" crossorigin="anonymous">

</Scripting.

(9)

This Libraries content graphical functions.

In this case, the integrity test is designed to prevent malicious code from being introduced into the library downloaded from the Internet.

Example of using an external graphics library

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js" integrity="sha256- arMsf+3JJK2LoTGqxfnuJPFTU4hAK57MtIPdFpiHXOU=" crossorigin="anonymous"></script>

<Body.

Chart.js" test for CLF teaching

<Canvas id="myChart"> canvas>

<Script

var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {

type: 'line', data:

{

labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'], datasets:

[

{

label: 'Temperature',

data: [12, 19, 3, 17, 6, 3, 7, 8],

backgroundColor: "rgba(153,255,51,0.2)"

}, {

label: 'Pressure',

data: [2, 29, 5, 5, 5, 2, 3, 10, 12],

backgroundColor: "rgba(255,153,0,0.0.2)"

} ]

} });

</Scripting.

</Body.

(10)

The rendition will be:

Example of a period picker

This function is used to get a dates values.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<Head.

<"My Picker Period" title.

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<meta name="generator" content="Geany 1.32" />

</Head.

<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>

<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>

<script type="text/javascript"

src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>

<link rel="stylesheet" type="text/css"

href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

<Body.

<input type="text" name="datetimes" />

<Script

$(function() {

$('input [name="datetimes"]').daterangepicker({

timePicker: true,

"timePicker24Hour": true,

startDate: moment().startOf('hour'),

endDate: moment().startOf('hour').add(32, 'hour'), local: {

format: 'DD/MM/YYY hh:mm'.

Temperature Pressure

(11)

} });

});

</Scripting.

</Body.

</html>

Rendering:

We now try to analyze the returned variable :

Natively, the library assigns the value returned by the operator to the "text" field referenced by the name "datetimes". A modification of the html and javascript in the "Body" section allows you to verify this:

<Body.

<form method="post" action=" RecupFormulaire.php">

<p>Please choose a period: </p>

<input type="text" name="datetimes" id="datetimes" onchange="Verif()"/>

<input type="text" name="datesLues" id="datesLues"/>

<Brr!

<input type="submit" value="Display" />

<Script

Verif() function {

var dates = document.getElementById("datetimes").value;

document.getElementById("datesLues").value=dates;

} ...

The hour is given in the AM/PM system

(12)

In this case, pressing the "Display" button will call the page "traitement.php" which will be generated by the web server and which will receive as parameters the form variables "datetimes" and

"datesLues".

In addition, the javascript function "Verif()" will assign the content of "datetimes" to the "datesRead"

field.

IV. IV. The PHPThe PHP

« PHP is a general-purpose scripting language especially suited to web development. PHP code is usually processed on a web server by a PHP interpreter implemented as a module, a daemon or as a Common Gateway Interface (CGI) executable. On a web server, the result of the interpreted and executed PHP code – which may be any type of data, such as generated HTML or binary image data – would form the whole or part of a HTTP response. »

(Wikipedia)

1. 1. Client-server operationClient-server operation a. Principle

Refer « Client-server operations » page 5.

b. Example

Source code in php of the page " page1.php ":

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<Head.

<title> untitled>

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<meta name="generator" content="Geany 1.32" />

</Head.

<Body.

<?php

echo("This text will appear in the body of the page <br>");

$a=2;

$b=5;

echo("The result of the addition is ");

echo($a+$b);

?>

</Body.

</html>

This program is deposited in the tree " /var/www/html " of the server (which can be your computer).

With the internet browser you call up the page: " http://localhost/page1.php ", it displays in return :

This text will appear in the body of the page The result of the addition is 7

and the source code of the page received by the web browser is :

(13)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<Head.

<title> untitled>

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<meta name="generator" content="Geany 1.32" />

</Head.

<Body.

This text will appear in the body of the page <br>The result of the addition is 7

</Body.

</html>

→ we notice that there are no more instructions in PHP, they have been interpreted by the PHP server and their result has been coded in HTML and returned to the browser.

2. 2. ApplicationsApplications

a. Reception of data entered in JavaScript

The data is sent to the web server with the "POST" method and PHP must retrieve it with the same method:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<Head.

<Title> Data retrieval. Title>

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<meta name="generator" content="Geany 1.32" />

</Head.

<Body.

<?php

$value=$_POST["datetimes"];

echo "<hr>";

echo "<br> Collect value: ".$value;

?>

</Body.

</html>

The string is now stored in the $value variable, and will be displayed in one piece.

You have to extract the times and dates from them in order to be able to then launch a query in the MySql database that hosts the meteorological data. Two possibilities, either do it in JavaScript before sending the form, or do it in PHP after receiving the data.

JavaScript pre-processing

The result is obtained by using the "split" method applied to the variable containing the selected period:

(14)

<Body.

<form method="post" action="RecupFormulaire.php">

<p>Please choose a period: </p>

<input type="text" name="datetimes" id="datetimes" onchange="Verif()"/>

<input type="hidden" name="datesLues" id="datesLues"/>

<input type="hidden" name="dateDebut" id="dateDebut"/>

<input type="hidden" name="dateFin" id="dateFin"/>

<input type="hidden" name="starttime" id="starttime"/>

<input type="hidden" name="endtime" id="endtime"/>

<Brr!

<input type="submit" value="Display" />

<Script

Verif() function {

var dates = document.getElementById("datetimes").value;

// format: 22/12/19 04:00 - 02/01/20 12:00

document.getElementById("datesLues").value=dates;

detail=dates.split(" ");

document.getElementById("dateDebut").value=detail[0];

document.getElementById("dateFin").value=detail[3];

document.getElementById("starttime").value=detail[1];

document.getElementById("endtime").value=detail[4];

}

Remarks :

 several fields have been switched to "hidden" instead of "text" to avoid overloading the web page unnecessarily.

 The Split method stores in a table the result of the operation, each item corresponds to a found item separated by the space character: " ".

Then you need to modify the PHP page as follows:

<?php

$value=$_POST["datetimes"];

$dateDebut=$_POST["dateDebut"];

$dateFin=$_POST["dateFin"];

$HourStart=$_POST["hourStart"];

$fin-hour=$_POST["fin-hour"];

echo "<hr>";

echo "<br> Collect value: ".$value;

echo "<br> Start Date: ".$dateDebut;

echo "<br> End date : ".$end date;

echo "<br> Start time: ".$starttime;

echo "<br> End time : "...hourFin;

?>

(15)

PHP post-processing

The PHP equivalent will be the "explode" function:

<?php

$value=$_POST["datetimes"];

$detail=explode(" ",$value);

$dateDebut=$detail[0];

$dateFin=$detail [3];

$hourDebut=$detail[1];

$hourEnd=$detail [4];

echo "<hr>";

echo "<br> Collect value: ".$value;

echo "<br> Start Date: ".$dateDebut;

echo "<br> End date : ".$end date;

echo "<br> Start time: ".$starttime;

echo "<br> End time : "...hourFin;

?>

In this case the processing of the chain will be done by the internet server and not the client's browser, what is preferable?

b. Accessing data stored on a MySql server The data we want to access is

automatically stored in a table in a MySql database hosted on a MySql server accessible on the Internet. The data format is as follows:

Timestamp

The date is stored as a "timestamp"

↔ number of seconds elapsed since 01/01/1970

In PHP the function " $timestampDebut=strtotime($dateDebut." ".$timeDebut.":00"); " allows to make this conversion from a string analysis. Another "mktime" function also does this transformation in a more rigorous way, hence the function :

function calcStamp($dateTxt,$timeTxt) {

//format: 09/12/19 12:00:00

$detailDate=explode("/",$dateTxt);

$detailHour=explode(":",$hourTxt);

return(mktime($detailHour[0],$detailHour[1],$detailDate[1],$detailDate[0],$detailDate[2]);

}

Who's going to return the timestamp.

In JavaScript, the timestamp is counted in milliseconds, so the value returned must be divided by 1,000.

(16)

Access to the Mysql database

The objective will be to plot the wind speed curve as a function of time and two dates entered by the user.

First, to test access to the database, we will launch a query to obtain the minimum and maximum dates in the "acquisitions" table.

// access to the weather database

$tabDate=array();

$dateMin=time(); //today dateMax=0; // January 1, 1970 try

{

// One connects to MySQL by providing the address, the name of the database, the identifier and the password.

$bdd = new PDO('mysql:host=srv36.haisoft.net;dbname=C07400_meteo;charset=utf8', 'cnp2019', 'Suf767!Hr');

}

wrestling(Exception $e) {

// If an error occurs, a message is displayed and everything is stopped.

die('Error: '.$e->getMessage());

}

// we retrieve all the dates from the acquisition table

$response = $bdd->query('SELECT date FROM acquisitions');

while($data = $response->fetch()) {

$tabDate[]=$data['date'];

if($dateMin>$data['date']) $dateMin=$data['date'];

if($dateMax<$data['date']) $dateMax=$data['date'];

}

reply->closeCursor(); // Ends processing of the query // Displaying the data :

echo "<br>Minimum date: ".$dateMin." / ".date('d/m/Y H:i:s', $dateMin);

echo "<br>Maximum date: ".$dateMax." / ".date('d/m/Y H:i:s', $dateMax);

It is preferable to know these dates before choosing, in JavaScript, the dates for which you want to obtain the measurements. It is therefore necessary to modify the page in which the calendar script is located. It will therefore become a "PHP" type page and will contain three languages: html/javascript/

php and it will be enough to insert the PHP code in it.

Reading Wind Data

The called page will execute the query in the database, the code will be as follows:

// we retrieve all the dates from the acquisition table

$request='SELECT date,windMean FROM acquisitions WHERE date >= '.$tmpMin.' and date <= '.

$tmpMax.';';

$response = $bdd->query;

(17)

while($data = $response->fetch()) {

$tabDate[]=$data['date'];

$tabVent[]=$data['averageVent'];

if($dateMin>$data['date']) $dateMin=$data['date'];

if($dateMax<$data['date']) $dateMax=$data['date'];

}

reply->closeCursor(); // Ends processing of the query // Displaying the data :

echo "<ul>";

echo "<li> Selected range: ".$value."</li>";

echo "<li>Minimum date: ".date('d/m/Y H:i:s', $dateMin)."</li>";

echo "<li>Maximum date: ".date('d/m/Y H:i:s', $dateMax)."</li>";

echo "<li> Number of measurements: ".count($tabDate)."</li>";

echo "</ul>";

echo "<hr>";

for ($i=0;$i<count($tabDate);$i++) {

echo("<br>".date('d/m/y h:m',$tabDate[$i])." ".$tabVent[$i]);

}

c. Displaying Weather Statistics

The only thing left to do is to represent these data with the "JavaScript/Charts.js" graphics library, which gives the following code:

<Script

var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {

type: 'line', data:

{

<?php

echo "labels: [";

for ($i=0;$i<count($tabDate);$i++) {

echo("'".date('d/m/y h:m',$tabDate[$i])."',");

}

echo "],";

?>

datasets:

[

{

label: 'Vent',

<?php

echo "data: [";

(18)

for ($i=0;$i<count($tabDate);$i++) {

echo($tabVent[$i].",");

}

echo "],";

?>

backgroundColor: "rgba(255,153,0,0.0.2)"

} ]

} });

</Scripting.

C. Hardware Interruption

"In computer science, an interrupt is a temporary suspension of the execution of a computer program by the microprocessor in order to execute a priority program (called an interrupt service).

"(Wikipedia)

I. I. PrerequisitePrerequisite

• Arduino basis knowledges,

• Algorithmic,

• C-Arduino functions

• sampling

II. II. HardwareHardware

• 1 Arduino microcontroller with its USB cable and the IDE installed on a client computer,

• Test wires for the first part, then Leds and resistors

• 1 weather station for the second part (anemometer and wind vane Silver Data Systems). You can get it there, e.g. :

• « https://www.robotshop.com/eu/fr/kit- station-meteorologique.html »

RJ11

Source L.V

(19)

III.

III. Final assemblyFinal assembly

The weather system used includes a weather vane and an anemometer. Both use ILS magnetic switches that close when a magnet is passed close by:

IV. IV. TargetTarget

By counting the interruptions sent by the anemometer, evaluate the wind speed.

First we will trigger interruptions with a simple wire and run a test program, then we will measure the wind speed.

V. V. Principle of interruptionPrinciple of interruption

The Arduino has two pins (2 and 3) that can transmit interruptions. Each time these pins receive a change of state, the Arduino will be informed and start a particular function. The interpreted states can be LOW, CHANGE, RISING, FALLING.

Their declaration in the IDE is done in the following way:

pinMode(n°broche, INPUT_PULLUP);

attachInterrupt(digitalPinToInterrupt(n°broche), NomFonction, CHANGE);

VI. VI. AssemblyAssembly

This simple assembly uses an LED connected to pin 2 (interruption 0) as well as a simple push button connected to pin 6.

From the Arduino:

• Pin 2 is an output □ input □

• Pin 6 is an output □ input □

Application

• Wire this assembly and make an Arduino program whose LED will change state with each impulse exerted on the push button.

(20)

VII.

VII. Mounting with the anemometerMounting with the anemometer

The wind measurement system (speed and orientation) is connected with an RJ11 socket, of which only the 4 central wires are used. They are connected to the ILS alone for the anemometer and in series with resistors for the wind vane, this allows to make a voltage divider bridge :

We will connect pins 2 and 3 to ground and input 2 to trigger the interrupts. The rotation of the anemometer triggers the LED twice per turn, the manufacturer gives this information :

« A wind speed of 1.492 MPH (2,4 km/h) causes the switch to close once per second. » Check the correct functioning of the assembly.

VIII.

VIII. Using the clockUsing the clock

« millis() : Returns the number of milliseconds passed since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 50 days. »

• Change the function called on interruption to increment a variable acting as a counter,

• After 4s (long enough to smooth out the error) calculate and display the wind speed on the console.

IX. IX. Mounting with the windvaneMounting with the windvane

Carry out the assembly with the weather vane.

• We are looking for where north is on the windvane, what voltage corresponds to the value 0°?

• The sampling is on 10 bits, what is the full scale decimal value corresponding to the 5 V analog value ?

• From this we can deduce what value will be given by the sampler for 0°.

• Modify the program so that the serial terminal displays the different values read from port A0 and compares them with those given by the table.

D. I2C Bus

I2C : Inter Integrated Circuit

This bus was developed at the beginning of the 80s by "Philips Semiconductor" to allow to easily connect the various circuits in the field of home automation to a microprocessor.

source : Argent Data Systems

(21)

The goal was to make very different electronic components communicate with each other thanks to only 3 wires:

• Data signal: SDA

• Clock signal: SCL

• Electrical reference signal: ground

• A 4th wire will power the device.

Exchanges always take place between a single master and one (or all) slave(s), always at the initiative of the master (never master to master or slave to slave) and each peripheral has a unique address.

I. I. PrerequisitePrerequisite

• Arduino basis knowledges,

• Algorithmic,

• C-Arduino functions

• sampling

II. II. HardwareHardware

• 1 Arduino microcontroller with its cable and the IDE installed on a client computer,

• 1 I2C device (BME 280 for this study), this board has got three sensors : temperature, pressure and humidity.

III.

III. AssemblyAssembly

Due to its design, assembly is extremely simple:

• Vin → 5 V

• Gnd

• SDI (SDA) → A4

• SCK (SCL) → A5

IV. IV. TargetTarget

The sensor under study returns the following three values: temperature, humidity, pressure. The aim will be to read them in order to integrate the data into a weather station site.

V. V. I2C device detectionI2C device detection

The address is encoded on 7 bits, the Arduino Wire library allows to use the serial port. The following program will send a request to all possible devices (1→ 126) and display the addresses of those that respond.

#include <Wire.h>

void setup()

(22)

{

Wire.begin(); //connection initialisation Serial.begin(9600);

Serial.println("\n I2C Device detector ");

}

void loop() {

byte erreur, adresse;

int nPeripheriques=0;

Serial.println("Scanning the different addresses...");

for(adresse = 1; adresse < 127; adresse++ ) // we're running down every possible address {

Wire.beginTransmission(adresse);

erreur = Wire.endTransmission(); //does the device respond?

if (erreur == 0) {

Serial.print("I2C device detected address 0x");

if (adresse<16) Serial.print("0");

Serial.print(adresse,HEX);

Serial.println(" !");

nPeripheriques++;

}

else if (erreur==4) {

Serial.print("Unknown error at address 0x");

if (adresse<16) Serial.print("0");

Serial.println(adresse,HEX);

} }

if (nPeripheriques == 0)

Serial.println("No devices detected.\n");

else

Serial.println("Scan completed \n");

delay(5000);

}

The program returns this information to the serial monitor:

• I2C device detector

• Scanning the different addresses...

• I2C device detected address 0x77!

• Scan completed

(23)

VI. VI. Reading the measured valuesReading the measured values

The datasheet of the component gives this information:« The data are read out in an unsigned 20-bit format both for pressure and for temperature and in an unsigned 16-bit format for humidity. »

The table below gives the addresses of the temperature registers :

#include "BME280I2C.h"

#include <Wire.h>

#define SERIAL_BAUD 9600 // better than the original value

BME280I2C bme; // Default : forced mode, standby time = 1000 ms

// Oversampling = pressure ×1, temperature ×1, humidity ×1, filter off, const byte ledPin = 6;

const byte interruptPin = 2;// caution 1 is attached to pin 3 and 0 to pin 2 volatile byte state = LOW;

void setup() {

Serial.begin(SERIAL_BAUD);

while(!Serial) {} // Wait Wire.begin();

while(!bme.begin()) {

Serial.println("Could not find BME280 sensor!");

delay(1000);

}

pinMode(ledPin, OUTPUT);

pinMode(interruptPin, INPUT_PULLUP);

}

void loop()

(24)

{

readBme();

delay(10000) ;

void readBme() // to get the data from the three sensors {

float temp(NAN), hum(NAN), pres(NAN);

BME280::TempUnit tempUnit(BME280::TempUnit_Celsius);

BME280::PresUnit presUnit(BME280::PresUnit_Pa);

bme.read(pres, temp, hum, tempUnit, presUnit);

Serial.print(" Pressure : ");

Serial.println(pres);

Serial.print(" Humidity : ");

Serial.println(hum);

Serial.print(" Temperature : ");

Serial.println(temp);

}

→ then you can get those data through the serial port of an computer.

E. Weather Station Data sending

In this chapiter we will describe the connection between the weather station and the MySql Data Base

I. I. PrincipePrincipe

The weather station, with the arduino board will collect the data from the sensors. Then it will send it to a computer (a RaspberryPi for exemple) thrue the USB serial port. Using a internet connection, the computer will send these data to the storage server.The hardware description is described in other

(25)

chapiters above (C, D)

II. II. Arduino CodeArduino Code

Here is the entire code on the Arduino board to collect all the data from the weather station

#include "BME280I2C.h"

#include <Wire.h>

#define SERIAL_BAUD 9600 // better than the original value

BME280I2C bme; // Default : forced mode, standby time = 1000 ms

// Oversampling = pressure ×1, temperature ×1, humidity ×1, filter off,

const byte ledPin = 6;

const byte interruptPin = 2;// caution 1 is attached to pin 3 and 0 to pin 2 volatile byte state = LOW;

float tempsInitial, temps, vitesseVent;

int compteur;

int directionVent;

/*

*** pin choice : ***

Arduino d2 : Press Button Arduino d6 : Led

*** angles values for the prototype ***

0 : 246 45 : 134 90 : 76 135 : 392 180 : 736 225 : 839 270 : 930 315 : 561

*/

void setup() {

Serial.begin(SERIAL_BAUD);

while(!Serial) {} // Wait Wire.begin();

while(!bme.begin()) {

Serial.println("Could not find BME280 sensor!");

(26)

delay(1000);

}

pinMode(ledPin, OUTPUT);

pinMode(interruptPin, INPUT_PULLUP);

attachInterrupt(digitalPinToInterrupt(interruptPin), allumeLed, CHANGE); // pin get low digitalWrite(ledPin, HIGH);

delay(1000);

digitalWrite(ledPin, LOW);

tempsInitial=millis();

compteur=0;

}

void loop() {

digitalWrite(ledPin, state);

if((millis()-tempsInitial)>4000)// we count interruptions during 4s {

tempsInitial=millis();

vitesseVent=(compteur/4)*2.4;

compteur=0;

lectureBme();

Serial.print("cnp:");

Serial.println(vitesseVent);

directionVent = analogRead(A0);

Serial.print(" Wind Direction : ");// 0° correspond to 786 proportional law

Serial.println(directionVent);

} }

void allumeLed() {

//Serial.print(" Interruption detected, time laps : ");

//Serial.println(-millis()-tempsInitial);

state = !state;

compteur++;

}

void lectureBme() {

float temp(NAN), hum(NAN), pres(NAN);

BME280::TempUnit tempUnit(BME280::TempUnit_Celsius);

BME280::PresUnit presUnit(BME280::PresUnit_Pa);

(27)

bme.read(pres, temp, hum, tempUnit, presUnit);

Serial.print(" Pressure : ");

Serial.println(pres);

Serial.print(" Humidity : ");

Serial.println(hum);

Serial.print(" Temperature : ");

Serial.println(temp);

}

III.

III. Python Code on the RaspberryPython Code on the Raspberry

Now we need a program on the computer to get the data from the Arduino board through the usb serial port :

# -*- coding: utf-8 -*- import serial

import string import time import pymysql import requests

mysqlhost = "*******" # put the server adress there mysqluser = "*******" # the user login

mysqlpass = "*******" # the mysql user’s password datenbank = "*******" # the name from the database

class meteo:

def _init_(self):

self.pluie self.temperature self.humidite self.pression self.direction self.ventMoyen self.ventMax acquis=meteo

ser = serial.Serial('/dev/ttyACM0', 9600) print("Serial port initialised :")

# print(ser)

# you can read the value on the arduino IDE 'tool/serial port'

#File Methode : read file and send characters print("Start of the data retrieval...")

valeurs=[]

dictValeurs={}

(28)

while(1):

print("Wiating for the data...") donnee=ser.readline() if(donnee) :

print("Data retrieved")

donneeUTF8=donnee.decode("utf8")

print(donneeUTF8) # you can see the data on a Linux computer with the console instruction : sudo screen /dev/ttyACM0

detail=donneeUTF8.split(";") if(detail[0]=="cnp") : print("Data validated") acquis.pluie=str(detail[1]) acquis.temperature=str(detail[2]) acquis.humidite=str(detail[3]) acquis.pression=str(detail[4]) #acquis.direction=str(detail[5]) # conversion direction

detail[5]=int(detail[5])

if(detail[5]>20 and detail[5]<35) : acquis.direction ="O" # about 27 if(detail[5]>90 and detail[5]<120) : acquis.direction ="NO" # about 107 if(detail[5]>490 and detail[5]<530) : acquis.direction ="N" # about 505 if(detail[5]>290 and detail[5]<330) : acquis.direction ="NE" # about 315 if(detail[5]>190 and detail[5]<220) : acquis.direction ="E" # about 204 if(detail[5]> 40 and detail[5]<60) : acquis.direction ="SE" # about 57 if(detail[5]> 0 and detail[5]<9) : acquis.direction ="S" # about 6 if(detail[5]> 8 and detail[5]<18) : acquis.direction ="SW" # about 13

acquis.ventMoyen=str(detail[6]) acquis.ventMax=str(detail[7])

print("N rain interrupt : "+str( acquis.pluie))

print("Temperature : "+str(acquis.temperature)+" °C") print("Humidity : "+str(acquis.humidite)+" %") print("Pressure : "+str(acquis.pression)+" mBar") print("Wind direction : "+str(acquis.direction)+" °")

print("Wind average speed : "+str(acquis.ventMoyen)+" km/h") print("wind maximal speed : "+str(acquis.ventMax)+" km/h")

#connexion = pymysql.connect( host=mysqlhost, user=mysqluser, passwd=mysqlpass, db=datenbank, charset='utf8' )

# http request

# r = requests.get(adresse+"/ecriture.php?

temp="+acquis.temperature+"&hum="+acquis.humidite+"&pres="+acquis.pression+"&direc="+acquis.

direction+"&vit="+acquis.vitesse) # data writing

connexion = pymysql.connect( host=mysqlhost, user=mysqluser, passwd=mysqlpass, db=datenbank, charset='utf8' )

sql = """INSERT INTO acquisitions(date,direction,humidite,pluvio,pression,temperature,ventMoyen, ventMax) VALUES ('"""+str(time.time()+7200)+"""','"""+str(acquis.direction)

+"""','"""+str(acquis.humidite)+"""','"""+str(acquis.pluie)+"""','"""+str(acquis.pression)

(29)

+"""','"""+str(acquis.temperature)+"""','"""+str(acquis.ventMoyen)+"""','"""+str(acquis.ventMax) +"""')"""

cur = connexion.cursor(pymysql.cursors.DictCursor) cur.execute( sql, ())

result = cur.fetchall()# return to a dictionnary connexion.commit()

connexion.close()

# You can read the data that you writed : # data display

connexion = pymysql.connect( host=mysqlhost, user=mysqluser, passwd=mysqlpass, db=datenbank, charset='utf8' )

sql = """SELECT * FROM acquisitions;"""

cur = connexion.cursor(pymysql.cursors.DictCursor) cur.execute( sql, ())

result = cur.fetchall()# return to a dictionnary connexion.commit()

connexion.close() dictValeurs=result #print(dictValeurs)

F. Internet Of Things

« The Internet of things (IoT) describes the network of physical objects—“things”—that are embedded with sensors, software, and other technologies for the purpose of connecting and exchanging data with other devices and systems over the internet. » (source Wikipedia)

The connected object that we will use in this project is a weather station, which performs measurements for the needs of TRYAT. These are then sent to a server which in turn "pushes" them to the TRYAT server.

The weather station is described in another document (IO4: Capteurs et serveur de données pour les microcontrôleurs et les systèmes embarqués)

I. I. SigfoxSigfox

1. 1. DescriptionDescription

« Sigfox is a French global network operator founded in 2010 that builds wireless networks to connect low-power objects such as electricity meters and smartwatches, which need to be continuously on and emitting small amounts of data.

Sigfox employs the differential binary phase-shift keying (DBPSK) and the Gaussian frequency shift keying (GFSK) that enables communication using the Industrial, Scientific and Medical ISM radio band which uses 868MHz in Europe and 902MHz in the US. It utilizes a wide-reaching signal that passes freely through solid objects, called "Ultra Narrowband" and requires little energy, being termed a "low-power wide-area network" (LPWAN). The network is based on one-hop star topology and requires a mobile operator to carry the generated traffic.The signal can also be used to easily cover large areas and to reach underground objects. As of October 2018, the Sigfox IoT network has

(30)

covered a total of 4.2 million square kilometers in a total of 50 countries and is on track to reach 60 countries by the end of 2018. » (source Wikipedia).

Sigfox module can send up to 140 messages per day. Each message size is 12 bytes. The year cost to send the messages is from 5 to 15 €.

2. 2. Sigfox weather station configurationSigfox weather station configuration

3.

3. DataData Frame Frame

The Sigfox module from the weather station send a message each 12 minutes to the Sigfox Server. the send frame contains several weather data :

temp::int:16 pres::uint:24 humi::uint:8 part1::uint:16 part25::uint:16 windspeed::uint:8 winddir::uint:8

00d2 018029 44 0000 0001 0d 02

On the sigfox backend, after selecting the device, you can see them by connecting to the web interface from the sigfox webservice and choicing the used module :

Temperature 2 bytes (tenth °)

Pressure 3 bytes (Pa)

Speed of the wind 2 bytes (km/h) Humidity 1 byte (%)

Wind direction2 bytes (°)

10μmm particles /m3

2.5 um particle / m3

Weather station with Sigfox Module

(31)

II. II. Data storageData storage

1. 1. Sigfox CallbacksSigfox Callbacks

To get those data on the TRYAT server, you have many solutions. Our choice is to create an « API ACCESS » push them true an HTTP request, using the « GET » method.

1. Select the device in the device list by clicking on its « device type » (in this case TRYAT_MKRFox):

2. Click on « CALLBACKS » menu on the left 3. Create your own « Callbacks »

Our URL pattern, on this test is :

http://saint-cricq.com: 82 /tryat/index.php?

deviceId={device}&quand={time}&temperature={customData#temp}&pression={customData#pres}&humidite

={customData#humi}&part1={customData#part1}&part25={customData#part25}&vitVent={customData#wind

(32)

speed}&dirVent={customData#winddir}

The Custom paylod config is :

temp::int:16 pres::uint:24 humi::uint:8 part1::uint:16 part25::uint:16 windspeed::uint:8 winddir::uint:8

2. 2. On the TRYAT serverOn the TRYAT server

The web apache2 server will receive this GET Request :

185.110.97.87 - - [24/Sep/2020:16:18:30 +0200] "GET /tryat/index.php?

deviceId=C05E8&quand=1600957108&temperature=210&pression=98352&humidite=67&part1=2&part 25=3&vitVent=2&dirVent=255 HTTP/1.1" 200 696 "-" "SIGFOX"

Now we have to store those data.

a. PHP/CSV mmethod

Now, you have to write the « index.php » webpage on the server to store the data. Our choice, for security is to write them on a CSV file :

<?php /*

*

Retrieved data : {

"Device-ID" : "{device}", "Date" : {time},

"Temperature" : {customData#temp}, "Pression" : {customData#pres}, "Humidite" : {customData#humi}, "part1" : {customData#part1}

"part25" : {customData#part25}

"Vit_Vent" : {customData#windspeed}, "Dir_Vent" : {customData#winddir}

} */

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<title>TRYAT - Récupération des données</title>

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<meta name="generator" content="Geany 1.36" />

</head>

<body>

Récupération des données Sigfox

<?php

References

Related documents

When working with our Top Practices Virtual Marketing Director Sevices, you and your staff receive access to the team as often as you need us – whether you need help with

(Wikipedia) As far as Unilever Pakistan is concerned, the culture of the company had a great impact upon the environment in which it is operating. Unilever claims that it is a

The Middle East recruitment market continues to be an attractive location for international lawyers, offering superb career opportunities within law firms.. It is fast paced,

Reduced memory space required for storing open and cleared items Reduced memory space required for storing open and cleared items Enables high performance processing of

A minimum limit of 18% in elongation has been adopted to optimise the mechanical properties of the prepared cast irons. On the other hand, a minimum silicon content of 3?00 wt-%

Solar radiation data is required (along with an anemometer and a.. temperature/humidity sensor) enables the weather station to report ET and THSW Index. 3- Finding new

Treatment differences in terms of R levels and transition frequency are mainly driven by the adaptation process: figure 3 shows that groups which transition to the efficient

Through the survey of aroids distribution in Hau and Perak Rivers for this study, the species presence and the habitats in surveyed areas are recorded and