def splitString(pattern, string):
    match = ure.search(pattern, string)
    match = match.group(0) if match else ['']
    counterStr = ''
    returnList = []
    counter, matching = 0, False
    print(pattern, string, match)
    for charStr in string:
        if charStr == match[0] and not matching:
            matching = True
            returnList.insert(len(returnList), counterStr)
            counterStr = charStr
            counter = 1
            if counter == len(match):
                counter = 0
                returnList.insert(len(returnList), counterStr)
                counterStr = ''
                matching = False
        elif charStr == match[counter] and matching:
            counterStr += charStr
            counter += 1
            if counter == len(match):
                counter = 0
                returnList.insert(len(returnList), counterStr)
                counterStr = ''
                matching = False
        else:
            matching = False
            counter = 0
            counterStr += charStr
    returnList.insert(len(returnList), counterStr)
    print('Finished splitString:', match, returnList, counterStr)
    return returnList
Beispiel #2
0
def b16decode(s, casefold=False):
    """Decode a Base16 encoded byte string.

    s is the byte string to decode.  Optional casefold is a flag
    specifying whether a lowercase alphabet is acceptable as input.
    For security purposes, the default is False.

    The decoded byte string is returned.  binascii.Error is raised if
    s were incorrectly padded or if there are non-alphabet characters
    present in the string.
    """
    s = _bytes_from_decode_data(s)
    if casefold:
        s = s.upper()
    if re.search(b'[^0-9A-F]', s):
        raise binascii.Error('Non-base16 digit found')
    return binascii.unhexlify(s)
Beispiel #3
0
def get(url):
    _, _, host, path = url.split('/', 3)
    addr = socket.getaddrinfo(host, 80)[0][-1]
    s = socket.socket()
    s.connect(addr)
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
    res = ''
    while True:
        text = s.readline()
        print(text)

        if text:
            r = ure.search('\"type\":[ ]*\"([A-Za-z]+)', text)
            if r:
                return r.group(1)
        if not text:
            return 0;
Beispiel #4
0
s.listen(1)
s.settimeout(0.1)
command = "off"
print('listening on', addr)

while True:

    try:
        cl, _ = s.accept()
        cl.setblocking(False)
        print('client connected from', addr)
        while True:
            line = cl.read()
            if line != None:
                break
        temp1 = ure.search('"key":"(.*)"}', line)
        command = temp1.group(1)
        # if command=="time":
        #     flag=1
        # if command=="off":
        #     flag=0
        response = b'HTTP/1.0 200 OK\r\nServer: esp8266\r\nContent-Type: application/json\r\nContent-Length: 0\r\nConnection: Closed\r\n\r\n '
        cl.send(response)
        cl.close()

    except:
        display(command)

    finally:
        pass
Beispiel #5
0
def handle_configure(client, request):
    match = ure.search("ssid=([^&]*)&password=(.*)", request)

    if match is None:
        send_response(client, "Parameters not found", status_code=400)
        return False
    # compatibildiade, e adiconamento de novos caracteres para senha.
    try:
        ssid = match.group(1).decode("utf-8").replace("%3F", "?").replace(
            "%21", "!").replace("%23", "#").replace("%40",
                                                    "@").replace("+", " ")
        password = match.group(2).decode("utf-8").replace("%3F", "?").replace(
            "%21", "!").replace("%23", "#").replace("%40",
                                                    "@").replace("+", " ")
    except Exception:
        ssid = match.group(1).replace("%3F", "?").replace("%21", "!").replace(
            "%23", "#").replace("%40", "@").replace("+", " ")
        password = match.group(2).replace("%3F", "?").replace(
            "%21", "!").replace("%23", "#").replace("%40",
                                                    "@").replace("+", " ")

    if len(ssid) == 0:
        send_response(client, "SSID must be provided", status_code=400)
        return False

    if do_connect(ssid, password):
        response = """\
            <html>
                <center>
                    <br><br>
                    <h1 style="color: #5e9ca0; text-align: center;">
                        <span style="color: #ff0000;">
                            A ESP foi conectada com sucesso à rede WiFi %(ssid)s.
                        </span>
                    </h1>
                    <br><br>
                </center>
            </html>
        """ % dict(ssid=ssid)
        send_response(client, response)
        try:
            profiles = read_profiles()
        except OSError:
            profiles = {}
        profiles[ssid] = password
        write_profiles(profiles)

        time.sleep(5)

        return True
    else:
        response = """\
            <html>
                <center>
                    <h1 style="color: #5e9ca0; text-align: center;">
                        <span style="color: #ff0000;">
                            ESP não conseguiu se conectar à rede WiFi %(ssid)s.
                        </span>
                    </h1>
                    <br><br>
                    <form>
                        <input type="button" value="Volte!" onclick="history.back()"></input>
                    </form>
                </center>
            </html>
        """ % dict(ssid=ssid)
        send_response(client, response)
        return False
Beispiel #6
0
    <div id="Lampada"></h1>
    <button type="submit" onclick="request('LightStatus=On');">Ligar</button>
    <button type="submit" onclick="request('LightStatus=Off');">Desligar</button> </div></body>
    </html>
    """

while True:
    cl, addr = s.accept()
    print('client connected from', addr)
    cl_file = cl.makefile('rwb', 0)

    while True:
        line = cl_file.readline()
        strLine = str(line)

        if not line or line == b'\r\n':
    		cl.send(html)
        	break

        if not ure.search('LightStatus=', strLine):
            continue
        else:
            status = strLine.split(' ')[1].split('=')[1]
            cl.send(html)
            if status == 'On':
                light.value(1)
            else:
                light.value(0)
        break
    cl.close()
Beispiel #7
0
    def __handle_configure(self, client, request):
        match = ure.search("ssid=([^&]*)&password=(.*)", request)

        if match is None:
            self.__send_response(client,
                                 "Parameters not found",
                                 status_code=400)
            return False
        # version 1.9 compatibility
        try:
            ssid = match.group(1).decode("utf-8").replace("%3F", "?").replace(
                "%21", "!")
            password = match.group(2).decode("utf-8").replace("%3F",
                                                              "?").replace(
                                                                  "%21", "!")
        except Exception:
            ssid = match.group(1).replace("%3F", "?").replace("%21", "!")
            password = match.group(2).replace("%3F", "?").replace("%21", "!")

        if len(ssid) == 0:
            self.__send_response(client,
                                 "SSID must be provided",
                                 status_code=400)
            return False

        if self.manager.do_connect(ssid, password):
            response = """\
                <html>
                    <center>
                        <br><br>
                        <h1 style="color: #5e9ca0; text-align: center;">
                            <span style="color: #ff0000;">
                                Successfully connected to WiFi network {0}.
                            </span>
                        </h1>
                        <br><br>
                        <h1 style="color: #5e9ca0; text-align: center;">
                            <span style="color: #ff0000;">
                                You may now close this window.
                            </span>
                        </h1>
                    </center>
                </html>
            """.format(ssid)
            self.__send_response(client, response)
            try:
                profiles = self.manager.read_profiles()
            except OSError:
                profiles = {}
            profiles[ssid] = password
            self.manager.write_profiles(
                profiles)  # write the new profile to disk
            return True
        else:
            response = """\
                <html>
                    <center>
                        <h1 style="color: #5e9ca0; text-align: center;">
                            <span style="color: #ff0000;">
                                Could not connect to WiFi network {0}.
                            </span>
                        </h1>
                        <br><br>
                        <form>
                            <input type="button" value="Go back!" onclick="history.back()"></input>
                        </form>
                    </center>
                </html>
            """.format(ssid)
            self.__send_response(client, response)
            return False
    def _handle_join_wifi(self, client, request):
        match = ure.search("ssid=([^&]*)&password=(.*)", request)

        if match is None:
            self._send_response(client,
                                "Parameters not found",
                                status_code=400)
            return False
        # version 1.9 compatibility
        try:
            self.ssid = match.group(1).decode("utf-8").replace("%3F",
                                                               "?").replace(
                                                                   "%21", "!")
            self.password = match.group(2).decode("utf-8").replace(
                "%3F", "?").replace("%21", "!")
            print('****ssid: {} password: {}'.format(self.ssid, self.password))
        except Exception:
            self.ssid = match.group(1).replace("%3F", "?").replace("%21", "!")
            self.password = match.group(2).replace("%3F",
                                                   "?").replace("%21", "!")

        if len(self.ssid) == 0:
            self._send_response(client,
                                "SSID must be provided",
                                status_code=400)
            return False
        # We have the ssid and password.  Now we'll try to use this info to connect to the self.wifi.
        if self._do_connect():
            response = """\
                <html>
                    <center>
                        <br><br>
                        <h1 style="color: #5e9ca0; text-align: center;">
                            <span style="color: #ff0000;">
                                ESP successfully connected to wifi network %(ssid)s.
                            </span>
                        </h1>
                        <br><br>
                    </center>
                </html>
            """ % dict(ssid=self.ssid)
            self._send_response(client, response)
        else:
            response = """\
                <html>
                    <center>
                        <h1 style="color: #5e9ca0; text-align: center;">
                            <span style="color: #ff0000;">
                                ESP could not connect to wifi network %(ssid)s.
                            </span>
                        </h1>
                        <br><br>
                        <form>
                            <input type="button" value="Go back!" onclick="history.back()"></input>
                        </form>
                    </center>
                </html>
            """ % dict(ssid=self.ssid)
            self._send_response(client, response)
            return False
        # No longer need access point.
        wlan_ap.active(False)
        return True
Beispiel #9
0
    def loadrules(self):
        # get all filenames in rules dir
        orgdir = os.getcwd()
        os.chdir('rules')
        listdir = os.listdir()
        os.chdir(orgdir)

        # delete rules records
        self._log.debug("Scripts: init rules records")
        rules = db.ruleTable.public()
        for rule in rules:
            if db.ruleTable.delete(rule['timestamp']):
                self._log.debug("Scripts: Rule record delete succeeded: " +
                                db.ruleTable.fname(rule['timestamp']))
            else:
                self._log.error("Scripts: Rule record delete failed: " +
                                db.ruleTable.fname(rule['timestamp']))

        cnt = 1
        advanced = db.advancedTable.getrow()
        # auto start or not?
        if advanced['rules'] == 'on': autorule = 'on'
        else: autorule = 'off'

        # get all flash rules
        for module in listdir:
            # get file/rule name
            if module[-5:] != '.rule':
                continue
            rulename = module[:-5]

            # load rule file
            self._log.debug("Scripts: Load rule " + rulename)
            rule_file = open("rules/{}".format(module), 'r')
            content = rule_file.read()
            rule_file.close()

            # parse file content and get event
            matchcontent = re.search(r'if (.*):', content)
            if matchcontent:
                # strip any comparison
                matchcomp = re.search(r'(.*)[<>=!]', matchcontent.group(1))
                if matchcomp:
                    match = re.search(r'\'(.*)\'', matchcomp.group(1))
                else:
                    match = re.search(r'\'(.*)\'', matchcontent.group(1))
                if match:
                    ruleevent = match.group(1)
                    self._log.debug("Scripts: Rule: {}, event: {}".format(
                        rulename, ruleevent))
                else:
                    self._log.warning(
                        "Scripts: Rule error, no event match 2: " + rulename)
                    continue
            else:
                self._log.warning("Scripts: Rule error, no event match: " +
                                  rulename)
                continue

            # done, save rule
            self._log.debug("Scripts: Create rule Record: " + rulename)

            #create rule table record
            try:
                cid = db.ruleTable.create(id=cnt,
                                          name=rulename,
                                          event=ruleevent,
                                          filename=module,
                                          pluginid=0,
                                          enable=autorule)
            except OSError:
                self._log.error("Scripts: Exception creating rule record:" +
                                rulename)

            # next rule, if any
            cnt += 1

            # Clean up!
            gc.collect()

        # Clean up!
        gc.collect()
Beispiel #10
0
    </div> </body> </html>"""

addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)

while True:
    cl, addr = s.accept()
    print('client connected from', addr)
    cl_file = cl.makefile('rwb', 0)

    while True:
        line = cl_file.readline()
        #Problemas: Necessita converçao da line para string
        # para fazer o .split()
        linha = str(line)
        if not line or line == b'\r\n':
            cl.send(html)
            break
        if not ure.search('MorseOf', line):
            continue
        else:
            numero = linha.split(' ')[1].split('=')[1]
            cl.send(html)
            piscaMorse(numero)
        break
    led.value(1)
    cl.close()
def removeWhiteSpace(s):
    newstr = ''
    for charStr in s:
        if not ure.search('\s', charStr):
            newstr += charStr
    return newstr
Beispiel #12
0
def websetup(timeout_s=60, lock_session=False):
    logger.info('Starting WebSetup')
    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
    s = socket.socket()
    s.bind(addr)
    s.listen(0)
    s.settimeout(timeout_s)
    logger.debug('Listening on ', addr)

    # Start AP mode and disable client mode
    sta = network.WLAN(network.STA_IF)
    sta.active(False)
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid="Thing_{}".format(hal.get_tid()),
              authmode=network.AUTH_WPA_WPA2_PSK,
              password="******")

    logger.info('Done, waiting for a connection... ({}s)'.format(timeout_s))

    while True:
        try:
            gc.collect()

            # Handle client connection
            cl, addr = s.accept()
            logger.info('Incoming client connection from', addr[0])
            s.settimeout(None)

            # Read request
            request = str(cl.recv(1024))

            # Parse GET request
            get_request_data = ure.search("GET (.*?) HTTP\/1\.1", request)
            if get_request_data:
                path, parameters = parseURL(get_request_data.group(1))
                #logger.debug('Got request for path = "{}" with params = "{}"'.format(path, parameters))
            else:
                path = []
                parameters = []

            cl.write('HTTP/1.0 200 OK\r\n')
            cl.write('Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n')
            cl.write("Access-Control-Allow-Origin: *\r\n")
            cl.write("Access-Control-Allow-Credentials: true\r\n")
            cl.write(
                "Access-Control-Allow-Headers: X-CSRFToken, ACCEPT, CONTENT-TYPE, X-CSRF-TOKEN, Content-Type, Authorization, X-Requested-With\r\n"
            )

            if not get_request_data:  # an OPTIONS, basically
                cl.write('Content-Length: 0\r\n\r\n')
                cl.close()
                continue

            def set_api():
                cl.write('Content-Type: application/json\r\n')
                cl.write('\r\n')

            def set_page():
                cl.write('Content-Type: text/html\r\n')
                cl.write('\r\n')

            # Close connection if requesting favicon
            if 'favicon' in path:
                set_api()
                cl.close()

            # This is an API call
            elif 'cmd' in parameters:
                logger.info('Called API with cmd={}'.format(parameters['cmd']))
                set_api()
                cmd = parameters['cmd']
                essid = None
                if 'essid' in parameters: essid = parameters['essid']
                password = None
                if 'password' in parameters: password = parameters['password']

                # Set app command
                if cmd == 'set_app':
                    aid = None
                    aid = parameters['aid']
                    if aid is None:
                        cl.write(json.dumps({'status': 'ERROR'}))
                    else:
                        with open('/aid', 'w') as f:
                            f.write(aid)
                    cl.write(
                        json.dumps({
                            'status': 'OK',
                            'aid': load_param('aid', None)
                        }))

                # Set apn command
                if cmd == 'set_apn':
                    apn = None
                    apn = parameters['apn']
                    if apn is None:
                        cl.write(json.dumps({'status': 'ERROR'}))
                    else:
                        with open('/apn', 'w') as f:
                            f.write(apn)
                    cl.write(
                        json.dumps({
                            'status': 'OK',
                            'apn': load_param('apn', None)
                        }))

                # Check command
                if cmd == 'check':
                    import os
                    essid = get_wifi_data()[0]
                    cl.write(
                        json.dumps({
                            'status': 'OK',
                            'tid': hal.get_tid(),
                            'platform': platform,
                            'version': version,
                            'aid': load_param('aid', None),
                            'apn': load_param('apn', None),
                            'essid': essid
                        }))

                # Check_wifi command
                if cmd == 'check_wifi':
                    sta.active(True)
                    essid = 'Unknown'
                    isconnected = False
                    essid, password = get_wifi_data()
                    if essid:
                        connect_wifi(sta, essid, password)
                        time.sleep(25)
                    isconnected = sta.isconnected()
                    sta.active(False)
                    cl.write(
                        json.dumps({
                            'status': 'OK',
                            'isconnected': isconnected,
                            'essid': essid
                        }))

                # Scan command
                elif cmd == 'scan':
                    sta.active(True)
                    nets = sta.scan()
                    sta.active(False)
                    cl.write(json.dumps(nets))

                # Join command
                elif cmd == 'join':
                    if password is None or essid is None:
                        cl.write(json.dumps({'status': 'ERROR'}))
                    else:
                        sta.active(True)
                        connect_wifi(sta, essid, password)
                        time.sleep(25)
                        isconnected = sta.isconnected()
                        saved = False
                        if isconnected:
                            try:
                                with open('/wifi', 'w') as f:
                                    f.write('{}\n{}'.format(essid, password))
                                saved = True
                            except:
                                saved = False
                        sta.active(False)
                        cl.write(
                            json.dumps({
                                'status': 'OK',
                                'isconnected': isconnected,
                                'essid': essid,
                                'saved': saved
                            }))

                # Close command
                elif cmd == 'close':
                    cl.write(json.dumps({'status': 'OK'}))
                    cl.close()
                    s.close()
                    break

            else:
                #logger.debug('Serving main page')
                set_page()
                cl.write(
                    'Please go to your vendor\'s Website to configure this device.\r\n'
                )

            # Close client connection at the end
            cl.close()

        except OSError as e:
            if str(e) == "[Errno 110] ETIMEDOUT":
                logger.info('Exiting due to no incoming connections')
                s.close()
                break
            import sys
            sys.print_exception(e)
            try:
                cl.close()
            except:
                pass
            try:
                s.close()
            except:
                pass
            time.sleep(3)
Beispiel #13
0
print(re.match("[a-]+", "-a]d").group(0))
print("===")

r = re.compile("o+")
m = r.search("foobar")
print(m.group(0))
try:
    m.group(1)
except IndexError:
    print("IndexError")


m = re.match(".*", "foo")
print(m.group(0))

m = re.search("w.r", "hello world")
print(m.group(0))

m = re.match('a+?', 'ab');  print(m.group(0))
m = re.match('a*?', 'ab');  print(m.group(0))
m = re.match('^ab$', 'ab'); print(m.group(0))
m = re.match('a|b', 'b');   print(m.group(0))
m = re.match('a|b|c', 'c'); print(m.group(0))

# Case where anchors fail to match
r = re.compile("^b|b$")
m = r.search("abc")
print(m)

try:
    re.compile("*")
Beispiel #14
0
     + str(vlaznost))
 print('Vlaznost : Update OK')
 # Temperatura prostorije - Update v0
 http_get(
     'http://blynk-cloud.com/15364b6f7e934f859ab8cc3803d2971b/update/V0?value='
     + str(temperatura))
 print('Temperatura : Update OK')
 # Temperatura vode u kotlu - v4
 http_get(
     'http://blynk-cloud.com/15364b6f7e934f859ab8cc3803d2971b/update/V4?value='
     + str(int(kotao_temperatura)))
 print('Kotao : Update OK')
 # Preuzmi RTC format podataka Update v10,v11 utime.localtime http://blynk-cloud.com/15364b6f7e934f859ab8cc3803d2971b/rtc
 rtc_format = http_get(
     'http://blynk-cloud.com/15364b6f7e934f859ab8cc3803d2971b/rtc')
 RTC_raw = ure.search('\[(\d+)]', rtc_format).group(1)
 formatirano_vreme = utime.localtime(int(RTC_raw))
 #print ('RTC je      : ', RTC_raw, '=',formatirano_vreme)
 # Ispisi Vreme - Datum poslednje konekcije 1-red v10 2-red v11
 datum = '___' + str(formatirano_vreme[1]) + '.' + str(
     formatirano_vreme[2]) + '.' + str(formatirano_vreme[0] - 30)
 #print(type(datum), datum)
 http_get(
     'http://blynk-cloud.com/15364b6f7e934f859ab8cc3803d2971b/update/V10?value='
     + datum)
 # Dodajemo 0 zbog formata sekundi
 if (formatirano_vreme[5] < 10):
     vreme = '____' + str(formatirano_vreme[3]) + ':' + str(
         formatirano_vreme[4]) + ':' + '0' + str(formatirano_vreme[5])
 else:
     vreme = '____' + str(formatirano_vreme[3]) + ':' + str(
Beispiel #15
0
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while True:
    cl, addr = s.accept()
    print('client connected from', addr)
    cl_file = cl.makefile('rwb', 0)
    while True:
        line = cl_file.readline()
        linha = str(line)
        if not line or line == b'\r\n':
            cl.send(html)
            break
        if not ure.search('Print', line):
            continue
        else:
            text = linha.split(' ')[1].split('=')[1]
            cl.send(html)
            if text == 'ip':
                ip = str(sta.ifconfig()).split('(')[1].split("'")[1]
                ToScreen(ip)
            elif text == 'mac':
                mac = '18:FE:39:CE:D3:26'
                ToScreen(mac)
            elif text == 'cpu':
                cpu = str(machine.freq())
                ToScreen(cpu)
            else:
                ToScreen(text)
Beispiel #16
0
def start(port=80):
    global server_socket

    addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]

    stop()

    wlan_sta.active(True)
    wlan_ap.active(True)

    # with open(CONFIG) as f:
    #     AP = yaml.load(f.read())['ap']
    with open(CONFIGFILE) as f:
        AP = json.load(f)['ap']

    essid = '{}-{}'.format(AP['ssid'],
                           ubinascii.hexlify(machine.unique_id()).decode())

    wlan_ap.config(essid=essid, password=AP['pswd'], authmode=int(AP['auth']))

    server_socket = socket.socket()
    server_socket.bind(addr)
    server_socket.listen(1)

    print('Connect to WiFi ssid ' + essid + ', default password: '******'pswd'])
    print('and access the ESP via your favorite web browser at 192.168.4.1.')
    print('Listening on:', addr)

    while True:
        if wlan_sta.isconnected():
            return True

        client, addr = server_socket.accept()
        print('client connected from', addr)
        try:
            client.settimeout(5.0)

            request = b""
            try:
                while "\r\n\r\n" not in request:
                    request += client.recv(512)
            except OSError:
                pass

            print("Request is: {}".format(request))
            if "HTTP" not in request:  # skip invalid requests
                continue

            # version 1.9 compatibility
            try:
                url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP",
                                 request).group(1).decode("utf-8").rstrip("/")
            except Exception:
                url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP",
                                 request).group(1).rstrip("/")
            print("URL is {}".format(url))

            if url == "":
                handle_root(client)
            elif url == "configure":
                handle_configure(client, request)
            else:
                handle_not_found(client, url)

        finally:
            client.close()
Beispiel #17
0
def start(port=80):
    global server_socket

    addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]

    stop()

    wlan_sta.active(True)
    wlan_ap.active(True)

    wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)

    server_socket = socket.socket()
    server_socket.bind(addr)
    server_socket.settimeout(60)
    server_socket.listen(1)

    print('Connect to WiFi ssid ' + ap_ssid + ', default password: '******'and access the ESP via your favorite web browser at 192.168.4.1.')
    print('Listening on:', addr)
    while True:
        if wlan_sta.isconnected():
            return True
        try:
            client, addr = server_socket.accept()
            print('client connected from', addr)
        except OSError as e:
            print(e, ': no connections after 5 seconds...')
            machine.reset()
        try:
            client.settimeout(5.0)

            request = b""
            try:
                while "\r\n\r\n" not in request:
                    request += client.recv(512)
            except OSError:
                pass

            print("Request is: {}".format(request))
            if "HTTP" not in request:  # skip invalid requests
                continue

            # version 1.9 compatibility
            try:
                url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP",
                                 request).group(1).decode("utf-8").rstrip("/")
            except Exception:
                url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP",
                                 request).group(1).rstrip("/")
            print("URL is {}".format(url))

            if url == "":
                handle_root(client)
            elif url == "configure":
                handle_configure(client, request)
            else:
                handle_not_found(client, url)

        finally:
            client.close()
Beispiel #18
0
s.bind(addr)
s.listen(5)
print('[+] Server http://myIpv4:80/')

while True:
    try:
        if is_waiting:
            print('[~] waiting for request')
            is_waiting = False

        res = s.accept()
        client_sock = res[0]
        client_addr = res[1]
        req = client_sock.recv(256)  # 4096
        print('\t\tRequest from {0}:\n\t\t{1}'.format(client_addr, req))
        if ure.search(b'/?state', req):
            print('\t\t[+] got state')
            client_sock.write(CONTENT % (200, 'OK', pins['relay'].value()))
            client_sock.close()
        elif ure.search(b'/?relay', req):
            print('\t\t[+] got relay')
            Relay()
            client_sock.write(CONTENT % (200, 'OK', pins['relay'].value()))
            client_sock.close()
        elif ure.search(b'/?exit', req):
            print('\t\t[+] got exit')
            client_sock.write(CONTENT % (200, 'OK', pins['relay'].value()))
            client_sock.close()
            sys.exit(0)
        else:
            print('\t\t[-] bad request')
Beispiel #19
0
print(m.group(0))


r = re.compile("o+")
m = r.search("foobar")
print(m.group(0))
try:
    m.group(1)
except IndexError:
    print("IndexError")


m = re.match(".*", "foo")
print(m.group(0))

m = re.search("w.r", "hello world")
print(m.group(0))

m = re.match('a+?', 'ab');  print(m.group(0))
m = re.match('a*?', 'ab');  print(m.group(0))
m = re.match('^ab$', 'ab'); print(m.group(0))
m = re.match('a|b', 'b');   print(m.group(0))
m = re.match('a|b|c', 'c'); print(m.group(0))

# Case where anchors fail to match
r = re.compile("^b|b$")
m = r.search("abc")
print(m)

try:
    re.compile("*")
Beispiel #20
0
    def do(self):
        """ called regularly from the main loop
        """
        try:
            cl, addr = self.sock.accept()
            #cl.setblocking(False) #TODO is it neccesarry?
            _debug('client connected from', addr)
        except OSError:
            #no connection
            return

        try:
            request = None
            for i in range(30):  #max X Iterationen
                try:
                    _debug("trying to receive data...")
                    request = str(cl.recv(1024))
                    _debug("REQUEST: ", request)
                    break
                except OSError:
                    #not ready to recv yet
                    time.sleep(0.1)
                    continue
            else:
                _debug("Error: This took too long!!")
                cl.close()
                return
            obj = ure.search("GET (.*?) HTTP\/1\.1", request)
            if obj:
                _debug(obj.group(1))
                path, parameters = self.parseURL(obj.group(1))
                if path.startswith("/folder"):
                    folder = parameters.get("folder", 1)
                    _debug(folder, repr(folder))
                    self.mp3Player.play_folder(int(folder))
                elif path.startswith("/play"):
                    track = parameters.get("track", 1)
                    self.mp3Player.play_track(int(track))
                elif path.startswith("/next"):
                    self.mp3Player.next()
                elif path.startswith("/prev"):
                    self.mp3Player.previous()
                elif path.startswith("/resume"):
                    self.mp3Player.resume()
                elif path.startswith("/pause"):
                    self.mp3Player.pause()
                elif path.startswith("/volume"):
                    level = int(parameters.get("level", 15))
                    self.mp3Player.set_volume(level)
                elif path.startswith("/halt"):
                    cl.close()
                    raise SystemExit('Stop program')
                else:
                    _debug(
                        "UNREGISTERED ACTION\r\nPATH: %s\r\nPARAMETERS: %s" %
                        (path, parameters))
            try:
                self.sendResponse(cl)
            except OSError as e:
                _debug(e)
        finally:
            cl.close()
            _debug("connection closed")