您好,登錄后才能下訂單哦!
這篇文章主要講解了python輪詢機(jī)制怎么控制led,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
我就廢話不多說了,大家還是直接看代碼吧!
# -*- coding:utf-8 -*- # File: ceshitianqi import urllib2 import json import time import datetime import serial import random import os import sys APIKEY = 'ZPdLyl***=' #改成你的APIKEY ser=serial.Serial("/dev/ttyUSB2",9600,timeout=1) def read(key): ser.write(key) print("output:"+key) time.sleep(1) response = ser.readall() print(response) print(type(response)) return response def http_put(key): val = read(key) #獲取Arduino的數(shù)據(jù) CurTime = datetime.datetime.now() url='http://api.heclouds.com/devices/**1/datapoints' #values={'datastreams':[{"id":"temp","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]} print(type(val)) if key== "a" : values={'datastreams':[{"id":"humidity","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]} if key== "b" : values={'datastreams':[{"id":"temperature","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]} jdata = json.dumps(values) # 對(duì)數(shù)據(jù)進(jìn)行JSON格式化編碼 #打印json內(nèi)容 print jdata request = urllib2.Request(url, jdata) request.add_header('api-key', APIKEY) request.get_method = lambda:'POST' # 設(shè)置HTTP的訪問方式 request = urllib2.urlopen(request) return request.read() str = ("a","b") while True: for i in str: f = open('1.txt') e = f.read() if e == "1\n": ser.write("c") if e == "0\n": ser.write("d") f.close() resp = http_put(i) time.sleep(2)
輪詢1.txt
1則點(diǎn)亮
0則關(guān)閉
補(bǔ)充知識(shí):python筆記(輪詢、長輪詢)
一、輪詢
views.py
from flask import Flask,render_template,request,jsonify app = Flask(__name__) USERS = { '1':{'name':'貝貝','count':1}, '2':{'name':'小東北','count':0}, '3':{'name':'何偉明','count':0}, } @app.route('/user/list') def user_list(): import time return render_template('user_list.html',users=USERS) @app.route('/vote',methods=['POST']) def vote(): uid = request.form.get('uid') USERS[uid]['count'] += 1 return "投票成功" @app.route('/get/vote',methods=['GET']) def get_vote(): return jsonify(USERS) if __name__ == '__main__': app.run(threaded=True)
html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> li{ cursor: pointer; } </style> </head> <body> <ul id="userList"> {% for key,val in users.items() %} <li uid="{{key}}">{{val.name}} ({{val.count}})</li> {% endfor %} </ul> <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script> <script> $(function () { $('#userList').on('dblclick','li',function () { var uid = $(this).attr('uid'); $.ajax({ url:'/vote', type:'POST', data:{uid:uid}, success:function (arg) { console.log(arg); } }) }); }); /* 獲取投票信息 */ function get_vote() { $.ajax({ url:'/get/vote', type:"GET", dataType:'JSON', success:function (arg) { $('#userList').empty(); $.each(arg,function (k,v) { var li = document.createElement('li'); li.setAttribute('uid',k); li.innerText = v.name + "(" + v.count + ')' ; $('#userList').append(li); }) } }) } setInterval(get_vote,3000); </script> </body> </html>
二、長輪詢
views.py
from flask import Flask,render_template,request,jsonify,session import uuid import queue app = Flask(__name__) app.secret_key = 'asdfasdfasd' USERS = { '1':{'name':'貝貝','count':1}, '2':{'name':'小東北','count':0}, '3':{'name':'何偉明','count':0}, } QUEQUE_DICT = { } @app.route('/user/list') def user_list(): user_uuid = str(uuid.uuid4()) QUEQUE_DICT[user_uuid] = queue.Queue() session['current_user_uuid'] = user_uuid return render_template('user_list.html',users=USERS) @app.route('/vote',methods=['POST']) def vote(): uid = request.form.get('uid') USERS[uid]['count'] += 1 for q in QUEQUE_DICT.values(): q.put(USERS) return "投票成功" @app.route('/get/vote',methods=['GET']) def get_vote(): user_uuid = session['current_user_uuid'] q = QUEQUE_DICT[user_uuid] ret = {'status':True,'data':None} try: users = q.get(timeout=5) ret['data'] = users except queue.Empty: ret['status'] = False return jsonify(ret) if __name__ == '__main__': app.run(threaded=True)
html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> li{ cursor: pointer; } </style> </head> <body> <ul id="userList"> {% for key,val in users.items() %} <li uid="{{key}}">{{val.name}} ({{val.count}})</li> {% endfor %} </ul> <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script> <script> $(function () { $('#userList').on('click','li',function () { var uid = $(this).attr('uid'); $.ajax({ url:'/vote', type:'POST', data:{uid:uid}, success:function (arg) { console.log(arg); } }) }); get_vote(); }); /* 獲取投票信息 */ function get_vote() { $.ajax({ url:'/get/vote', type:"GET", dataType:'JSON', success:function (arg) { if(arg.status){ $('#userList').empty(); $.each(arg.data,function (k,v) { var li = document.createElement('li'); li.setAttribute('uid',k); li.innerText = v.name + "(" + v.count + ')' ; $('#userList').append(li); }) } get_vote(); } }) } </script> </body> </html>
看完上述內(nèi)容,是不是對(duì)python輪詢機(jī)制怎么控制led有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。