Arduino+W5100+ Sina Cloud SAE (development language: Python) + WeChat public platform (to achieve LED control)
Before reading this blog, it is recommended to refer to the blog:WeChat client + WeChat public platform + Sina Cloud SAE+Arduino+WS100 (control LED)
Difference: Mainly the language used by the server, this blog uses Python
1. Hardware part
1) Arduino、W5100
The connection diagram is as follows:
The hardware side is the pit I encountered, record it
a. Control the pin of the LED light:
Pin 13 is selected in many tutorials, but in the board I purchased, Pin13 is a multiplexed pin. When the Arduino and W5100 board are connected, pin13 is occupied and cannot be passed pin13 to control the LED switch. So I changed pin9
An external LED light, the reference picture is as follows:
b. The method of Ethernet.begin() to connect to the network:
According to the library data, there are five connection methods: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);
I overlooked a problem at the time. After arduino library 1.0, DHCP mode is supported, so when I test again, I don’t need to manually set the IP. The direct connection method is as follows: Ethernet.begin(mac);
2) Arduino device program burning
Arduino IDE
https://www.arduino.cc/en/Main/Software
Arduino code
#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 is my own server, you need to replace it with your own
char server[] = "arduino1.applinzi.com";
int sensrdata = 50;
unsigned long lastConnectionTime = 0;
boolean lastConnected = false;
// Set a time interval, request once every 10 seconds
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 == '{'){ //Turn off the lights 0
Serial.println(state);
digitalWrite(9, LOW);
delay(3000);
}else if(state == '}'){ //Turn on the light 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();
}
Second, the server part
Server application:
Database design:
List part of the code, see Github for detailed code:https://github.com/shfscut/Arduino
index.wsgi code
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 code
# -*- 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" #Change into your own prestige 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 "Will not deal with it temporarily"
return "success"
except Exception, Argment:
return Argment
3. WeChat public platform
1) Register WeChat official account
2) Start server configuration
Settings -> Official Account Settings -> Server Settings
Note: The Sina cloud server needs to be set up, and the WeChat server submission can be successful
COMMENTS