Example #1
0
def main():
    print("Hello Welcome to SYDCA ESP OS")

    print("Flash_id:" + str(esp.flash_id()))
    machid = str(machine.unique_id())
    machid = ure.sub("\\\\x", "", machid)
    machid = ure.sub("b'", "", machid)
    machid = ure.sub("'", "", machid)
    print("Machine Id:" + str(machid))
    print("Flash Size:" + str(esp.flash_size()))
    boot_init()
    # print(initfile.readlines())
    print("Start Running Mode")
    load_init_file()
Example #2
0
 def sub(self, pattern, replacement):
     before = self.get_lines()[:self.begin]
     lines = self.get_lines()[self.begin:self.end]
     after = self.get_lines()[self.end:]
     lines = [ure.sub(pattern, replacement, line) for line in lines]
     self.set_lines(before + lines + after)
     return self
 def close_recorder(self):
     if self._rec == None:
         return
     filename = ure.sub("\.writing$", "", self._rec.filename)
     uos.rename(self._rec.filename, filename)
     self._rec.close()
     self._rec = None
     stat = uos.stat(filename)
     print("Close", filename, stat[6], stat)
    def record(self):
        lcd.draw_string(10, 50, ure.sub("(.+)/", "", self._rec.filename),
                        lcd.WHITE, lcd.BLACK)
        lcd.draw_string(10, 70, "%d" % (self._record_count), lcd.WHITE,
                        lcd.BLACK)
        lcd.draw_string(10, 90, "fps=%.2f" % (self._fps), lcd.WHITE, lcd.BLACK)

        self._rec.write_number("v_ms", time.ticks_ms(), 4)
        img = sensor.snapshot()
        self._rec.write_jpeg_image(img)
        self._record_count += 1
Example #5
0
def replaceRe(FileName, pat, repline): 
    from ure import sub
    from os import rename
    f = open(FileName)
    newfile = '/'+FileName+'.tmp'
    f2 = open(newfile,'w')
    for line in f.readlines():
        newline = sub(pat,repline,line)
        f2.write(newline)
    f.close()
    f2.close()
    rename(newfile,FileName)
def save_device_name(server, name):
    new_name = ure.sub('[^A-Za-z0-9_-]+', '-', name).strip('-_')  # noqa
    if name != new_name:
        server.message = 'Error: Device name contains not allowed characters!'
        raise ValueError(new_name)

    if len(new_name) < 3:
        server.message = 'Error: New Device name is too short. Enter at leased 3 characters!'
        raise ValueError(new_name)

    from config_files import save_json_config
    save_json_config(key=_CFG_KEY, cfg=name)
    del save_json_config
    del sys.modules['config_files']
    gc.collect()

    server.message = 'Device name %r saved.' % new_name
Example #7
0
    def render_block(self, typ, block):
        if not block:
            return

        def tt(m):
            return "<tt>" + m.group(1).replace("<", "&lt;") + "</tt>"

        block = ure.sub("`(.+?)`", tt, block)
        block = ure.sub("\*\*(.+?)\*\*", "<b>\\1</b>", block)
        block = ure.sub("\*(.+?)\*", "<i>\\1</i>", block)
        block = ure.sub("~~(.+)~~", "<strike>\\1</strike>", block)
        block = ure.sub("!\[(.+?)\]\((.+?)\)", '<img src="\\2" alt="\\1">', block)
        block = ure.sub("\[(.+?)\]\((.+?)\)", '<a href="\\2">\\1</a>', block)

        if typ == "list":
            tag = "li"
        elif typ == "bquote":
            tag = "blockquote"
        else:
            tag = "p"

        self.out.write("<%s>\n" % tag)
        self.out.write(block)
        self.out.write("</%s>\n" % tag)
Example #8
0
    except ImportError:
        print("SKIP")
        raise SystemExit

try:
    re.sub
except AttributeError:
    print("SKIP")
    raise SystemExit


def multiply(m):
    return str(int(m.group(0)) * 2)


print(re.sub("\d+", multiply, "10 20 30 40 50"))

print(re.sub("\d+", lambda m: str(int(m.group(0)) // 2), "10 20 30 40 50"))


def A():
    return "A"


print(re.sub("a", A(), "aBCBABCDabcda."))

print(
    re.sub(
        r"def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):",
        "static PyObject*\npy_\\1(void){\n  return;\n}\n",
        "\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():",
Example #9
0
def access_point():
    gc.collect()

    # Access Point credentials
    ssid = 'Electronic Pet Door'
    password = '******'

    # Local network credentials placeholders
    USERNAME = ''
    PASSWORD = ''

    header = {}

    # Creates an Acess Point for the user to connect to
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid=ssid,
              authmode=network.AUTH_WPA_WPA2_PSK,
              password=password)
    while ap.active() == False:
        pass
    print('Connection successful')
    print(ap.ifconfig())
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while True:
        try:
            s.bind(('', 80))
            print("Socket work.")
            break
        except:
            s.close()
            print("Socket no work. Retry.\n")
            return "oserror"

            gc.collect()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.listen(5)

    while True:
        try:
            conn, addr = s.accept()
            req = conn.readline()
        except KeyboardInterrupt:
            raise OSError('Interrupt')
        except Exception as e:
            print(e)
            return

        l = 0
        while True:
            h = conn.readline()
            if not h or h == b'\r\n':
                break
            if 'Content-Length: ' in h:
                try:
                    l = int(h[16:-2])
                    print('Content Length is : ', l)
                except:
                    continue

        if l:
            postquery = conn.read(l)
            postquery = str(postquery)
            postquery = postquery.split("&")
            USERNAME = postquery[0][7:]
            PASSWORD = postquery[1][9:-1]
            print(USERNAME)
            print(PASSWORD)
            conn.close()
            break
        response = ap_web_page()
        conn.send('HTTP/1.1 200 OK\n')
        conn.send('Content-Type: text/html\n')
        conn.send('Connection: close\n\n')
        conn.sendall(response)
        conn.close()

    # Closes connection
    ap.active(False)
    while ap.active() == True:
        pass
    sleep(5)
    s.close()
    gc.collect()
    # Greps the USERNAME and PASSWORD
    USERNAME = ure.sub("\+", " ", USERNAME)
    USERNAME = ure.sub("\%91", "\'", USERNAME)
    USERNAME = ure.sub("\%92", "\'", USERNAME)
    USERNAME = ure.sub("\%2B", "+", USERNAME)
    print(USERNAME)
    PASSWORD = ure.sub("\+", " ", PASSWORD)
    print("Username= "******"\nPassword= "******"credentials.txt", "w") as file:
        file.write(USERNAME)
        file.write("\n")
        file.write(PASSWORD)

    gc.collect()
Example #10
0
 def _render(self, string, **kwargs):
     import ure as re
     for key, value in kwargs:
         pattern = "{{{{{}}}}}".format(key)
         string = re.sub(pattern, value, string)
     return string
Example #11
0
def main():
    #    print("Oii")
    s = socket.socket()
    ai = socket.getaddrinfo("0.0.0.0", 8080)
    print("Bind address info:", ai)
    addr = ai[0][-1]
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to http://<this_host>:8080/")
    while True:
        res = s.accept()
        client_sock = res[0]
        client_addr = res[1]
        print("Client address: {}  socket: {} ".format(client_addr,
                                                       client_sock))
        client_stream = client_sock.makefile("rwb")
        #print(type(client_stream))
        print("HEAD:")
        obj = None
        objHost = None
        while True:
            request = client_stream.readline()
            #print("Resultado Requisição:  {}".format(request))
            if not obj:
                obj = ure.search("GET (.*?) HTTP\/1\.1", request.decode())
            if not objHost:
                objHost = ure.search("Host: (.*?)\r\n", request.decode())
            if (request == b"\r\n" or request == b""):
                break
        if not obj:
            html = '''HTTP/1.0 404 OK\r\nAccess-Control-Allow-Origin: *\r\n\r\n'''
            client_stream.write(html.encode())
            #print("INVALID REQUEST - GET")
        else:
            #print(" REGEX: {}  ".format(obj.group(1)))
            path, parameters = parseURL(obj.group(1))
            print("path: {}  parameters: {} ".format(path, parameters))
            if (ure.search('^\/(.+\.(css|xml|js|html|htm|json|ico|png))$',
                           path)):
                global ctypeDict
                try:
                    if (ure.search('^\/(.+\.(css|xml|js|html|htm|json))$',
                                   path)):
                        arq_html = open(".{}".format(path)).read()
                        if (sys.platform == 'esp8266'):
                            if (path != "/nipplejs.js"):
                                arq_html = arq_html.replace(
                                    "{[host]}",
                                    "http://{}".format(objHost.group(1)))
                        else:
                            #arq_html = ure.sub("\{\[host\]\}","http://{}".format(objHost.group(1)),arq_html.decode())
                            arq_html = ure.sub(
                                "\{\[host\]\}",
                                "http://{}".format(objHost.group(1)), arq_html)
                        html = '''HTTP/1.0 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-type: %s\r\nContent-length: %d\r\n\r\n%s''' % (
                            ctypeDict[path[path.index('.'):]], len(arq_html),
                            arq_html)
                        client_stream.write(html.encode())
                    else:
                        f = open(".{}".format(path), "rb")
                        arq_html = f.read()
                        f.close()
                        f = None
                        html = '''HTTP/1.0 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-type: %s\r\nContent-length: %d\r\n\r\n''' % (
                            ctypeDict[path[path.index('.'):]], len(arq_html))
                        client_stream.write(html.encode())
                        client_stream.write(arq_html)
                        client_stream.close()
                        arq_html = None
                        html = None
                        if (sys.platform == 'esp8266'): gc.collect()
                except Exception as e:
                    html = '''HTTP/1.0 404  Not Found\r\n\r\n<html><body><center><h3>Error 404: File not found</h3><p>ESP8266 HTTP Server</p></center></body></html>'''
                    print(e)
                    client_stream.write(html.encode())
            elif (path == "/"):
                print("Pagina inicial")
                client_stream.write(buildResponse("").encode())
            elif path.startswith("/api"):
                print("/api")
                val_r = parameters.get("r", None)
                val_g = parameters.get("g", None)
                val_b = parameters.get("b", None)
                if not val_r or not val_g or not val_b:
                    val_r = "0"
                    val_g = "0"
                    val_b = "0"
                print(" RGB: r={} g={} b={}".format(val_r, val_g, val_b))
                if (sys.platform == 'esp8266'):
                    pin_r = PWM(Pin(5))
                    pin_g = PWM(Pin(4))
                    pin_b = PWM(Pin(0))
                    pin_r.duty(int((float(255 - int(val_r)) / 255) * 1023))
                    pin_g.duty(int((float(255 - int(val_g)) / 255) * 1023))
                    pin_b.duty(int((float(255 - int(val_b)) / 255) * 1023))
                html = '''HTTP/1.0 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-type: text/plain\r\nContent-length: %d\r\n\r\n%s''' % (
                    len("12213.33"), "12213.33")
                client_stream.write(html.encode())
                print("API")
            elif path.startswith("/ana0"):
                html = '''HTTP/1.0 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-type: text/plain\r\nContent-length: %d\r\n\r\n%s''' % (
                    len("12213.33"), "12213.33")
                client_stream.write(html.encode())
            elif path.startswith("/halt"):
                print("rota /halt")
                client_stream.write(
                    buildResponse("Shutting down server\n").encode())
                client_stream.close()
                client_sock.close()
                s.close()
                break
            else:
                html = '''HTTP/1.0 404  Not Found\r\n\r\n<html><body><center><h3>Error 404: File not found</h3><p>ESP8266 HTTP Server</p></center></body></html>'''
                client_stream.write(html.encode())
                print("INVALID REQUEST - GET")
        client_stream.close()
        client_sock.close()
        print("-----------------------------------------------------")
    print("Finaliza a conexão socket")
    s.close()
Example #12
0
def access_point():
    gc.collect()

    # Access Point credentials
    ssid = 'Electronic Pet Door'
    password = '******'

    # Local network credentials placeholders
    USERNAME = ''
    PASSWORD = ''

    header = {}

    # Creates an Acess Point for the user to connect to
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid=ssid,
              authmode=network.AUTH_WPA_WPA2_PSK,
              password=password)
    while ap.active() == False:
        pass
    print('Connection successful')
    print(ap.ifconfig())
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 80))
    s.listen(5)

    # Looks for a connection and received HTTP GETs
    while True:
        conn, addr = s.accept()
        print('Got a connection from %s' % str(addr))
        request = conn.recv(1024)
        request = str(request)
        if request[:6] == "b'GET " and request.find("ssid=") > 0:
            print("Closing Access Point. Storing Credentials.")
            break
        print('Content = %s' % request)
        response = ap_web_page()
        conn.send('HTTP/1.1 200 OK\n')
        conn.send('Content-Type: text/html\n')
        conn.send('Connection: close\n\n')
        conn.sendall(response)
        conn.close()

    # Closes connection
    conn.close()
    ap.active(False)
    s.close()

    # Greps the USERNAME and PASSWORD
    USERNAME = request[int(request.find("ssid=")) +
                       5:int(request.find("&password="******"&password="******" HTTP/1.1\r\nHost:")]
    PASSWORD = PASSWORD.split(" ")
    PASSWORD = PASSWORD[0]
    USERNAME = ure.sub("\+", " ", USERNAME)
    PASSWORD = ure.sub("\+", " ", PASSWORD)
    print("Username= "******"\nPassword= "******"credentials.txt", "w") as file:
        file.write(USERNAME)
        file.write("\n")
        file.write(PASSWORD)

    gc.collect()
Example #13
0
# test re.sub with unmatched groups, behaviour changed in CPython 3.5

try:
    import ure as re
except ImportError:
    try:
        import re
    except ImportError:
        print('SKIP')
        raise SystemExit

try:
    re.sub
except AttributeError:
    print('SKIP')
    raise SystemExit

# first group matches, second optional group doesn't so is replaced with a blank
print(re.sub(r'(a)(b)?', r'\2-\1', '1a2'))
Example #14
0
    except ImportError:
        print('SKIP')
        raise SystemExit

try:
    re.sub
except AttributeError:
    print('SKIP')
    raise SystemExit


def multiply(m):
    return str(int(m.group(0)) * 2)


print(re.sub("\d+", multiply, "10 20 30 40 50"))

print(re.sub("\d+", lambda m: str(int(m.group(0)) // 2), "10 20 30 40 50"))


def A():
    return "A"


print(re.sub('a', A(), 'aBCBABCDabcda.'))

print(
    re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
           'static PyObject*\npy_\\1(void){\n  return;\n}\n',
           '\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():'))
Example #15
0
        import re
    except ImportError:
        print('SKIP')
        raise SystemExit

try:
    re.sub
except AttributeError:
    print('SKIP')
    raise SystemExit


def multiply(m):
    return str(int(m.group(0)) * 2)

print(re.sub("\d+", multiply, "10 20 30 40 50"))

print(re.sub("\d+", lambda m: str(int(m.group(0)) // 2), "10 20 30 40 50"))

def A():
    return "A"
print(re.sub('a', A(), 'aBCBABCDabcda.'))

print(
    re.sub(
        r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', 
        'static PyObject*\npy_\\1(void){\n  return;\n}\n', 
        '\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():'
    )
) 
# test re.sub with unmatched groups, behaviour changed in CPython 3.5

try:
    import ure as re
except ImportError:
    try:
        import re
    except ImportError:
        print("SKIP")
        raise SystemExit

try:
    re.sub
except AttributeError:
    print("SKIP")
    raise SystemExit

# first group matches, second optional group doesn't so is replaced with a blank
print(re.sub(r"(a)(b)?", r"\2-\1", "1a2"))