2013年8月

树莓派 声控开关

接线

VCC -> 2(物理)
GND -> 6(物理)
OUT -> 7(物理)

2013-08-10 16.07.53.jpg

代码

#!/usr/bin/env python
# encoding: utf-8
# @author xiaozi <245565986@qq.com>

import RPi.GPIO as GPIO
import time

# pin: 物理7 -> 4

GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN)

while 1:
    # 0是有声音,1是没声音
    print(GPIO.input(4))
    time.sleep(0.001)

树莓派 CPU内存监视

前提

需要一个 http服务器提供访问,还需要一个 websocket吐服务器数据,至于怎么编译nginx这边就不讲了

预览

屏幕快照 2013-08-06 下午2.29.19.png

代码

这里主要给出后端python的代码,前端主要是用backbone + smoothiecharts实现

#!/usr/bin/env python
# encoding: utf-8

import tornado.web
import tornado.websocket
import tornado.ioloop
import subprocess, threading, json, re

def vmstat():
	memoryKey = ['swpd', 'free', 'buff', 'cache', 'total']
	cpuKey = ['us', 'sy', 'id', 'wa']
	space = re.compile('\s+')
	memTotal = subprocess.check_output("cat /proc/meminfo | grep MemTotal | sed 's/\\w*:\\s*\\([0-9]*\\).*/\\1/'", shell = True).strip()
	# print(memTotal)
	# 这个地方要使用 shell = True 的话,需要记得退出的时候关闭子进程
	p = subprocess.Popen(['vmstat', '1', '-n'], stdout = subprocess.PIPE)
	io_loop = tornado.ioloop.IOLoop.instance()
	p.stdout.readline()
	p.stdout.readline()
	for line in iter(p.stdout.readline, ''):
		# print(line)
		fields = space.split(line.strip())
		memoryVal = fields[2: 6]
		memoryVal.append(memTotal)
		result = dict(memory=dict(zip(memoryKey, memoryVal)), cpu=dict(zip(cpuKey, fields[12: 16])))
		result = json.dumps(result)
		print(result)
		for waiter in MonitorHandler.waiters:
			io_loop.add_callback(waiter.write_message, result)

class MonitorHandler(tornado.websocket.WebSocketHandler):
	waiters = set()
	def open(self):
		MonitorHandler.waiters.add(self)
		print('waiters: ', len(MonitorHandler.waiters))
	def on_message(self, message):
		pass

	def on_close(self):
		MonitorHandler.waiters.remove(self)
		print('waiters: ', len(MonitorHandler.waiters))

class Application(tornado.web.Application):
	def __init__(self):
		handlers = [
			('/', MonitorHandler)
		]
		super(Application, self).__init__(handlers)

def main():
	app = Application()
	app.listen(8888)
	t = threading.Thread(target=vmstat)
	t.daemon = True
	t.start()
	print('Starting the server...')
	tornado.ioloop.IOLoop.instance().start()


if __name__ == '__main__':
	main()

树莓派 报IP 和 lcd显示IP

接 16x2 LCD

网上找的,就属这张图清晰了。lc_wire.png2013-07-18 13.05.08.jpg2013-07-18 17.48.54.jpg

准备

由于我使用的是pidora, 所以很多库默认都没装(貌似是没wheezy方便,不过习惯了centos)


播放声音本想用mpc的,但安装完总有问题,于是就编译了一个 madplay

yum -y install alsa-utils alsa-lib-devel

至于TTS嘛,木有,就自己从网上下载了几段,然后拼起来播放。屏幕快照 2013-08-06 下午2.04.54.png

for i in {0..255}; do wget -O $i.mp3 http://tts-api.com/tts.mp3?q=$i; done

实现代码

#!/usr/bin/env python
# encoding: utf-8

import Adafruit_CharLCD
import subprocess, time, datetime, math, signal, sys, os

def get_ip(device):
	ip = subprocess.check_output("ip -4 addr show " + device + " | grep inet | awk '{print $2}' | cut -d/ -f1", shell = True).strip()
	return ip

def main():
	last_ip = ip = ''
	maxLen = 16
	while True:
		ip = get_ip('eth0')
		if ip == last_ip:
			time.sleep(10)
			continue
		last_ip = ip
		sounds = ' /root/Music/tts/dot.mp3 '.join(['/root/Music/tts/' + i + '.mp3' for i in last_ip.split('.')]).split(' ')
		spaceLen = maxLen - len(ip)
		ip = int(math.floor(spaceLen / 2)) * ' ' + ip
		lcd.clear()
		lcd.message('  Raspberry Pi  \n')
		lcd.message(ip)
		subprocess.call(['madplay', '/root/Music/tts/your_ip_address_is.mp3'] + sounds)
		time.sleep(10)
		# + chr(0xdf) + 'C'
		# while True:
		# 	time.sleep(1)
		# 	lcd.clear()
		# 	lcd.message(datetime.datetime.now().strftime('  %I : %M : %S \n%a %b %d %Y'))

def onShutdown(sig, id):
	lcd.clear()
	time.sleep(.1)
	sys.exit(0)

if __name__ == '__main__':
	pid = os.fork()
	if pid == 0:
		signal.signal(signal.SIGTERM, onShutdown)
		lcd = Adafruit_CharLCD.Adafruit_CharLCD()
		main()
	else:
		sys.exit(0)