Sunteți pe pagina 1din 8

UNIVERSIDAD NACIONAL DE CHIMBORAZO

FACULTAD DE INGENIERÍA
CARRERA DE ELECTRÓNICA Y TELECOMUNICACIONES
ASIGNATURA:

SISTEMAS EMBEBIDOS Y LABORATORIO – PYTHON

NOMBRES:

DANNY LOZANO

RICARDO AGUIRRE

DOCENTE:

ING. LEONARDO RENTERÍA

PERIODO:

OCTUBRE 2018-MARZO 2019


Código del Cliente

import pyfirmata
from pyfirmata import Arduino,util
import urllib2
from threading import Timer
import time
import random

board=Arduino('com1')
it = util.Iterator(board)
it.start()
s1 = board.get_pin('a:0:i')
s2 = board.get_pin('a:1:i')

def send_sensor(val,val2):
response = urllib2.urlopen('http://127.0.0.1:8080/?sensor='+str(val)+'&sensor1='+str(val2))

def _timer():

v1=s1.read()
v2=s2.read()
print v1,v2
send_sensor(v1,v2)
Timer(1, _timer, ()).start()
Timer(1, _timer, ()).start()

Fig.01 Envio de datos leidos a traves de los puertos A0 y A1


Codigo Servidor
Una vez recibido los datos del cliente se los pasa a separar en la función def getArguments(path) donde se crean
dos variables donde se guardarán los valores en este caso son s1 y s2. Estas deben ser declaradas de forma global
para su reutilización en el código.

global s1,s2
s1 = query_components['sensor']
s2 = query_components['sensor'1]

Se debe tener en cuenta con que nombre se enviaron los datos en este caso se enviaron desde el cliente como
sensor y sensor 1.

FInalmente en la function def do_GET(self): debemos cargar los archivos de la página web en una variable en este
caso lo hacemos de la siguiente forma
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()

Pasamos a cargar nuevamente los valores en otra variable para buscar los datos de s1 y s2 de los sensores y
reemplazarlos con valores recibidos del cliente. Para esto se utiliza replace y se reescriben los datos.

data=f.read()
data=data.replace('s1',str(s1)).replace('s2',str(s2))
self.wfile.write(data)

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
from urlparse import urlparse
from urlparse import urlparse, parse_qs
PORT_NUMBER = 8080

sensor=0
#This class will handles any incoming request from
#the browser
s1=0
s2=0
def getArguments(path):
global s1,s2
try:
# print path
query = urlparse(path).query
query_components = dict(qc.split("=") for qc in query.split("&"))
print query_components
try:
s1 = query_components['sensor']
except:
pass
try:
s2 = query_components['sensor1']
except:
pass
print s1,s2

except:
print('no argumentos')

def action(path):
getArguments(path)
class myHandler(BaseHTTPRequestHandler):

#Handler for the GET requests


def do_GET(self):
if self.path=="/":
self.path="/index.html"
if self.path.find('?'):
print self.path
query_components = parse_qs(urlparse(self.path).query)
#imsi = query_components["imsi"]
action(self.path)
self.path="/index.html"
#print query_components

try:
#Check the file extension required and
#set the right mime type

sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype='image/gif'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True

if sendReply == True:
#Open the static file requested and send it
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
data=f.read()
data=data.replace('s1',str(s1)).replace('s2',str(s2))
self.wfile.write(data)
f.close()
return

except IOError:
self.send_error(404,'File Not Found: %s' % self.path)

try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER

#Wait forever for incoming htto requests


server.serve_forever()

except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
Fig.02 Servidor recibiendo los datos de los sensores

Fig.03 Simulación en Arduino


Fig.04 Página web lectura del sensor 1 a través de un botón

Fig.05 Página web lectura del sensor 1 a través de un botón


Código Pagina Web
En el presente código se muestra la creación de la pagina web la cual consta de un titulo y dos botones
para mostrar los resultados de los valores para esto se utilizan las variables s1 y s2 anteriormente creadas
y se las coloca en los respectivos botones
<!DOCTYPE html>
<html>
<body>
<h2>Lectura de sensores</h2>
<button type="button" onclick="alert(s1)">Sensor 1</button>

<button type="button" onclick="alert(s2)">Sensor 2</button>


</body>
</html>

S-ar putea să vă placă și