📜 ⬆️ ⬇️

Arduino sensors in Jelastic Cloud

Arduino in Jelastic Cloud The emergence of a new comprehensive network of Internet of Things (IoT) has now become possible due to the development of cloud computing. In IoT, real objects have a virtual presentation that allows us to interact with them via the Internet. Relevant resources in IoT are provided using cloud computing. Connecting devices to each other and to the Internet allows you to manage your data remotely.
This requires applications that:Jelastic PaaS is one of the most suitable platforms for hosting web applications that serve IOT networks. It provides web developers with everything they need to quickly and easily deploy scalable applications that manage sensor data online. Jelastic platform is the best solution to this problem, because it provides full access to the application environment, the ability to create and use your own database and even access to the local file system (unlike Google App Engine).


Let's look at a simple example of creating and deploying a web application that receives and visualizes data from a sensor.

Creating an environment on Jelastic

  1. First, you must create and configure the environment for your application. In order to obtain and visualize data from sensors, we need an application server (Tomcat 6) and a database server (MySQL 5.0)
    image

    In a few minutes, an environment will be created. You will also receive a confirmation email that will include your username and password for your database and a link to the MySQL admin page.
  2. Go to the MySQL admin page and create a new database for the sensor data (do not worry about sorting, we will use the database to process simple data).
    image

    For this example, we need two tables: one for information about the sensor (for example, name or id) and the second for data from the sensor.
    image

    image

    ')
    You can also create a new user with all privileges, but in our case, you can use the default user.
    Now your environment is complete and configured for your application and your data.

Creating a Java Servlet

The second step involves developing a Java application that will receive information from the sensor and visualize it. For this case, we need two servlets: one to receive data from the sensor and the second to visualize it.
  1. Launch the Eclipce IDE and create a new Dynamic Web Project (for example, JelasticSensorArduino ), select Tomcat as the application server.
  2. Open the project and create the appropriate servlet class (we suggest you create the package hierarchy first). Create a JelasticArduinoServlet class and add the following code to it:

    1. import java.io.IOException ;
    2. import java.util.Date ;
    3. import javax.servlet.http. * ;
    4. import java.sql.Connection ;
    5. import java.sql.DriverManager ;
    6. import java.sql.ResultSet ;
    7. import java.sql.Statement ;
    8. @SuppressWarnings ( "serial" )
    9. public class JelasticArduinoServlet extends HttpServlet {
    10. public void doGet ( HttpServletRequest req, HttpServletResponse resp )
    11. throws IOException {
    12. resp. setContentType ( "text / plain" ) ;
    13. // Retrieve the GET requests
    14. String SensorName = req. getParameter ( "sensor" ) ;
    15. String value = req. getParameter ( "value" ) ;
    16. // Create a new date from the server
    17. Date date = new Date ( ) ;
    18. // Create MySQL DB hosted on Jelastic
    19. String url = "jdbc: mysql: //mysql.arduinocloud.jelastic.servint.net: 3306 / sensor" ;
    20. // User your credential for connecting to the DB
    21. String user = "DBUSERNAME" ;
    22. String password = "DBPASSWORD" ;
    23. Connection con = null ;
    24. Statement st = null ;
    25. ResultSet rs = null ;
    26. boolean exists = false ;
    27. int id = 0 ;
    28. // Make the connection to the server
    29. try {
    30. con = drivermanager . getConnection ( url, user, password ) ;
    31. st = con. createStatement ( ) ;
    32. // Execute the sensor for the sensor id
    33. rs = st. executeQuery ( "SELECT id from sensor where name = '" + SensorName + "';" ) ;
    34. if ( rs. next ( ) ) {
    35. exists = true ;
    36. id = rs. getInt ( 1 ) ;
    37. }
    38. // If there is an ID
    39. if ( exists ) {
    40. st. executeUpdate ( "Insert into data (sensor, date, value) VALUES ('" + id + "', '" + date + "', '" + value + "');" ) ;
    41. }
    42. resp. getWriter ( ) . println ( "Sensor data updated!" ) ;
    43. con. close ( ) ;
    44. } catch ( Exception ex ) {
    45. resp. getWriter ( ) . println ( ex. toString ( ) ) ;
    46. }
    47. }
    48. }

    This is the servlet code that handles updates to the sensor values. It can be invoked using Arduino or your browser:
    http: //server.ip/servletname? sensor = sensorname & value = sensorvalue
    First, it accesses the sensor database and gets its ID. The ID then updates the table data accordingly.
  3. Let's go to the JSP file , which will visualize the data from the sensor. The JSP file must be created in the WebContent folder in your project structure. Create a new file (for example, sensorgraph.jsp ):

    1. <% @ page contentType = "text / html; charset = UTF-8" language = "java" %>
    2. <% @ page import = "java.util.List" %>
    3. <% @ page import = "java.sql.Connection" %>
    4. <% @ page import = "java.sql.DriverManager" %>
    5. <% @ page import = "java.sql.ResultSet" %>
    6. <% @ page import = "java.sql.Statement" %>
    7. < html >
    8. < head >
    9. < link type = "text / css" rel = "stylesheet" href = "/stylesheets/main.css" />
    10. < script type = "text / javascript" src = " www.google.com/jsapi" > </ script >
    11. < script type = "text / javascript" >
    12. google. load ( "visualization" , "1" , { packages : [ "corechart" ] } ) ;
    13. google. setOnLoadCallback ( drawChart ) ;
    14. function drawChart ( ) {
    15. var data = new google. visualization . DataTable ( ) ;
    16. data. addColumn ( 'string' , 'Time' ) ;
    17. data. addColumn ( 'number' , '<% = request.getParameter ("sensor")%>' ) ;
    18. <%
    19. int counter = 1 ;
    20. String SensorName = request. getParameter ( "sensor" ) ;
    21. if ( SensorName == null ) {
    22. SensorName = "temp" ;
    23. }
    24. String url = "jdbc: mysql: //mysql.arduinocloud.jelastic.servint.net: 3306 / sensor" ;
    25. String user = "DBUSERNAME" ;
    26. String password = "DBPASSWORD" ;
    27. Connection con = null ;
    28. Statement st = null ;
    29. ResultSet rs = null ;
    30. boolean exists = false ;
    31. int id = 0 ;
    32. try {
    33. con = drivermanager . getConnection ( url, user, password ) ;
    34. st = con. createStatement ( ) ;
    35. rs = st. executeQuery ( "SELECT id from sensor where name = '" + SensorName + "';" ) ;
    36. if ( rs. next ( ) ) {
    37. exists = true ;
    38. id = rs. getInt ( 1 ) ;
    39. }
    40. if ( exists ) {
    41. rs = st. executeQuery ( "SELECT value from data where sensorid =" + id ) ;
    42. while ( rs. next ( ) ) {
    43. counter ++;
    44. }
    45. %>
    46. data. addRows ( <% = counter %> ) ;
    47. <%
    48. rs = st. executeQuery ( "SELECT date, value from data where sensorid =" + id ) ;
    49. counter = 0 ;
    50. while ( rs. next ( ) ) {
    51. %>
    52. data. setValue ( <% = counter %> , 0 , '<% = rs.getString (1)%>' ) ;
    53. data. setValue ( <% = counter %> , 1 , <% = rs. getString ( 2 ) %> ) ;
    54. <%
    55. counter ++;
    56. }
    57. }
    58. con. close ( ) ;
    59. } catch ( Exception ex ) { ex. printStackTrace ( ) ; }
    60. %>
    61. var chart = new google. visualization . LineChart ( document. GetElementById ( 'chart_div' ) ) ;
    62. chart. draw ( data, { width : 600 , height : 240 , title : 'My Arduino <% = SensorName%> Sensor Readings' } ) ;
    63. }
    64. </ script >
    65. </ head >
    66. < body >
    67. < p > </ p >
    68. < div id = "chart_div" > </ div >
    69. </ body >
    70. </ html >


    JSP uses the Google Chart API to visualize data ( chart_div element). To do this, it needs to fill in the data fields for the chart by retrieving values ​​from the database.
    You may have noticed that at the beginning of the HTML code uses a specific CSS style included in a file called main.css . To include such a file in your project, simply create a new folder in the WebContent / stylesheets section of your project.

    body {
    font-family: Verdana, Helvetica, sans-serif;
    background-color: #FFFFFF;
    }

  4. Last but not least, you need to edit the web.xml file ( WEB-INF folder) and create the corresponding name-mapping servlet to associate the servlets with the JSP file. Replace web.xml with the following:

    1. <? xml version = “1.0 ″ encoding =“ UTF-8 ″ ?>
    2. <web-app xmlns: xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns = “http://java.sun.com/xml/ns/javaee” xmlns: web = “http : //java.sun.com/xml/ns/javaee/web-app_2_5.xsd ” xsi: schemaLocation =“ http://java.sun.com/xml/ns/javaee http://java.sun.com /xml/ns/javaee/web-app_2_5.xsd ” id =“ WebApp_ID ” version =“ 2.5 ″ >
    3. <display-name > JelasticSensorArduino </ display-name >
    4. <servlet >
    5. <servlet-name > JelasticArduino </ servlet-name >
    6. <servlet-class > doukas.jelastic.arduino.JelasticArduinoServlet </ servlet-class >
    7. </ servlet >
    8. <servlet-mapping >
    9. <servlet-name > JelasticArduino </ servlet-name >
    10. <url-pattern > / jelasticarduino </ url-pattern >
    11. </ servlet-mapping >
    12. <welcome-file-list >
    13. <welcome-file > sensorgraph.jsp </ welcome-file >
    14. </ welcome-file-list >
    15. <servlet >
    16. <servlet-name > add </ servlet-name >
    17. <servlet-class > doukas.jelastic.arduino.JelasticArduinoServlet </ servlet-class >
    18. </ servlet >
    19. <servlet-mapping >
    20. <servlet-name > add </ servlet-name >
    21. <url-pattern > / add </ url-pattern >
    22. </ servlet-mapping >
    23. </ web-app >


Deploy and test the application

Now you are one step away from seeing how your application receives and visualizes data from the sensor.
  1. First, you will need to create a WAR archive with your servlets to deploy the application in Jelastic environment.
  2. Upload your WAR archive to the Deployment Manager .
    image
  3. Deploy your application.
    image
  4. Another small detail: you need to load the mysql-connector jar file.
    image

    image
  5. Let's test our application.

    To do this, follow the following link ( sensorcloud - the name of the environment):
    http://sensorcloud.jelastic.servint.net/add?sensor=temp&value=20
    You will see the message: “Sensor data updated!”. If this is not the case (it is very unlikely if you completed all the steps correctly), you will see an error message. Add multiple sensor values ​​using the previous link. Then go to the following link to see the visualized data as a graph:
    http://sensorcloud.jelastic.servint.net/?sensor=temp
    image
  6. Now it remains to add a code that will read data from the sensor and save them to the database.
    The following C code reads data from a sensor connected via Ethernet and stores it in the base of your environment:

    1. #include <SPI.h>
    2. #include <Ethernet.h>
    3. // Enter a MAC address for your controller below.
    4. byte mac [ ] = { 0x00 , 0xAA , 0xBB , 0xCC , 0xDE , 0x02 } ;
    5. char serverName [ ] = "sensorcloud.jelastic.servint.net" ;
    6. // Initialize the Ethernet client library
    7. Ethernet Client ;
    8. void setup ( ) {
    9. // start the serial library:
    10. Serial. begin ( 57600 ) ;
    11. // start the Ethernet connection:
    12. if ( ethernet. begin ( mac ) == 0 ) {
    13. Serial. println ( "Failed to configure Ethernet using DHCP" ) ;
    14. }
    15. }
    16. void loop ( ) {
    17. int temperature = analogRead ( 0 ) ;
    18. String s = String ( temperature , DEC ) ;
    19. if ( client. connect ( serverName , 80 ) ) {
    20. // Make a HTTP request:
    21. client. println ( "GET / add? sensor = temp & value =" + s + "HTTP / 1.0" ) ;
    22. client. println ( "Host: sensorcloud.jelastic.servint.net" ) ;
    23. client. println ( ) ;
    24. client. stop ( ) ;
    25. }
    26. delay ( 60000 ) ;
    27. }


Applications of this type provide you with a direct and affordable way to download sensor readings. All you need is a network microcontroller, such as an Arduino , that can easily access URLs.

It is very important that Jelastic allows you to concentrate on the functionality of the application and does not worry about the number of simultaneous requests for updating sensor values ​​and setting up a server environment for creating backup copies of your data. Jelastic eliminates all the extra hassle and makes it easy to deploy and scale your applications.

In preparing the article was used Charalampos Doukas, author of the book "Arduino, Sensors and the Cloud" , Using Jelastic for the Internet of Things .

Source: https://habr.com/ru/post/136583/


All Articles