1. 程式人生 > >Arduino+W5100+新浪雲SAE(開發語言:Python)+微信公眾平臺(實現LED控制)

Arduino+W5100+新浪雲SAE(開發語言:Python)+微信公眾平臺(實現LED控制)

閱讀本部落格之前,建議先參考部落格:微信客戶端+微信公眾平臺+新浪雲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(); }

二、伺服器部分
伺服器應用:
伺服器應用
資料庫設計:
這裡寫圖片描述
這裡寫圖片描述

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)啟動伺服器配置
設定–>公眾號設定–>伺服器設定
這裡寫圖片描述
注意:需要新浪雲伺服器搭建好了,微信伺服器提交才能成功