PyScada on Raspberry PI for temperature monitoring with DS18B20 on 1-Wire – Part 4 – PyScada HMI Configuration

In this part of the series we will configure the PyScada HMI using the web interface.

PyScada HMI Structure.

The PyScada HMI has a display structure based on a hierarchy of:

  • Views – Collections of pages
  • Pages – Collections of widgets that make up a single page
  • Widgets – Objects that control the layout of the page and the position of the various HMI components
  • HMI components – The actual objects that make up the HMI, charts, control panels  or custom html panel

The following diagrams shows the relationship the various items using an example implementation.

Views

The diagram below shows two separate views, the intention here is that the views group pages into two groups, one designed for operators and the other for engineers.

Dia-Views

Pages and Widgets

In the diagram below the relationships formed on a single page are shown. This page for motors will contain four objects, a control panel and a chart each for two motors. When building pages the objects are laid out by containing them in widgets, the widget positions are defined by their position in a row/column relationship.

Dia-Pages

HMI Components

We can now discuss the three types of HMI components.

Charts

Simply graphs of the data recorded in PyScada for the points selected.

Chart

Control Panels

Again a hierarchy is applied here with a Control Panel being a collection of Control Items. A number of Control Items are available shown in the screenshot below:

Note: as the only devices I have connected to PyScada at the time of writing are the temperature sensors I do not have digital inputs to test the indicators below with. I hope the information below on the labels is not misleading.

Control Items

Label Blue

A blue text label that background changes colour based on the input variable (shown in deactivated state above).

Label Light Blue

A light blue text label that background changes colour based on the input variable (shown in deactivated state above).

Label OK

A green text label that background changes colour based on the input variable (shown in deactivated state above).

Label Warning

A yellow text label that background changes colour based on the input variable (shown in deactivated state above).

Label Alarm

A red text label that background changes colour based on the input variable (shown in deactivated state above).

Label Alarm Inverted

A red text label that background changes colour based on the input variable (shown in deactivated state above).

Control Element

A collection of displays and update buttons to set a value in the host device.

Display Value

A simple string based text display of the variable.

Custom HTML Panels

These will require a topic of their own due to the complexity but as an overview you can write your own HTML to be inserted into the page and have PyScada render some components. As a basic example the following table, note the temperature column is realtime measurements from PyScada.

CustomHTML

This was generated using the code below

<table>
<tr>
<th>Sensor Number</th>
<th>Sensor Location</th>
<th>Temp</th>
</tr>
<tr>
<td>01</td>
<td>Bedroom 1</td>
<td><span class="type-numeric var-Var-Temp-01">NaN</span></td>
</tr>
<tr>
<td>02</td>
<td>Bedroom 2</td>
<td><span class="type-numeric var-Var-Temp-02">NaN</span></td>
</tr>
<tr>
<td>03</td>
<td>Bedroom 3</td>
<td><span class="type-numeric var-Var-Temp-03">NaN</span></td>
</tr>
<tr>
<td>04</td>
<td>Lounge Room</td>
<td><span class="type-numeric var-Var-Temp-04">NaN</span></td>
</tr>
<tr>
<td>05</td>
<td>Kitchen</td>
<td><span class="type-numeric var-Var-Temp-05">NaN</span></td>
</tr>
<tr>
<td>06</td>
<td>Office</td>
<td><span class="type-numeric var-Var-Temp-06">NaN</span></td>
</tr>
<tr>
<td>07</td>
<td>Front Door</td>
<td><span class="type-numeric var-Var-Temp-07">NaN</span></td>
</tr>
<tr>
<td>08</td>
<td>Old Kitchen</td>
<td><span class="type-numeric var-Var-Temp-08">NaN</span></td>
</tr>
<tr>
<td>09</td>
<td>Outside</td>
<td><span class="type-numeric var-Var-Temp-09">NaN</span></td>
</tr>
<tr>
<td>10</td>
<td>Attic</td>
<td><span class="type-numeric var-Var-Temp-10">NaN</span></td>
</tr>
</table>

PyScada HMI Implementation.

Now that we have the basics of the PyScada system this section will build a HMI for monitoring our temperature sensors. The diagram of the PyScada implementation is shown below.

Dia-Plan

As shown in the diagram above we will create a single view containing one page. On this page will be three HMI components, a “Control Panel”, a “Custom HTML Panel” and a chart. To create this system we will work form the inside out, creating the three HMI components, setting up a new page then its contents using widget definition and finally defining a view to hold them all.

Control Panel – List of temperatures

Log into the web interface as described in Part 3 (Link) scroll down on the administration menu to find the HMI section.

Blog-4-1

Click the “Control Items – Add” button and create a display value for each of the 10 temperatures. The first one is shown below, the position field allows for control of the order when there is more than one of these used in a control panel.

Blog-4-2.PNG

I repeated this process for the other 9 variables to build a list of control items as shown below.

Blog-4-3.PNG

Now we can combine them into a Control Panel, from the administration menu choose “Control Panels – Add”

Blog-4-1

Create a new Control Panel and add all the DV-Temp-xx display values we just created to it.

Blog-4-4

Click save and that is our “Control Panel” complete.

Custom HTML Panel

This panel will be generated in the next post in this series, mostly because I have not written it yet but I expect it to be large enough to demand its own post. For now we will simply place a simple rectangle with a line in it using the code below.

<h1>Testing</h1>
<canvas id="HouseCanvas" width="300" height="150"></canvas>
<script>
var c = document.getElementById("HouseCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>

From the administration menu

Blog-4-1

Click the “Custom HTML Panels – Add” button and complete the form as shown below, I just added a single variable but for the moment we are not defining any references to the temperature.

Blog-4-13.PNG

This completes our placeholder Custom HTML panel.

Chart

This chart will show the historical data for all the 10 temperature sensors.

From the administration menu

Blog-4-1

Click the “Charts – Add” button and complete the form as shown below.

Blog-4-6.PNG

Click save and the chart configuration is complete.

Page

Create a page to hold the widgets that assemble the page, from the administration menu

Blog-4-1

Click the “Pages – Add” button and name it as shown below.

Blog-4-7.PNG

Click save and then move on to the Widget configuration

Widget

Create the first widget, from the administration menu

Blog-4-1

Click the “Widgets – Add” button and name it as shown below.

Blog-4-8

Then complete the other two based on the details below.

Blog-4-9.PNG

We now have our page configured with three widgets containing items. Now we need to add a view to provide access to the page.

View

Create a view to hold the page, from the administration menu

Blog-4-1

Click the “Views – Add” button and name it as shown below (the other fields further down can be left as default)

Blog-4-10

Review the results

The configuration is now complete, head back to the main page and the new view should be visible.

Blog-4-12.PNG

Click on the “Home Temperatures” link to access our new page. This looks as expected however some tidy up is definitely required.

Blog-4-14

Advertisements

PyScada on Raspberry PI for temperature monitoring with DS18B20 on 1-Wire – Part 3 – PyScada Basic Configuration

In this part we will perform initial configuration of the 1-Wire devices into PyScada system and then create a simple interface for displaying our measurements. In the screenshots below you may notice the two different IP addresses, I have taken some of these screenshots from different instances but the content should be ok.

Logging in

From a web browser connect to the IP address of your Raspberry PI, click on the Admin button and login with the superuser password we created in part 1 of this series (Link)

Raspi-03

After logging in you will be presented with the main menu looking something like this.

Raspi-05

and continuing like this

Raspi-06.png

Setup 1-wire inputs

PyScada has a model of abstraction in the devices and the variables. As a result we need to create a “Device” before connecting the “One wire device” to this generic device, similarly we need to create variables before connecting the 1-wire variables to them.

In the “PyScada Core” section at the top we need to add a device. Click the add button next to “Devices” and add the details similar to the screenshot below, note the polling interval setting can be adjusted to suit your requirements. Click “Save” and go back to the main menu by clicking “Home”

Raspi-07

Now scrolling down the bottom of the main menu in the section “PyScada Onewire” click the Add “One Wire Devices” button to connect the actual 1-wire interface to the device we already created. Check the details in the screenshot below and click save, then back to the main menu again.

Raspi-08

Now that we have the overarching devices configured we can configure the first actual sensor.  Back on the main menu in the PyScada Core section click Add next “Variables” and configure as shown below.

Raspi-09

Then just like with the devices now head down to the PyScada OneWire variables section and click Add.

 

Click on the magnifying glass to select the variable we wish to connect the address to. Then set the address location to the serial number of the 1-wire device, in Part 2 (Link) in the “Software and first measurements” section we listed the 1-wire devices on my network as being.

28-0317019e43ff
28-031701a251ff
28-031701e813ff
28-031701e81aff
28-0416b3e789ff
28-041701e0caff
28-041701e495ff
28-04170201acff
28-0417020b6bff
28-0417020be3ff
28-0417022dd5ff

To complete the setup we need to use the address field without the 28- at the front. The screenshot below shows the configuration for the third sensor on the list, which happens to be the one I marked as sensor 1.

Raspi-10

I now repeated this process for all my sensors before moving on to the display elements, these will be covered in part 4 of this series.

PyScada on Raspberry PI for temperature monitoring with DS18B20 on 1-Wire – Part 2 – DS18B20 Hardware and Software

Following on from Part 1 (Link)  of this series, this post will cover the DS18B20 and 1-wire communication parts of this project.

Hardware Design

The DS18B20s are connected to the Raspberry PI based on the schematic below.

Using the Raspberry PI’s internal 3.3V Supply and GND pins we can power the DS18B20s on their VDD and GND pins respectively. The 1-wire network is a daisy chained system so we just tie all the DQ pins together. The final component is a single 4.7kOhm resistor that we connect across the 3.3V and Data line. The choice of GPIO4 for the 1-wire connection for the Rasberry PI is based on the default configuration of the 1-wire module.
Raspi-04

The full details are available on the circuits.io page at this (Link).

Current Considerations

When designing the system it was noted that the temperature sensors are powered by the Raspberry PI internal 3.3V supply. It was difficult to find definition of the maximum current rating of the 3.3V regulator. Some sources described the maximum demand from a GPIO point of view to be 50mA however others point out that the hardware has changed between revisions and that this is likely a very conservative number.

If we start with this 50mA number and head to the DS18B20 datasheet (Link) in the DC characteristics table the maximum active current is 1.5mA and the typical is 1mA. So considering the design above does not have anything else connected to the to the 3.3V bus and the likely conservative nature of the 50mA maximum we are looking at being able to calculate the maximum number of DS18B20 on our network using the formula below.

Number of Devices = \frac{50mA}{1.5mA} = 33

This is many more devices than I will be using so we can continue as planned.

Software testing and first measurements

In part 1 (Link) of this series we turned on 1-wire support in the raspi-config application. With the devices connected the setup is complete. Login to the Raspberry PI using SSH run the command below to access the folder where the 1-wire devices will be enumerated and then list everything in the directory.

cd /sys/devices/w1_bus_master1/
ls

My results are below.

28-0317019e43ff
28-031701a251ff
28-031701e813ff
28-031701e81aff
28-0416b3e789ff
28-041701e0caff
28-041701e495ff
28-04170201acff
28-0417020b6bff
28-0417020be3ff
28-0417022dd5ff
driver
power
subsystem
uevent
w1_master_add
w1_master_attempts
w1_master_max_slave_count
w1_master_name
w1_master_pointer
w1_master_pullup
w1_master_remove
w1_master_search
w1_master_slave_count
w1_master_slaves
w1_master_timeout
w1_master_timeout_us

While there is a number of different items here rows 1-11 are the ones that we are interested in at the moment. At the time of writing I have 11 DS18B20 devices connected to the Raspberry PI and their unique serial numbers are listed starting with 28- and ending in ff. The 1-wire driver automatically searches the network and lists the devices found here by creating a folder for each device. If we now look inside the first devices folder using

cd /sys/devices/w1_bus_master1/28-0317019e43ff
ls

We get the following results

driver
id
name
power
subsystem
uevent
w1_slave

Again there are a number of useful files here but the one we are interested in is called w1_slave. Run the cat command to read the file.

cat /sys/devices/w1_bus_master1/28-0317019e43ff/w1_slave

Returns

1e 01 4b 46 7f ff 0c 10 18 : crc=18 YES
1e 01 4b 46 7f ff 0c 10 18 t=17875

This file shows us the current reading by this sensor. The two components that are useful here are the crc=18 YES. Where the YES confirms that we have a valid reading and that it did not get corrupted in transit. The other t=17875 is the temperature measured in millidegree Celsius where the temperature in the room is 17.875 Degrees Celsius.

That’s the basic temperature measurements working nicely, the next part of this series will be about implementing PyScada for monitoring and logging.

PyScada on Raspberry PI for temperature monitoring with DS18B20 on 1-Wire – Part 1 – Software Installation

When looking for a temperature monitoring solution I considered a number of options but landed on the DS18B20 sensors in a TO-92 package (Datasheet Link). These nifty little sensors are cost effective and provide an accuracy of +-0.5 degrees over a range much wider than the temperature range in my house. These also provide a 1-wire interface that is compatible with the old Raspberry PI model B I have in the cupboard.

Initial operating system configuration

Starting with the RaspberryPI model B I went for the Rasbian Stretch lite iso (Download Link) and wrote it to an SD card using Etcher (Download Link). Connecting the RaspberryPI to a HDMI cable, usb keyboard and the freshly written SD card the system was ready for first boot.

After first power up the login with the default username and password

pi
raspberry

After login run the update commands to ensure that our operating system is up to date

sudo apt-get update
sudo apt-get dist-upgrade

Then perform some initial configuration using the raspi-config

 sudo raspi-config 

Raspi-01

From this application perform the following configurations

Set the password to something unique instead of the default

Menu 1 - Change Password

Set the Localisation settings

Menu 4 - Localisation
Menu I1 - Change Locale
Set to en_AU UTF-8 UTF-8
Untick en_GB UTF-8
Set en_AU UTF-8 to default

Set the timezone

Menu 4 - Localisation
Menu I1 - Chage Timezone

Enable SSH so we can perform the remainder of the configuration from a remote PC

Menu 5 - Interfacing Option
Menu P2 - Enable SSH

Enable the 1-wire support

Menu 5 - Interfacing Option
Menu P7 - Enable 1-wire

Select finish to complete the configuration
Reboot
On reboot note the “My IP Address is 192.168.1.14” line on the boot screen, we will need this to remotely login to the raspberry pi

Remotely Connect the Raspberry PI

To connect to the Raspberry PI remotely we will use the SSH server we enabled in the previous section. My preferred SSH client for Windows is putty (Download Link)

Run putty and all we need to set is the IP Address of the Raspberry PI and click open. This will provide a remote command prompt to complete the installation of PyScada and the testing of our 1-wire network.

Installation and configuration of PyScada

These instructions are based on the instructions at http://pyscada.rtfd.io/ however these instructions cover a wide range of linux distributions and hardware and I struggled to get the correct combination for the Raspberry PI.

Create a user dedicated to the PyScada application

sudo -i
sudo useradd -r pyscada
sudo mkdir -p /var/www/pyscada/http
sudo chown -R pyscada:pyscada /var/www/pyscada
sudo mkdir -p /home/pyscada
sudo chown -R pyscada:pyscada /home/pyscada
sudo ln -s /var/www/pyscada/ ~/www_pyscada

Install the dependencies, PyScada and then create the django project

sudo apt-get -y install python-pip libhdf5-dev python-dev nginx gunicorn
sudo pip install cython
sudo pip install numpy
sudo export HDF5_DIR=/usr/lib/arm-linux-gnueabihf/hdf5/serial/
sudo pip install h5py
sudo pip install https://github.com/trombastic/PyScada/archive/dev/0.7.x.zip
cd /var/www/pyscada/
sudo -u pyscada django-admin startproject PyScadaServer

Edit the configuration files

sudo nano /var/www/pyscada/PyScadaServer/PyScadaServer/urls.py

Set the file to the following:

"""PyScadaServer URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('pyscada.hmi.urls')),
]
sudo nano /var/www/pyscada/PyScadaServer/PyScadaServer/settings.py

Edit the file to the following:

Add this to the top

#!/usr/bin/python
# -*- coding: utf-8 -*-

Change

DEBUG = False

Set

ALLOWED_HOSTS = ['*']

Set

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'pyscada',
    'pyscada.modbus',
    'pyscada.phant',
    'pyscada.visa',
    'pyscada.hmi',
    'pyscada.systemstat',
    'pyscada.export',
    'pyscada.onewire'
]

Add this to the bottom

STATIC_ROOT = '/var/www/pyscada/http/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = '/var/www/pyscada/http/media/'

# PyScada settings
# https://github.com/trombastic/PyScada

# email settings
DEFAULT_FROM_EMAIL = 'example@host.com'
EMAIL_HOST = 'mail.host.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'pyscada@host.com'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PREFIX = 'PREFIX' # Mail subject will be "PREFIX subjecttext"

# meta informations about the plant site
PYSCADA_META = {
        'name':'A SHORT NAME',
        'description':'A SHORT DESCRIPTION',
}

# export properties
#
PYSCADA_EXPORT = {
        'file_prefix':'PREFIX_',
        'output_folder':'~/measurement_data_dumps',
}

The file at the end should look something like mine below (note the secret key will be different)

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
Django settings for PyScadaServer project.

Generated by 'django-admin startproject' using Django 1.11.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8*5gy8$$e8&+cka+&a1lz!#_)s*#zooz6d!+7!f*j%z+uxx376'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'pyscada',
    'pyscada.modbus',
    'pyscada.phant',
    'pyscada.visa',
    'pyscada.hmi',
    'pyscada.systemstat',
    'pyscada.export',
    'pyscada.onewire'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'PyScadaServer.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'PyScadaServer.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = '/var/www/pyscada/http/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = '/var/www/pyscada/http/media/'

# PyScada settings
# https://github.com/trombastic/PyScada

# email settings
DEFAULT_FROM_EMAIL = 'example@host.com'
EMAIL_HOST = 'mail.host.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'pyscada@host.com'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PREFIX = 'PREFIX' # Mail subject will be "PREFIX subjecttext"

# meta informations about the plant site
PYSCADA_META = {
        'name':'A SHORT NAME',
        'description':'A SHORT DESCRIPTION',
}

# export properties
#
PYSCADA_EXPORT = {
        'file_prefix':'PREFIX_',
        'output_folder':'~/measurement_data_dumps',
}

Configure the PyScada Installation

Build the basic instance of PyScada

cd /var/www/pyscada/PyScadaServer
sudo -u pyscada python manage.py migrate
sudo -u pyscada python manage.py collectstatic
sudo -u pyscada python manage.py loaddata color
sudo -u pyscada python manage.py loaddata units

Create the admin user within PyScada

sudo -u pyscada python manage.py createsuperuser

Note your username and password you will need this later to login

Configure nginx

Get the nginx configuration from the PyScada source

sudo wget https://raw.githubusercontent.com/trombastic/PyScada/dev/0.7.x/extras/nginx_sample.conf -O /etc/nginx/sites-available/pyscada.conf
sudo nano /etc/nginx/sites-available/pyscada.conf

My version is below, the only item I set is the server_name to the IP address of my Raspberry PI.

# pyscada.conf

# the upstream component nginx needs to connect to
upstream app_server {
        server unix:/tmp/gunicorn.sock fail_timeout=0; # for a file socket
        #server 127.0.0.1:8000 fail_timeout=0; # for a file socket
}

# configuration of the server
server {

        listen 80 default;     # the port your site will be served on
        server_name 192.168.1.14;      # substitute your machine's IP address or                                                                                                                                                              FQDN
        charset utf-8;
        keepalive_timeout 5;
        client_max_body_size 75M;   # max upload size, adjust to taste

        # Django media
        location /media  {
                alias /var/www/pyscada/http/media;  # your Django project's medi                                                                                                                                                             a files - amend as required
        }

        location /static {
                alias /var/www/pyscada/http/static; # your Django project's stat                                                                                                                                                             ic files - amend as required
        }
        location / {
            # checks for static file, if not found proxy to app
            try_files $uri @proxy_to_app;
        }

        location @proxy_to_app {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;

            proxy_pass   http://app_server;
        }
}

Activate the PyScada nginx site, remove the default one, start the nginx service on boot and restart the service.

sudo ln -s /etc/nginx/sites-available/pyscada.conf /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default
sudo systemctl enable nginx.service
sudo systemctl restart nginx

Download the other systemd services from PyScada and activate them.


sudo wget https://raw.githubusercontent.com/trombastic/PyScada/dev/0.7.x/extras/service/systemd/pyscada_daq.service -O /lib/systemd/system/pyscada_daq.service
sudo wget https://raw.githubusercontent.com/trombastic/PyScada/dev/0.7.x/extras/service/systemd/pyscada_event.service -O /lib/systemd/system/pyscada_event.service
sudo wget https://raw.githubusercontent.com/trombastic/PyScada/dev/0.7.x/extras/service/systemd/pyscada_mail.service -O /lib/systemd/system/pyscada_mail.service
sudo wget https://raw.githubusercontent.com/trombastic/PyScada/dev/0.7.x/extras/service/systemd/pyscada_export.service -O /lib/systemd/system/pyscada_export.service
sudo wget https://raw.githubusercontent.com/trombastic/PyScada/dev/0.7.x/extras/service/systemd/gunicorn.socket -O /lib/systemd/system/gunicorn.socket
sudo wget https://raw.githubusercontent.com/trombastic/PyScada/dev/0.7.x/extras/service/systemd/gunicorn.service -O /lib/systemd/system/gunicorn.service
# enable the services
sudo systemctl enable gunicorn
sudo systemctl enable pyscada_daq
sudo systemctl enable pyscada_event
sudo systemctl enable pyscada_mail
sudo systemctl enable pyscada_export

I had issues with the service files provided so in each of them I needed to make the following change.

In each of these files

/lib/systemd/system/pyscada_daq.service
/lib/systemd/system/pyscada_event.service
/lib/systemd/system/pyscada_mail.service
/lib/systemd/system/pyscada_export.service
/lib/systemd/system/gunicorn.service

Use the following commands

sudo nano /lib/systemd/system/pyscada_daq.service
sudo nano /lib/systemd/system/pyscada_event.service
sudo nano /lib/systemd/system/pyscada_mail.service
sudo nano /lib/systemd/system/pyscada_export.service
sudo nano /lib/systemd/system/gunicorn.service

Replace the line

replace all the %u with pyscada or the username you intend to use

Then I needed to reduce the number or guincorn workers as the load was too high for my little Raspberry PI.

sudo nano /lib/systemd/system/gunicorn.service

Edit the line

ExecStart=/usr/bin/gunicorn --pid /tmp/gunicorn.pid --workers 8 PyScadaServer.wsgi:application

To

ExecStart=/usr/bin/gunicorn --pid /tmp/gunicorn.pid --workers 3 PyScadaServer.wsgi:application

From here restart the Raspberry PI and give it a few minutes to catch up and that is the end of the initial configuration. From a web browser we can now connect to the IP Address of the Raspberry PI and access the web based configuration interface.

Raspi-03

In the next post we will look at connecting and testing the 1-wire network to the Raspberry PI and after that the setup of PyScada. Click here (Link) for part 2 of this series.

Install and Setup of Bit Torrent Sync (btsync) on Raspberry PI for Family Photo Sync

Note: This post is a work in progress and will become more detailed as I complete the project.

This post will guide you through the process of installing Bit Torrent Sync on a Raspberry PI for the purpose of syncing family photos between computers.

This system will include, Windows 7, Windows XP and Linux Mint clients with the initial server located on the Raspberry PI.

Installation of main instance on Raspberry PI

Login to the Raspberry PI via ssh and run the following commands, I am running RaspBMC (debian based).

Download the latest copy of bysync

pi@raspbmc:~$ wget http://btsync.s3-website-us-east-1.amazonaws.com/btsync_arm.tar.gz

Extract the Tarball

 pi@raspbmc:~$ tar -xzf btsync_arm.tar.gz

When I tried to run ./btsync to execute the application I got the following error.

pi@raspbmc:~$ ./btsync
-bash: ./btsync: No such file or directory

To resolve this we need to symlink the following library

pi@raspbmc:~$ sudo ln -s /lib/arm-linux-gnueabihf/ld-linux.so.3 /lib/ld-linux.so.3

Now dump a copy of the default configuration file

pi@raspbmc:~$ ./btsync --dump-sample-config >> sync.conf

We now have a sync.conf file with the default settings.

Host Configuration

The following lines of the default configuration file require modification

“device_name”: “RaspberryPI-Craig”,
“listening_port” : 55555,

“storage_path” : “/home/user/DataFolder”,

“use_upnp” : false,

“listen” : “0.0.0.0:8888”,
“login” : “admin”,
“password” : “password”

To start btsync automatically get the init.d script from https://gist.github.com/MendelGusmao/5398362

Copy the text to /etc/init.d/btsync

Allow execution of init.d script with chmod +x btsync

Edit the init.d script to set the username

copy the btsync binary to /usr/bin/btsync

Autostart the init.d script with

sudo update-rc.d btsync defaults

If you reboot your raspberry pi it should not start btsync automatically.

Following the reboot you should be able to access the web interface of bysync using the username, password and web address defined in the configuration file.

My address was http://192.168.0.2:8888

From here you can create folder shares.

Network Configuration

On your router port forward the listening port to the raspberry pi.

The port you need is the one defined in the “Listening Port” in the configuration file.

I also needed to modify the raspbmc firewall to let external traffic into my listening port.

in /etc/network/if-up/secure-rmc look for the section with the lines that look like IP table configurations and add these two lines

iptables -A INPUT -p tcp --dport 55555 -i $IFACE -j ACCEPT
iptables -A INPUT -p udp --dport 55555 -i $IFACE -j ACCEPT

Client Configuration

From the servers web interface create a one time key.

Add this key to the client and you will be syncing.

 

BeagleBone SFTP issues with Demo Images

When using the demo images and attempting to use WinSCP or some other sftp application you may get an error like

“Cannot initialize SFTP protocol. Is the host running a SFTP server?” from WinSCP or

“Connecting
[SFTP] Host key accepted
[SFTP] Successfully authenticated
[SFTP] Error initialising sftp: Access denied. Authentication that can continue: publickey,password
Unable to connect”

from Notepad++

This is due to demo images not including the openssh-sftp-server package by default

To install login to the Beaglebone using SSH (via putty) and run

opkg update

opkg install openssh-sftp-server

Your WinSCP or Notepad++ or other SFTP application should now work nicely

BeagleBone Mux Settings – Lookup Table

Download links are below for full A3 printable tables showing the details of the BeagleBone multiplexer settings.
To configure the BeagleBone multiplexer under Angstrom from the command line use

echo 6 > /sys/kernel/debug/omap_mux/gpmc_a2

Where

6 = Multiplexer Mode

gpmc_a2 = the Mode0 name of the pin you are trying to configure

Results in setting of Port 9 Pin 14 soe ehrpwm1A_mux1

Download links for Mux Lookup tables

BeagleBone-Port8-Mux-A3-Rev1.pdf

BeagleBone-Port9-Mux-A3-Rev1.pdf

BeagleBone-Port8-Mux-A3-Rev1.xlsx

BeagleBone-Port9-Mux-A3-Rev1.xlsx

Install BeagleBone C Build Environment and Write Hello World for BeagleBone Using C and a Makefile

All these instructions are to be run on the Beaglebone itself using putty.

Install the C Compiler, make and a few other bits and pieces with

opkg install task-native-sdk

Make a folder for your code by running

mkdir code

cd code

Now create a makefile using nano

nano Makefile

Paste the following code and then press ctrl+O and then ctrl+x

CC = gcc
CFLAGS = -Wall -g -O2
OBJECTS = main.o

all: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o main

Now create the C source file by running

nano main.c

Paste the following code and then press ctrl+O and then ctrl+x

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main (int argc, char **argv)
{
printf (“Hello from BeagleBone”);
return 0;
}

To compile your new application run

make all

To run your application

./main

 

Setup Time Service to Set the Clock on Angstrom BeagleBone

If you run the “date” command and see a date not far from Jan 1 2000 then you will need to set the date.

Update your Package List

opkg update

Get the ntp Package

opkg install ntp ntpdate

Remove the file that describes your local time

rm /etc/localtime

Add a symlink between the file that describes your timezone in the timezones folder to the localtime file.

If you do not live in the sydney nsw timezone you may need to look around in the /usr/share/zoneinfo folder for your timezone.

ln -s /usr/share/zoneinfo/Australia/Sydney /etc/localtime

Now we need to stop the ntpd service so we can request a manual update

/etc/init.d/ntpd stop

Now request the manual update

ntpdate pool.ntp.org

Confirm the correct time with the “date” command

Restart the ntp daemon with

/etc/init.d/ntpd start

 ToDo

  • Add insructions to start the service automatically on boot. If someone knows how to autostart an Angstrom Service please let me know.

How To Build Custom Angstrom Build for BeagleBone with Ubuntu or Debian

This guide details the process of building a systemd image from the Angstrom source on a ubuntu or debian host.

For the steps below I have used Debian 6.0.4 via a net install

Install Debian 6.0.4 net install choosing only Standard system utilites

From root command prompt run

sudo apt-get install openssh-server

This will allow us to access the machine remotely via ssh

Following instructions on http://wiki.openembedded.org/index.php/OEandYourDistro#Debian

Install the mandatory packages as root

sudo apt-get install sed wget cvs subversion git-core coreutils unzip texi2html texinfo docbook-utils gawk python-pysqlite2 diffstat help2man make gcc build-essential g++ desktop-file-utils chrpath dosfstools kpartx

Logout as root and return to regular user

Following instructions on http://www.angstrom-distribution.org/demo/beaglebone/ in the section down the bottom on “how to reproduce”

Run the following commands

git clone git://git.angstrom-distribution.org/setup-scripts

EDIT: I had trouble with this line since I posted this so I have since been using “git clone https://github.com/Angstrom-distribution/setup-scripts.git”


cd setup-scripts
./oebb.sh config beaglebone/

MACHINE=beaglebone ./oebb.sh bitbake systemd-image

When the build completes the files of interest will be stored in.

cd ~/setup-scripts/build/tmp-angstrom_2010_x-eglibc/deploy/images/beaglebone/

Insert the BeagleBone SD Card into the debian host.

Run dmesg

you should see the last few lines look like this
[28915.028000] mmc0: new SDHC card at address 1234
[28915.675869] mmcblk0: mmc0:1234 SA04G 3.63 GiB
[28915.675912] mmcblk0: p1 p2
The above notes show that we have an SD card mounted at /dev/mmc/blk0

We now want to format the SD card using the script file here http://www.angstrom-distribution.org/demo/beaglebone/mkcard.txt

First get the script on the debian host

wget http://www.angstrom-distribution.org/demo/beaglebone/mkcard.txt

Rename the file

mv mkcard.txt mkcard.sh

Login as root

su

Make the file executable

chmod +x mkcard.sh

Run the script to format the SD card

./mkcard.sh /dev/mmcblk0

If this is runs nicely then write the Angstrom image to the BeagleBone SD card using
Create a place to mount the new file systems

cd /mnt/

mkdir boot

mkdir Angstrom

Mount the File systems

mount -t vfat /dev/mmcblk0p1 /mnt/boot/

mount /dev/mmcblk0p2 /mnt/Angstrom/

Now using df -h we can see the file systems are mounted and empty

Filesystem Size Used Avail Use% Mounted on

/dev/sda1 226G 9.3G 205G 5% /

tmpfs 1013M 0 1013M 0% /lib/init/rw

udev 1009M 212K 1009M 1% /dev

tmpfs 1013M 0 1013M 0% /dev/shm

/dev/mmcblk0p1 70M 512 70M 1% /mnt/boot

/dev/mmcblk0p2 3.6G 72M 3.3G 3% /mnt/Angstrom

Change directory back to the location of our build

cd /home/craig/setup-scripts/build/tmp-angstrom_2010_x-eglibc/deploy/images/beaglebone/

Copy the boot files to the first partition

cp u-boot.img /mnt/boot/

cp MLO /mnt/boot/

cp uImage-3.2-r5b+gitr09e9651bcf2ee8d86685f2a8075bc6557b1d3b91-beaglebone-20120311054152.bin /mnt/boot

 

Rename the uImage to just uImage

mv /mnt/boot/uImage-3.2-r5b+gitr09e9651bcf2ee8d86685f2a8075bc6557b1d3b91-beaglebone-20120311054152.bin /mnt/boot/uImage

Copy the root filesystem from the tarball we created earlier to the second partition

tar -xjv -C /mnt/Angstrom/ -f Angstrom-systemd-image-eglibc-ipk-v2012.03-core-beaglebone.rootfs.tar.bz2

Unmount the SD card

umount /mnt/boot

umount /mnt/Angstrom

Your SD card is now ready for booting.

Remove the SD card from the Debian host
Remove all cables from BeagleBone
Insert SD card into BeagleBone
Plug in Ethernet cable to BeagleBone
Plug in power adapter.

The LEDs on the BeagleBone should flash as the device is booting.

Once it has booted it should show up in your routers DHCP Client list with the hostname “beaglebone”

You should now have access to the BeagleBone via an SSH client.
Using the username “root” password “root”

To change the root password use the passwd command.

Now you have a systemd image running on your BeagleBone