Andrej Sládkovič, AngularJS and Node.js

Zápisník experimentátora

Hierarchy: Node.js

In today's article we will continue to work on the poem Marína by Andrey Sládkovič. The aim is to get this poem into the Arduino. Because with Arduino itself, development would take a long time, we will make a small stop at Node.js. We will create an HTTP server in Node.js that will secure the backend for the AngularJS application. We will later use this app in Arduino, when we replace the server in Node.js with the Arduino server.

A poem by Andrew Sládkoviča has 291 stanzas. At one point, we'll show only one stanza on the screen. Therefore, we use four control buttons to scroll through the entire poem. As the poem looks like in the browser, you can see the picture.

HTTP

The application is designed as one-page application in AngularJS. It uses the following interface.

  • / - From the server is downloaded HTML page where are the links to other pages. It downloads Bootstrap, AngularJS and then the application itself in javascript. Everything is downloaded from the Internet so we do not have to put large files in Arduino.
  • /sladkovic.js - Source code of the AngularJS application.
  • /marina?verse=X - Download the text of a specific stanza.
  • /marinaverses - Getting the number of stanzas in the poem.

HTML

The HTML source code of the page looks like this. The AngularJS application is enclosed in the tag <div ng-app="sladkovicApp" ng-controller="sladkovicCtrl">. The code makes it easy to recognize how the buttons are being created and connected to the functions. For example, jump to the first stroke of a poem is created by using <button ng-click="doFirst()">Prvý</button>. Listing of the poem itself is done using special tags for AngularJS. For example, the number of the current stanza is made by tag {{verse}}.

<!DOCTYPE html>
<html lang="sk">
<head>
  <title>Andrej Sládkovič - Marína</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
  <script src="sladkovic.js"></script>
</head>

<body>
  <div ng-app="sladkovicApp" ng-controller="sladkovicCtrl">
  <div class="container">
  <div class="row">
    <div class="col-sm-12">
      <h1>Andrej Sládkovič - Marína</h1>
      <p><button ng-click="doFirst()">Prvý</button> <button ng-click="doPrev()">Predchádzajúci</button> <button ng-click="doNext()">Nasledujúci</button> <button ng-click="doLast()">Posledný</button></p>
    </div>
  </div>

  <div class="row">
    <div class="col-sm-12">
      <p>Verš {{verse}}/{{maxverse}}</p>
      <pre>{{text}}</pre>
    </div>
  </div>

  </div>
  </div>
</body>

</html>

AngularJS

The source code in javascript is easy to read. The communication between HTML and javascipt is done using the variable $scope. Using the function $http.get we will download all the necessary information from the server. You can find a nice example of the function that is used to retrieve the text of a particular strof in updateText. It is called from many other functions that are connected to the buttons on the page.

var app = angular.module('sladkovicApp', []);

app.controller('sladkovicCtrl', ['$scope', '$http', function($scope, $http) {

  $scope.verse = 1;
  $scope.maxverse = 1;
  $scope.text = '';

  $http.get('/marinaverses')
    .then(function(response) {
      console.log(response);
      $scope.maxverse = response.data.maxverse;
    }, function(error) {
      console.log(error);
    });

  updateText();

  function updateText() {
    $http.get('/marina?verse=' + $scope.verse)
      .then(function(response) {
        console.log(response);
        $scope.text = response.data;
      }, function(error) {
        console.log(error);
      });
  }

  $scope.doFirst = function() {
    if($scope.verse>1) {
      $scope.verse = 1;
      updateText();
    }
  }

  $scope.doPrev = function() {
    if($scope.verse>1) {
      $scope.verse--;
      updateText();
    }
  }

  $scope.doNext = function() {
    if($scope.verse<$scope.maxverse) {
      $scope.verse++;
      updateText();
    }
  }

  $scope.doLast = function() {
    if($scope.verse<$scope.maxverse) {
      $scope.verse = $scope.maxverse;
      updateText();
    }
  }

}]);

Node.js

The last part of the application is the HTTP server itself. is generated using the application express-generator. From the generated code I removed everything unnecessary and left only the part that delivers static content. It serves to send an initial HTML page and javascript with the AngularJS application to your browser. I've just added array with stanzas (var marina) and two functions that send responses to the AngularJS application (app.get('/marina'... and app.get('/marinaverses'...).

You will install the Node.js application using the command npm install and run it with the command npm start.

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

var marina = [
  "Ja sladké túžby, túžby po kráse\nspievam peknotou nadšený,\na v tomto duše mojej ohlase\nsvet môj je celý zavrený;\nz výsosti Tatier ona mi svieti,\nona mi z ohňov nebeských letí,\nona mi svety pohýna;\nona mi kýva zo sto životov:\nNo centrom, živlom, nebom, jednotou\nkrás mojich moja Marína!",
...
  "Marína moja! teda tak sme my\nako tie božie plamene,\nako tie kvety v chladnej zemi,\nako tie drahé kamene;\npadajú hviezdy, aj my padneme,\nvädnú tie kvety, aj my zvädneme,\na klenoty hruda kryje:\nAle tie hviezdy predsa svietili,\na pekný život tie kvety žili,\na diamant v hrude nezhnije!",
];

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'), {'extensions': ['html']}));

app.get('/marina', function (req, res) {
  var id = req.query.verse || 1;
  res.send(marina[id-1]);
});

app.get('/marinaverses', function (req, res) {
  res.json({maxverse: marina.length});
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Source code

The source code is located on the GitHub server.

If you have a git installed, you can install the source code as follows. If you do not have it, you can also download zip archives. Run the Command Line Console. Important is the last line that installs all the related libraries that are in package.json.

cd d:
mkdir arduino
cd arduino
git clone https://github.com/roboulbricht/arduinoslovakia
cd arduinoslovakia\node.js\sladkovic_demo
npm install

20.01.2018


Menu