运行效果图

服务器端程序

#!/usr/bin/python'''服务器端程序 do_GET() 方法调用webcam摄像头,查看监控视频,同时识别二维码,do_POST()方法连接Mysql数据库,获取数据,并以webservice的形式发布出去供移动客户端与Mysql数据交互。'''import cv2import Imageimport threadingfrom BaseHTTPServer import BaseHTTPRequestHandler,HTTPServerfrom SocketServer import ThreadingMixInimport StringIOimport timeimport qrtoolsimport serialimport MySQLdbimport datetimeimport cgiimport randomimport stringcapture = Noneqr = qrtools.QR()sr = serial.Serial('/dev/ttyACM0', baudrate=9600, timeout=1)db = MySQLdb.connect('localhost', 'root', 'root', 'homedb')cursor = db.cursor()def passwd_generator():    s = string.ascii_letters + string.digits    l = len(s)    passwd_l = 10    return ''.join([s[random.randrange(0, l-1)] for x in range(passwd_l)])class CamHandler(BaseHTTPRequestHandler):    def do_GET(self):        if self.path.endswith('.mjpg'):            self.send_response(200)            self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')            self.end_headers()            while True:                try:                    rc, img = capture.read()                    if not rc:                        continue                    imgRGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)                    jpg = Image.fromarray(imgRGB)                    tmpFile = StringIO.StringIO()                    jpg.save(tmpFile,'JPEG')                    if qr.decode(tmpFile):                        print(qr.data)                        ''' Verify QR code '''                        username, passwd = qr.data.trim().split(',')                        cursor.execute('select * from user where username="' + qr.username + '"')                        data = cursor.fetchone()                        if not data:                            continue                        d = datetime.datetime.now() - data[3]                        if d < datetime.delta(seconds=10):                            if passwd == data[2]:                                ''' Open lock via arduino'''                                if sr.isOpen():                                    sr.write(b'1')                    self.wfile.write("--jpgboundary")                    self.send_header('Content-type','image/jpeg')                    self.send_header('Content-length',str(tmpFile.len))                    self.end_headers()                    jpg.save(self.wfile,'JPEG')                    time.sleep(0.05)                except KeyboardInterrupt:                    break            return        if self.path.endswith('.html'):            self.send_response(200)            self.send_header('Content-type','text/html')            self.end_headers()            with open('front.html', 'r') as f:                self.wfile.write(f.read());            # self.wfile.write('')            self.wfile.write('')            # self.wfile.write('')            with open('end.html', 'r') as f:                self.wfile.write(f.read())            return    def do_POST(self):        if self.path == '/authenticate':            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))            if ctype == 'multipart/form-data':                postvars = cgi.parse_multipart(self.rfile, pdict)            elif ctype == 'application/x-www-form-urlencoded':                length = int(self.headers.getheader('content-length'))                postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)            else:                postvars = {}            if postvars:                username = postvars['username'][0]                print("username=" + username)                cursor.execute('select * from user where username=%s', (username, ))                d = cursor.fetchone()                if d:                    new_passwd = passwd_generator()                    print("new passwd=" + new_passwd)                    # cursor.execute('select * from user')                    cursor.execute('update user set passwd=%s, last_update=%s where username=%s', (new_passwd, datetime.datetime.now(), username))                    db.commit()                    if cursor:                        self.send_response(200)                        self.end_headers()                        self.wfile.write(username + ',' + new_passwd)                        print("response OK!")            return        else:            self.send_response(200)            self.send_header('Content-type', 'text/html')            self.end_headers()            self.wfile.write('Hello world')            returnclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):    """Handle requests in a separate thread."""def main():    global capture    global qr    global sr    global cursor    capture = cv2.VideoCapture(0)    capture.set(cv2.CAP_PROP_FRAME_WIDTH, 960);    capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 544);    capture.set(cv2.CAP_PROP_SATURATION,0.2);    global img    try:        server = ThreadedHTTPServer(('192.168.1.201', 8800), CamHandler)        print "server started"        server.serve_forever()    except KeyboardInterrupt:        capture.release()        server.socket.close()        cursor.close()        db.close()if __name__ == '__main__':    main()

Android 手机客户端程序

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.king.httppostdemo.MainActivity"    android:orientation="vertical">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Click"        android:id="@+id/button"        android:layout_alignTop="@+id/text1"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true" />    <TextView        android:id="@+id/text1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!" />LinearLayout>

MainActivity.java

package com.example.king.httppostdemo;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import java.util.HashMap;public class MainActivity extends Activity {    private TextView tv1;    private Button bt;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tv1=(TextView)findViewById(R.id.text1);        bt=(Button)findViewById(R.id.button);        bt.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                HashMap data = new HashMap();                data.put("username", "hello");                AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);                asyncHttpPost.setListener(new AsyncHttpPost.Listener(){                    @Override                    public void onResult(String result) {                        // do something, using return value from network                        tv1.setText(result);                    }                });                asyncHttpPost.execute("http://192.168.1.201:8800/authenticate");            }        });    }}

asyncHttpPost.class

package com.example.king.httppostdemo;import android.os.AsyncTask;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.StatusLine;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;/** * Created by king on 16-10-6. */class AsyncHttpPost extends AsyncTask {    interface Listener {        void onResult(String result);    }    private Listener mListener;    private HashMap mData = null;// post data    /**     * constructor     */    public AsyncHttpPost(HashMap data) {        mData = data;    }    public void setListener(Listener listener) {        mListener = listener;    }    /**     * background     */    @Override    protected String doInBackground(String... params) {        byte[] result = null;        String str = "";        HttpClient client = new DefaultHttpClient();        HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL        try {            // set up post data            ArrayList nameValuePair = new ArrayList();            Iterator it = mData.keySet().iterator();            while (it.hasNext()) {                String key = it.next();                nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));            }            post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));            HttpResponse response = client.execute(post);            StatusLine statusLine = response.getStatusLine();            if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){                result = EntityUtils.toByteArray(response.getEntity());                str = new String(result, "UTF-8");            }        }        catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        catch (Exception e) {        }        return str;    }    /**     * on getting result     */    @Override    protected void onPostExecute(String result) {        // something...        if (mListener != null) {            mListener.onResult(result);        }    }}

源码(click here)

更多相关文章

  1. android 程序运行出现错误 Unable to execute dex: java.nio.Buf
  2. (转)认识Android手机--来自MIUI[
  3. NFC之让Android自动运行程序
  4. Android的应用程序的异常处理2
  5. android MQTT的使用及demo
  6. Android开发指南(30) —— Multimedia and Camera
  7. Android用户界面程序设计示例
  8. Activity的架构设计
  9. [置顶] 第8章android动态调试

随机推荐

  1. Cocos-Lua IDE中打包android apk失败---
  2. Android(安卓)Spinner不触发onItemSelect
  3. 关于layout_weight的理解及使用方法
  4. ViewPagerIndicator导入Android(安卓)Stu
  5. Android中使用断言
  6. android中Logcat的深层理解
  7. 将Android(安卓)7.0 Browser 的搜索引擎
  8. Android(安卓)一次性关闭所有的activity
  9. android高德地图定位
  10. Android数据流详解