2016-10-08 4 views
0

모니터링 프로젝트를 진행하면서 펄스 미터의 펄스를 계산해야합니다. 나는 이미 나의 해결책에 부합하려고 노력 해왔다. 여기 마지막 줄에있는 파이썬

는 라즈베리 파이에서 실행 파이썬 스크립트입니다

#!/usr/bin/env python 

import RPi.GPIO as GPIO 
import datetime 
import sys 
import signal 
from subprocess import check_output 

#verbose = True  # global variable 

############################################################################################################ 
############################################################################################################ 

def printusage(progname): 
     print progname + ' <gpio-pin-number> <filename> [debug]' 
     print 'Example usage: ' 
    print progname + ' 23 /path/to/mylogfile' 
     print progname + ' 23 /path/to/mylogfile debug' 
    sys.exit(-1) 

def signal_handler(signal, frame): 
     if verbose: 
     print('You pressed Ctrl+C, so exiting') 
    GPIO.cleanup() 
     sys.exit(0) 


def readvalue(myworkfile): 
    try: 
     f = open(myworkfile, 'ab+')  # open for reading. If it does not exist, create it 
     line=subprocess.check_output(['tail','-f','-1',f]) 
     elmts=line.split(" ") 
     value = int(elmts[2]) 
    except: 
     value = 0    # if something went wrong, reset to 0 
    #print "old value is", value 
    f.close() # close for reading 
    return value 


def writevalue(myworkfile,value): 
    f = open(myworkfile, 'a') 
    f.write((str(datetime.datetime.now())+' '+str(value)+'\r\n')) # timestamp 
    f.close() 

############################################################################################################ 
############################################################################################################ 

######### Initialization 


#### get input parameters: 

try: 
    mygpiopin = int(sys.argv[1]) 
    logfile = sys.argv[2] 
except: 
    printusage(sys.argv[0]) 

verbose = False 
try: 
    if sys.argv[3] == 'debug': 
     verbose = True 
     print "Verbose is On" 
    else: 
     printusage(sys.argv[0]) 
except: 
    pass 

#### if verbose, print some info to stdout 

if verbose: 
    print "GPIO is " + str(mygpiopin) 
    print "Logfile is " + logfile 
    print "Current value is " + str(readvalue(logfile)) 


#### setup 

GPIO.setmode(GPIO.BCM) 
GPIO.setup(mygpiopin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) 

signal.signal(signal.SIGINT, signal_handler) # SIGINT = interrupt by CTRL-C 


########## Main Loop 

while True: 
    # wait for pin going up 
    GPIO.wait_for_edge(mygpiopin, GPIO.RISING) 

    # read value from file 
    counter=readvalue(logfile) + 1 
    if verbose: 
     print "New value is", counter 

    # write value to file 
    writevalue(logfile,counter) 

    # and wait for pin going down 
    GPIO.wait_for_edge(mygpiopin, GPIO.FALLING) 

############################################################################################################ 
############################################################################################################ 

내가 마지막 인덱스 등록 얻고, 그것을 증가하고 싶지만, 내가 지금까지 테스트 한 모든 것이 붙어 루프 잎 인덱스 1

예를 들어 전체 파일 탐색과 같이 마지막 라인을 찾는 데 "무거운"방법을 사용할 수 없습니다. 시간이 지날수록 더 무겁고 무겁기 때문에 펄스.

저는 프로그래밍에 익숙하지 않으므로 도와 주셔서 감사합니다.

편집 : 결과 파일은 다음과 같다 :

2016-10-08 16:54:23.072469 1 
2016-10-08 16:54:23.462465 1 
2016-10-08 16:54:23.777977 1 
2016-10-08 16:54:24.010045 1 
2016-10-08 16:54:24.194032 1 
2016-10-08 16:54:24.388120 1 
2016-10-08 16:54:24.549389 1 
2016-10-08 16:54:24.737994 1 
2016-10-08 16:54:24.959462 1 
2016-10-08 16:54:25.164638 1 
2016-10-08 16:54:25.351850 1 
2016-10-08 16:54:25.536655 1 
2016-10-08 16:54:25.716214 1 
2016-10-08 16:54:25.794152 1 
2016-10-08 17:06:13.506531 1 
2016-10-08 17:06:14.097642 1 
2016-10-08 17:06:14.211579 1 
2016-10-08 17:06:15.237852 1 
2016-10-08 17:06:15.752239 1 
2016-10-08 17:06:16.320419 1 
2016-10-08 17:06:16.842906 1 
2016-10-08 17:06:17.391121 1 
2016-10-08 17:06:17.851521 1 
2016-10-08 17:06:18.444486 1 
2016-10-08 17:06:18.858358 1 
+0

왜 하위 프로세스를 사용하여 파일을 읽으십니까? 게다가 왜 파일 객체를 전달하는 중입니까? –

+0

탭과 공백을 혼합합니다. 아마도 현재의 문제는 아니지만 미래의 문제의 원인 일 것입니다. 하지 마. 공백 만 사용하십시오. 탭을 누를 때 4 칸을 삽입하도록 편집기를 구성하십시오. – zvone

+0

또한 왜 당신은'line.split ("" ")'이고 세 번째 요소를 얻는가? 여러분이 쓰는 것은'str (datetime.datetime.now()) + ''+ str (value) + '\ r \ n')'입니다. 따라서 두 개의 요소가 최대로 존재합니다 –

답변

0

이 큰 파일의 마지막 줄을 읽어 파일의 끝 부분 위치를 선택하고 읽을 수 있습니다. 거기에 줄 바꿈이 없으면 조금만 돌아가서 다시 읽으십시오.

그런 다음 마지막 줄 바꿈을 찾고 나머지는 마지막 줄을 찾습니다. 값이 다른 곳에서 바로 할 생성 된 경우

def next_index(index): 
    with open(index, 'a+') as f: # open for reading. If it does not exist, create it 
     val = int(next(f, -1)) + 1 # first run value will be 0 
    open(index,"w").write(str(val)) # overwrite 
    return val 

: 당신은 그냥 계속 덮어 별도의 파일의 마지막 인덱스를 저장하는 스크립트를 서로 다른 시간에 실행 될 경우

EXPECTED_MAX_LINE_SIZE = 500 # this should be both small enough and big enough 

def get_last_line(f): 
    end = f.seek(0, os.SEEK_END) # detect file size 
    pos = end-EXPECTED_MAX_LINE_SIZE 
    if pos < 0: pos = 0 
    f.seek(pos, os.SEEK_SET) 
    end_of_file = f.read(EXPECTED_MAX_LINE_SIZE) 

    # TODO: check if '\n' is not there and read some more 

    return end_of_file.splitlines()[-1] 
0

당신의 논리는 방법을 통해 복잡하다 그곳에 글을 쓰려면 이전 값을 w으로 덮어 씌우십시오.

0

그게 Padraic 커닝햄이 무엇을 의미하는지 생각하지 않습니다,하지만 난 값을 저장하는 두 개의 파일, 업데이트 된 인덱스 값을 로깅을위한 하나, 하나를 사용하여 내 문제를 해결하기 위해 관리했습니다 :

#!/usr/bin/env python 

import RPi.GPIO as GPIO 
import datetime 
import sys 
import signal 

#verbose = True  # global debug variable 

############################################################################################################ 

def printusage(progname): #show how to use the script 
    print progname + ' <gpio-pin-number> <index file> <store file> [debug]' 
    print 'Example usage: ' 
    print progname + ' 23 /path/to/mylogfile /path/to/storefile' 
    print progname + ' 23 /path/to/mylogfile /path/to/storefile debug' 
    sys.exit(-1) 

def signal_handler(signal, frame): #exiting the script 
    if verbose: 
     print('You pressed Ctrl+C, so exiting') 
    GPIO.cleanup() 
    sys.exit(0) 


def readvalue(myworkfile): 
    try: 
     f = open(myworkfile, 'ab+')  # open for reading. If it does not exist, create it 
     line=f.readline() #read the first and only line of the file 
     elmts=line.split(" ") # the format is <yyyy-mm-dd hh:mm:ss.ssssss indexvalue> 
     value = int(elmts[2]) #get the index value 
    except: 
     value = 0    # if something went wrong, reset to 0 
    #print "old value is", value 
    f.close() # close for reading 
    return value 


def writevalue(myworkfile,value): 
    f = open(myworkfile, 'w') #overwrite the value 
    f.write((str(datetime.datetime.now())+' '+str(value))) # timestamp + data 
    f.close() 

def store_value(index_file,index_value): 
    f=open(index_file, 'a+') 
    f.write(str(datetime.datetime.now())+' '+str(index_value)+'\r\n') #store timestamp + data 
    f.close() 

############################################################################################################ 

######### Initialization 
#### get input parameters 
try: 
    mygpiopin = int(sys.argv[1]) 
    logfile = sys.argv[2] 
    storefile=sys.argv[3] 
except: 
    printusage(sys.argv[0]) 

verbose = False 
try: 
    if sys.argv[4] == 'debug': 
     verbose = True 
     print "Verbose is On" 
    else: 
     printusage(sys.argv[0]) 
except: 
    pass 

if verbose: #### if verbose, print some info to stdout 
    print "GPIO is " + str(mygpiopin) 
    print "Logfile is " + logfile 
    print "Storefile is " + storefile 
    print "Current value is " + str(readvalue(logfile)) 

#### SETUP 
GPIO.setmode(GPIO.BCM) 
GPIO.setup(mygpiopin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) 
signal.signal(signal.SIGINT, signal_handler) # SIGINT = interrupt by CTRL-C 

########## Main Loop ##### 

while True: 
    GPIO.wait_for_edge(mygpiopin, GPIO.RISING) # wait for pin going up 
    counter=readvalue(logfile) + 1 # read value from file and increment index 
    if verbose: 
     print "New value is", counter 
    writevalue(logfile,counter) # write value to logfile 
    store_value(storefile,counter) # store value in storefile 
    GPIO.wait_for_edge(mygpiopin, GPIO.FALLING) # and wait for pin going down 
############################################################################################################ 

도움 주셔서 감사합니다.

+0

* 나는 그렇게 생각하지 않습니다. Padraic Cunningham은 그 의미를 정확히 나타냅니다. ** 별도의 파일에 마지막 색인을 저장하십시오 ** –

+0

잘 이해했습니다, 다시 한번 감사드립니다! – NyuengBo