A simple custom solution to multi-language support using JS

Recently, I needed to add a multi-language support to a website that was run using PHP. Sure, I could use some i18n PHP framework to deliver translated web-page directly from a server, but I decided to design a simple approach based on Javascript.

Here it goes …

The default language is supposed to be slovene, so visiting a page by url http://mywebpage would show a slovene version. To get a webpage in a specific language, you need to explicitly define the language using a parameter, like so: http://mywebpage?lang={sl, hr, en}. Of course, this is used in a header of a web page for a languages selection menu:

<a id="lang-sl" href="/?lang=sl">Slovenski</a>|
<a id="lang-hr" href="/?lang=hr">Hrvatski</a>|
<a id="lang-en" href="/?lang=en">English</a>

In the webpage, I introduced a “lang” HTML tag, which acts as a placeholder for a language-specific text:

<lang id="home" />

For each language I create a separate JS file that includes a map variable, whose keys are ids used in HTML placeholders and values are translated texts. For example, a file “lang.sl.js” includes slovene translations:

var lang = {
    home: "Domov",
    about: "O programu",
    functionalities: "Funkcionalnosti",

Now, as we have everything prepared, we are going to write a JS script that (A) automatically detects a selected language from query string, (B)  includes an appropriate translation file and (C) automatically populates prepared HTML placeholders. I do this as follows:

$(document).ready(function() {
	$.urlParam = function(name){
		var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
		if (results==null){
		   return null;
		   return results[1] || 0;
	function loadJS(file) {
		var jsElm = document.createElement("script");
		jsElm.type = "application/javascript";
		jsElm.src = file;
	if ($.urlParam("lang") == "en") {
		$("#lang-en").css("font-weight", "bolder");
	} else if ($.urlParam("lang") == "hr") {
		$("#lang-hr").css("font-weight", "bolder");
	} else {
		$("#lang-sl").css("font-weight", "bolder");	
	function fillIn(key, value) {
		document.getElementById(key).innerHTML = value;	 	
	//Fill in translations	
	for(var key in lang) {
	  fillIn(key, lang[key]);

Additionally to that basic example I added some exceptions to insert language-specific values into some HTML tag attributes.

Such approach works like a charm for about 200 language keys – I have not tested for more. The whole site is served by an RPi and JS loading of language-specific texts is not noticeable on a client.

Part 3/3: Reading analog input using RPi

Continuing from the previous example, we would like our LED to turn on automatically, based on the light level of the environment.


First we need to read the value of the photocell that measures the value of light. Photocells (aka. photoresistor) acts as a dynamically-adapting resistor according to the light levels. In dark areas, the resistance is high and in bright areas the resistance is low.

As Raspberry Pi does not have an analog input, we can make a trick to read a value from an analog sensor (resistor-based sensor). We just use a small capacitor and measure time that is needed to fill the capacitor to the full level.

On Raspberry Pi we use 3.3V pin as power supply, GND as ground and pin 18 as an input pin that will be used to measure time to fill the capacitor. In the circuit we measure voltage levels using pin 18 between photoresistor and capacitor.

To get the light level, we need to:

  1. Set pin 18 as out and to LOW voltage.
  2. Set pin 18 as input to be able to read input voltage. Now we can just read if voltage is LOW or HIGH.
  3. Measure, how much time is needed until read voltage on pin 18 is HIGH.

Normally you can use a 1μF but we had just a capacitor of 100μF (if it is designed to higher voltage, it is okay). The difference is only you will need more time to fill the capacitor in darker conditions. In our case, we need about 800000ms to detect dark light and about 30000ms to detect twilight.

Automatic light switching

Above we got the information whether the light conditions are daylight, twilight or darkness. Now we set a LED that will be turned off in daylight, burn lightly in twilight and be very bright in darkness.

For this, we use two pins to turn on a LED and for each pin, we use different resistor to set the brightness of a LED. For darkness we use a 220Ohm resistor and for twilight we use 1120Ohm (2x560Ohm) resistor.

The script to control all of the above looks like:

#!/usr/bin/env python
import RPi.GPIO as GPIO, time, os
#Variables setup
class Light(object):
        DAYLIGHT = "Daylight"
        TWILIGHT = "Twilight"
        DARKNESS = "Darkness"
def LightInfo():
        # This takes about 1 millisecond per loop cycle
        repeats_to_full_capacitor = 0
        while (GPIO.input(LIGHT_STATUS_PIN) == GPIO.LOW):
                repeats_to_full_capacitor += 1
        if (repeats_to_full_capacitor < TWILIGHT_THRESHOLD):
                return Light.DAYLIGHT
        elif (repeats_to_full_capacitor < DARK_THRESHOLD):
                return Light.TWILIGHT
                return Light.DARKNESS
def TurnLEDOnOff(status):
        #Turn all off
        #Turn appropriate pin on
        if (status == Light.TWILIGHT):
                GPIO.setup(DARKNESS_LIGHT_PIN, GPIO.IN)
                GPIO.output(TWILIGHT_LIGHT_PIN, GPIO.HIGH)
        elif (status == Light.DARKNESS):
                GPIO.setup(TWILIGHT_LIGHT_PIN, GPIO.IN)
                GPIO.output(DARKNESS_LIGHT_PIN, GPIO.HIGH)
#Main program
status = Light.DAYLIGHT
while True:
        newStatus = LightInfo()
        print newStatus
        if (newStatus != status):
                status = newStatus

When we run the script as “sudo ./LightSwitch.py” in daylight conditions, the LED is off:


In twilight, the LED is not that bright:


Lastly in the darkness, the LED becomes very bright:


Part 2/3: OpenHAB + RPi + LEDs + Camera

We are continuing with the example from the first part of the tutorial: https://blog.zitnik.si/2016/02/04/part-13-controlling-leds-using-raspberry-pi/.

In this part we are going to install OpenHAB platform on an RPi and remotely control LEDs.

OpenHAB (http://www.openhab.org/)  is a software that is intended to connect to many sensors or devices for home automation. It works as a smart devices gateway and includes tools to design a custom GUI to control these connected smart devices. A GUI can be accessed using a web browser or from a nice mobile application (iOS, Android).

OpenHab Installation

We first installed OpenHAB core and then Demo from the official site: http://www.openhab.org/getting-started/downloads.html. These are compressed packages which I unzip into /opt/openhab folder. Within the new directory, there’ll be a folder called configurations. Within this folder create a copy of the default configuration file openhab_default.cfg and name it openhab.cfg. This is where you’ll store all your settings for openHAB and any bindings you need.

To start the OpenHAB server, run /opt/openhab/start.sh.

OpenHAB configuration

To control our LEDs we will need to create three files.

Create a file configurations/items/default.items. This will be an inventory for definition of our sensors. The file should look like:

Switch RedLight				"Rdeca luc"
Switch GreenLight			"Zelena luc"
Switch YellowLight			"Rumena luc"

The next file should define the rules and actions for these sensors. So, create a file named configurations/rules/default.rules to look like:

import org.openhab.core.library.types.*
import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*
import org.openhab.action.pushover.*
import org.openhab.action.pushover.internal.*
rule "RedLight changed"
 Item RedLight received command ON
 logInfo("RedLight", "Received red light command to turn on.")
 executeCommandLine("python /home/pi/red_on.py")
 pushover("Rdeca luc je bila prizgana.")
rule "RedLight changed"
 Item RedLight received command OFF
 logInfo("RedLight", "Received red light command to turn on.")
 executeCommandLine("python /home/pi/red_off.py")

As you can see I also configured the pushover service so that I am notified about the change via a push notification. It can also be observed that on some command received, a log message is created and a command line script is executed. These scripts look the same as in the first part of the tutorial, where we introduced how to turn LED on or off.

In the last file, named configuration/sitemaps/default.sitemap we will define the GUI for our application. Our file looks like this:

sitemap demo label="Raspberry demo"
 Frame label="Luci" {
   Switch item=GreenLight label="Zelena luc"
   Switch item=YellowLight label="Rumena luc"
   Switch item=RedLight label="Rdeca luc"
 Frame label="Videokamere" {
   Text label="Raspberry kamera" icon="video" {
     Frame label="Raspberry kamera" {
       Video url="http://localhost:8081?action=stream" encoding="mjpeg"
   Text label="Raspberry kamera" icon="garden" {
     Frame label="Raspberry kamera (snapshot)" {
       Image url="http://localhost:8081?action=snapshot" refresh=5000

For now you can skip the “Videokamere” part as it defines video stream and snapshot images of a camera that we will attach to the raspberry (below).

As you save the file and run the server, the GUI can be accessed via a web browser using URL http://RPi_IP:8080:

Screen Shot 2016-02-04 at 14.01.19

You can also use this URL in a mobile application and have a native interface – e.g. on your iPhone, which looks like this (for our sitemap definition):


You should now be able to turn on or off your LEDs using OpenHAB platform. Try it out!

OpenHAB and Raspberry Pi Camera Module

Now we would also like to check our lights remotely via a camera. We will use mjpeg stream for video streaming.

We have an RPi Camera Module, which we attached to the RPi. After that we run “sudo raspi-config” command and enable the camera module.

First we need to install some dependencies:

sudo apt-get install libjpeg8-dev
sudo apt-get install imagemagick
sudo apt-get install libjpeg62-dev
sudo apt-get install cmake
sudo apt-get install libv4l-dev
#create a symbolic link
sudo ln -s /usr/include/libv4l1-videodev.h /usr/include/linux/videodev.h

Then we download mjpeg repository and build the library:

# You can also choose to download some stable version instead of current master
git clone https://github.com/jacksonliam/mjpg-streamer.git .
sudo make clean all

Now copy the directory of build files to /opt/mjpg-streamer and run mjpeg streamer using the following command (I am using parameter vf to vertically flip the image):

LD_LIBRARY_PATH=/opt/mjpg-streamer /opt/mjpg-streamer/mjpg_streamer -i "input_raspicam.so -fps 5 -q 50 -x 640 -y 480 -vf" -o "output_http.so -w /opt/mjpg-streamer/www -p 8081" &

If everything is okay, a video stream should be accessible at http://RPi_IP:8081:

Screen Shot 2016-02-04 at 14.26.03

Also if OpenHAB is configured as above, videostream should be accesible over its GUI:

Screen Shot 2016-02-04 at 14.28.36