2014년 7월 30일 수요일

Raspberry PI MP3 Player Temp Source


from time import sleep
import os
from subprocess import Popen, PIPE
import RPi.GPIO as GPIO
import pyinotify

GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN)
GPIO.setup(27, GPIO.IN)
GPIO.setup(25, GPIO.IN)
GPIO.setup(24, GPIO.IN)
GPIO.setup(23, GPIO.IN)
GPIO.setup(18, GPIO.IN)

startDelay = 20
sw = [1, 1, 1, 1, 1, 1]
swold = [1, 1, 1, 1, 1, 1]

p = Popen(['mpg321', '-R', 'n', '-g',  '100'], stdin=PIPE, stdout=PIPE)

wm = pyinotify.WatchManager()
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE

class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
print "Create: %s" % event.pathname
p.stdin.write('STOP\n')


def process_IN_DELETE(self, event):
print "Remove: %s" % event.pathname
p.stdin.write('STOP\n')

notifier = pyinotify.ThreadedNotifier(wm, EventHandler())
notifier.start()

wdd = wm.add_watch('/media', mask, rec=True)

while True:
sw[0] = GPIO.input(23)
sw[1] = GPIO.input(18)
sw[2] = GPIO.input(27)
sw[3] = GPIO.input(24)
sw[4] = GPIO.input(22)
sw[5] = GPIO.input(25)
#print(GPIO.input(23), GPIO.input(18), GPIO.input(27), GPIO.input(24), GPIO.input(22), GPIO.input(25))

sleep(0.1)

if( startDelay == 0 ):
for x in range(0, 4):
if( (swold[x] == 0) and (sw[x] == 1) ):
printstr = 'clicked' + str(x)
print(printstr)
cmdStr = 'LOAD /home/pi/320/0' + str(x+1) + '.mp3\n'
p.stdin.write(cmdStr)
if( (swold[4] == 0) and (sw[4] == 1) ):
print('clicked5')
p.stdin.write('STOP\n')
if( (swold[5] == 0) and (sw[5] == 1) ):
print('clicked6')
p.stdin.write('QUIT\n')
wm.rm_watch(wdd.values())
notifier.stop()
exit()
else:
startDelay = startDelay - 1

for x in range(0, 6): swold[x] = sw[x]

# /media/2088-0EBF/Disc1/01.\ Yello\ -\ The\ Race.mp3

Pyinotify : 리눅스에서 파이썬으로 파일시스템 이벤트 감시하기

Pyinotify는 현재 http://github.com/seb-m/pyinotify 에서 호스트됨.
새로운 버전의 Pyinotify는 위의 새로운 위치에 릴리즈 됨.


설명
 - 수정일 : 2007년 12월 30일 21:13
Pyinotify는 파일시스템 변경을 감시하기 위한 파이썬 모듈이다. Pyinotify는 inotify라 불리는 리눅스 커널 특징(머지된 커널 2.6.13)에 의지한다. inotiry는 이벤트 기반 알림자이고 그것의 알림은 커널 공간으로부터 세가지 시스템 호출을 통하여 사용자 공간으로 나온다. pyinotify는 이 시스템 호출과 그들이 일반적으로 제공하는 것들의 위에서의 수행과 이 기능들을 조작하기 위한 추상적인 방법을 결합한다.


다운로드
 - 수정일 : 2008년 1월 29일 02:43
새로운 site의 Pyinotify의 현재 버전 다운로드 (http://github.com/seb-m/pyinotify)
: 이 버전은 최근 모든 시스템에 추천된다. 파이썬 2.5(또는 그이상). 새로운 기능을 모두 포함한다.

예전 버전 0.7.1 다운로드 (옳지않아~)
: 이 버전은 최근의 개발 기능은 포함하지 않는다. 사실은 파이썬 2.3과 파이썬 2.4를 지원하는 Pyinotify의 마지막 버전이다.


빠른 시작
 - 수정일 : 2006년 5월 6일 13:07
pyinotify에 익숙해지기 위해 다음의 첫 예제를 실행하라.
$ cd pyinotify-x-x-x && python setup.py build
$ python src/pyinotify/pyinotify.py -v my-dir-to-watch

my-dir-to-watch는 유효한 디렉토리 패쓰다. 지금 이 디렉토리로 가서 파일을 작업하라: 하나를 읽거나 새로 생성하거나... 그리고 pyinotify에 의해 생성된 출력물로 당신의 행동을 비교하라. 당신의 첫 디렉토리를 보는 것을 즐겨라.

참고: pyinotify를 설치하길 원하면 다음과 같이 하시길...
$ cd pyinotify-x-x-x && python setup.py install

설치된 파일이 어디에 있는지 알려면 README 파일을 봐라.


문서
 - 수정일 : 2008년 1월 29일 02:37
생성된 온라인 문서 버전 0.7.x 를 전체 클래스 분류를 보기위해 둘러봐라.


네임스페이스
 - 수정일 : 2006년 11월 26일 10:47
로직을 이해하는데 도움이 되고 접근될 수 있는 pyinotify를 통하여 파이썬 네임스페이스를 소개합니다. pyinotify는 inotify와 pyinotify의 두 모듈이 혼합되었다.


간결 지도서
 - 수정일 : 2008년 1월 28일 23:38
좀 더 자세한 예제를 시작하자. 임시 디렉토리 '/tmp'와 그 하위의 모든 디렉토리에 있는 파일들의 새로운 파일 생성와 삭제를 감시하길 원한다고 하자. 우리는 모든 알림에 대한 메시지를 기본 출력으로만 출력한다.

지금 당신은 모니터링을 예로들어 쓰레드에서의 알림을 받거나 처리하는 것을 고를 수 있다.
주된 편의는 그것이 새로은 쓰레드를 필요로 하지 않는다는 것이고, 결점은 이 태스크에서 당신의 프로그램은 블럭되는 것이다. 또는, 당신의 메인 쓰레드가 블럭되길 원치 않는다면, 새로 나뉘어진 쓰레드에서 알람을 제어할 수 있다. 너의 요구에 가장 적합한 하나를 골라라.
다음은 두 접근에 대해 자세히 할 것이다.
알림자 쓰레드알림자
현재쓰레드 Y N
분리 쓰레드 N Y

첫째로 statement를 들인다 : watch manager(감시 관리자)는 감시의 감시와 제공 운용을 저장한다. EventsCodes(이벤트코드)는 코드의 설정을 초래한다. 각 코드는 이벤트에 연합되어 있다. ProcessEvent(처리이벤트)는 처리하기 클래스이다.

import os
from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent

wm = WatchManager()

다음의 클래스는 ProcessEvent로부터 상속받고, 알림을 제어하고, 특별한 문법으로 쓰여진 이름의 개인 처리 메소드로 정의된 행동을 처리한다. process_EVENT_NAME의 EVENT_NAME은 처리를 위해 제어되는 이벤트의 이름이다.

mask = EventsCodes.IN_DELETE | EventsCodes.IN_CREATE  # watched events

class PTmp(ProcessEvent):
    def process_IN_CREATE(self, event):
        print "Create: %s" %  os.path.join(event.path, event.name)

    def process_IN_DELETE(self, event):
        print "Remove: %s" %  os.path.join(event.path, event.name)

다음은 알림자와 쓰레드 알림자 각각의 클래스를 설명한다.



[ Class Notifier ]
이 statement는 우리의 알림자 클래스와 inotify의 인스턴스화 실제 초기화를 예를든다. 두번째 파라미터는 다음의 방법으로 알림된 이벤트 처리에 사용되어질 수 있는 하나의 호출가능한 객체이다.
: PTmp()(event)에서 event는 알려진 이벤트이다.

notifier = Notifier(wm, PTmp())

그 다음 statement는 첫번째 파라미터에 감시를 추가하고 모든 하위 디렉토리에 재귀적이다. 참고로 심볼릭링크는 따르지 않는다. 재귀는 'rec'라 이름된 옵션 파라미터를 True로 설정하는 것이 적당하다. 기본적으로 모니터링은 주어진 디렉토리의 단계에 제한적이다. 그것의 키는 경로이고 값은 감시 설명자(watch descriptors)에 상응하고 wdd에 할당된 dict를 반환한다. 유일한 wd는 모든 새로운 감시에 특징된다. 그것은 감시 중 하나를 차후 업데이트나 제거를 위해 이들 wds를 유지하는데 유용하거나 종종 필수적이다. 물론, 감시되는 요소가 파일을 가진 경우, rec 파라미터는 값이 무엇이든간에 무시되어진다.

wdd = wm.add_watch('/tmp', mask, rec=True)

이벤트를 잃고 처리해 보자. loop동안에 우리는 어떤 감시(watch)든 자유롭게 추가하고 갱신하고 제거할 수 있다. 또한 pyinotify와 관계없는 재료조차 우리가 원하는 어떤것이든 할 수 있다. 우리는 모니터링을 그만하고 싶을 때 stop() 메소드를 호출한다.

while True:  # loop forever
    try:
        # process the queue of events as explained above
        notifier.process_events()
        if notifier.check_events():
            # read notified events and enqeue them
            notifier.read_events()
        # you can do some tasks here...
    except KeyboardInterrupt:
        # destroy the inotify's instance on this interrupt (stop monitoring)
        notifier.stop()
        break



[ Class ThreadNotifier ]
두번째 줄은 새로운 쓰레드를 시작한다. 실제로 아무것도 하지 않는다. 디렉도리도 파일도 감시되지 않는다.

notifier = ThreadedNotifier(wm, PTmp())
notifier.start()

wdd = wm.add_watch('/tmp', mask, rec=True)

어떤 순간에 우리는 예제처럼 '/tmp'의 감시(watch)를 제거할 수 있다.

if wdd['/tmp'] > 0:  # test if the wd is valid, this test is not mandatory
   wm.rm_watch(wdd['/tmp'])

참고로 그것의 하부 디렉토리는 여전히 감시된다. 만약 당신이 '/tmp'와 그 하부 디렉토리의 감시까지도 제거하길 원한다면, 다음처럼 할 수 있다.

wm.rm_watch(wdd['/tmp'], rec=True)

또는 다음처럼 하는게 더 낫다.

wm.rm_watch(wdd.values())

대부분의 코드가 쓰여졌다. 다음으로, 우리는 파일이나 디렉토리에 같은 방법으로 감시를 추가하고 갱신하고 제거할 수 있다. 오직 남아있는 중요한 태스크는 우리가 모니터링을 멈추고자 할 때 쓰레드를 멈출 것이다. 그것은 자동적으로 inotify의 인스턴스를 파괴할 것이다. 다음의 메소드를 호출하자.

notifier.stop()



[ EventsCodes Class ]
Event Name Is an Event Description
IN_ACCESS Yes file was accessed.
IN_ATTRIB Yes metadata changed.
IN_CLOSE_NOWRITE Yes unwrittable file was closed.
IN_CLOSE_WRITE Yes writtable file was closed.
IN_CREATE Yes file/dir was created in watched directory.
IN_DELETE Yes file/dir was deleted in watched directory.
IN_DELETE_SELF Yes watched item itself was deleted.
IN_DONT_FOLLOW No don't follow a symlink (lk 2.6.15).
IN_IGNORED Yes raised on watched item removing. Probably useless for you, prefer instead IN_DELETE*.
IN_ISDIR No event occurred against directory. It is always piggybacked to an event. The Event structure automatically provide this information (via .is_dir)
IN_MASK_ADD No to update a mask without overwriting the previous value (lk 2.6.14). Useful when updating a watch.
IN_MODIFY Yes file was modified.
IN_MOVE_SELF Yes watched item itself was moved, currently its full pathname destination can only be traced if its source directory and destination directory are both watched. Otherwise, the file is still being watched but you cannot rely anymore on the given path (.path)
IN_MOVED_FROM Yes file/dir in a watched dir was moved from X. Can trace the full move of an item when IN_MOVED_TO is available too, in this case if the moved item is itself watched, its path will be updated (see IN_MOVE_SELF).
IN_MOVED_TO Yes file/dir was moved to Y in a watched dir (see IN_MOVE_FROM).
IN_ONLYDIR No only watch the path if it is a directory (lk 2.6.15). Usable when calling .add_watch.
IN_OPEN Yes file was opened.
IN_Q_OVERFLOW Yes event queued overflowed. This event doesn't belongs to any particular watch.
IN_UNMOUNT Yes backing fs was unmounted. Notified to all watches located on this fs.