本帖最后由 gongqingkui 于 2016-10-18 10:42 编辑
web封装编写好串口发送函数后,可在命令行下进行简单测试。测试无误后,可以编写web程序,在web程序中,根据用户点击,来调用串口发送函数,进行指令的传递。Web服务器这里用的是python的web库。代码如下: web_manual.py程序导入相应的包后,首先用render指明模板所在目录templates/,然后指定URL访问列表情况,最后根据URL中制定名字,编写相应的控制器。控制器中的GET和POST分别指代两种访问方法,用render.具体模板名来传值到相应模板。Db类和sqldb类用来访问本地sqlite3数据库。经过以上程序,在服务器中打开python web.py 1234,然后访问localhost:1234既可以访问到这个简单的网站,实现局域网内查看和控制设备的能力。 [mw_shl_code=python,true]# encoding: utf-8
import web
import os
import sqlite3
import time
import serial
from actuatorModule import execute
from web import form
# templete floder
render = web.template.render('templates/')
# url tables
urls = ('/', 'index',
'/manualcontroller', 'manualcontroller',
'/temperature', 'temperature',
'/humidity', 'humidity'
)
class index:
def GET(self):
return render.index()
class temperature:
def GET(self):
db1 = db()
rs = db1.execute('select * from temperature order by id desc limit 20')
return render.temperature(rs)
class humidity:
def GET(self):
db1 = db()
rs = db1.execute('select * from humidity order by id desc limit 20')
return render.humidity(rs)
class manualcontroller:
def GET(self):
return web.seeother('/')
def POST(self):
i = web.input()
print i.switcher1, i.servor1, i.led1
if i.servor1 != "":
if int(i.servor1)>=0 and int(i.servor1) <=180:
execute("d",i.servor1)
elif i.led1 != "":
if i.led1 !="":
execute("s",i.led1)
elif i.switcher1 != "":
if i.switcher1 == "1" or i.switcher1 == "0" :
execute("b",i.switcher1)
return web.seeother('/')
class db:
def __init__(self):
self.db = sqldb()
def insert(self,table,values):
return
def delete(self,table,index):
return
def update(self,table,index,values):
return
def select(self,table,index):
i = (table,index)
sql = 'select * from %s where id = %d'%(table,index)
self.db.cu.execute(sql)
rs = self.db.cu.fetchall()
self.db.conn.commit()
return rs
def execute(self,sql):
self.db.cu.execute(sql)
rs = self.db.cu.fetchall()
self.db.conn.commit()
return rs
class sqldb:
def __init__(self):
self.db = 'db.db'
if os.path.exists(self.db):
self.conn = sqlite3.connect(self.db)
self.cu = self.conn.cursor()
else:
self.conn = sqlite3.connect(self.db)
self.cu = self.conn.cursor()
self.cu.execute(
'create table sensors(id integer primary key autoincrement,date text,value text)')
self.cu.execute(
'insert into sensors values(null,\'2016-1-1 12:00:00\',\'32\')')
self.cu.execute(
'create table actuators(id integer primary key autoincrement,date text,value text)')
self.cu.execute(
'insert into actuators values(null,\'2016-1-1 12:00:02\',\'open AC ato 26\')')
self.conn.commit()
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()[/mw_shl_code] 采用上诉方法开启服务器之后,智能内网访问web服务,为了达到外网操作的能力,需要使用花生壳的动态IP的映射的服务。
|