def monitor_srslte(self, proc):
        """ Monitor for crashes and restart srsLTE"""
        # TODO
        global EXIT
        out = []
        sleep(1)
        nbsr = NBSR(proc.stdout)
        line = ''
        while not EXIT:
            line = nbsr.readline(int(self.config["general"]["crash_timeout"]))
            if line is not None:
                self.logger.debug(line.decode("ascii").rstrip())
            out.append(line)

            if proc.poll() is not None or line is None:
                self.logger.warning(f"srsUE has exited unexpectedly")
                try:
                    self.logger.warning(
                        f"It's dying words were: {out[-2].decode('ascii').rstrip()}"
                    )
                except IndexError as e:
                    pass
                proc.kill()
                self.update_earfcn_list()
                proc = self.start_srslte()
                self.monitor_srslte(proc)
Example #2
0
    def run_instrument(self):
        context = self.context

        start = int(time.time())
        args = ['adb', '-s', context.ip, 'shell', 'am', 'instrument', '-w', '-r', '-e', 'debug', 'false',
                context.appPkgName + '.test/android.support.test.runner.AndroidJUnitRunner']
        result = ''
        child = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE)

        nbsr = NBSR(child.stdout)

        # 若进程尚未结束, popen() 返回 none
        while child.poll() is None:
            logging.debug("child.poll() is none")
            now = int(time.time())
            costTime = (now - start) / 60
            if costTime < context.timeout and costTime < 100:
                logging.debug('cost time:' + str(costTime))
                # result += child.stdout.readline()
                output = nbsr.readline(30)
                if not output:
                    logging.debug("no output")
                else:
                    result += output
            else:
                logging.debug('time out, the process will be killed')
                child.kill()
                child.wait()
                break
        logging.debug("child is over !!")
        return context.make_report(result)
Example #3
0
def runTestcase(testplan):
    subprocess.call("rm -f *.card; rm .*.card", shell=True)
    subprocess.call("rm -f *.auth", shell=True)
    print("Exec bank process")
    popen = subprocess.Popen(["./bank"], stdout=subprocess.PIPE)
    atexit.register(popen.kill)
    print("Read first line")
    nbsr = NBSR(popen.stdout)
    print(nbsr.readline(5))
    error = False
    print("--" * 30)

    for test in testplan:
        same = runExceution(nbsr, test["input"], test["bank"], test["atm"])
        print("--" * 30)
        if not same:
            error = True
            break

    subprocess.call("rm -f *.card", shell=True)
    subprocess.call("rm -f *.auth", shell=True)
    popen.terminate()
    print("BANK SIGTERM")
    popen.wait(10.0)
    if popen.returncode is None:
        popen.kill()
        print("ERROR BANK: did not exit in time")
        error = True
    elif popen.returncode != 0:
        print("ERROR BANK: did not exit with code 0")
        error = True
    else:
        print("BANK EXIT OK")
    return not (error)
Example #4
0
    def do_start_heartrate(self, line):
        self.sp_heartrate = subprocess.Popen(
            ['./gatttool', '-t', 'random', '-b', 'D4:48:C2:4C:A0:19', '-I'],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=False)

        self.nbsr_heartrate = NonBlockingStreamReader(self.sp_heartrate.stdout)
        print self.nbsr_heartrate.readline(0.1)

        self.sp_heartrate.stdin.write('\n')
        self.sp_heartrate.stdin.write('connect')
        self.sp_heartrate.stdin.write('\n')

        sleep(2)

        self.nbsr_heartrate.readline(0.1)
        self.sp_heartrate.stdin.write('char-write-req 18 0100')
        self.sp_heartrate.stdin.write('\n')

        sleep(2)

        print self.nbsr_heartrate.readline(0.1)

        self.sp_heartrate.stdin.write('\n')
Example #5
0
 def do_start_mindwave(self, line):
     """starts listening for attention value from attention.py"""
     self.sp_mindwave = subprocess.Popen(["python", "attention.py"],
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         shell=False)
     self.nbsr_mindwave = NonBlockingStreamReader(self.sp_mindwave.stdout)
Example #6
0
 def do_start_voice(self, line):
     """start listening for voice commands"""
     self.sp_voice = subprocess.Popen(['python', 'easyvr.py'],
                                      stdin=subprocess.PIPE,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      shell=False)
     self.nbsr_voice = NonBlockingStreamReader(self.sp_voice.stdout)
     self.sp_vocie.stdin.write('\n')
Example #7
0
    def do_start_proximity(self, line):
        """start tracking people using proximity"""
        self.sp_proximity = subprocess.Popen(
            ['python', 'mb1200_analog_test_karli.py'],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=False)

        self.nbsr_proximity = NonBlockingStreamReader(self.sp_proximity.stdout)
        self.sp_proximity.stdin.write('\n')
Example #8
0
	def CreateChildProcess(self,Execution_Command,Executable_File):
		if platform == 'win32' and Executable_File.endswith('.exe'):
			self.ChildProcess = Popen (str(Executable_File), stdin = PIPE, stdout = PIPE, bufsize=0)
		elif platform == "darwin" or platform == "linux" or platform == "linux2":
			self.ChildProcess = Popen ([Execution_Command, Executable_File], stdin = PIPE, stdout = PIPE, bufsize=0,preexec_fn=os.setsid)
		else:
			self.ChildProcess = Popen ([Execution_Command, Executable_File], stdin = PIPE, stdout = PIPE, bufsize=0)
			# self.ChildProcess = Popen (str(Executable_File), stdin = PIPE, stdout = PIPE, bufsize=0)
		self.ModifiedOutStream = NBSR(self.ChildProcess.stdout)
Example #9
0
class Writer(object):
    def __init__(self, path, size, in_fps=25.0,
                 in_vcodec='rawvideo', in_pix_fmt='bgr24',
                 out_fps=None, out_vcodec='h264', out_pix_fmt='yuvj420p'):
        command = [
            FFMPEG_BIN,
            '-hide_banner',
            '-y',   # (optional) overwrite output file if it exists
            '-s', '%dx%d' % (size[0], size[1]),
            '-r', '%.02f' % in_fps,  # frames per second
            '-f', 'rawvideo' if in_vcodec == 'rawvideo' else 'image2pipe',  # image2pipe for image stream
            '-vcodec', in_vcodec,
            '-pix_fmt', in_pix_fmt,
            '-i', '-',  # input comes from a pipe
            '-an',  # no audio
            '-r', '%.02f' % (out_fps or in_fps),  # frames per second
            '-vcodec', out_vcodec,
            '-pix_fmt', out_pix_fmt,
            path,
        ]
        self.path = path
        self.pipe = sp.Popen(command, stdin=sp.PIPE, stderr=sp.PIPE)
        self.nb_stderr = NBSR(self.pipe.stderr)

    def write(self, data):
        try:
            self.nb_stderr.read(0.1)
            self.pipe.stdin.write(data)
        except IOError as err:
            ffmpeg_error = self.nb_stderr.read()
            error = (str(err) + ("\n\nFFMPEG error: FFMPEG encountered "
                                 "the following error while writing file %s:"
                                 "\n\n %s" % (self.path, ffmpeg_error)))
            raise IOError(error)

    def close(self):
        if hasattr(self, 'pipe'):
            self.pipe.stdin.close()
            self.nb_stderr.close()
            self.pipe.wait()
            del self.pipe

    def __del__(self):
        self.close()
 def CreateChildProcess(self, Execution_Command, Executable_File,
                        args_list):
     if platform == "darwin" or platform == "linux" or platform == "linux2":
         self.ChildProcess = Popen([Execution_Command, Executable_File] +
                                   args_list,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   bufsize=0,
                                   preexec_fn=os.setsid)
     else:
         self.ChildProcess = Popen([Execution_Command, Executable_File] +
                                   args_list,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   bufsize=0)
     self.ModifiedOutStream = NBSR(self.ChildProcess.stdout)
Example #11
0
    def play(self, irc, msg, args):
	""" takes no arguments

	loads pandora and starts music
	"""

	if not self.isPlaying:

	    # pianobar subprocess
	    self.p = Popen('pianobar', stdin=PIPE, stdout=PIPE, stderr=PIPE,
                shell=True)
	    
	    # non-blocking stream reader
	    self.nbsr = NBSR(self.p.stdout)
	    self.isPlaying = True
	    irc.reply('playing...')
	else:
	    irc.reply('already playing')
Example #12
0
class Terminal():

    def __init__(self):
        self.term_started = False
        self.proc = None
        self.nbsr = None

    def start_terminal(self):
        self.proc = subprocess.Popen(["/bin/sh"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        self.nbsr = NBSR(self.proc.stdout)
        self.term_started = True


    def execute_command(self, input_cmd):
        out_out = []

        #Format the command
        args_list = shlex.split(input_cmd)
        args_str = " ".join(i for i in args_list)
        args_str += "\n"

        if args_str == "exit\n":
            print("EXITING TERMINAL")
            self.term_started = False
            self.proc.terminate()
            return "Left Terminal mode"

        #Write the command
        self.proc.stdin.write(args_str)

        #Parse output
        while True:
            out = self.nbsr.readline(0.1)
            if not out:
                break
            out_out.append(out)

        print out_out

        #Format output
        response = "".join(i for i in out_out)

        return response
Example #13
0
 def __init__(self, path, size, in_fps=25.0,
              in_vcodec='rawvideo', in_pix_fmt='bgr24',
              out_fps=None, out_vcodec='h264', out_pix_fmt='yuvj420p'):
     command = [
         FFMPEG_BIN,
         '-hide_banner',
         '-y',   # (optional) overwrite output file if it exists
         '-s', '%dx%d' % (size[0], size[1]),
         '-r', '%.02f' % in_fps,  # frames per second
         '-f', 'rawvideo' if in_vcodec == 'rawvideo' else 'image2pipe',  # image2pipe for image stream
         '-vcodec', in_vcodec,
         '-pix_fmt', in_pix_fmt,
         '-i', '-',  # input comes from a pipe
         '-an',  # no audio
         '-r', '%.02f' % (out_fps or in_fps),  # frames per second
         '-vcodec', out_vcodec,
         '-pix_fmt', out_pix_fmt,
         path,
     ]
     self.path = path
     self.pipe = sp.Popen(command, stdin=sp.PIPE, stderr=sp.PIPE)
     self.nb_stderr = NBSR(self.pipe.stderr)
Example #14
0
class Communicator(object):
	def __init__(self):
		self.Socket = None
		self.ChildProcess = None

	def setSocket(self,Socket,TIMEOUT=60):
		self.Socket = Socket
		self.Socket.settimeout(TIMEOUT)


	def isSocketNotNone(self):
		if(self.Socket is None):
			return False
		else:
			return True

	def isChildProcessNotNone(self):
		if(self.ChildProcess is None):
			return False
		else:
			return True

	def closeSocket(self):
		if(self.isSocketNotNone()):
			# Try in case the connection is already closed by the other process
			try:
				self.Socket.close()
			except:
				pass
			self.Socket = None

	def SendDataOnSocket(self,data):
		success_flag = False
		if(self.isSocketNotNone()):
			try:
				self.Socket.send(data)
				success_flag = True
			except Error:
				pass
		return success_flag

	def RecvDataOnSocket(self):
		data = None
		if(self.isSocketNotNone()):
			while True:
				try:
					data = self.Socket.recv(1024)
				except:
					data = None
					break
				if(data is None):
					break
				elif(len(data) > 0):
					break
		return data


	def CreateChildProcess(self,Execution_Command,Executable_File):
		if platform == "darwin" or platform == "linux" or platform == "linux2":
			self.ChildProcess = Popen ([Execution_Command, Executable_File], stdin = PIPE, stdout = PIPE, bufsize=0,preexec_fn=os.setsid)
		else:
			self.ChildProcess = Popen ([Execution_Command, Executable_File], stdin = PIPE, stdout = PIPE, bufsize=0)
		self.ModifiedOutStream = NBSR(self.ChildProcess.stdout)


	def RecvDataOnPipe(self,TIMEOUT):
		data = None
		if(self.isChildProcessNotNone()):
			try:
				data = self.ModifiedOutStream.readline(TIMEOUT)
			except:
				pass
		return data

	def SendDataOnPipe(self,data):
		success_flag = False
		if(self.isChildProcessNotNone()):
			try:
				self.ChildProcess.stdin.write(data)
				success_flag = True
			except:
				pass
		return success_flag

	def closeChildProcess(self):
		if(self.isChildProcessNotNone()):
			if platform == "darwin" or platform == "linux" or platform == "linux2":
				try:
				 	os.killpg(os.getpgid(self.ChildProcess.pid), 15)
				except:
					pass
			else:
				self.ChildProcess.kill()
			self.ChildProcess = None
Example #15
0
#run with zbarcam --prescale=640x480 -S*.disable -Sqrcode.enable | python kevin.py

from strobeClass import Heartbeat

import sys
import time
from heartLeds import tidyup

from nbstreamreader import NonBlockingStreamReader as NBSR

nbsr = NBSR(sys.stdin)

#constants
baseline_hr = 70
max_hr = 220
min_hr = 30
change_time = 3
effect_time = 25
recovery_time = 5
hb = Heartbeat(70)

#variables
heart_rate = baseline_hr
qr_codes = []
target_rates = []
times_scanned = []
target_hr = baseline_hr

heart_rate = baseline_hr
scanned = False
Example #16
0
from subprocess import Popen, PIPE
from time import sleep
from nbstreamreader import NonBlockingStreamReader as NBSR

# run the shell as a subprocess:
p = Popen(['/bin/sh'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)
# wrap p.stdout with a NonBlockingStreamReader object:
nbsr = NBSR(p.stdout)
# issue command:
p.stdin.write('gateone\n')
# get the output
while True:
    output = nbsr.readline(0.1)  # 0.1 secs to let the shell output the result
    if not output:
        print '[No more data]'
        break
    print output
Example #17
0
class Dress(cmd.Cmd):
    pin_demo_switch = '2'

    # subprocess for each sensor interface used in dress
    sp_voice = None
    sp_mindwave = None
    sp_heartrate = None
    sp_proximity = None
    sp_demo_lights = None

    # used for reading output from subprocess
    nbsr_voice = None
    nbsr_mindwave = None
    nbsr_heartrate = None
    nbsr_proximity = None

    def do_EOF(self, line):
        return True

    def do_start_heartrate(self, line):
        self.sp_heartrate = subprocess.Popen(
            ['./gatttool', '-t', 'random', '-b', 'D4:48:C2:4C:A0:19', '-I'],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=False)

        self.nbsr_heartrate = NonBlockingStreamReader(self.sp_heartrate.stdout)
        print self.nbsr_heartrate.readline(0.1)

        self.sp_heartrate.stdin.write('\n')
        self.sp_heartrate.stdin.write('connect')
        self.sp_heartrate.stdin.write('\n')

        sleep(2)

        self.nbsr_heartrate.readline(0.1)
        self.sp_heartrate.stdin.write('char-write-req 18 0100')
        self.sp_heartrate.stdin.write('\n')

        sleep(2)

        print self.nbsr_heartrate.readline(0.1)

        self.sp_heartrate.stdin.write('\n')

    def do_start_mindwave(self, line):
        """starts listening for attention value from attention.py"""
        self.sp_mindwave = subprocess.Popen(["python", "attention.py"],
                                            stdin=subprocess.PIPE,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            shell=False)
        self.nbsr_mindwave = NonBlockingStreamReader(self.sp_mindwave.stdout)

    def do_start_voice(self, line):
        """start listening for voice commands"""
        self.sp_voice = subprocess.Popen(['python', 'easyvr.py'],
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         shell=False)
        self.nbsr_voice = NonBlockingStreamReader(self.sp_voice.stdout)
        self.sp_vocie.stdin.write('\n')

    def do_start_proximity(self, line):
        """start tracking people using proximity"""
        self.sp_proximity = subprocess.Popen(
            ['python', 'mb1200_analog_test_karli.py'],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=False)

        self.nbsr_proximity = NonBlockingStreamReader(self.sp_proximity.stdout)
        self.sp_proximity.stdin.write('\n')

    def do_monitor(self, line):
        """Monitors all sensor output"""

    def do_monitor(self, line):
        """Monitors all sensors"""
        #open connection to database for web server
        #db = sqlite3.connect('web_server/./dress.db')
        #c = db.cursor()

        while True:
            if self.sp_voice is not None:
                try:
                    voice_output = self.nbsr_voice.readline(0.1).strip()
                    if voice_output is EXERCISE:
                        print 'activate exercise lights routine'
                    elif voice_output is PORTRAY:
                        print 'activate portray lights routine'
                    elif voice_output is SPECULATE:
                        print 'activate speculate lights routine'
                    elif voice_output is MUSE:
                        print 'activate muse lights routine'
                    elif voice_output is NEVERMIND:
                        print 'canceling lights for previous command'
                except AttributeError:
                    pass

            if self.sp_heartrate is not None:
                heartrate_output = self.nbsr_heartrate.readline(0.1)
                self.sp_heartrate.stdin.write('\n')
                if heartrate_output:
                    try:
                        # Add logic for what to do with heart rate
                        heartrate = int("0x" + heartrate_output[-4:], 16)
                        #c.execute("INSERT INTO heartrate (value) VALUES (?)", (heartrate,))
                        #self.write_heartrate(str(heartrate).strip())
                        #led_lights.stdin.write(str(heartrate).strip() + '\n')
                        print heartrate
                    except TypeError:
                        pass

            if self.sp_proximity is not None:
                proximity_output = self.nbsr_proximity.readline(0.1)
                #c.execute("INSERT INTO proximity (value) VALUES (?)", (proximity_output.strip(),))
                print proximity_output

            if self.sp_mindwave is not None:
                mindwave_output = self.nbsr_mindwave.readline(0.1)
                #c.execute("INSERT INTO attention (value) VALUES (?)", (mindwave_output.strip(),))
                print mindwave_output
Example #18
0
import subprocess
import shlex
import time
from nbstreamreader import NonBlockingStreamReader as NBSR

cmd = "/home/lotus/leela-zero-0.15/src/leelaz -w /home/lotus/leela-zero-0.15/best-network --gpu 4"
args  = shlex.split(cmd)
p = subprocess.Popen(args,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,shell=False)

nbsr = NBSR(p.stdout)
colors = 'bw'
while p.poll() is None:
    output = nbsr.readline(3)
    if not output:

        color = colors[0]
        print('No more data')
        # p.stdin.write('genmove black'.encode('utf-8'))
        p.stdin.write(('genmove {}\n'.format(color)).encode('utf-8'))
        p.stdin.flush()
        colors = colors[::-1]

        # p.stdout.flush()
    print(output)
Example #19
0
def main(argv):
    field = initialField()
    offender = []
    defender = []

    verbose = False
    pos = None
    for arg in argv:
        if arg == '-o':
            pos = 'offender'
        elif arg == '-d':
            pos = 'defender'
        elif arg == '-v':
            verbose = True
        elif pos == 'offender':
            offender.append(arg)
        elif pos == 'defender':
            defender.append(arg)

    if len(offender) == 0 or len(defender) == 0:
        print "no args"
        return 1

    offender_proc = subprocess.Popen(offender,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     shell=False)
    offender_in = offender_proc.stdin
    offender_out = NBSR(offender_proc.stdout)
    offender_pid = offender_proc.pid

    defender_proc = subprocess.Popen(defender,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     shell=False)
    defender_in = defender_proc.stdin
    defender_out = NBSR(defender_proc.stdout)
    defender_pid = defender_proc.pid

    turn = 0
    score = 0
    while True:
        turn += 1
        if verbose:
            print '=== Turn %d (Score: %d) ===' % (turn, score)
            printField(field, sys.stdout)

        offender_in.write('game\n')
        printField(field, offender_in)
        put = offender_out.readline(2.0)
        if verbose:
            print '>> ' + put,

        field = place(field, put)
        if gameover(field):
            break
        if verbose:
            printField(field, sys.stdout)

        defender_in.write('game\n')
        printField(field, defender_in)
        direction = defender_out.readline(2.0)
        if verbose:
            print '>> ' + direction,

        moved, field, plusscore = slide(field, direction.strip())
        score += plusscore
        if not placeable(field):
            break

        if verbose:
            printField(field, sys.stdout)
        if gameover(field):
            break

    offender_in.write('quit\n')
    defender_in.write('quit\n')
    offender_proc.wait()
    defender_proc.wait()
    time.sleep(0.2)
    print 'Score: %d' % score
Example #20
0
    '-c:v',
    'rawvideo',
    '-f',
    'rawvideo',
    '-an',
    '-sn',  # we want to disable audio processing (there is no audio)
    '-pix_fmt',
    'rgb24',
    '-s',
    '{}x{}'.format(s_height, s_width),
    'pipe:1'
]
process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
print("Command: '{}' started".format(" ".join(str(x) for x in cmd)))
fin = process.stdin
fout = NBSR(process.stdout, rgb_frame_size)

frames = []
frameBAs = []
for i in range(0, len(input_data) - 1, slice_size):
    start = i
    stop = min([i + slice_size, len(input_data)])
    slice_data = input_data[start:stop]

    #print(slice_data)
    fin.write(slice_data)

    try:
        decoded_frame = fout.read(unblocking_factor)
        #print(decoded_frame)
        if decoded_frame is not None:
Example #21
0
i_surprise = i_max
i_anger = i_max
neutral = 0
sad = 0
happy = 0
anger = 0
surprise = 0
sad_nr = 0
happy_nr = 0
anger_nr = 0
surprise_nr = 0
neutral_nr = 0

p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
# wrap p.stdout with a NonBlockingStreamReader object:
nbsr = NBSR(p.stdout)
# issue command:
#p.stdin.write('command\n')
# get the output
while True:
    output = nbsr.readline(60)
    #output = p.stdout.read()
    # 0.1 secs to let the shell output the result
    #sleep(0.1)
    if not output:
        print('[No more data]')
        break
    #print (output)
# time.sleep(0.1)
    flag = 0
    #cuv=7
Example #22
0
class Djbot(callbacks.Plugin):
    """plays Pandora locally
        """
    # initialize plugin
    def __init__(self, irc):
        self.__parent = super(Djbot, self)
        self.__parent.__init__(irc)
        self.isPlaying = False
	# don't initialize pianobar and streamreader yet

    # start pianobar
    def play(self, irc, msg, args):
	""" takes no arguments

	loads pandora and starts music
	"""

	if not self.isPlaying:

	    # pianobar subprocess
	    self.p = Popen('pianobar', stdin=PIPE, stdout=PIPE, stderr=PIPE,
                shell=True)
	    
	    # non-blocking stream reader
	    self.nbsr = NBSR(self.p.stdout)
	    self.isPlaying = True
	    irc.reply('playing...')
	else:
	    irc.reply('already playing')
    play = wrap(play)

    # stop pianobar
    def stop(self, irc, msg, args):
	""" takes no arguments

	stops music and unloads pandora
	"""
	if self.isPlaying:
            # exit pianobar
            self.p.stdin.write('q')
	    # kill pianobar subprocess
            sleep(1)
	    self.p.terminate()
            self.isPlaying = False

	    irc.reply('stopping...')
	else:
	    irc.reply('not playing')
    stop = wrap(stop)

    # this prevents pianobar from running after unload
    def die(self):
        if self.isPlaying:
            self.p.stdin.write('q')
            sleep(1)
        self.p.terminate()
        self.isPlaying = False

    # increase system volume
    def volup(self, irc, msg, args):
        """takes no arguments

        increase the volume 5%
        """
        subprocess.call(['amixer', '-c0', 'set', 'PCM', '5dB+'])
    volup = wrap(volup)

    # decrease system volume
    def voldown(self, irc, msg, args):
        """takes no arguments

        decrease the volume 5db
        """
        subprocess.call(['amixer', '-c0', 'set', 'PCM', '5dB-'])
    voldown = wrap(voldown)

    # get recent output, formatted (somewhat) nicely
    def getOutput(self):
        temp = ''
        output = ''
        while True:	# clean up output and format for irc
            output += temp.expandtabs(0).replace('\x1b[2K',
                '').replace('\n', ' ') + ' '
            temp = self.nbsr.readline(0.3) #sometimes it takes time
            if not temp:
                break
        return output

    # clears output buffer so we don't get detritus
    def clearOutput(self):
	self.getOutput()

    # checks text for unwanted characters
    def isSafe(self, text):
        
        # check if all characters are allowed (zero tolerance)
	allowed = string.letters + string.digits + ' ?,.'
        for i in text:
            if not i in allowed:
                return False
        return True

    # speak text using shell wrapper
    def speak(self, irc, msg, args, text):
        """text

        pauses music, speaks given text, resumes music
        """
        if self.isSafe(text):

            # speak text
            subprocess.call([SWIFT, text])
    speak = wrap(speak, ['text'])
    
    # stop song announcements (driven by eventcmd)
    def nosongannounce(self, irc, msg, args):
        """takes no arguments

        causes djbot not to announce songs
        """

        subprocess.call(['touch', MUTE])
        irc.reply('song announce off')
    nosonganounce = wrap(nosongannounce)

    # start song announcements (driven by eventcmd)
    def songannounce(self, irc, msg, args):
        """takes no arguments

        causes djbot to announce songs
        """

        subprocess.call(['rm', '-f', MUTE])
        irc.reply('song announce on')
    songannounce = wrap(songannounce)


    ### Pianobar control
    # if there is a pending query when a song ends, the next song
    # will not start until the query has been answered
    # to dismiss a query without action, give it a newline

    # input: + 
    # expect: (i) Loving song... Ok.
    def love(self, irc, msg, args):
        """takes no arguments

        loves currently playing song
        """
        self.p.stdin.write('+')
        irc.reply('loving song...')
    love = wrap(love)


    # input: -
    # expect: (i) Banning song... Ok.
    def hate(self, irc, msg, args):
        """takes no arguments

        hates currently playing song
        """
        self.p.stdin.write('-')
        irc.reply('SUCH HATE!')
    hate = wrap(hate)

    # input: -
    # expect: (i) Banning song... Ok.
    def ban(self, irc, msg, args):
        """takes no arguments

        bans currently playing song
        """
        self.p.stdin.write('-')
        irc.reply('banning song')
    ban = wrap(ban)

    # input: a
    # expect: [?] Add artist or title to station:
    # input: <artist or title>
    # expect: (i) Searching... Ok.
    # 0) <artist>
    # 1) <artist>
    # [?] Select artist:
    # input: <number>
    # expect: (i) Adding music to station... Ok.
    def addmusic(self, irc, msg, args):
        """takes no arguments

        adds music to current station
        """
        #self.p.stdin.write('a')
        irc.reply('todo')

    # input: c
    # expect: [?] Create station from artist or title:
    # input: <artist or title>
    # expect: (i) Searching... Ok.
    # 0) <artist>
    # 1) <artist>
    # [?] Select artist:
    # input: <number>
    # expect: Creating station... Ok.
    def create(self, irc, msg, args):
        """takes no arguments

        creates new station, but does not switch to it
        """
        #self.p.stdin.write('c')
        #irc.reply(self.getOutput().replace(' |>  ', ''))
        irc.reply('not yet implemented')

    # input: d
    # expect: [?] Really delete "<station>"? [yN]
    # input: y
    # expect: (i) Deleting station... Ok.
    # Playback stops pending station selection
    def delete(self, irc, msg, args):
        """takes no arguments

        deletes current station
        """
        self.p.stdin.write('dy')
        irc.reply('Station deleted')

    # input: e
    # expect: (i) Receiving explanation... Ok.
    # (i) We're playing this track because ... (2-4 lines)
    def explain(self, irc, msg, args):
        """takes no arguments

        explains why current song is playing
        """
	self.getOutput()
        self.p.stdin.write('e')
        irc.reply(self.getOutput())
    
    # input: g
    # expect: (i) Receiving genre stations... Ok.
    # 0) <category>
    # 1) ... (about 30 lines)
    # [?] Select category:
    # input: <number>
    # expect: 0) <genre>
    # 1) ... (fewer lines)
    # [?] Select genre:
    # input: <number>
    # expect: (i) Adding genre station "<genre>"... Ok.
    def addgenre(self, irc, msg, args):
        """takes no arguments

        adds genre station, but does not switch to it
        """
        #self.p.stdin.write('g')
        irc.reply('todo')

    # input: h
    # expect: 0) <artist> - <title>
    # 1) <artist> - <title>
    # 2) ...
    # [?] Select song:
    # input: <number>
    # expect: [?] What to do with this song?
    # (I assume we can love / ban / explain from history)
    def history(self, irc, msg, args):
        """takes no arguments

        return recently played songs
        """
	self.getOutput()
        self.p.stdin.write('h\n')
        irc.reply(self.getOutput())

    # input: i
    # expect: |> Station "<station>" (<station id>)
    # "<title>" by "<artist>" on "<album>"
    def info(self, irc, msg, args):
        """takes no arguments

        returns title, artist, and album
        """
        self.clearOutput()
	self.p.stdin.write('i')
        irc.reply(self.getOutput().replace(' |>  ', ''))

    # input: n
    # no response, next song plays
    def skip(self, irc, msg, args):
        """takes no arguments

        moves to next song
        """
        self.p.stdin.write('n')
        irc.reply('skipping...')
    skip = wrap(skip)

    # input: S
    # no response, music pauses playback
    def pause(self, irc, msg, args):
        """takes no arguments

        pause playback (use resume to continue)
        """
        self.p.stdin.write('S')
        irc.reply('paused. use resume to continue')
    pause = wrap(pause)

    # input: P
    # no response, music resumes playback
    def resume(self, irc, msg, args):
        """takes no arguments

        resume playback after pause
        """
        self.p.stdin.write('P')
        irc.reply('resuming playback...')
    resume = wrap(resume)

    # input: q
    # pianobar closes
    # we don't want this to happen without unloading the plugin
#    def quit(self, irc, msg, args):
#        """takes no arguments
#
#        exit pianobar
#        """
#        irc.reply('Please unload the plugin instead')
#
    # input: r
    # expect: [?] New name:
    # input: <name>
    # expect: Renaming station... Ok.
    def rename(self, irc, msg, args, newname):
        """takes no arguments

        rename station
        """
        #if isSafe(newname):
        #	self.p.stdin.write('r' + newname)
        irc.reply('todo')
    rename = wrap(rename, ['text'])

    # input: s
    # expect: 0) <station>
    # 1) <station>
    # 2) <station>
    # (etc)
    # [?] Select station:
    # input: <number>
    # expect: |> Station "<station>" (<station id>)
    # selected station plays
    def station(self, irc, msg, args, cmd):
        """<list> or <integer>

        list returns a list of available stations
        integer selects corresponding station
        """
        if cmd == "list":
            self.clearOutput()
            self.p.stdin.write('s\n') # select station, but cancel
            irc.reply(self.getOutput().replace(' q  ', '')
		.replace('  Q  ', ' ')) # get station list
        elif self.isSafe(cmd) and (0 <= int(cmd) < 100):
            self.p.stdin.write('s' + cmd + '\n')
            irc.reply('selected ' + cmd)
    station = wrap(station, ['text'])

    # input: t
    # expect: (i) Putting song on shelf... Ok.
    # will not play again for one month
    def tired(self, irc, msg, args):
        """takes no arguments

        do not play this song again for one month
        """
        self.p.stdin.write('t')
        irc.reply('shelving...')
    tired = wrap(tired)

    # input: u
    # expect: 0) <next song>
    # 1) <song after next>
    def upcoming(self, irc, msg, args):
        """takes no arguments

        returns upcoming songs
        """
        self.clearOutput()
        self.p.stdin.write('u')
        irc.reply(self.getOutput())

    # input: x
    # expect: 0) <station>
    # 1) <station>
    # 2) ...
    # [?] Toggle quickmix for station:
    # this only works when we are on the quickmix station!
    # selection repeats until we give it \n
    # if we are not on a quickmix station, it replies with
    # /!\ Not a QuickMix station
    def quickmix(self, irc, msg, args, cmd):
        """<list> or <integer>

        toggle quickmix stations
        """
        if cmd == 'list':
	    self.clearOutput()
            self.p.stdin.write('x')
	    output = self.getOutput()
	    if 'Not a QuickMix station' in output:
	        irc.reply('you must be listening to the QuickMix station first')
            else:
                irc.reply(output)
        elif isSafe(cmd) and 0 <= int(cmd) < 100:
		self.clearOutput()
		self.p.stdin.write('x' + cmd)
		irc.reply(self.getOutput())
    quickmix = wrap(quickmix, ['text'])

    # input: b
    # expect: [?] Bookmark [s]ong or [a]rtist?
    # input: s
    # expect: (i) Bookmarking song... Ok.
    def bookmark(self, irc, msg, args, option):
        """'artist' or 'song'

        bookmark song
        """
        if option == 'artist':
            cmd = 'a'
        elif option == 'song':
            cmd = 's'
        self.p.stdin.write('b' + cmd)
        irc.reply('Bookmarked ' + option)
    bookmark = wrap(bookmark, ['text'])


    # input: =
    # expect: (i) Fetching station info... Ok.
    # [?] Delete [a]rtist/[s]ong seeds or [f]eedback?
    # input: s
    # expect: 0) <station seed>
    # 1) ...
    # [?] Select song:
    # input: 0
    # expect: (i) Deleting artist seed... Ok.
    def removeseed(self, irc, msg, args):
        """takes no arguments

        remove seed from station
        """
        #self.p.stdin.write('=')
        irc.reply('todo')

    # input: v
    # expect: [?] Create station from [s]ong or [a]rtist?
    # input: s
    # expect: (i) Creating station... Ok.
    def newfromsong(self, irc, msg, args):
        """takes no arguments

        new station from song
        """
        #self.p.stdin.write('v')
        irc.reply('todo')
    
    # parse info command and return only song title
    def title(self, irc, msg, args):
        """takes no arguments

        returns song title
        """
        irc.reply('todo')

    # parse info command and return only artist name
    def artist(self, irc, msg, args):
        """takes no arguments

        returns song artist
        """
        irc.reply('todo')

    # parse info command and return only album name
    def album(self, irc, msg, args):
        """takes no arguments

        returns song album
        """
        irc.reply('todo')

    # get song info
    def songinfo(self, irc, msg, args):
        """takes no arguments

        returns title, artist, and album
        """
        irc.reply('todo')
Example #23
0
from subprocess import Popen, PIPE
from time import sleep
from nbstreamreader import NonBlockingStreamReader as NBSR

# run the shell as a subprocess:
p = Popen(['cat', '/dev/ttyUSB0'],
        stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = False)
# wrap p.stdout with a NonBlockingStreamReader object:
nbsr = NBSR(p.stdout)
# issue command:
p.stdin.write('command\n')
# get the output
while True:
    try:
        output = nbsr.readline(0.3)
        # 0.1 secs to let the shell output the result
        if output == None:
                pass
        else:
             	print output
                #x = output.split(",")
                #print int(x[13])-128
    except:
	if not output:
            print '[No more data]'
            break
            #print output


Example #24
0
 def CreateChildProcess(self, Execution_Command, Executable_File):
     self.ChildProcess = Popen([Execution_Command, Executable_File],
                               stdin=PIPE,
                               stdout=PIPE,
                               bufsize=0)
     self.ModifiedOutStream = NBSR(self.ChildProcess.stdout)
Example #25
0
def main():
    #build ipcam list from config.xml
    config = 'config.xml'
    parser = XmlParser(config)
    cam_list = parser.build_cam_list()
    print 'Full List'
    for item in cam_list:
        print item.get_name()
    default = 0
    current_proc = subprocess.Popen(
        ['omxplayer', cam_list[default].get_rem_addr()],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    #input section
    cec_proc = subprocess.Popen('cec-client',
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=False)
    # wrap p.stdout with a NonBlockingStreamReader object:
    nbsr = NBSR(cec_proc.stdout)
    while True:
        output = nbsr.readline()
        # 0.1 secs to let the shell output the result
        if output:
            if (output.startswith('waiting')):
                print "Ready for input"
            if (output.startswith('TRAFFIC:')):
                sub = output.split('>>')
                if (len(sub) > 1):
                    if (sub[1].startswith(' 01:44:2')):
                        code = sub[1].split(':2')
                        print code[1]
                        char = int(code[1])
                        #while True:
                        #char = raw_input("choose camera [1 - %s ]: " % len(cam_list))
                        if char == 0:
                            subprocess.Popen(['killall', 'omxplayer.bin'])
                            break
                        if (int(char) <= len(cam_list)):
                            index = int(char) - 1
                            url = cam_list[index].get_rem_addr()
                            print url
                            #comment
                            try:
                                next_proc = subprocess.Popen(
                                    ['omxplayer', url],
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
                                #current_proc.communicate('p')
                                #current_proc.stdin.flush()
                                #print next_proc.stdout
                                current_proc.communicate('q')
                                temp = current_proc
                                current_proc = next_proc
                                next_proc = temp
                            except:
                                out, err = current_proc.communicate()
                                print("Error: " + err.rstrip())
                        else:
                            print(
                                "there are no cam corresponding to this number"
                            )

    sleep(0.1)
Example #26
0
 def start_terminal(self):
     self.proc = subprocess.Popen(["/bin/sh"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
     self.nbsr = NBSR(self.proc.stdout)
     self.term_started = True
Example #27
0
from subprocess import Popen, PIPE
from time import sleep
from nbstreamreader import NonBlockingStreamReader as NBSR
import sys

nbsr = NBSR(sys.stdin)
# issue command:
#p.stdin.write('command\n')
# get the output
while True:
    output = nbsr.readline(0.1)
    # 0.1 secs to let the shell output the result
    if output:
        #print '[No more data]'
        #break
        print output
Example #28
0
from subprocess import Popen, PIPE
from time import sleep
from nbstreamreader import NonBlockingStreamReader as NBSR

# run the shell as a subprocess:
p = Popen(['perl','nikto.pl','-host','127.0.0.1'],
        stdin = None, stdout = PIPE, stderr = None, shell = False)
# wrap p.stdout with a NonBlockingStreamReader object:
nbsr = NBSR(p.stdout)
# issue command:
# get the output
while True:
    output = nbsr.readline(1)
    # 0.1 secs to let the shell output the result
    if output != None:
        print output,
    elif "End Time" in str(output):
    	break
Example #29
0
def main(argv):
    field = initialField()
    offender = []
    defender = []

    verbose = False
    pos = None
    for arg in argv:
        if arg == '-o':
            pos = 'offender'
        elif arg == '-d':
            pos = 'defender'
        elif arg == '-v':
            verbose = True
        elif pos == 'offender':
            offender.append(arg)
        elif pos == 'defender':
            defender.append(arg)

    if len(offender) == 0 or len(defender) == 0:
        print "no args"
        return 1

    offender_proc = subprocess.Popen(offender,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     shell=False)
    offender_in = offender_proc.stdin
    offender_out = NBSR(offender_proc.stdout)
    offender_pid = offender_proc.pid

    defender_proc = subprocess.Popen(defender,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     shell=False)
    defender_in = defender_proc.stdin
    defender_out = NBSR(defender_proc.stdout)
    defender_pid = defender_proc.pid

    turn = 0
    score = 0
    while True:
        turn += 1
        if verbose:
            print '=== Turn %d (Score: %d) ===' % (turn, score)
            printField(field, sys.stdout)

        offender_in.write('game\n')
        printField(field, offender_in)
        put = offender_out.readline(2.0)
        if verbose:
            print '>> ' + put,

        field = place(field, put)
        if gameover(field):
            break
        if verbose:
            printField(field, sys.stdout)

        defender_in.write('game\n')
        printField(field, defender_in)
        direction = defender_out.readline(2.0)
        if verbose:
            print '>> ' + direction,

        moved, field, plusscore = slide(field, direction.strip())
        score += plusscore
        if not placeable(field):
            break

        if verbose:
            printField(field, sys.stdout)
        if gameover(field):
            break

    offender_in.write('quit\n')
    defender_in.write('quit\n')
    offender_proc.wait()
    defender_proc.wait()
    time.sleep(0.2)
    print 'Score: %d' % score