1 Reply Latest reply on Dec 25, 2014 5:59 AM by rgb

    Setting Up Distribute and Flask Web Server on Galileo

    rgb

      Hi All

      I haven't seen anyone use Flask on the Galileo, which is a shame as it is a great way to include a web interface in your projects

      Distribute is a way of installing programs, and you may have used it on other platforms with the command “easy_install” and Flask is a really nice, easy to use, Web Server.

      Below are my notes on how to set up a Galileo and used Flask. I assume you are familiar with how to work with Linux and are coming from a background with Arduino and/or Raspberry Pi.

      If you already have AlexT's uClibc-based distribution of Yocto running and a text editor you like,  you can skip to Install distribute and Flask below.
      If confused as to what you are running, see https://communities.intel.com/message/241845#241845 for a discussion of different versions.

       

      First things is to get the Galileo up and running.
      There are a number of good tutorials, such as one I like at SparkFun. https://learn.sparkfun.com/tutorials/galileo-getting-started-guide
      Do not forget to update the firmware or will have problems.

       

      When you reach the part about installing the bigger form of  Linux, download Alex's developmental version of Linux.
      You can check https://communities.intel.com/message/239581#239581 to find the latest version.
      But for now it is at http://telekinect.media.mit.edu/galileo/image-devtools-1.0.1-3.tar.bz2
      Uncompress and copy to a micro SD card. You can now insert the micro SD card and power up the Galileo.

       

      Finding the IP address and hostname

      As discussed on Clay and Galileo (http://www.hofrock.com/connecting-to-linux) there are a number of ways to connect to the Galileo.

      Since the system at my university assigns new IP addresses every time one connects and the each SD card has a different name, I like to have a small screen display the hostname and IP address,  as it makes connecting easier.

      In addition, since the Galileo is so easily damaged if the USB cable is left in when power is lost, and a normal LCD shield or screen uses a lot of GPIO pins, I would suggest using an I2C LCD.

      You can set up a I2C backpack LCD or Grove RGB LCD to show IP address following instructions at https://communities.intel.com/thread/57741?sr=inbox

      If you want to use an LCD screen, the following sketch will display the IP address onto an DFRobot LCD screen. Just be sure to remove the USB cable once the sketch is loaded so you don't forget and turn power off with it connected.

      /*
        LCD_Print_IP
      Richard Bradley
      Program to display IP Address on DFRobot LCD Shield
      Note: Ethernet cable must be plugged in prior to starting Galileo or it won't get an address
      Note: Need to put electrical tape on LCD or will short against Ethernet port connector
      Note: Needs updated Liquid Crystal Library
        https://github.com/mikalhart/galileo-LiquidCrystal/releases/
        Download and put in Sketches/library directory
      Based on sketches from
      http://www.arduino.cc/en/Tutorial/LiquidCrystal
      and http://www.cyberciti.biz/faq/how-to-find-out-the-ip-address-assigned-to-eth0-and-display-ip-only/
      and https://communities.intel.com/thread/45335
      ---------------------------------------------------
      The circuit:
      * LCD RS pin to digital pin 12
      * LCD Enable pin to digital pin 11
      * LCD D4 pin to digital pin 5
      * LCD D5 pin to digital pin 4
      * LCD D6 pin to digital pin 3
      * LCD D7 pin to digital pin 2
      * LCD R/W pin to ground
      * 10K resistor:
      * ends to +5V and ground
      * wiper to LCD VO pin (pin 3)
      */

       

      // include the library code:
      #include <LiquidCrystal.h>
      // initialize the library with the numbers of the interface pins
      LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
      char FileBuffer[15]; //set up space to read in files

       

      void setup() {
        // set up the LCD's number of columns and rows:
        lcd.begin(16, 2);
        // Print a message to the LCD.
        lcd.setCursor(0, 0);
        lcd.print("Welcome to VGU!");
        // initialize serial communications:
        //Serial.begin(9600);
        // Start the telnet server on Galileo
         system("telnetd -l /bin/sh");
         delay(5000);
      }

       

      void loop()
      {
        // Call ifconfig, pipe through grep to get ipaddress and redirect to file in /home/root
           system("ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'>/home/root/ip.txt");
           FILE *fp;
           fp=fopen("/home/root/ip.txt","r");
           fgets(FileBuffer, 15, fp);
           fclose(fp);
           lcd.setCursor(0, 1);
           lcd.print(FileBuffer);
           delay(5000);
      }

       

      Set up access to Alex's repository
      Now that you can SSH into your Galileo
      ssh root@172,16,3,147 (using the IP address displayed)
      Alex of Intel (not part of Galileo team) has put up a repository
      Go to his blog at http://alextgalileo.altervista.org/ and click on Package repo configuration HowTo.
      The Linux on Galileo (Openwrt) uses opkg instead of apt(like Debian Linux on Raspberry Pi)
      If you used the files that AlexT put up, you should already be set up to access the repository.
      You can check by running
      #cat /etc/opkg/base-feeds.conf
      you should see
      src/gz all     http://repo.opkg.net/galileo/all
      src/gz clanton http://repo.opkg.net/galileo/clanton
      src/gz i586    http://repo.opkg.net/galileo/i586
      If not, an easy way to set up access to his repository so can download files is first to go to the opkg directory
      #cd /etc/opkg
      Then use echo to create a base-feeds.conf file (the original is blank)
      #echo src all http://repo.opkg.net/galileo/all  > base-feeds.conf
      #echo src clanton http://repo.opkg.net/galileo/clanton  >> base-feeds.conf
      #echo src i586    http://repo.opkg.net/galileo/i586  >> base-feeds.conf

       

      You can check with:
      #cat base-feeds.conf

       

      Now you can run opkg update (same as apt-get update on Raspberry) and install packages like openssh-sftp-server that allows you to upload/download files using filezilla.
      #opkg update
      #opkg install openssh-sftp-server

       

      Installing a text editor
      If you hate vi as much as I do, you can install nano. AlexT has added nano to his repository, so all you need to do is:
      #opkg update
      #opkg install nano

      open Nano and you will see a help screen across the bottom with the most important commands

      Ex: Control + K will cut a line of text and Control + L will insert it

      Control + x will end the session and prompt you for the name to save it under.

       

      Another option you can use is Notepad++

      It is a free source code editor and Notepad replacement that supports several languages.
      Notepad++ is written in C++ and uses Win32 API and STL
      Notepad++ allow use of SFTP protocol so users can edit files on another computer using familiar Notepad interface – such as on the Galileo - from your windows PC

      Download Notepad++ installer from http://notepad-plus-plus.org/
      Run installer
      Run Notepad++

      To set it up for use open Plugins Menu > NppFTP > Show NppFTP Window
      The NppFTP window will be available to you now, press the Configuration button > Profile settings

      Click on “Add New”
      Give new profile a name, like Galileo

      Enter IP address of Galileo for Hostname (or you can try hostname if have bonjour)
      Select SFTP for connection type
      Username: root
      Password: should be blank, unless you changed it
      Click close

      Click on (Dis)connect icon (in top left corner)
      Then Click on profile you created
      You should now see the directory on the Galileo
      In the message window you should see that there was a successful connection

      You now can use the familiar Notepad interface to create/edit files

       

      Installing Filezilla

      You will want to be able to move files between your PC and the Galileo and I found filezilla to be useful

      download from https://filezilla-project.org/
      and follow their instructions

      once it is installed you click on File -> site manager and it will bring up a screen for you to fill in

      Click on the New Site button and it will create a new site. You can type over the highlighted text with a name and click return

      In the area on the right

      Enter the IP address in host name

      Select SFTP for protocol

      Enter root for username

      Leave password blank, unless you changed it

      and click on connect

      You will then have a split screen with your PC on the left and the Galileo on the right

      You can then upload and download files and directories

       

      Install distribute and Flask
      Now that everything is set up you can start to do some things.
      Downloaded distribute from  https://pypi.python.org/pypi/distribute/0.6.49
      and uncompress it.
      I would suggest you make a “tmp” directory on /media/realroot so as to not waste the limited space you have in the virtual partition, then use filezilla or whatever you want to move it to the tmp directory.

      SSH into your galileo and go to the directory you copied distribute and install it with

      #python distribute_setup.py
      You now can install flask
      # easy_install flask
      Test it by creating a simple web page - hello.py
      Create a new directory
      #mkdir /media/realroot/www
      # cd  /media/realroot/www
      Create a python file with nano

       

      #nano hello.py
      and type in the following
      -------------------------------------------
      from flask import Flask
      app = Flask(__name__)

       

      @app.route("/")
      def hello():
         return "Hello World!"

       

      if __name__ == "__main__":
          app.run(host='0.0.0.0')
      save it and run it with:
      #python hello.py
      and you should see returned
      * Running on http://0.0.0.0:5000/

       

      You can then access your web page at the IP address and socket 5000
      ex: 172.16.3.247:5000

       

      If flask didn't install correctly you will get errors when you try to run hello.py, most likely something like:
          from werkzeug.exceptions import abort

       

      This probably means that you are far from the center of the Internet, like me, and easy_install didn't work. You can try again or you can then install pip, which is another great little tool for getting applications for your system.
      Run:
      #easy_install pip
      then
      #pip install flask
      (Get a coffee or some other beverage while waiting on werkzeug to download and be installed)
      If it still doesn't install you can try to install werkzeug by it self.
      #pip install werkzeug
      and try again.
      Ok now for a discussion of how Flask works
      There are a number of tutorials on the web including the official one at:
      http://flask.pocoo.org/docs/0.10/
      I will try to simplify the information and just cover what I think would normally be used on the Galileo.

      Below is a discussion of the sample program

      #hello.py                                             
      from flask import Flask                          Imports the Flask class which allows python to run an  WSGI application.
      app = Flask(__name__)                         Creates and names website variable (“app”) that will run an instance of this class.
      @app.route('/')                                      The @ is used to declare function definitions.
                                                                  Route('/') redirects  browser requests for the address / (the default, or home address) to the current directory and hello_world function.
      def hello_world():
          return 'Hello World!'                           Creates a function that returns the string “Hello World!” to the web browser.
      if __name__ == '__main__':                    Causes the server to run the script if it is executed directly from the Python interpreter.
          app.run(host='0.0.0.0')                       The “run” function tells the system to run the program specified by the variable app.  host='0.0.0.0' tells the app to listen to all public IP addresses.

       

      Creating web pages in python is annoying. It is much easier to use HTML and flask allows this. Flask expects to see html files (templates) in a templates sub-directory and static files (CSS, Javascript Text and image files) in a static  subdirectory.
      So you should have the home directory and two subdirectories
      www
          templates
          static

       

      You can now create a simple web page that will be able to communicate with a python program.
      If you don't know how to do html, I would suggest you go through the great tutorial that was originally created by Maricopa Community Colleges and is now hosted at
      http://www.math.unm.edu/writingHTML/tut/index.html
      You can also download the tutorial for off-line browsing
      http://www.math.unm.edu/writingHTML/tut/download.html
      <soapbox>
      Yes I know it is HTML 3.2 and doesn't include all the latest bells and whistles of HTML5, but it is simpler and easier to understand. This tutorial is focused on making a simple web page to display information and control the Galileo, and HTML3.2 is more than what you need. After you understand the basics you can add in all the additional complexity you want.
      </soapbox>

       

      First, after making the folders, create a file called GaliStatus.py
      #!/usr/bin/python
      """GaliStatus1.py
           your_name
           Get system information for display in web page
      """
      import datetime
      from flask import Flask, render_template
      import os
      app = Flask(__name__)
      @app.route('/')
      def Gali_Status():
          AppName =  "GaliStatus"
          Now = datetime.datetime.now()
          DateNow = Now.ctime()
      # Get HostName
          fout = open("/etc/hostname","r+") #open file
          HostName = fout.read()
          fout.close()
      # Get IP Address
          os.popen("ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'>ipaddr.txt")
          fout = open("ipaddr.txt","r")
          IPAddr = fout.read()
          fout.close()
          return render_template('GaliStatus1.html', AppName=AppName, DateNow=DateNow, HostName=HostName, IPAddr=IPAddr)

       

      if __name__ == "__main__":
          app.debug = True
          app.run(host='0.0.0.0', port=80, debug=True)
      You should note some differences from the prior program, aside from the standard Python statements.
      >from flask import Flask, render_template

      This line tells Flask that it will be using a template (html file).
      >return render_template('GaliStatus1.html', AppName=AppName, DateNow=DateNow, HostName=HostName, IPAddr=IPAddr)

      This line tells flask to display the file GaliStatus1.html when a browser requests a page and pass on information stored in a set of variables (I used the same name to pass the information as the variable name to keep life easier)
      >    app.run(host='0.0.0.0', port=80, debug=True)
      This line tells Flask to, respond to requests, use port 80, the default port for html, and to turn on debugging. Debugging is useful doing testing. If you make a mistake in coding you will get a page showing your errors instead of what you expected. After all is running correctly you should set debug=False, as it is a security risk.
      Now you can work on the web page.
      You should copy your image files into the static folder (in my example I used VGU.jpg, you should use whatever small jpg you have lying around) and create a new web page in templates called GaliStatus1.html as follows:
      ----------------
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
      <!--  Galileo Status Web Page
               (your name)
                Shows data received from Galileo on web page -->
      <html>
        <head>
            <table align="center" border="0" width="100%">
                <tr>
                    <th width="25%"><img src="{{ url_for('static',filename="vgu.jpg", height="100")}}"></th>
                    <th width="50%"><font size="+1">
                        Vietnamese-German University<br>
                       Foundation Year Studies<br></font><br></th>
                    <th width="25%"><img src="{{ url_for('static',filename="vgu.jpg", height="100")}}"></th>
                </tr>
            </table>
           <hr>
          <title>{{ AppName }} app</title>
        </head>

       

        <body>
          <h3 align="center">{{ AppName }}</h3>
          <p align="center"> {{DateNow}}<br> 
            Host Name: {{ HostName }} <br>
            IP Address: {{ IPAddr }} <br>
          </p>
           <address>
           <p> Created by Your <u>Name</u> <br>
               YourTitle, <a href="http://www.vgu.edu.vn">Vietnamese-German University</a><br>
               <a href="mailto:your_email@yourprovider">your_email@yourprovider</a><br>
               <tt>Last modified:12 Dec 2014</tt></p>
          </address>
        </body>
      </html>
      -------------------------------------------------------------------
      If you did the tutorial on web page you should notice some differences from normal html.
      <img src="{{ url_for('static',filename="vgu.jpg", height="100")}}">
      Everything set off with double curly brackets “{{ }}” is pulled in.
      In this case Flask is told to look in the static directory and retrieve the file vgu.jpg
      <title>{{ AppName }} app</title>
      In this case, Flask is being told to insert the information passed to it from the python program by the variable “AppName”.
      Since the python program just uses standard python you can use one of the python libraries for Galileo (such as wiring_x86 https://communities.intel.com/thread/57741?sr=inbox or Clay's PyGalileo at https://github.com/galileo-chofrock/pyGalileo) to read and display information from sensors.  You can also display pictures taken with a webcam or control pins from a web page.
      Attached is the sample web page discussed above. Uncompress the file and move the contents “www” directory and sub-directories to /media/realroot/www. You can then run the python program and access the web page from  your browser either by the IP address or, if you have bonjour install, by the hostname with .local Ex:MyGalileo.local.

       

      More later
      rgb

       

      Message was edited by: Richard Bradley Cleaned up old post and added section on editing Sorry posted as question, but can't seem to change it to a discussion