Python代码示例

Python代码示例的详细介绍

创作者:贝壳物联 | 更新日期:2021-10-27 | 在线时长:15天
树莓派Python代码运行监测

树莓派自动应答,可控制led灯,并保持在线。

可参见教程:http://www.bigiot.net/help/26.html

#!/usr/bin/python3
import socket
import time
import json
from gpiozero import LED
#must be modified===
DEVICEID='xx9'
APIKEY='dfxxxx14b'
#modify end=========
led = LED(17)
host="www.bigiot.net"
port=8181
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(0)
#connect bigiot
while True:
    try:
        s.connect((host,port))
        break
    except:
        print('waiting for connect bigiot.net...')
        time.sleep(2)
#check in bigiot
checkinBytes=bytes('{\"M\":\"checkin\",\"ID\":\"'+DEVICEID+'\",\"K\":\"'+APIKEY+'\"}\n',encoding='utf8')
s.sendall(checkinBytes)
data=b''
flag=1
t=time.time()
def keepOnline(t):
    if time.time()-t>40:
        s.sendall(b'{\"M\":\"status\"}\n')
        print('check status')
        return time.time()
    else:
        return t
def say(s,id,content):
    sayBytes=bytes('{\"M\":\"say\",\"ID\":\"'+id+'\",\"C\":\"'+content+'\"}\n',encoding='utf8')
    s.sendall(sayBytes)
def process(msg,s,checkinBytes):
    msg=json.loads(msg)
    if msg['M'] == 'connected':
        s.sendall(checkinBytes)
    if msg['M'] == 'login':
        say(s,msg['ID'],'Welcome! Your public ID is '+msg['ID'])
    if msg['M'] == 'say':
        say(s,msg['ID'],'You have send to me:{'+msg['C']+'}')
        if msg['C'] == "play":
            led.on()
            say(s,msg['ID'],'LED turns on!')
        if msg['C'] == "stop":
            led.off()
            say(s,msg['ID'],'LED turns off!')
    #for key in msg:
    #    print(key,msg[key])
    #print('msg',type(msg))
#main while
while True:
    try:
        d=s.recv(1)
        flag=True
    except:
        flag=False
        time.sleep(1)
        t = keepOnline(t)
    if flag:
        if d!=b'\n':
            data+=d
        else:
            #do something here...
            msg=str(data,encoding='utf-8')
            process(msg,s,checkinBytes)
            print(msg)
            data=b''