Sunspot Home

Setting up the Raspberry Pi as the master of my LAN

NB! all code produced by "Google-copy-paste-test-Google-fix-pray-save" - details not often understood.
But it does the job for me - do not use to run a lift. . . . .

Objective
Build web pages that control hardware on my house and garden LAN
- learn to control and measure with ESP8266 devices with and without linked Arduinos
(build a timed watering system under the control of the Raspi)

Method
Google for working code then learn how it works and customise it.
Evaluate the application of aREST with my own scripts in order to build a LAN control web page to my own design

(rather than use the simple 2 button pages that several sites offer)

Build on my earlier work using OpenWrt linux on router boxes .

Links
Open Home Automation
aREST

IOT-playground

First prepare the Raspberry Pi
I need a ramdisk for changing data so as to not burn out the flash memory
Place this with 755 permissions into
/etc/init.d/graham_startup.sh

Every time the Raspberry Pi is booted the temporary RAM disk will be created - 2M means 2 Mega Bytes
it could be much larger - I use it for the output of bash scripts and the input of Blassic basic programs.

(Blassic basic acts as great glue to hold together other software including C, bash etc and can save and read files as needed.
It handles and manipulates text string in ways I can understand and remember - (unlike C !!!!).
Learn Python and C++ if you can but if you only program a couple of times a year consider Blassic as a tool to get the job done.
See a few notes at pull down menu item 12 at -> http://www.sunspot.co.uk/Projects/sweexproject.htm )

#! /bin/sh
#
# My startup script at
# /etc/init.d/graham_startup.sh
#

# note, when changed do the following at a ssh command line-
# update-rc.d -f graham_startup.sh remove
# update-rc.d -f graham_startup.sh defaults 99
#

# Now carry out specific functions when asked to by the system
case "$1" in
start)

# make a ramdisk to save the flash
mkdir /var/www/ramdisk
mount -o size=2M -t tmpfs tmpfs /var/www/ramdisk

;;
stop)
;;
*)
echo "Usage: /etc/init.d/graham_startup.sh {start|stop}"
exit 1
;;
esac

exit 0

and set a fixed web address for the Raspi at /etc/network/interfaces -

# The loopback network interface - always needed here
auto lo
iface lo inet loopback

# this one for dhcp
# auto eth0
# iface eth0 inet dhcp

# this one for WIFI D-Link DWL-G122
# allow-hotplug wlan0
# iface wlan0 inet static
# pre-up ifconfig wlan0 up
# pre-up iwconfig wlan0 mode Managed
# pre-up iwconfig wlan0 essid "225"

# The primary network interface - use this for ethernet cable if WIFI above not used
# in that case disable the WIFI above with # before each line
allow-hotplug eth0
iface eth0 inet static

# set these for the LAN address
address 192.168.0.80
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255

# set this for the Internet modem gateway to the LAN
gateway 192.168.0.230
# dns-* options are implemented by the resolvconf package, if installed

# my gateway acts as a local dns-nameserver
dns-nameservers 192.168.0.230

 



Setting up the Pi as a webserver

Get the latest software and links
apt-get update

install Apache
apt-get install apache2

There should be a simple webpage index.html in /var/www/

see it at http://192.168.0.82


CGI scripting in bash

in :-
/usr/lib/cgi-bin/hello.cgi

put :-
#!/bin/bash
echo -e "Content-type: text/html\n\n"
echo "<h1>Hello World</h1>"

then create a link to cgi-bin in the www folder :-
ln -s /usr/lib/cgi.bin /var/www/cgi-bin

see it at http://192.168.0.82/cgi-bin/hello.cgi


Add PHP

sudo apt-get install php5 libapache2-mod-php5 -y

To test PHP put into /var/www/php_test.php

<html>
<head>
<title>PHP test</title>
</head>
<body>

<?php
echo "<b>Hello World!</b><BR><BR>The date is ";
echo date('Y-m-d'), "<BR>and the time is ", date('H:i:s');
echo "<BR><BR>Now for some information about PHP :-<BR><BR>", phpinfo();
?>

</body>
</html>

see it at http://192.168.0.82/php_test.php


Building a custom webpage to control the ESP8266
Using a set of bash scripts to generate the webpage

Some years ago I added OpenWrt Linux to a Sweex router - the following codes are adapted from the code that came with the Sweex.

The webpage is created by calling http://192.168.0.80/cgi-bin/esp_control/esp_control.cgi from a remote browser.

The folder /var/www/cgi-bin is actually a shortcut to /usr/lib/cgi-bin as required by apache2 that comes with the Raspian (Debian) image for the Pi (see above)
Google for "setup cgi scripting Apache2 Raspian".
e.g. see http://raspberrywebserver.com/cgiscripting/writing-cgi-scripts-on-a-raspberry-pi.html

esp_control.cgi

#!/bin/bash

#Decode query string

IFS="&"
for QUERY_PARTS in $QUERY_STRING; do
QKEY="`echo $QUERY_PARTS | cut -d '=' -f 1`"
QVAL="`echo $QUERY_PARTS | cut -d '=' -f 2`"
eval "`httpd -d "$QKEY"`=\"`httpd -d "$QVAL"`\""
# remove next line for OpenWrt
eval "$QKEY=\"$QVAL\""
done

# has the variable page been given a value?
if [ -e "pg-$page.sh" ]; then
inc="./pg-$page.sh"

# if not then show the default text
else
inc="./pg-default.sh"
page="default"
fi

echo "Content-type: text/html"
echo
cat esp_page-top.html

echo "<!-- Content goes here -->"
. $inc
echo "<!-- End of content -->"

#you can add shell command line commands here such as-
#echo "Server uptime: `cat /proc/uptime | cut -d ' ' -f 1` seconds.<br>"

# now finish the html
echo "<BR></body></html>"

When first run the cgi script first outputs -
/var/www/cgi-bin/esp_control/esp_page-top.html

<html>
<head>

<title>ESP8266 Control.html</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head>
<body bgcolor="#FFFFCC">
<HR>

<a href="esp_control.cgi?page=esp_on&string=2">turn pin 2 on</a><br>
<BR>
<a href="esp_control.cgi?page=esp_off&string=2">turn pin 2 off</a><br>

<HR>

followed by the default bottom of the page created by
/var/www/cgi-bin/esp_control/pg-default.sh

#!/bin/bash

#Generate the message that is first seen

echo "<BR><font color=red size=3 face=Arial>"
echo "This part of the webpage only comes up as a welcome screen<BR>"
echo "to offer instructions, it was created by <BR></font>"
echo "<font color=green size=3 face=Arial>"
echo "/var/www/cgi-bi/esp_control/pg-default.sh</font><BR>"
echo "<font color=red size=3 face=Arial>Please click on a link above to switch the LED on pin 2</font>"

The web page looks like -

welcome page

Clicking on a link makes the cgi script run -
/var/www/cgi-bin/esp_control/pg-esp_off.sh

#!/bin/bash

# file location -> /var/www/cgi-bin/esp_control/pg-esp_off.sh

# use > to replace file , >> to append to a file
# "> /dev/null 2>&1" means "destroy any output"

# make pin 2 an output
curl "http://192.168.0.85/mode/2/o" > /dev/null 2>&1

# save the output to the ramdisk
# (of more use when we receive sensor data)
curl "http://192.168.0.85/digital/2/0" > /var/www/ramdisk/temp.txt
date
echo "<BR>esp now off<br>"


or -
/var/www/cgi-bin/esp_control/pg-esp_on.sh

#!/bin/bash

# file location -> /var/www/cgi-bin/esp_control/pg-esp_on.sh

# use > to replace file , >> to append to a file
# "> /dev/null 2>&1" means "destroy any output"

# make pin 2 an output
curl "http://192.168.0.85/mode/2/o" > /dev/null 2>&1

# save the output to the ramdisk
# (of more use when we receive sensor data)
curl "http://192.168.0.85/digital/2/1" > /var/www/ramdisk/temp.txt
date
echo "<BR>esp now on<br>"


 The ESP8266 (ESP-01) contains this code loaded from the Arduino IDE
(with thanks to aREST by Marco Schwartz - and see this)
In my case the original aREST UI page can still be seen at http://192.168.0.85/
(it is brilliant code but beyond my current ability to customise for my complex LAN!)

// Relay control using the ESP8266 WiFi chip

// Import required libraries
#include <ESP8266WiFi.h>

#include <aREST.h>
#include <aREST_UI.h>

// Create aREST instance
aREST_UI rest = aREST_UI();

// WiFi parameters
const char* ssid = "garden";
const char* password = "put password here";

// The port to listen for incoming TCP connections
#define LISTEN_PORT 80

// Create an instance of the server
WiFiServer server(LISTEN_PORT);
void setup(void)
{
// Start Serial
Serial.begin(115200);

// Create UI
rest.title("Relay Control pin 2");
rest.button(2);

// Give name and ID to device
rest.set_id("1");
rest.set_name("esp8266");

// Connect to WiFi network with a fixed address
WiFi.begin(ssid, password);
IPAddress ip(192, 168, 0, 85);
IPAddress gateway(192, 168, 0, 230);
IPAddress subnet(255, 255, 255, 0);
WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

// Start the server
server.begin();
Serial.println("Server started");

// Print the IP address
Serial.println(WiFi.localIP());

}

void loop() {

// Handle REST calls
WiFiClient client = server.available();
if (!client) {
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);

}

I have trusty set of bash scripts that I adapt to make web pages that control my LAN devices.
They were adapted for the above and are here for backup.
They can be placed in /var/www/cgi-bin/xxxxx/ as a demonstration of adding a Blassic program to this process.
See them in use by adapting http://192.168.0.80/xxxxx/xxxxx.cgi for your LAN.

Please email me if you want to swap notes
- especially if you do a better job !!!!
and/or
add i2c port expanders, thermometers, displays etc
(my next learning exercise)

SUNSPOT HOME

more to come . . .