阅读本博客之前,建议先参考博客:微信客户端+微信公众平台+新浪云SAE+Arduino+WS100(控制LED)
不同之处:主要是服务器使用的语言,本博客使用的是Python
一、硬件部分
1) Arduino、W5100
连接图如下:
硬件这边是我遇到的坑,记录下来
a. 控制LED灯的pin脚:
很多教程里都选择了Pin 13, 但是我购买的板中,Pin13是一个复用引脚,当Arduino和W5100板连接的时候,pin13被占用了,无法通过pin13来控制LED的开关。因此我更换了pin9
外接一个LED灯, 参考图如下:
b. Ethernet.begin()连接网络的方式:
根据library资料有五种连接方式:https://www.arduino.cc/en/Reference/EthernetBegin
Ethernet.begin(mac);
Ethernet.begin(mac, ip);
Ethernet.begin(mac, ip, dns);
Ethernet.begin(mac, ip, dns, gateway);
Ethernet.begin(mac, ip, dns, gateway, subnet);
当时忽略了一个问题,arduino库1.0后,支持DHCP模式,所以我再测试的时候,不需要手动设置IP,直接的连接方式如下:Ethernet.begin(mac);
2)Arduino设备程序烧录
Arduino IDE
https://www.arduino.cc/en/Main/Software
Arduino代码
#include "Arduino.h"
#include <SPI.h>
#include <Ethernet.h>
char state = '0';
char c;
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
EthernetClient client;
// arduino1.applinzi.com是我自己的服务器,你们需要更换成自己的
char server[] = "arduino1.applinzi.com";
int sensrdata = 50;
unsigned long lastConnectionTime = 0;
boolean lastConnected = false;
// 设置一个时间间隔,10秒请求一次
const unsigned long postingInterval = 10*1000;
void setup()
{
// Add your initialization code here
Serial.begin(9600);
delay(1000);
Ethernet.begin(mac);
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
pinMode(9, OUTPUT);
}
// The loop function is called in an endless loop
void loop()
{
//Add your repeated code here
while(client.available()) {
state = client.read();
if(state == '{'){ //关灯 0
Serial.println(state);
digitalWrite(9, LOW);
delay(3000);
}else if(state == '}'){ //开灯 1
Serial.println(state);
digitalWrite(9, HIGH);
delay(3000);
}
}
if (!client.connected() && lastConnected) {
Serial.println("disconnecting 2.");
client.stop();
}
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
if (client.connect(server, 80)) {
Serial.println("connecting");
// send the HTTP PUT request:
client.println("GET / HTTP/1.1");
client.println("Host: arduino1.applinzi.com");
// client.println("User-Agent: arduino-ethernet");
client.println("Connection: close");
client.println();
lastConnectionTime = millis();
}else {
Serial.println("connection failed");
Serial.println("disconnecting 1.");
client.stop();
}
}
lastConnected = client.connected();
}
二、服务器部分
服务器应用:
数据库设计:
列出部分代码,详细代码见Github:https://github.com/shfscut/Arduino
index.wsgi代码
import os
import sae
import web
from handle import Handle
urls = (
'/', 'Handle'
)
app_root = os.path.dirname(__file__)
templates_root = os.path.join(app_root, 'templates')
render = web.template.render(templates_root)
app = web.application(urls, globals()).wsgifunc()
application = sae.create_wsgi_app(app)
handle.py代码
# -*- coding: utf-8 -*-
# filename: handle.py
import hashlib
import web
import reply
import receive
import sae.const
import MySQLdb
class Handle(object):
def GET(self):
try:
data = web.input()
if len(data) == 0:
db=MySQLdb.connect(host=sae.const.MYSQL_HOST,port=int(sae.const.MYSQL_PORT), user=sae.const.MYSQL_USER, passwd=sae.const.MYSQL_PASS, db=sae.const.MYSQL_DB)
cursor = db.cursor()
sql_query = "SELECT * FROM switch where id=1"
content=""
try:
cursor.execute(sql_query)
results = cursor.fetchall()
for row in results:
arduino_id = row[0]
arduino_state = row[1]
content = arduino_state
except:
content = "Error: unable to fetch data"
if content==1:
return "}"
elif content==0:
return "{"
return None
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
token = "xxxxxxx" #改成自己的威信token
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)
hashcode = sha1.hexdigest()
print "handle/GET func: hashcode, signature: ", hashcode, signature
if hashcode == signature:
return echostr
else:
return ""
except Exception, Argument:
return Argument
def POST(self):
try:
webData = web.data()
print "Handle Post webdata is ", webData
recMsg = receive.parse_xml(webData)
if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
toUser = recMsg.FromUserName
fromUser = recMsg.ToUserName
content =sae.const.MYSQL_USER
db=MySQLdb.connect(host=sae.const.MYSQL_HOST,port=int(sae.const.MYSQL_PORT), user=sae.const.MYSQL_USER, passwd=sae.const.MYSQL_PASS, db=sae.const.MYSQL_DB)
cursor = db.cursor()
sql_query = "SELECT * FROM switch where id=1"
sql_update_1 = "UPDATE switch set state=1 where id=1"
sql_update_0 = "UPDATE switch set state=0 where id=1"
arduino_id, arduino_state = None, None
try:
cursor.execute(sql_query)
results = cursor.fetchall()
for row in results:
arduino_id = row[0]
arduino_state = row[1]
except:
content = "Error: unable to fetch data"
if recMsg.Content == "open":
if arduino_state != 1:
try:
cursor.execute(sql_update_1)
db.commit()
except:
db.rollback()
elif recMsg.Content == "close":
if arduino_state != 0:
try:
cursor.execute(sql_update_0)
db.commit()
except:
db.rollback()
else:
content = recMsg.Content
try:
cursor.execute(sql_query)
results = cursor.fetchall()
for row in results:
arduino_id = row[0]
arduino_state = row[1]
content = "arduino_state:" + str(arduino_state)
except:
content = "Error: unable to fetch data"
db.close()
replyMsg = reply.TextMsg(toUser, fromUser, content)
return replyMsg.send()
else:
print "暂且不处理"
return "success"
except Exception, Argment:
return Argment
三、微信公众平台
1)注册微信公众号
2)启动服务器配置
设置–>公众号设置–>服务器设置
注意:需要新浪云服务器搭建好了,微信服务器提交才能成功