【SmartHome】使用Python制作拍手开灯-基于HomeAssistant PythonAPI

感受到Google Home以及Alexa的语音助手带来的便捷体验后,想到了使用拍手来开灯的想法,由于在家里已经部署了Home Assistant并且考虑到它的可二次开发的特性,使用Home Assistant API制作了这个程序。

拍两下手可判断开灯状态来进行开灯或关灯,支持设置拍手次数执行不同操作。

Home Assistant是一个开源智能家居管理平台:

Home Assistant is an open-source home automation platform running on Python 3. Track and control all devices at home and automate control. Perfect to run on a Raspberry Pi.

官网:https://www.home-assistant.io/

 

GitHub 详情页:https://github.com/KrunkZhou/PI-Clap

 

代码部分:


import pyaudio
import sys
import threading
import time
from time import sleep
from array import array
import KRUNKHOMEAPI as kapi
import homeassistant.remote as koapi #You will need to download homeassistant python api

def main():
	kapi.api=koapi.API('sample.com', 'password','8123') # HA-API:domain, password, port
	check=kapi.apicheck()
	if check:
		start()
	kapi.endscript()

clap = 0
wait = 1
flag = 0
pin = 24
exitFlag = False	

def toggleLight(c):
	domain = 'light' #domain
	switch_name = 'light.lamp' #switch name
	print (str(kapi.get_state(switch_name)))
	lamp=kapi.get_state(switch_name)
	if (lamp.state=='off'):
		kapi.turn_on(domain,switch_name)
	else:
		kapi.turn_off(domain,switch_name)
	sleep(1)
	print("Light toggled")

def waitForClaps(threadName):
	global clap
	global flag
	global wait
	global exitFlag
	global pin
	print ("Waiting for more claps")
	sleep(wait)
	if clap == 2:
		print ("Two claps")
		toggleLight(pin)
	# elif clap == 3:
	# 	print "Three claps"
	#elif clap == 4:
	#	exitFlag = True
	print ("Claping Ended")
	clap = 0
	flag = 0

def start():
	global clap
	global flag
	global pin

	chunk = 1024
	FORMAT = pyaudio.paInt16
	CHANNELS = 1
	RATE = 44100
	threshold = 3000
	max_value = 0
	p = pyaudio.PyAudio()
	stream = p.open(format=FORMAT,
					channels=CHANNELS, 
					rate=RATE, 
					input=True,
					output=True,
					frames_per_buffer=chunk)
	try:
		print ("Start")
		while True:
			data = stream.read(chunk)
			as_ints = array('h', data)
			max_value = max(as_ints)
			if max_value > threshold:
				clap += 1
				print ("Clapped")
			if clap == 1 and flag == 0:
				t=threading.Thread( target=waitForClaps, args=("waitThread",) )
				t.start()
				flag = 1
			if exitFlag:
				sys.exit(0)
	except (KeyboardInterrupt, SystemExit):
		print ("\rExiting")
		stream.stop_stream()
		stream.close()
		p.terminate()

if __name__ == '__main__':
	main()

下载:

https://github.com/KrunkZhou/PI-Clap

 

本文链接:【SmartHome】使用Python制作拍手开灯-基于HomeAssistant PythonAPI

转载声明:本站文章若无特别说明,皆为原创,转载请注明来源:Krunk Zhou,谢谢!^^


1 comment

  1. Heya outstanding blog! Does running a blog like this require a large amount of work?

    I have no knowledge of computer programming however I was hoping
    to start my own blog soon. Anyhow, should you have any suggestions or techniques for new blog owners please
    share. I know this is off subject but I simply needed to ask.
    Thanks a lot!

Leave a Reply

Your email address will not be published. Required fields are marked *