コード例 #1
0
ファイル: onOffPin.py プロジェクト: DBrianKimmel/pi-web-agent
def set_pin_value(args):
    value = args['value']
    pin_no = args['id']
    command="sudo " + gpio + " write " + str(pin_no) + " " + value
    r, c = execute(command.replace("\n", "")) #protect command from newlines
    status, code = execute(gpio + ' readalljson');
    return json.loads(status)
コード例 #2
0
def getValues():

    leftValues = []
    for pin in leftPins:
        pinNo = name2PinNo(pin)
        if pinNo >= 0:
            msgInitialize, errorcode = execute(
                "sudo gpio-query value \"GPIO " + str(pinNo) + "\"")
            if msgInitialize[0] == "H":
                value = GPIO.HIGH
            else:
                value = GPIO.LOW
            leftValues.append(value)
        else:
            leftValues.append(pin)

    rightValues = []
    for pin in rightPins:
        pinNo = name2PinNo(pin)
        if pinNo >= 0:
            msgInitialize, errorcode = execute(
                "sudo gpio-query value \"GPIO " + str(pinNo) + "\"")
            if msgInitialize[0] == "H":
                value = GPIO.HIGH
            else:
                value = GPIO.LOW
            rightValues.append(value)
        else:
            rightValues.append(pin)
    return leftValues, rightValues
コード例 #3
0
 def __init__(self):
     self.chains={}
     list_chains, exit_code = execute("sudo iptables -n -L | grep 'Chain' | cut -d ' ' -f 2")
     lines = list_chains.split('\n')
     for line in lines[0:len(lines)-1]:
         chain_body, exit_code = execute("sudo iptables -S " + line)
         self.chains[line]=Chain(chain_body)
コード例 #4
0
ファイル: onOffPin.py プロジェクト: DBrianKimmel/pi-web-agent
def set_pin_direction(args):
    direction = args['direction']
    pin_no = args['id']
    command = "sudo " + gpio + " mode " + str(pin_no) + " " + direction
    r, c = execute(command.replace("\n", ""))
    status, code = execute(gpio + ' readalljson');
    return json.loads(status)
コード例 #5
0
ファイル: gpio_manager.py プロジェクト: ciscomc/pi-web-agent
def getValues():

    leftValues = []
    for pin in leftPins:
        pinNo = name2PinNo(pin)
        if pinNo >= 0 :
            msgInitialize, errorcode=execute("sudo gpio-query value \"GPIO " + str(pinNo) + "\"")
            if msgInitialize == "High":
                value=GPIO.HIGH
            else:
                value=GPIO.LOW
            leftValues.append(value)
        else:
            leftValues.append(pin)
            
    rightValues = []
    for pin in rightPins:
        pinNo = name2PinNo(pin)
        if pinNo >= 0:
            msgInitialize, errorcode=execute("sudo gpio-query value \"GPIO " + str(pinNo) + "\"" )
            if msgInitialize[0] == "H":
                value=GPIO.HIGH
            else:
                value=GPIO.LOW
            rightValues.append(value)
        else:
            rightValues.append(pin)                
    return leftValues, rightValues
コード例 #6
0
ファイル: onOffPin.py プロジェクト: IliEle/pi-web-agent
def main():
    form = cgi.FieldStorage()
    msg=""
    if 'cmd' in form:
        command=form['cmd'].value
        if (command=='cleanup'):
            msg, errorcode=execute("sudo " + gpio + " reset")
        else:
            errorcode="140"
    else:
        pinID = form['id'].value
        pinTypeOfChange = pinID.split('GPIO')[0]
        pinName = form['pinNumber'].value
        pinNo = pinName.split('GPIO')[1]
        wiringPiIndex, err = execute("sudo gpio-query wiringpi \"GPIO " + str(pinNo) + "\"")
    
        pinNo = wiringPiIndex
        errorcode = None

        if pinTypeOfChange == 'V' :
            pinValue = form['value'].value
            msg, errorcode = set_pin_value(pinNo, pinValue)
        elif pinTypeOfChange == 'D' :
            pinDirection = form['direction'].value
            msg, errorcode = set_pin_direction(pinNo, pinDirection)
        else:
            msg="Uknown command"
            errorcode="130"
    response = Response(errorcode)
    
    response.buildResponse(errorcode, message=msg)
    composeXMLDocument(response.xml)
コード例 #7
0
ファイル: onOffPin.py プロジェクト: solutionguy/pi-web-agent
def set_pin_direction(args):
    direction = args['direction']
    pin_no = args['id']
    command = "sudo " + gpio + " mode " + str(pin_no) + " " + direction
    r, c = execute(command.replace("\n", ""))
    status, code = execute(gpio + ' readalljson')
    return json.loads(status)
コード例 #8
0
ファイル: onOffPin.py プロジェクト: solutionguy/pi-web-agent
def set_pin_value(args):
    value = args['value']
    pin_no = args['id']
    command = "sudo " + gpio + " write " + str(pin_no) + " " + value
    r, c = execute(command.replace("\n", ""))  #protect command from newlines
    status, code = execute(gpio + ' readalljson')
    return json.loads(status)
コード例 #9
0
def main():
    form = cgi.FieldStorage()
    msg=""
    if 'cmd' in form:
        command=form['cmd'].value
        if (command=='cleanup'):
            msg, errorcode=execute("sudo " + gpio + " reset")
        else:
            errorcode="140"
    else:
        pinID = form['id'].value
        pinTypeOfChange = pinID.split('GPIO')[0]
        pinName = form['pinNumber'].value
        pinNo = pinName.split('GPIO')[1]
        wiringPiIndex, err = execute("sudo gpio-query wiringpi \"GPIO " + str(pinNo) + "\"")
    
        pinNo = wiringPiIndex
        errorcode = None

        if pinTypeOfChange == 'V' :
            pinValue = form['value'].value
            msg, errorcode = set_pin_value(pinNo, pinValue)
        elif pinTypeOfChange == 'D' :
            pinDirection = form['direction'].value
            msg, errorcode = set_pin_direction(pinNo, pinDirection)
        else:
            msg="Uknown command"
            errorcode="130"
    response = Response(errorcode)
    
    response.buildResponse(errorcode, message=msg)
    composeXMLDocument(response.xml)
コード例 #10
0
 def startStream(self):
     '''
     try to use mplayer for the given parameters
     '''
     command=(os.environ['MY_HOME'] + "/scripts/mplayer.sh "+self.output+" "+str(self.volume)+" \""+self.uri + "\" "+os.environ['ssl_cert']+" "+os.environ['ssl_key']);
     fireAndForget(command)
     execute("echo '"+str(self.volume)+"\n0:0:0:0:0:0:0:0:0:0' > /tmp/mplayer_status")
     return 0;
コード例 #11
0
def checkBusy(view) :
    a, errorcode_apt_get = execute('pgrep apt-get')
    a, errorcode_aptitude = execute('pgrep aptitude')
    if errorcode_apt_get == 0 or errorcode_aptitude == 0 :
        view.setContent('Package Management',\
         'The package manager is busy right now. . . Try again later!' )
        view.output()
        return True
コード例 #12
0
def takeSnapshot():
    image_path = MY_PICS + str(int(time.time() * 1000)) + '.jpg'
    a, b = execute("sudo raspistill -w 640 -h 480 -t 2000 -o " + image_path)
    execute("sudo chown -R pi-web-agent:pi-web-agent " + MY_PICS)
    thumbnail(image_path)
    file_name = os.path.basename(image_path)
    response_js = {"name": file_name}
    composeJS(json.dumps(response_js))
    sys.exit(0)
コード例 #13
0
def takeSnapshot( ):
    image_path = MY_PICS + str(int(time.time()*1000)) + '.jpg'
    a,b = execute( "sudo raspistill -w 640 -h 480 -t 2000 -o " + image_path  )
    execute("sudo chown -R pi-web-agent:pi-web-agent " + MY_PICS)
    thumbnail(image_path)
    file_name = os.path.basename(image_path)
    response_js = {"name":file_name}
    composeJS(json.dumps(response_js))
    sys.exit(0)
コード例 #14
0
 def __init__(self):
     self.chains={}
     list_chains, exit_code = execute("sudo iptables -L | grep 'Chain' | cut -d ' ' -f 2")
     lines = list_chains.split('\n')
     for line in lines[0:len(lines)-1]:
         #print "WHAAAT: ", line
         chain_body, exit_code = execute("sudo iptables -L " + line)
         #print chain_body
         self.chains[line]=Chain(chain_body)
コード例 #15
0
 def executeCommand( command ) :
   errorMessage = ''
   output, errorcode = execute( command )
   if errorcode != 0 :
     #TODO We need something here to display the stack trace... maybe a terminal css
     # use terminal css to display error in an overlay
     errorMessage += DivManager.getStackTrace( output + "<br>ErrorCode: " + str( errorcode ) )
   #date, command, errorcode
   todayDate = (time.strftime( "%d/%m/%Y" ))
   output, errorcode = execute( "sudo echo '" + todayDate + ", \"" + command + "\", " + str( errorcode ) + "' >> dateCommandErrorLog.csv" )
   return errorMessage
コード例 #16
0
def main():

    form = cgi.FieldStorage()

    pictures, returncode = execute(
        "ls /usr/share/pi-web-agent/camera-media/*.jpg")
    linearray = pictures.split('\n')

    html = '''<div id="camera_toolbar">
                  <div class="btn-group btn-group-justified">
                      <a href='javascript:navigate("/cgi-bin/toolkit/camera.py?type=js")' class="btn btn-default">Live stream</a>
                      <a href='javascript:camera_utils("snapshot")' class="btn btn-default">Snapshot</a>
                      <a href='javascript:alert("Coming soon")' class="btn btn-default">Record</a>
                      <a href='javascript:camera_utils("stoprecord")' class="btn btn-default">Stop</a>
      
                 </div></div><br>
          '''
    html += '''<div id="gallery_thumbnails">'''

    for thisline in linearray:
        justname = thisline.split('/')[-1]
        if len(justname) <= 0:
            continue
        html += '<a href="/cgi-bin/toolkit/image_manager.py?image=' + justname + '" rel="thumbnail"><img style="padding:4px; border:2px solid #021a40;" src="/cgi-bin/toolkit/image_manager.py?image=' + justname.split(
            '.')[0] + '.png" style="width: 64px; height: 64px" /></a>'
    html += '</div><br>'

    view.setContent('Pi Camera Controller', html)
    output(view, cgi.FieldStorage())
コード例 #17
0
def set_volume(args):
    # Sets volume of mixer specified in args
    command = "sudo amixer sset {mixer} {vol}\%"
    out, exit_code = execute(
        command.format(mixer=args['mixer'], vol=args['val']))

    return get_volume(args)
コード例 #18
0
def main():
    """
    The mplayer port for py web agent
    If you read this code, it is better acompanied
    with the following documentation for improved
    understanding:
    http://www.mplayerhq.hu/DOCS/man/en/mplayer.1.txt 
    You can also have a look at:
    http://jqueryui.com/slider/ for /css/sliders.js
    And for mplayer_status.py:
    	mplayer slave cmmands:
    		http://www.mplayerhq.hu/DOCS/tech/slave.txt
    	rfc3875:
    		http://www.ietf.org/rfc/rfc3875.txt
    If you have any questons about this feature send me an email at:
    andreasgalazis-AT-yahoo.com(replace -At- with @)
    or for more generic pi-web agent questions
    ask any member of the kupepia team.
    """
    form = cgi.FieldStorage()
    if execute('pidof mplayer')[1]==0:
        settingsReader=SettingsReader("/tmp/mplayer_status")
        settingsReader.read()
        view.setContent('Mplayer', getRunningView("",settingsReader.getVolume(), settingsReader.getEQ().split(':')))
    elif "uri" not in form and "volume" not in form:
        view.setContent('Mplayer', getView(None))
    elif "uri" not in form :
        view.setContent('Mplayer', getView("Please provide a uri"))
    else:
        player = MPlayer(form)
        player.startStream();
        view.setContent('Mplayer', getRunningView(form.getvalue("uri"),form.getvalue("volume"),"0:0:0:0:0:0:0:0:0:0".split(':')))
    
    output(view, form)
コード例 #19
0
def main():

    form = cgi.FieldStorage()
    
    pictures, returncode = execute("ls /usr/share/pi-web-agent/camera-media/*.jpg")
    linearray = pictures.split('\n')
    
    html = '''<div id="camera_toolbar">
                  <div class="btn-group btn-group-justified">
                      <a href='javascript:navigate("/cgi-bin/toolkit/camera.py?type=js")' class="btn btn-default">Live stream</a>
                      <a href='javascript:camera_utils("snapshot")' class="btn btn-default">Snapshot</a>
                      <a href='javascript:alert("Coming soon")' class="btn btn-default">Record</a>
                      <a href='javascript:camera_utils("stoprecord")' class="btn btn-default">Stop</a>
      
                 </div></div><br>
          '''
    html += '''<div id="gallery_thumbnails">'''
    
    for thisline in linearray:
        justname = thisline.split('/')[-1]
        if len(justname) <= 0:
            continue
        html += '<a href="/cgi-bin/toolkit/image_manager.py?image='+justname +'" rel="thumbnail"><img style="padding:4px; border:2px solid #021a40;" src="/cgi-bin/toolkit/image_manager.py?image='+justname.split('.')[0]+'.png" style="width: 64px; height: 64px" /></a>'
    html += '</div><br>'

    view.setContent('Pi Camera Controller', html)
    output(view, cgi.FieldStorage())
コード例 #20
0
def set_volume(args):
    # Sets volume of mixer specified in args
    command = "sudo amixer sset {mixer} {vol}\%"
    out, exit_code = execute(command.format(mixer=args['mixer'],
                                            vol=args['val']))

    return get_volume(args)
コード例 #21
0
ファイル: mplayer.py プロジェクト: IliEle/pi-web-agent
def main():
    """
    The mplayer port for py web agent
    If you read this code, it is better acompanied
    with the following documentation for improved
    understanding:
    http://www.mplayerhq.hu/DOCS/man/en/mplayer.1.txt 
    You can also have a look at:
    http://jqueryui.com/slider/ for /css/sliders.js
    And for mplayer_status.py:
    	mplayer slave cmmands:
    		http://www.mplayerhq.hu/DOCS/tech/slave.txt
    	rfc3875:
    		http://www.ietf.org/rfc/rfc3875.txt
    If you have any questons about this feature send me an email at:
    andreasgalazis-AT-yahoo.com(replace -At- with @)
    or for more generic pi-web agent questions
    ask any member of the kupepia team.
    """
    form = cgi.FieldStorage()
    config=Configuration()
    view = View(config.system.actions) 
    if execute('pidof mplayer')[1]==0:
        settingsReader=SettingsReader("/tmp/mplayer_status")
        settingsReader.read()
        view.setContent('Mplayer', getRunningView(settingsReader.getVolume(), settingsReader.getEQ().split(':')))
    elif "uri" not in form and "volume" not in form:
        view.setContent('Radio', getView())
    else:
        player = MPlayer(form)
        player.startStream();
        view.setContent('Radio', getRunningView(form.getvalue("volume"),"0:0:0:0:0:0:0:0:0:0".split(':')))
    
    output(view, form)
コード例 #22
0
ファイル: mplayer.py プロジェクト: IliEle/pi-web-agent
 def startStream(self):
     '''
 try to use mplayer for the given parameters
 '''
     self.uri=self.form.getvalue("uri")
     self.volume=self.form.getvalue("volume")
     self.cache=self.form.getvalue("cache") 
     command=("sh -c '[ -f /tmp/mplayer-control ]" 
              "|| mkfifo /tmp/mplayer-control;"
              " sudo mplayer -slave -input "
              "file=/tmp/mplayer-control -ao alsa:device=hw "
              "-af equalizer=0:0:0:0:0:0:0:0:0:0 ") 
     command+=" -volume "+self.volume+" "
     command+=self.uri+" </dev/null >/dev/null 2>&1 &'"
     fireAndForget(command)
     execute("echo '"+self.volume+"\n0:0:0:0:0:0:0:0:0:0' > /tmp/mplayer_status")
コード例 #23
0
ファイル: ask.py プロジェクト: koullislp/pi-web-agent
def find_answer(question):
    
    script = os.environ['MY_HOME'] + "/scripts/ask.py"
    output, err_code = execute(script + " " + question)
    json_dictionary = {'question':question, 'answer':output,\
                       'exit_code':err_code}
    
    composeJSONDocument(json_dictionary)
コード例 #24
0
def get_volume(args):
    # Returns current volume of args['mixer']
    command = "sudo amixer sget {mixer}"
    out, exit_code = execute(command.format(mixer=args['mixer']))
    m = re.search("[0-9]+%", out)
    vol = m.group(0)[:-1]
    data_line = out.split('\n')[-2]
    m = re.search("(\[on\]|\[off\])+", data_line)
    st = m.group(0)
    return json.dumps({'volume': int(vol), 'status': status[st[1:-1]]})
コード例 #25
0
 def startStream(self):
     '''
     try to use mplayer for the given parameters
     '''
     self.uri=urllib.unquote(self.form.getvalue("uri")).decode('utf8')
     self.volume=self.form.getvalue("volume")
     self.cache=self.form.getvalue("cache") 
     #wow I ll be a bit pythonic here xD
     self.outout="2" if self.form.getvalue("output")=="HDMI" else "1" if self.form.getvalue("output")=="HEADPHONES" else "0"
     command=("sh -c '[ -f /tmp/mplayer-control ]" 
              "|| mkfifo /tmp/mplayer-control;"
              "sudo amixer cset numid=3 "+self.outout+";"
              "sudo mplayer -slave -input "
              "file=/tmp/mplayer-control -ao alsa:device=hw "
              "-af equalizer=0:0:0:0:0:0:0:0:0:0 ") 
     command+=" -volume "+self.volume
     command+=" \""+self.uri + "\" </dev/null >/dev/null 2>&1 &'"
     fireAndForget(command)
     execute("echo '"+self.volume+"\n0:0:0:0:0:0:0:0:0:0' > /tmp/mplayer_status")
コード例 #26
0
ファイル: mplayer.py プロジェクト: koullislp/pi-web-agent
 def startStream(self):
     '''
 try to use mplayer for the given parameters
 '''
     self.uri=self.form.getvalue("uri")
     self.volume=self.form.getvalue("volume")
     self.cache=self.form.getvalue("cache") 
     #wow I ll be a bit pythonic here xD
     self.outout="2" if self.form.getvalue("output")=="HDMI" else "1" if self.form.getvalue("output")=="HEADPHONES" else "0"
     command=("sh -c '[ -f /tmp/mplayer-control ]" 
              "|| mkfifo /tmp/mplayer-control;"
              "sudo amixer cset numid=3 "+self.outout+";"
              "sudo mplayer -slave -input "
              "file=/tmp/mplayer-control -ao alsa:device=hw "
              "-af equalizer=0:0:0:0:0:0:0:0:0:0 ") 
     command+=" -volume "+self.volume+" "
     command+=self.uri+" </dev/null >/dev/null 2>&1 &'"
     fireAndForget(command)
     execute("echo '"+self.volume+"\n0:0:0:0:0:0:0:0:0:0' > /tmp/mplayer_status")
コード例 #27
0
def get_volume(args):
    # Returns current volume of args['mixer']
    command = "sudo amixer sget {mixer}"
    out, exit_code = execute(command.format(mixer=args['mixer']))
    m = re.search("[0-9]+%", out)
    vol = m.group(0)[:-1]
    data_line = out.split('\n')[-2]
    m = re.search("(\[on\]|\[off\])+", data_line)
    st = m.group(0)
    return json.dumps({'volume':int(vol), 'status':status[st[1:-1]]})
コード例 #28
0
def getContents(path):
    path = checkPathValidity(path)
    contents, exitcode = execute("sudo ls -l " + path)
    contents = contents.split("\n")[1:len(contents)]
    files = []
    for content in contents:
        entry = parseFile(content)
        if entry != None:
            files.append(entry)
    return files
コード例 #29
0
 def getImages(self):
     
     pictures, returncode = execute("ls /usr/share/pi-web-agent/camera-media/*.png")
     if (returncode != 0):
         linearray = [returncode]
     else:
         linearray = pictures.split('\n')
         for i, value in enumerate(linearray):
             linearray[i] = os.path.basename(value)
         del linearray[-1]
     return linearray
コード例 #30
0
ファイル: gpio_manager.py プロジェクト: ciscomc/pi-web-agent
def getDirections():
    leftDirections = []
    for pin in leftPins:
        pinNo = name2PinNo(pin)
        if pinNo >= 0:
            msgInitialize, errorcode=execute("sudo gpio-query direction \"GPIO " + str(pinNo) + "\"")
            leftDirections.append(msgInitialize.strip())
        else:
            leftDirections.append(pin)
            
    rightDirections = []
    for pin in rightPins:
        pinNo = name2PinNo(pin)
        if pinNo >= 0 :
            msgInitialize, errorcode=execute("sudo gpio-query direction \"GPIO " + str(pinNo) + "\"")
            rightDirections.append(msgInitialize.strip())
        else:
            rightDirections.append(pin)
                            
    return leftDirections, rightDirections  
コード例 #31
0
 def _store(self):
     pFile = os.environ['MY_HOME'] + '/.htpasswd'
     if "'" in self.username or "'" in self.password1:
         e=Exception()
         e.strerror="Invalid character `'` in password"
         raise e        
     command = 'htpasswd -bd ' + pFile + ' \'' + self.username + '\' ' + ' \'' + self.password1 +'\''
     output, error_code = execute(command)
     if error_code != 0:
         e=Exception()
         e.strerror="Failed to store password: " + str(error_code)
         raise e    
コード例 #32
0
    def getImages(self):

        pictures, returncode = execute(
            "ls /usr/share/pi-web-agent/camera-media/*.png")
        if (returncode != 0):
            linearray = [returncode]
        else:
            linearray = pictures.split('\n')
            for i, value in enumerate(linearray):
                linearray[i] = os.path.basename(value)
            del linearray[-1]
        return linearray
コード例 #33
0
 def _store(self):
     pFile = os.environ['MY_HOME'] + '/.htpasswd'
     if "'" in self.username or "'" in self.password1:
         e = Exception()
         e.strerror = "Invalid character `'` in password"
         raise e
     command = 'htpasswd -bd ' + pFile + ' \'' + self.username + '\' ' + ' \'' + self.password1 + '\''
     output, error_code = execute(command)
     if error_code != 0:
         e = Exception()
         e.strerror = "Failed to store password: " + str(error_code)
         raise e
コード例 #34
0
ファイル: camera.py プロジェクト: DBrianKimmel/pi-web-agent
def main():    
    
    form = cgi.FieldStorage()
    if 'cmd' in form:
        command = form['cmd'].value
        if command == 'start':
            response("0")
            p = subprocess.Popen(['/bin/bash', '/usr/bin/start-stream-cam.sh'], 
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
        elif command == 'stop':
            try:
                execute('sudo kill $(pidof raspivid)')
            except:
                pass
        response("0")
        return
    
    content=getView()
    view.setContent('Live camera', content)
    
    output(view, form)
コード例 #35
0
ファイル: camera.py プロジェクト: solutionguy/pi-web-agent
def main():

    form = cgi.FieldStorage()
    if 'cmd' in form:
        command = form['cmd'].value
        if command == 'start':
            response("0")
            p = subprocess.Popen(['/bin/bash', '/usr/bin/start-stream-cam.sh'],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
        elif command == 'stop':
            try:
                execute('sudo kill $(pidof raspivid)')
            except:
                pass
        response("0")
        return

    content = getView()
    view.setContent('Live camera', content)

    output(view, form)
コード例 #36
0
def getDirections():
    leftDirections = []
    for pin in leftPins:
        pinNo = name2PinNo(pin)
        if pinNo >= 0:
            msgInitialize, errorcode = execute(
                "sudo gpio-query direction \"GPIO " + str(pinNo) + "\"")
            leftDirections.append(msgInitialize.strip())
        else:
            leftDirections.append(pin)

    rightDirections = []
    for pin in rightPins:
        pinNo = name2PinNo(pin)
        if pinNo >= 0:
            msgInitialize, errorcode = execute(
                "sudo gpio-query direction \"GPIO " + str(pinNo) + "\"")
            rightDirections.append(msgInitialize.strip())
        else:
            rightDirections.append(pin)

    return leftDirections, rightDirections
コード例 #37
0
def checkFlags(pName):
    bashCommand = "dpkg-query -l " + pName
    text, errorcode = execute(bashCommand)
    if errorcode != 0:
        return False
    lines = text.split('\n')
    del lines[-1]
    package_line = lines[-1]
    flags = package_line.split()[0]
    if flags.find('r') >= 0:
        return False
    if flags.find('un') >= 0:
        return False
    return True
コード例 #38
0
def checkFlags(pName):
    bashCommand = "dpkg-query -l " + pName
    text, errorcode = execute( bashCommand )
    if errorcode != 0:
        return False
    lines = text.split('\n')
    del lines[-1]
    package_line = lines[-1]
    flags = package_line.split()[0]
    if flags.find('r') >= 0:
        return False
    if flags.find('un') >= 0:
        return False
    return True
コード例 #39
0
ファイル: pm_api.py プロジェクト: coursera4ashok/pi-web-agent
def search_package(args):
    package_name = args['key']
    out, code = execute('apt-cache search --names-only ' + package_name)
    package_list = out.split('\n')
    packages={}
    if (len(package_list) > 0):
        package_list = package_list[:-1]
    else:    
        return {}
    for entry in package_list:
        name=entry.split(' ')[0]
        description=entry[len(name)+3:]
        packages[name] = description
    return packages
コード例 #40
0
ファイル: pm_api.py プロジェクト: solutionguy/pi-web-agent
def search_package(args):
    package_name = args['key']
    out, code = execute('apt-cache search --names-only ' + package_name)
    package_list = out.split('\n')
    packages = {}
    if (len(package_list) > 0):
        package_list = package_list[:-1]
    else:
        return {}
    for entry in package_list:
        name = entry.split(' ')[0]
        description = entry[len(name) + 3:]
        packages[name] = description
    return packages
コード例 #41
0
def createOnOffSwitch( pName ) :
    checkedText = ""
    bashCommand = "dpkg-query -l " + pName
    output, errorcode = execute( bashCommand )

    text = '<div class="on_off_switch">\n'
    text +='<input type="checkbox" name="'+pName+'" onclick="submit_package(this)" class="on_off_switch-checkbox" id="'+pName 
    if errorcode != 0:
        checkedText = text + '" checked>'
    elif errorcode == 0 and checkFlags(output):
        checkedText = text + '">'
    else:
        checkedText = text + '" checked>'
    checkedText += '<label class="on_off_switch-label" for="'+pName+'">\n'
    checkedText += '<div class="on_off_switch-inner"></div>\n'
    checkedText += '<div class="on_off_switch-switch"></div>\n'
    checkedText += '</label>\n'
    checkedText += '</div>\n'
    return checkedText
コード例 #42
0
def createOnOffSwitch(pName):
    checkedText = ""
    bashCommand = "dpkg-query -l " + pName
    output, errorcode = execute(bashCommand)

    text = '<div class="on_off_switch">\n'
    text += '<input type="checkbox" name="' + pName + '" onclick="submit_package(this)" class="on_off_switch-checkbox" id="' + pName
    if errorcode != 0:
        installed = False
        checkedText = text + '" checked>'
    elif errorcode == 0 and checkFlags(output):
        installed = True
        checkedText = text + '">'
    else:
        installed = False
        checkedText = text + '" checked>'
    checkedText += '<label class="on_off_switch-label" for="' + pName + '">\n'
    checkedText += '<div class="on_off_switch-inner"></div>\n'
    checkedText += '<div class="on_off_switch-switch"></div>\n'
    checkedText += '</label>\n'
    checkedText += '</div>\n'
    return checkedText, installed
コード例 #43
0
def main():

    form = cgi.FieldStorage()
    
    pictures, returncode = execute("ls /usr/share/pi-web-agent/camera-media/*.jpg")
    linearray = pictures.split('\n')
    
    html = '<div id="camera_toolbar">\n'
    html += '<a id="makePreview" class="btn btn-primary" onclick=\'camera_utils("play")\'>Play</a>'
    html += '<a id="takeSnapshot" class="btn btn-primary" onclick=\'camera_utils("snapshot")\'>Snapshot</a>'
    html += '<a id="startRecord" class="btn btn-primary" onclick=\'camera_utils("startrecord")\'>Record</a>'
    html += '<a id="stopRecord" class="btn btn-primary" onclick=\'camera_utils("stoprecord")\'>Stop</a>'
    html += '</div><br>'
    html += '''<div id="gallery_thumbnails"<p>'''
    
    for thisline in linearray:
        justname = thisline.split('/')[-1]
        if len(justname) <= 0:
            continue
        html += '<a href="/cgi-bin/toolkit/image_manager.py?image='+justname +'" rel="thumbnail"><img style="padding:4px; border:2px solid #021a40;" src="/cgi-bin/toolkit/image_manager.py?image='+justname.split('.')[0]+'.png" style="width: 64px; height: 64px" /></a>'
    html += '</p></div><br>'

    view.setContent('Live camera', html)
    output(view, cgi.FieldStorage())
コード例 #44
0
def getDpkgInfo(pName, fieldName):
    bashCommand = "apt-query " + pName + " " + fieldName
    output, errorcode = execute(bashCommand)
    if output == "":
        return fieldName + " not available"
    return output
コード例 #45
0
def test_speakers():
    command="sudo mplayer -ao alsa \"http://translate.google.com/translate_tts?tl=en&q='This is a sound test'\""
    execute(command)
    return json.dumps({'code':0})
コード例 #46
0
def get_mixers(args):
    out, exit_code = execute("sudo amixer scontrols")
    mixers = re.findall(r"'.+'", out)
    mixers = list(m[1:-1] for m in mixers)

    return json.dumps(mixers)
コード例 #47
0
        self.output = ('2' if output == 'HDMI' else ('1' if output
                       == 'HEADPHONES' else '0'))

    def startStream(self):
        '''
        try to use mplayer for the given parameters
        '''
        command=(os.environ['MY_HOME'] + "/scripts/mplayer.sh "+self.output+" "+str(self.volume)+" \""+self.uri + "\" "+os.environ['ssl_cert']+" "+os.environ['ssl_key']);
        fireAndForget(command)
        execute("echo '"+str(self.volume)+"\n0:0:0:0:0:0:0:0:0:0' > /tmp/mplayer_status")
        return 0;

if __name__ == '__main__':
    if os.environ['REQUEST_METHOD'] == 'GET':
        
        if execute('pidof mplayer')[1] == 0:
            fireAndForget('echo "get_property volume" > /tmp/mplayer-control;');
            composeJS('{ "status" : "playing" }')
        else:
            composeJS('{ "status" : "stoped" }')
    elif os.environ['REQUEST_METHOD'] == 'DELETE':

        if execute('echo "quit" > /tmp/mplayer-control')[1] == 0:
            composeJS('{ "status" : "success" }')
        else:
            composeJS('{ "status" : "failure" }',
                      httplib.INTERNAL_SERVER_ERROR)
    elif os.environ['REQUEST_METHOD'] == 'POST':
        data=json.loads(sys.stdin.read())
        try:
            if 'volume' in data:
コード例 #48
0
def addIPwithProtocolRule(chain, action, protocol, ip_address):
    if (validate_address(ip_address) == None):
        return
    return execute('sudo iptables -A ' + chain + ' -p ' + protocol + ' -s ' +
                   ip_address + ' -j ' + action)
コード例 #49
0
def addIPRule(chain, action, ip_address):
    if (validate_address(ip_address) == None):
        return
    return execute('sudo iptables -A ' + chain + ' -s ' + ip_address + ' -j ' +
                   action)
コード例 #50
0
def enableCamera():
    return execute(os.environ['MY_HOME'] + "/scripts/camera_enable.sh")
コード例 #51
0
def test_speakers():
    command = "sudo mplayer -ao alsa \"http://translate.google.com/translate_tts?tl=en&q='This is a sound test'\""
    execute(command)
    return json.dumps({'code': 0})
コード例 #52
0
def stopRecord():
    try:
        execute('sudo kill $(pidof raspivid) $(pifof raspistill)')
    except:
        pass
コード例 #53
0
def toggle_mute(args):
    command = "sudo amixer sset {mixer} toggle"
    mixer = args['mixer']
    cmd = command.format(mixer=args['mixer'])
    out, exit_code = execute(cmd)
    return get_volume(args)
コード例 #54
0
def toggle_mute(args):
    command = "sudo amixer sset {mixer} toggle"
    mixer = args['mixer']
    cmd = command.format(mixer=args['mixer'])
    out, exit_code = execute(cmd)
    return get_volume(args)
コード例 #55
0
def addIPwithProtocolRule(chain, action, protocol, ip_address):
    if validate_address(ip_address) == None:
        return
    return execute("sudo iptables -A " + chain + " -p " + protocol + " -s " + ip_address + " -j " + action)
コード例 #56
0
def addProtocolRule(chain, action, protocol):
    return execute('sudo iptables -A ' + chain + ' -p ' + protocol + ' -j ' +
                   action)
コード例 #57
0
def getCameraStatus():
    return execute("sudo vcgencmd get_camera")