To practice our knowledge also learn new technology, we decide to build up a project “Fan Remote Control”. It is used to control fan remotely that make people more easy. Especially, disable person who difficult to move. This Application is run on Android mobile has three main buttons to control fan speed one, tow and three and off button to turn off fan. To remote to fan, first of all we need to connect our mobile to a Wi-Fi. Then, we connect our raspberry pi device to the same Wi-Fi. Now, we can use this application easily with its good interface. Through this project, it’s a proof to show that technology of raspberry pi is very useful. We can transform this idea apply to other project that can solve people problems and improve their living style.
Artificial intelligence in the post-deep learning era
Fan remote control report
1. រកសួងអប់រ ំយុវជន និង កីឡ
វិទយសថ នបេចចកវិទយកមពុជ
េដប៉ តឺម៉ង់ េទពេកសលយ ព័ត៌មនវិទយ និង ទំនក់ទំនង
របយករណ៍ រសវរជវគេរមង អនកបេចចកេទសជន់ខពស់ឆន ំទី៤
របធនបទ : ករបញជ កងហ រេដយទូរស័ពទ
រកុមនិសស ិត : សរសត ែវ៊
ឯកេទស : ព័ត៌មនវិទយ និង ទំនក់ទំនង
រគូ : េលករគូ ជ េឈៀង
ឆន ំសិកស : ២០១៤ - ២០១៥
MINISTRY OF EDUCATION, YOUTH AND SPORT
INSTITUTE OF TECHNOLOGY OF CAMBODIA
DEPARTEMENT OF INFORMATION AND COMMUNICATION ENGINEERING
RESEARCH REPORT OF 4th
YEAR STUDENTS
Title : Fan Remote Control by Smart Phone
Group Student : SastraWare
Department : INFORMATION AND COMMUNICATION
Adviser : Mr. CHHEA Cheang
Year : 2014 - 2015
2. Page | i
ACKNOWLEDGEMENTS
This dissertation would not have been possible without the guidance and the help of several
individuals who in one way or another contributed and extended their valuable assistance in
the preparation and completion of this project.
First and foremost, we want to express our utmost and deepest gratitude to our parents who
always provide us with all kinds of support and advice.
We would like to show our respect to Dr. OM ROMNY, Director of Institute of Technology
of Cambodia for his general management and cooperation with other University to make the
quality of the student of both levels (Engineering and Technician) to become stronger and
professional.
We would like to show our best regard to Dr. LAY HENG, Dean of Computer Science
Department at Institute of Technology of Cambodia for his management of the department and
his good kindness to provide research place.
We would like to say thank to Mr. CHHEA CHEANG, Lecturer Computer Science
Department at Institute of Technology of Cambodia for help us to solve some problems that
We met during our researching and provide all devices for us to test.
We would like to say thank to our team, SastraWare for your hardworking to research and
solve problems. We really respect all contribute of team member. We believe that teamwork is
the power that can push us to success in this project.
Last but now least, we would like to say thank to all the people who involve and help us to
write this report and develop the Fan Remote Control by Smart phone project successful.
3. Page | ii
TABLE OF CONTENTS
I. INTRODUCTION
1.
Team presentation.............................................................................................................4
II. CONCEPTION IN DETAIL
1.
System architecture...........................................................................................................5
2.
Resources..........................................................................................................................6
3.
Programming language.....................................................................................................7
4.
Framework........................................................................................................................7
III. IMPLEMENTATION
1.
Coding on Android (Client)..............................................................................................8
1.1
Create an android project............................................................................................9
1.2
Build interface with xml file.......................................................................................9
1.3
Handle user event .....................................................................................................10
1.3.1
Detect if Wi-Fi is already enable, turn the switch to on......................................................10
1.3.2
Event on the switch to enable/disable Wi-Fi.......................................................................10
1.3.3
Performs http request to server via method post.................................................................10
1.4
Adding permission into android manifest file ..........................................................12
2.
Installing Debian OS on SD card of Raspberry Pi .........................................................13
3.
Coding on Raspberry Pi (Server)....................................................................................15
3.1
Connect to Raspberry Pi ...........................................................................................15
3.2
Setting Wi-Fi for Raspberry pi .................................................................................17
3.3 Installing and Create Project using Django……………………………………………16
4.
Forbidden (403) CSRF verification failed......................................................................24
IV. REFERENCS BERS
4. Page | 3
I. INTRODUCTION
1. Project presentation
To practice our knowledge also learn new technology, we decide to build up a project
“Fan Remote Control”. It is used to control fan remotely that make people more easy.
Especially, disable person who difficult to move. This Application is run on Android
mobile has three main buttons to control fan speed one, tow and three and off button to
turn off fan. To remote to fan, first of all we need to connect our mobile to a Wi-Fi. Then,
we connect our raspberry pi device to the same Wi-Fi. Now, we can use this application
easily with its good interface. Through this project, it’s a proof to show that technology of
raspberry pi is very useful. We can transform this idea apply to other project that can solve
people problems and improve their living style.
Figure 6: Data Processing
5. Page | 4
2. Team presentation
“SastraWare” is the 4th
year student team, which is formed in March 2015. This team is
created in order to group students who want to create, learn something new and share
knowledge together. We also join to do research and create application. Moreover, we
develop on iOS, android and web site. We have 14 members currently.
To communicate with our team:
Contact Person : Ms. Soung Sreynoch
Tel : (855) 69 659 855
Email : sreynoch.soung5@gmail.com
Figure 1: Team Logo
6. Page | 5
II. CONCEPTION IN DETAIL
This part will introduce some technical choices including system architecture, resources
and programming language to develop this project.
1. System architecture
Fan Remote Control is an android application that uses Http protocol to request to server
in Django project. Getting data from phone application by function in file view.py, then
send the output as GPIO signal to Relay.
Figure 2: Application architecture
7. Page | 6
2. Resources
We need some important devices and other tools in order to develop this application
successfully.
Smart Phone: It is used for running application on client side and send request with data to
server.
Raspberry Pi: Django is a high-level Python Web framework that encourages rapid
development and clean, pragmatic design. Built by experienced developers, it takes care of
much of the hassle of Web development, so you can focus on writing your app without
needing to reinvent the wheel. It’s free and open source. We use Django for coding
because this framework can make us to code with raspberry pi easier since it already has
library to connect with pi. Moreover, it is easy to learn. It’s used to receive data, request
from client side (phone app).
Relay: are switches that open and close circuits electromechanically or electronically.
Relays control one electrical circuit by opening and closing contacts in another circuit.
When a relay contact is Normally Closed (NC), there is a closed contact when the relay is
not energized. In either case, applying electrical current to the contacts will change their
state. Relays are generally used to switch smaller currents in a control circuit and do not
usually control power consuming devices except for small motors and Solenoids that draw
low amps. Nonetheless, relays can "control" larger voltages and amperes by having an
amplifying effect because a small voltage applied to a relays coil can result in a large
voltage being switched by the contacts. Protective relays can prevent equipment damage
by detecting electrical abnormalities, including overcurrent, undercurrent, overloads and
reverse currents. In addition, relays are also widely used to switch starting coils, heating
elements, pilot lights and audible alarms.
Fan: It is used to receive electric signal from relay and start to process.
8. Page | 7
3. Programming language
To develop this application, we chose Python programming language, which is used for
implementation on server side such as view.py is used to create function and to interact
client request. We decided to use Python because it is a well-known programming
language with a lot of libraries that is easy for using in the development. More than that, It
is better to compile on Linux OS that we’ve install on Raspberry Pi.
4. Framework
To help our implementing going well, we need to include an important framework for
using in our project. It is Django Python framework, a high-level Python Web framework
that encourages rapid development and clean, pragmatic design.
Figure 3: django Framework
9. Page | 8
III. IMPLEMENTATION
In this part we will explain the technique for implementation this project.
1. Coding on Android (Client)
Steps to develop the application:
Ø Create an android project
Ø Build an interface in xml file with
o 4 buttons:
§ 1 button for turning the fan off
§ 3 buttons for control the fan speed 1,2,3
o 1 switch: to enable Wi-Fi connection
Ø Handle user event in java file
o Detect if Wi-Fi is already enable, turn the switch to on
o Event on the switch to enable/disable Wi-Fi
o Performs http request to server via method post
§ Sending data to server if user click any of the 4 buttons
• Send 1 if click button number 1
• Send 2 if click button number 2
• Send 3 if click button number 3
• Send 0 if click button off
Ø Be sure to add the permission of accessing Wi-Fi, internet in android
manifest file.xml
10. Page | 9
Create an android project1.1
You can use any IDE to develop the application but we recommend, Android Studio. In
our case, we use Android Studio as an IDE because it’s an easy tool for android
development with many functionalities (dependency, drag-drop, code highlight and
completion) that we can use.
To create the android project:
=>Click file -> new project, then give your application named Fan Controller after that
follow the instructions and be sure to check and choose the minimum version of android
that can support our application.
After creating the project we have to modify the xml and java file.
Build interface with xml file1.2
id=view_switch
id=view_btn_off
id=view_btn_num
3
id=view_btn_num
2
id=view_btn_num
1
4 buttons
1 switch
1 TextView
Figure 4: Application interface
11. Page | 10
Handle user event1.3
1.3.1 Detect if Wi-Fi is already enable, turn the switch to on
• Get reference to the switch view
• Use method in android to check the Wi-Fi status
o If status on, then turn on the switch
o Else, turn off the switch
o To handle external user interaction enable Wi-Fi, we must
put the above pieces of code in onCreate and onResume of
android life circle
1.3.2 Event on the switch to enable/disable Wi-Fi
• When click, start an internal activity of android to let use enable and
pick the network in setting mode
• In case the Wi-Fi has enabled, turn the switch to on
• If Wi-Fi is not enabled, turn the switch to off
1.3.3 Performs http request to server via method post
• Because it’s a task that needed to be executed when user click button
and send data to the network we have to define it as a thread.
• So we create another class called: RequestTaskWithPost.java that
extends the asynchronies task then we have to override the
doInBackground method in order to work. public class
RequestTaskWithPost extends async
Inside this class we need a property called String value, which is
used to send data to the network
• To pass the value from main activity to this class we need to define a
constructor inside RequestTaskWithPost class. Let say we like to
initialize the value of speed fan.
public RequestTaskWithPost(String value){
this.value = value
}
12. Page | 11
• To make the http request we have to
o Write the below process of code in doInBackground
method to perform the http request to the network
o Create an HttpClient so that we have a client
o Create an HttpPost which is used to pass data via method
post
o Pass data as a list type to the HttpPost using setEntity
method
o Get client execute the post method
o Create an HttpResponse to get response from server
whether the data is successfully sent
• To execute the method doInBackground in main class we have to
o Instance the RequestTaskWithPost object and pass the value
of constructor then pass the url to the server in execute
method
new RequestTaskWithPost(1+“”).execute(url_to_server)
14. Page | 13
2. Installing Debian OS on SD card of Raspberry Pi
Here we show you how to install Debian OS on SD card using Linux.
ü Download OS, Raspbian (Raspberry + Debian) from this website :
www.raspberrypi.org/downloads/
ü Install OS in to SD card using command dd
Note: using of the dd tool can overwrite any partition of your machine. If you specify the
wrong device in the instructions below you could delete your primary Linux partition.
Please be careful.
• Run df -h to see what devices are currently mounted.
• If your computer has a slot for SD cards, insert the card. If not, insert the card into an SD
card reader, then connect the reader to your computer.
15. Page | 14
• Run df -h again. The new device that has appeared is your SD card. The left column
gives the device name of your SD card; it will be listed as something
like /dev/mmcblk0p1 or /dev/sdd1. The last part (p1 or 1 respectively) is the
partition number but you want to write to the whole SD card, not just one partition.
Therefore you need to remove that part from the name (getting, for
example, /dev/mmcblk0 or /dev/sdd) as the device for the whole SD card. Note that
the SD card can show up more than once in the output of df; it will do this if you
have previously written a Raspberry Pi image to this SD card, because the
Raspberry Pi SD images have more than one partition.
• Now that you've noted what the device name is, you need to unmount it so that files can't
be read or written to the SD card while you are copying over the SD image.
• Run umount /dev/sdd1, replacing sdd1 with whatever your SD card's device name is
(including the partition number).
• If your SD card shows up more than once in the output of df due to having multiple
partitions on the SD card, you should unmount all of these partitions.
• In the terminal, write the image to the card with the command below, making sure you
replace the input file if= argument with the path to your .imgfile, and
the /dev/sdd in the output file of= argument with the right device name. This is very
important, as you will lose all data on the hard drive if you provide the wrong
device name. Make sure the device name is the name of the whole SD card as
described above, not just a partition of it; for example sdd, not sdds1 or sddp1;
or mmcblk0, not mmcblk0p1. dd bs=4M if=2015-05-05-raspbian-wheezy.img
of=/dev/sdd
16. Page | 15
3. Coding on Raspberry Pi (Server)
3.1 Connect to Raspberry Pi
Firstly, you have to find your network preference that is in the upper right hand corner
of your screen, click on the Wi-Fi icon.
Next, plug one end of your Ethernet cable into your Raspberry Pi, and the other
into your computer Ethernet card. Power the Raspberry Pi up. You should see all of the
lights flashing on the Raspberry Pi!
And then, try to test if your raspberry pi is connected on the network by opening
terminal and type
ping raspberrypi.local
17. Page | 16
Then, you will see the result as below picture.
For this one means that your raspberry pi is using ip address: 192.168.1.104. About
the ip address of raspberry pi can be change every times when it is reconnected to network
Ethernet. So, you can check ip address by using the above command or you can check it
via browser by ip address 192.168.0.1 and click on DHCP to find device client lists in
network. And you will see ip address of raspberry pi.
You can log into your Raspberry Pi using Bash on your Mac. Again, we’ll open up
a new terminal: Press “Command Space”, which opens Spotlight. Type “Terminal” and
the terminal will come to the top. Click on the terminal icon. In Bash, type
sudo ssh pi@raspberrypi.local
Or Example:
sudo ssh pi@192.168.104
Note: Then you will be required to input password of your computer and password of
Raspberry Pi. The default of passwords of Raspberry Pi is “raspberry”.
18. Page | 17
3.2 Setting Wi-Fi for Raspberry pi
We need to set Wi-Fi for raspberry pi because we want to use it without wire. It is
especially suited for use with a serial console cable if you don't have access to a screen or
wired Ethernet network. Also note that no additional software is required; everything you
need is already included on the Raspberry Pi.
3.2.1 Getting Wi-Fi Network Details
To scan for Wi-Fi networks, we have command sudo iwlist wlan0. This will list the
entire available Wi-Fi network along with the other useful information.
• ESSID: “TP-LINK_WiFi” is the name of the Wi-Fi network.
19. Page | 18
3.2.2 Add The Network Details To The Raspberry Pi
Open the wpa-supplicant configuration file in nano:
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
Go to the bottom of the file and add the following:
network={
ssid="The_ESSID_from_earlier"
psk="Your_wifi_password"
}
In the case of the example network, we would enter:
network={
ssid="YES"
psk="123"
}
Now save the file by pressing ctrl+x then y, then finally press enter.
At this point, wpa-supplicant will normally notice a change has occurred within a
few seconds, and it will try and connect to the network. If it does not, either manually
restart the interface with sudo ifdown wlan0 and sudo ifup wlan0, or reboot your
Raspberry Pi with sudo reboot.
You can verify if it has successfully connected using ifconfig wlan0. If the inet addr field
has an address beside it, the Pi has connected to the network. If not, check your password
and ESSID are correct.
20. Page | 19
3.3 Installing and Create Project using Django
To install Django, we need to follow the steps below:
1. Need to install python on raspberry pi by using command
sudo apt-get install python3.1
2. Then install django on raspberry pi by using command
pip install django
3. After finish the installing, we can create new project in raspberry pi
django-admin.py startproject fanController
Note: There’re manage.py file and fanController folder
inside fanController project.
• __init__.py: An empty file that tells Python that this directory should be considered
a Python package.
• settings.py: Settings/configuration for this Django project. Django settings will tell
us all about how settings work. In other words, this file will hold all apps, database
settings information.
• urls.py: The url declarations for this Django project; a "table of contents" of our
Django-powered site. This is a file to hold the urls of our website such as
"http://localhost/FanControllerApp". In order to use /FanControllerApp in our
fanController project we have to mention this in urls.py.
• wsgi.py: An entry-point for WSGI-compatible web servers to serve our project.
This file handles our requests/responses to/from django development server.
4. Then, we can run a development server. Since we use server for raspberry pi so,
we also run server with the ip address of raspberry pi too.
Example: sudo python manage.py runserver 192.168.1.104:8000
5. Next, we can create app inside the fanController project directory. We can run
the command: django-admin startapp FanControllerApp
21. Page | 20
When we create app by using the command above, you will see that the django-admin
startapp app created files:
• __init__.py - this file indicates our app as python package.
• models.py - file to hold our database information.
• views.py - our functions to hold requests and logics.
• tests.py - for testing.
Ø Edit settings.py
We need to edit settings.py under fanController project directory to add our
application FanControllerApp as shown below:
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'FanControllerApp',
)
22. Page | 21
Ø Edit urls.py
How does Django know what view to send a particular request?
Django uses a mapping file called urls.py which maps html addresses to views, using
regular expressions. In other words, Django has a way to map a requested url to a view
which is needed for a response via regular expressions.
Let's
modify
the
urls.py,
which
is
under
the
project
directory,
fanController:
from django.conf.urls import include, url
from django.contrib import admin
from FanControllerApp.views import foo
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^FanControllerApp/',foo),]
23. Page | 22
Ø Edit views.py
In
this
file,
we
write
the
code
that
used
to
connect
with
relay
that
used
to
connect
with
Fan.
We
just
write
the
simple
one
in
python
program.
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponse,HttpResponseRedirect
from django.core.urlresolvers import reverse
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(10,GPIO.OUT)
GPIO.setup(12,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
def foo(request):
print "in foo"
print request
lv = int(request.POST["level"])
if 1 == lv:
GPIO.output(10,0)
GPIO.output(12,1)
GPIO.output(13,1)
print "in 1"
elif 2 == lv:
GPIO.output(10,1)
GPIO.output(12,0)
GPIO.output(13,1)
print "in 2"
elif 3 == lv:
GPIO.output(10,1)
GPIO.output(12,1)
GPIO.output(13,0)
elif 0 == lv:
GPIO.output(10,1)
GPIO.output(12,1)
GPIO.output(13,1)
return HttpResponse("{stutu:send success}")
24. Page | 23
Now, we can run server by using command:
sudo
python
manage.py
runserver
192.168.1.104:8000
How it works?
1. When we type 192.168.1.104:8000/FanControllerApp into the browser, this will
send request to Django. Django framework provides a way to
map FanControllerApp to a code to do something as listed in the next steps.
2. Django will read urls.py and look for url matching pattern.
3. If it matches, it calls the associated function.
4. In our case, it matches FanControllerApp in urls.py.
5. So, foo() in views.py is called.
6. In views.py, we have the code to catch the request from client and send to
raspberry Pi pin by GPIO output.
25. Page | 24
4. Forbidden (403) CSRF verification failed
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious
Web site, email, blog, instant message, or program causes a user's Web browser to perform
an unwanted action on a trusted site for which the user is currently authenticated.
To solve this problem you can write some code in file view.py to disable this detected
function.
from django.core.urlresolvers import reverse
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(10,GPIO.OUT)
GPIO.setup(12,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def foo(request):
print "in foo"
print request
lv = int(request.POST["level"])
if 1 == lv:
GPIO.output(10,0)
GPIO.output(12,1)
26. Page | 25
VI. REFERENCES
www.bogotobogo.com/python/Django/Python_Django_hello_world.php
https://www.raspberrypi.org/documentation/configuration/wireless/wireless
-cli.md
http://www.dexterindustries.com/BrickPi/getting-started/using-the-
pi/connect-to-your-raspberry-pi-from-a-mac/
https://wiki.archlinux.org/index.php/WPA_supplicant
https://www.youtube.com/watch?v=J9cEAGTLaC8
http://www.slideshare.net/itembedded/raspberry-pi-usage-
tutorial?qid=f830df10-2469-49b9-bac3-
fe95ece3cb89&v=default&b=&from_search=28
http://www.commandlinefu.com/commands/view/3447/connect-via-ssh-
using-mac-address
http://dancarroll.org/blog/2011/01/debugging-django-dev-server/
http://www.it-ebooks.info/book/4634/
https://wiki.debian.org/WiFi/HowToUse
http://www.cyberciti.biz/faq/linux-list-network-interfaces-names-command/
Note: Some useful command
ü copy from raspberry to local sudo scp -r
pi@192.168.0.104:~/fanController_vs_1 ~/Desktop
§ It’s used to copy project from Raspberry Pi to our Computer
ü sudo shutdown -h now
§ To shutdown raspberry pi
§ Please definitely don't just pull the plug. This can cause problems
with the SD card and file system.