Exemplo n.º 1
13
def updateStats():
    # Download the JSON file
    s = usocket.socket()
    try:
        s.connect(connectto[0][4])

        s.send("GET /api/\r\n")
        output = s.recv(4096)
        s.close()
    except Exception as e:
        sys.print_exception(e)
        curIn.text("NET")
        curOut.text("GONE?")
        time.sleep(5)
        return

    # Decode the JSON
    print(output)
    try:
        data = ujson.loads(output)
    except Exception as e:
        sys.print_exception(e)
        curIn.text("JSON")
        curOut.text("ERROR")
        return

    # Update the display

    curIn.text("%.0f Mbps" % (data['uplink_in'] / 1000000))
    curOut.text("%.0f Mbps" % (data['uplink_out'] / 1000000))
Exemplo n.º 2
0
def open_http_socket(method, url, json=None, timeout=None, headers=None, urlencoded = None):
	urlparts = url.split('/', 3)
	proto = urlparts[0]
	host = urlparts[2]
	urlpath = '' if len(urlparts) < 4 else urlparts[3]

	if proto == 'http:':
		port = 80
	elif proto == 'https:':
		port = 443
	else:
		raise OSError('Unsupported protocol: %s' % proto[:-1])

	if ':' in host:
		host, port = host.split(':')
		port = int(port)

	if json is not None:
		content = ujson.dumps(json)
		content_type = CONTENT_TYPE_JSON
	elif urlencoded is not None:
		content = urlencoded
		content_type = "application/x-www-form-urlencoded"
	else:
		content = None

	# ToDo: Handle IPv6 addresses
	if is_ipv4_address(host):
		addr = (host, port)
	else:
		ai = usocket.getaddrinfo(host, port)
		addr = ai[0][4]

	sock = None
	if proto == 'https:':
		sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM, usocket.SEC_SOCKET)
	else:
		sock = usocket.socket()

	sock.connect(addr)
	if proto == 'https:':
		sock.settimeout(0) # Actually make timeouts working properly with ssl

	sock.send('%s /%s HTTP/1.0\r\nHost: %s\r\n' % (method, urlpath, host))

	if headers is not None:
		for header in headers.items():
			sock.send('%s: %s\r\n' % header)

	if content is not None:
		sock.send('content-length: %s\r\n' % len(content))
		sock.send('content-type: %s\r\n' % content_type)
		sock.send('\r\n')
		sock.send(content)
	else:
		sock.send('\r\n')

	return sock
Exemplo n.º 3
0
    def start(self):
        """
        Starts the LoRaWAN nano gateway.
        """

        self._log('Starting LoRaWAN nano gateway with id: {}', self.id)

        # setup WiFi as a station and connect
        self.wlan = WLAN(mode=WLAN.STA)
        self._connect_to_wifi()

        # get a time sync
        self._log('Syncing time with {} ...', self.ntp_server)
        self.rtc.ntp_sync(self.ntp_server, update_period=self.ntp_period)
        while not self.rtc.synced():
            utime.sleep_ms(50)
        self._log("RTC NTP sync complete")

        # get the server IP and create an UDP socket
        self.server_ip = usocket.getaddrinfo(self.server, self.port)[0][-1]
        self._log('Opening UDP socket to {} ({}) port {}...', self.server, self.server_ip[0], self.server_ip[1])
        self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM, usocket.IPPROTO_UDP)
        self.sock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
        self.sock.setblocking(False)

        # push the first time immediatelly
        self._push_data(self._make_stat_packet())

        # create the alarms
        self.stat_alarm = Timer.Alarm(handler=lambda t: self._push_data(self._make_stat_packet()), s=60, periodic=True)
        self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(), s=25, periodic=True)

        # start the UDP receive thread
        self.udp_stop = False
        _thread.start_new_thread(self._udp_thread, ())

        # initialize the LoRa radio in LORA mode
        self._log('Setting up the LoRa radio at {:.1f} Mhz using {}', self._freq_to_float(self.frequency), self.datarate)
        self.lora = LoRa(
            mode=LoRa.LORA,
            frequency=self.frequency,
            bandwidth=self.bw,
            sf=self.sf,
            preamble=8,
            coding_rate=LoRa.CODING_4_5,
            tx_iq=True
        )

        # create a raw LoRa socket
        self.lora_sock = usocket.socket(usocket.AF_LORA, usocket.SOCK_RAW)
        self.lora_sock.setblocking(False)
        self.lora_tx_done = False

        self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self._lora_cb)
        self._log('LoRaWAN nano gateway online')
Exemplo n.º 4
0
def main(use_stream=False):
    s = socket.socket()

    # Binding to all interfaces - server will be accessible to other hosts!
    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/")

    counter = 0
    while True:
        res = s.accept()
        client_s = res[0]
        client_addr = res[1]
        print("Client address:", client_addr)
        print("Client socket:", client_s)
        print("Request:")
        if use_stream:
            # MicroPython socket objects support stream (aka file) interface
            # directly.
            print(client_s.read(4096))
            client_s.write(CONTENT % counter)
        else:
            print(client_s.recv(4096))
            client_s.send(CONTENT % counter)
        client_s.close()
        counter += 1
        print()
Exemplo n.º 5
0
 def connect(self, clean_session=True):
     self.sock = socket.socket()
     self.sock.connect(self.addr)
     if self.ssl:
         import ussl
         self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
     msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0")
     msg[1] = 10 + 2 + len(self.client_id)
     msg[9] = clean_session << 1
     if self.user is not None:
         msg[1] += 2 + len(self.user) + 2 + len(self.pswd)
         msg[9] |= 0xC0
     if self.keepalive:
         assert self.keepalive < 65536
         msg[10] |= self.keepalive >> 8
         msg[11] |= self.keepalive & 0x00FF
     if self.lw_topic:
         msg[1] += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
         msg[9] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
         msg[9] |= self.lw_retain << 5
     self.sock.write(msg)
     #print(hex(len(msg)), hexlify(msg, ":"))
     self._send_str(self.client_id)
     if self.lw_topic:
         self._send_str(self.lw_topic)
         self._send_str(self.lw_msg)
     if self.user is not None:
         self._send_str(self.user)
         self._send_str(self.pswd)
     resp = self.sock.read(4)
     assert resp[0] == 0x20 and resp[1] == 0x02
     if resp[3] != 0:
         raise MQTTException(resp[3])
     return resp[2] & 1
Exemplo n.º 6
0
def test(peer_addr):
    s = socket.socket()
    s.connect(peer_addr)
    s = ssl.wrap_socket(s)
    cert = s.getpeercert(True)
    print(type(cert), len(cert) > 100)
    s.close()
def request(method, url, json=None, timeout=None, headers=None):
    urlparts = url.split('/', 3)
    proto = urlparts[0]
    host = urlparts[2]
    urlpath = '' if len(urlparts) < 4 else urlparts[3]

    if proto == 'http:':
        port = 80
    elif proto == 'https:':
        port = 443
    else:
        raise OSError('Unsupported protocol: %s' % proto[:-1])

    if ':' in host:
        host, port = host.split(':')
        port = int(port)

    if json is not None:
        content = ujson.dumps(json)
        content_type = CONTENT_TYPE_JSON
    else:
        content = None

    ai = usocket.getaddrinfo(host, port)
    addr = ai[0][4]

    sock = usocket.socket()

    if timeout is not None:
        assert SUPPORT_TIMEOUT, 'Socket does not support timeout'
        sock.settimeout(timeout)

    sock.connect(addr)

    if proto == 'https:':
        assert SUPPORT_SSL, 'HTTPS not supported: could not find ussl'
        sock = ussl.wrap_socket(sock)

    sock.write('%s /%s HTTP/1.0\r\nHost: %s\r\n' % (method, urlpath, host))

    if headers is not None:
        for header in headers.items():
            sock.write('%s: %s\r\n' % header)

    if content is not None:
        sock.write('content-length: %s\r\n' % len(content))
        sock.write('content-type: %s\r\n' % content_type)
        sock.write('\r\n')
        sock.write(content)
    else:
        sock.write('\r\n')

    l = sock.readline()
    protover, status, msg = l.split(None, 2)

    # Skip headers
    while sock.readline() != b'\r\n':
        pass

    return Response(int(status), sock)
Exemplo n.º 8
0
def main_client(addr):
    nic = network.WIZNET5K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4)
    nic.ifconfig((SENSOR_IP, SENSOR_MASK, SENSOR_GATEWAY, SENSOR_DNS))
    # print(nic.ifconfig())
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    count = 0
    try:
        s.connect(addr)
    except:
        pass
    data = {
        'serial_no':'1234567890',
        'ip':SENSOR_IP,
        'op':gOperator['OP_REGISTER'],
        'type':gSensorType['TEMPERATURE']
    }
    DHT22.init()
    while True:
        pyb.delay(100)
        hum, tem = measure()
        print('%d hum:%f, tem:%f' % (count,hum, tem))
        data['value'] = {'hum':hum, 'tem':tem}
        count += 1

        try:
            send(s, 'post', '/test_pymagic', data)
            print(s.recv(4096))
        except:
            pass
        pyb.delay(1000)
Exemplo n.º 9
0
def open_connection(host, port, ssl=False):
    if DEBUG and __debug__:
        log.debug("open_connection(%s, %s)", host, port)
    ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
    ai = ai[0]
    s = _socket.socket(ai[0], ai[1], ai[2])
    s.setblocking(False)
    try:
        s.connect(ai[-1])
    except OSError as e:
        if e.args[0] != uerrno.EINPROGRESS:
            raise
    if DEBUG and __debug__:
        log.debug("open_connection: After connect")
    yield IOWrite(s)
#    if __debug__:
#        assert s2.fileno() == s.fileno()
    if DEBUG and __debug__:
        log.debug("open_connection: After iowait: %s", s)
    if ssl:
        print("Warning: uasyncio SSL support is alpha")
        import ussl
        s.setblocking(True)
        s2 = ussl.wrap_socket(s)
        s.setblocking(False)
        return StreamReader(s, s2), StreamWriter(s2, {})
    return StreamReader(s), StreamWriter(s, {})
Exemplo n.º 10
0
def urlopen(url, data=None):
    if data:
        raise NotImplementedError("POST is not yet supported")
    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto != "http:":
        raise ValueError("Unsupported protocol: " + proto)

    ai = usocket.getaddrinfo(host, 80)
    addr = ai[0][4]
    s = usocket.socket()
    s.connect(addr)
    s.send(b"GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (path, host))

    l = s.readline()
    protover, status, msg = l.split(None, 2)
    status = int(status)
    #print(protover, status, msg)
    while True:
        l = s.readline()
        if not l or l == b"\r\n":
            break
        #print(line)
        if l.startswith(b"Transfer-Encoding:"):
            if b"chunked" in line:
                raise ValueError("Unsupported " + l)
        elif l.startswith(b"Location:"):
            raise NotImplementedError("Redirects not yet supported")

    return s
Exemplo n.º 11
0
    def download(url, local_name):
        proto, _, host, urlpath = url.split('/', 3)
        ai = usocket.getaddrinfo(host, 443)
        #print("Address infos:", ai)
        addr = ai[0][4]

        s = usocket.socket()
        #print("Connect address:", addr)
        s.connect(addr)

        if proto == "https:":
            s = ussl.wrap_socket(s)

        # MicroPython rawsocket module supports file interface directly
        s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
        l = s.readline()
        protover, status, msg = l.split(None, 2)
        if status != b"200":
            raise OSError()
        while 1:
            l = s.readline()
            if not l:
                raise OSError()
            if l == b'\r\n':
                break
        with open(local_name, "wb") as f:
            while 1:
                l = s.read(1024)
                if not l:
                    break
                f.write(l)
Exemplo n.º 12
0
def main(use_stream=True):
    s = _socket.socket()

    ai = _socket.getaddrinfo("google.com", 443)
    print("Address infos:", ai)
    addr = ai[0][-1]

    print("Connect address:", addr)
    s.connect(addr)

    s = ssl.wrap_socket(s)
    print(s)

    if use_stream:
        # Both CPython and MicroPython SSLSocket objects support read() and
        # write() methods.
        s.write(b"GET / HTTP/1.0\n\n")
        print(s.read(4096))
    else:
        # MicroPython SSLSocket objects implement only stream interface, not
        # socket interface
        s.send(b"GET / HTTP/1.0\n\n")
        print(s.recv(4096))

    s.close()
Exemplo n.º 13
0
def url_open(url):
    global warn_ussl
    proto, _, host, urlpath = url.split('/', 3)
    ai = usocket.getaddrinfo(host, 443)
    #print("Address infos:", ai)
    addr = ai[0][4]

    s = usocket.socket(ai[0][0])
    #print("Connect address:", addr)
    s.connect(addr)

    if proto == "https:":
        s = ussl.wrap_socket(s)
        if warn_ussl:
            print("Warning: %s SSL certificate is not validated" % host)
            warn_ussl = False

    # MicroPython rawsocket module supports file interface directly
    s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
    l = s.readline()
    protover, status, msg = l.split(None, 2)
    if status != b"200":
        if status == b"404":
            print("Package not found")
        raise ValueError(status)
    while 1:
        l = s.readline()
        if not l:
            raise ValueError("Unexpected EOF")
        if l == b'\r\n':
            break

    return s
Exemplo n.º 14
0
 def __init__(self, host, port=HTTP_PORT):
     self.host = host
     self.port = int(port)
     addr_info = socket.getaddrinfo(host, port)
     self.addr = addr_info[0][-1]
     self.connected = False
     self.socket = socket.socket()
Exemplo n.º 15
0
def urlopen(url, data=None, method="GET"):
    if data is not None and method == "GET":
        method = "POST"
    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto == "http:":
        port = 80
    elif proto == "https:":
        import ussl
        port = 443
    else:
        raise ValueError("Unsupported protocol: " + proto)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)

    ai = usocket.getaddrinfo(host, port)
    addr = ai[0][4]
    s = usocket.socket()
    s.connect(addr)
    if proto == "https:":
        s = ussl.wrap_socket(s, server_hostname=host)

    s.write(method)
    s.write(b" /")
    s.write(path)
    s.write(b" HTTP/1.0\r\nHost: ")
    s.write(host)
    s.write(b"\r\n")

    if data:
        s.write(b"Content-Length: ")
        s.write(str(len(data)))
        s.write(b"\r\n")
    s.write(b"\r\n")
    if data:
        s.write(data)

    l = s.readline()
    protover, status, msg = l.split(None, 2)
    status = int(status)
    #print(protover, status, msg)
    while True:
        l = s.readline()
        if not l or l == b"\r\n":
            break
        #print(l)
        if l.startswith(b"Transfer-Encoding:"):
            if b"chunked" in l:
                raise ValueError("Unsupported " + l)
        elif l.startswith(b"Location:"):
            raise NotImplementedError("Redirects not yet supported")

    return s
Exemplo n.º 16
0
def request(method, url, data=None, json=None, headers={}, stream=None):
    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto == "http:":
        port = 80
    elif proto == "https:":
        import ussl
        port = 443
    else:
        raise ValueError("Unsupported protocol: " + proto)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)

    ai = usocket.getaddrinfo(host, port)
    addr = ai[0][4]
    s = usocket.socket()
    s.connect(addr)
    if proto == "https:":
        s = ussl.wrap_socket(s)
    s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
    if not "Host" in headers:
        s.write(b"Host: %s\r\n" % host)
    if json is not None:
        assert data is None
        import ujson
        data = ujson.dumps(json)
    if data:
        s.write(b"Content-Length: %d\r\n" % len(data))
    s.write(b"\r\n")
    if data:
        s.write(data)

    l = s.readline()
    protover, status, msg = l.split(None, 2)
    status = int(status)
    #print(protover, status, msg)
    while True:
        l = s.readline()
        if not l or l == b"\r\n":
            break
        #print(line)
        if l.startswith(b"Transfer-Encoding:"):
            if b"chunked" in line:
                raise ValueError("Unsupported " + l)
        elif l.startswith(b"Location:"):
            raise NotImplementedError("Redirects not yet supported")

    resp = Response(s)
    resp.status_code = status
    resp.reason = msg.rstrip()
    return resp
Exemplo n.º 17
0
    def __init__(self, ip=config.UDP_IP, port=config.UDP_PORT, num_leds=240):

        # Init and clear LED Strip
        self.ledstrip = driver.LedStrip(num_leds)
        self.ledstrip.clear()
        self.ledstrip.send()

        # Init UDP-Socket listener
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind((ip, port))
Exemplo n.º 18
0
def connectSocket():
    # connect to artnet port
    sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
    # sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # addr = socket.getaddrinfo(UDP_IP, UDP_PORT, socket.AF_INET, socket.SOCK_DGRAM)[0][4]
    # print(addr)
    sock.bind((UDP_IP, UDP_PORT))
    # sock.settimeout(1)
    sock.setblocking(0)
    return sock
Exemplo n.º 19
0
def main():
    server = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    server.bind(("0.0.0.0", 1080))
    server.listen(3)

    while True:
        sock, addr = server.accept()
        print("Accepted", addr)
        handle(sock)
        print("Closing", addr)
        sock.close()
Exemplo n.º 20
0
def ntp(): # noqa
    ntp_query = bytearray(48)
    ntp_query[0] = 0x1b
    addr = socket.getaddrinfo('pool.ntp.org', 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(1)
    s.sendto(ntp_query, addr)
    msg = s.recv(48)
    s.close()
    val = struct.unpack("!I", msg[40:44])[0]
    return val - NTP_DELTA
Exemplo n.º 21
0
def main():

    if len(sys.argv) != 3:
        help(1)

    if ":" in sys.argv[1] and ":" in sys.argv[2]:
        error("Operations on 2 remote files are not supported")
    if ":" not in sys.argv[1] and ":" not in sys.argv[2]:
        error("One remote file is required")

    if ":" in sys.argv[1]:
        op = "get"
        host, port, src_file = parse_remote(sys.argv[1])
        dst_file = sys.argv[2]
        if os.path.isdir(dst_file):
            basename = src_file.rsplit("/", 1)[-1]
            dst_file += "/" + basename
    else:
        op = "put"
        host, port, dst_file = parse_remote(sys.argv[2])
        src_file = sys.argv[1]
        if dst_file[-1] == "/":
            basename = src_file.rsplit("/", 1)[-1]
            dst_file += basename

    if 1:
        print(op, host, port)
        print(src_file, "->", dst_file)

    s = socket.socket()

    ai = socket.getaddrinfo(host, port)
    addr = ai[0][4]

    s.connect(addr)
    #s = s.makefile("rwb")
    websocket_helper.client_handshake(s)

    ws = websocket(s)

    import getpass
    passwd = getpass.getpass()
    login(ws, passwd)
    print("Remote WebREPL version:", get_ver(ws))

    # Set websocket to send data marked as "binary"
    ws.ioctl(9, 2)

    if op == "get":
        get_file(ws, dst_file, src_file)
    elif op == "put":
        put_file(ws, src_file, dst_file)

    s.close()
Exemplo n.º 22
0
def time():
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1b
    addr = socket.getaddrinfo(host, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(1)
    res = s.sendto(NTP_QUERY, addr)
    msg = s.recv(48)
    s.close()
    val = struct.unpack("!I", msg[40:44])[0]
    return val - NTP_DELTA
Exemplo n.º 23
0
def http_post(url):
    _, _, host, path = url.split('/', 3)
    addr = usocket.getaddrinfo(host, 80)[0][-1]
    s = usocket.socket()
    s.connect(addr)
    s.send(bytes('POST /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
    while True:
        data = s.recv(100)
        if data:
            print(str(data, 'utf8'), end='')
        else:
            break
Exemplo n.º 24
0
 def __init__(self, server, port=61440):
     self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     self.addr = socket.getaddrinfo(server, port)[0][4]
     self.addr2 = socket.getaddrinfo('0.0.0.0', port)[0][4]
     self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self.s.bind(self.addr2)
     # self.s.settimeout(3)
     self.s.connect(self.addr)
     log("open local port:" + str(port))
     log("DEBUG MODE:"+ str(DEBUG))
     self.server = server
     self.port = port
Exemplo n.º 25
0
 def connect(self):
     try:
         print('Connecting to {}:{}'.format(self.host, self.port))
         self.socket = usocket.socket()
         self.socket.connect(self.socket_addr)
         print('Connected')
         self.is_connected = True
     except Exception as e:
         print('Could not connect to {}:{} due to: {}: {}'.format(
             self.host, self.port, type(e), e)
         )
     return self.is_connected
Exemplo n.º 26
0
 def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
     """Constructor.  May be extended, do not override."""
     BaseServer.__init__(self, server_address, RequestHandlerClass)
     self.socket = socket.socket(self.address_family,
                                 self.socket_type)
     if bind_and_activate:
         try:
             self.server_bind()
             self.server_activate()
         except:
             self.server_close()
             raise
def scan():
    sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
    try:
        if hasattr(sock, 'settimeout'):
            sock.settimeout(TIMEOUT)

        addrs = usocket.getaddrinfo(MCAST_IP, MCAST_PORT)
        sock.sendto(QUERY, addrs[0][4])
        data, addr = sock.recvfrom(1024)
        return ujson.loads(data.decode('utf-8'))
    finally:
        sock.close()
Exemplo n.º 28
0
def update(file="main.py"):
    s = socket.socket()

    ai = socket.getaddrinfo("192.168.1.101", 8000)
    print("Address infos:", ai)
    addr = ai[0][-1]

    print("Connect address:", addr)
    s.connect(addr)
    s = s.makefile("rwb", 0)
    s.write(b"GET /{} HTTP/1.0\n\n".format(file))
    open(file, "w").write(s.read())
Exemplo n.º 29
0
def alert():
    """
    Alert the remove server of a moisture event!
    """ 
    # Connect to the remote listener
    ipv4_socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    ipv4_socket.connect(listener_addr)
    # Notify
    msg = "V:"+str(apin())
    bytes_type = 'ascii'
    msg_bytes = bytes('GET /{}'.format(msg), bytes_type)
    ipv4_socket.sendall(msg_bytes)
    ipv4_socket.close()
Exemplo n.º 30
0
 def __init__(self,
              callback = None,
              websocket_handler = None,
              addr = ("0.0.0.0", 80),
              backlog = 3,
             ):
     self.callback = callback
     self.websocket_handler = websocket_handler
     self.websockets = []
     self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.s.setblocking(False)
     self.s.bind( socket.getaddrinfo(addr[0], addr[1])[0][-1] )
     self.s.listen(backlog)
Exemplo n.º 31
0
    def request(self, method, url, data=None, json=None, headers={}, stream=None):
        try:
            proto, dummy, host, path = url.split('/', 3)
        except ValueError:
            proto, dummy, host = url.split('/', 2)
            path = ''
        if proto == 'http:':
            port = 80
        elif proto == 'https:':
            import ussl
            port = 443
        else:
            raise ValueError('Unsupported protocol: ' + proto)

        if ':' in host:
            host, port = host.split(':', 1)
            port = int(port)

        ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
        ai = ai[0]

        s = usocket.socket(ai[0], ai[1], ai[2])
        try:
            s.connect(ai[-1])
            if proto == 'https:':
                s = ussl.wrap_socket(s, server_hostname=host)
            s.write(b'%s /%s HTTP/1.0\r\n' % (method, path))
            if not 'Host' in headers:
                s.write(b'Host: %s\r\n' % host)
            # Iterate over keys to avoid tuple alloc
            for k in headers:
                s.write(k)
                s.write(b': ')
                s.write(headers[k])
                s.write(b'\r\n')
            # add user agent
            s.write('User-Agent')
            s.write(b': ')
            s.write('MicroPython OTAUpdater')
            s.write(b'\r\n')
            if json is not None:
                assert data is None
                import ujson
                data = ujson.dumps(json)
                s.write(b'Content-Type: application/json\r\n')
            if data:
                s.write(b'Content-Length: %d\r\n' % len(data))
            s.write(b'\r\n')
            if data:
                s.write(data)

            l = s.readline()
            # print(l)
            l = l.split(None, 2)
            status = int(l[1])
            reason = ''
            if len(l) > 2:
                reason = l[2].rstrip()
            while True:
                l = s.readline()
                if not l or l == b'\r\n':
                    break
                # print(l)
                if l.startswith(b'Transfer-Encoding:'):
                    if b'chunked' in l:
                        raise ValueError('Unsupported ' + l)
                elif l.startswith(b'Location:') and not 200 <= status <= 299:
                    raise NotImplementedError('Redirects not yet supported')
        except OSError:
            s.close()
            raise

        resp = Response(s)
        resp.status_code = status
        resp.reason = reason
        return resp
Exemplo n.º 32
0
    elif method == b"GET":
        if path == b"/":
            ok(socket, query)
        else:
            err(socket, "404", "Not Found")
    elif method == b"POST":
        if path == b"/on":
            pin.on()
            ok(socket, query)
        elif path == b"/off":
            pin.off()
            ok(socket, query)
        else:
            err(socket, "404", "Not Found")
    else:
        err(socket, "501", "Not Implemented")


server = usocket.socket()
server.bind(('192.168.0.116', 80))
server.listen(1)
while True:
    try:

        (socket, sockaddr) = server.accept()
        handle(socket)
    except:
        socket.write("HTTP/1.1 500 Internal Server Error\r\n\r\n")
        socket.write("<h1>Internal Server Error</h1>")
    socket.close()
Exemplo n.º 33
0
    def connect(self, clean_session=True):

        self.sock = socket.socket()

        addr = socket.getaddrinfo(self.server, self.port)[0][-1]

        self.sock.connect(addr)

        if self.ssl:

            import ussl

            self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)

        premsg = bytearray(b"\x10\0\0\0\0\0")

        msg = bytearray(b"\x04MQTT\x04\x02\0\0")

        sz = 10 + 2 + len(self.client_id)

        msg[6] = clean_session << 1

        if self.user is not None:

            sz += 2 + len(self.user) + 2 + len(self.pswd)

            msg[6] |= 0xC0

        if self.keepalive:

            assert self.keepalive < 65536

            msg[7] |= self.keepalive >> 8

            msg[8] |= self.keepalive & 0x00FF

        if self.lw_topic:

            sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)

            msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3

            msg[6] |= self.lw_retain << 5

        i = 1

        while sz > 0x7f:

            premsg[i] = (sz & 0x7f) | 0x80

            sz >>= 7

            i += 1

        premsg[i] = sz

        self.sock.write(premsg, i + 2)

        self.sock.write(msg)

        #print(hex(len(msg)), hexlify(msg, ":"))

        self._send_str(self.client_id)

        if self.lw_topic:

            self._send_str(self.lw_topic)

            self._send_str(self.lw_msg)

        if self.user is not None:

            self._send_str(self.user)

            self._send_str(self.pswd)

        resp = self.sock.read(4)

        assert resp[0] == 0x20 and resp[1] == 0x02

        if resp[3] != 0:

            raise MQTTException(resp[3])

        return resp[2] & 1
Exemplo n.º 34
0
 def __init__(self, client_address, RequestHandlerClass):
     self.client_address = client_address
     self.RequestHandlerClass = RequestHandlerClass
     self.socket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
Exemplo n.º 35
0
def main():

    #conectamos a wifi segun configuracion en datos.dat
    configuracion.convertir()
    indice = 0
    wlan = network.WLAN(network.STA_IF)
    aplan = network.WLAN(network.AP_IF)
    aplan.active(False)
    wlan.active(True)
    # si forzar es True, se forzara el ip al determinado en datos.dat, sino se utilizara el que determine el router.
    if configuracion.forzar == True:
        wlan.ifconfig(configuracion.ST_CONF)
    tiempo = utime.time()
    wlan.connect(configuracion.ST_SSID, configuracion.ST_PASSW)
    while not wlan.isconnected():
        if utime.time() - tiempo_espera > tiempo:
            break
    if wlan.isconnected():
        msg_inicio = "conectado como ST en: " + str(wlan.ifconfig()[0])
        print(msg_inicio)
        #--------------------------------------------------------------
        #Aqui llamariamos a la funcion o modulo principal del programa.
        #--------------------------------------------------------------
        print('fin del programa. todo ok')  #y eliminar esta linea.


#Cuando falla sta se crea un ap y se debe conectar en el y en un navegador enviar: [192.168.4.1/<SSID>,<PASSW>]
#el chip se reseteara con la nueva configuracion, y si no es correcta, volvera al ap de nuevo para reconfigurar.

    else:
        tipo = []
        motivo = []
        valores = configuracion.lee()
        pagina = crea_pagina(valores)
        wlan.active(False)
        aplan.active(True)
        aplan.ifconfig(configuracion.AP_CONF)
        aplan.config(essid=configuracion.AP_SSID,
                     password=configuracion.AP_PASSW)
        print("Conectado como AP en:", aplan.ifconfig())
        p0 = Pin(piloto, Pin.OUT)
        if invertir:
            p0.value(0)
        else:
            p0.value(1)
        confserv = ("", 80)
        serv_socket = usocket.socket()
        serv_socket.bind(confserv)
        serv_socket.listen(1)
        while True:
            conn, addr = serv_socket.accept()
            recepcion = ''
            datos = ''
            datos = conn.readline()
            while datos != b'':
                recepcion += (datos.decode())
                datos = conn.readline()
                if datos == b'\r\n':
                    break
            if recepcion != '':
                lineas = recepcion.splitlines()
                nombres = lineas[0].split(' ')
                tipo = nombres[0]  #'GET' o 'POST'
                motivo = nombres[1]  # '/' o 'configura.html'
            else:
                print('no llegaron datos validos')
            a = ['GET', '/']
            if tipo == 'GET' and motivo == '/':
                conn.sendall(pagina)
                conn.close()
            elif tipo == 'POST' and motivo == '/configura.html':
                for linea in lineas:
                    valores_linea = separa_por_espacios.split(linea)
                    nombre_dato = valores_linea[0]
                    if nombre_dato == 'Content-Length:':
                        longitud = int(valores_linea[1])
                datos = conn.read(longitud).decode()

                #         modifica respuestas para poder ingresarlas en el archivo de configuracion
                #                 resultados = separa_por_and.split(datos)
                resultados = datos.split('&')
                for resultado in resultados:
                    resultado_ok = resultado.replace("%27", "'")
                    resultado = resultado_ok.replace("%5B", "[")
                    resultado_ok = resultado.replace("%5D", "]")
                    resultado = resultado_ok.replace("%2C", ",")
                    resultado_ok = resultado.replace("%3A", ":")
                    k, v = resultado_ok.split("=")
                    configuracion.unir(k, v)
                conn.send(
                    b'HTTP/1.1 200 OK\r\nContent-Type: text/html \r\nConnection: close \r\n\r\n<html><body>Cambios realizados</body></html>\r\n\r\n'
                )
                conn.close()
                ahora = utime.time()
                while utime.time() - 5 > ahora:
                    pass
                break
            else:
                conn.send(
                    b'HTTP/1.1 404 Not Found\r\nContent-Type: text/html \r\nConnection: close \r\n\r\n<html><body>Pagina no aceptada</body></html>\r\n\r\n'
                )
                conn.close()
        serv_socket.close()
        if invertir:
            p0.value(1)
        else:
            p0.value(0)
        configuracion.reinicia()
Exemplo n.º 36
0
def request(method, url, data=None, json=None, headers={}, stream=None):
    try:
        request_sema.acquire(1)
        try:
            proto, dummy, host, path = url.split("/", 3)
        except ValueError:
            proto, dummy, host = url.split("/", 2)
            path = ""
        if proto == "http:":
            port = 80
        elif proto == "https:":
            import ussl
            port = 443
        else:
            raise ValueError("Unsupported protocol: " + proto)

        if ":" in host:
            host, port = host.split(":", 1)
            port = int(port)

        ai = usocket.getaddrinfo(host, port)
        addr = ai[0][4]
        s = usocket.socket()
        s.connect(addr)
        if proto == "https:":
            s = ussl.wrap_socket(s)
        s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
        if not "Host" in headers:
            s.write(b"Host: %s\r\n" % host)
        # Iterate over keys to avoid tuple alloc
        for k in headers:
            s.write(k)
            s.write(b": ")
            s.write(headers[k])
            s.write(b"\r\n")
        if json is not None:
            assert data is None
            import ujson
            data = ujson.dumps(json)
        if data:
            s.write(b"Content-Length: %d\r\n" % len(data))
        s.write(b"\r\n")
        if data:
            s.write(data)

        l = s.readline()
        protover, status, msg = l.split(None, 2)
        status = int(status)
        #print(protover, status, msg)
        while True:
            l = s.readline()
            if not l or l == b"\r\n":
                break
            #print(l)
            if l.startswith(b"Transfer-Encoding:"):
                if b"chunked" in l:
                    raise ValueError("Unsupported " + l)
            elif l.startswith(b"Location:") and not 200 <= status <= 299:
                raise NotImplementedError("Redirects not yet supported")

        resp = Response(s)
        resp.status_code = status
        resp.reason = msg.rstrip()
        request_sema.release()
        return resp
    except Exception as e:
        print('uquest: ' + str(e))
        request_sema.release()
        return ''
Exemplo n.º 37
0
def postBodyFromFile(url, headers, file):

    print("postBodyFromFile")
    mylib.collectMemory()
    #print(mylib.reportMemory())  # for debug

    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto == "https:":
        port = 443
    else:
        raise ValueError("Unsupported protocol: " + proto)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)

    ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
    ai = ai[0]

    s = usocket.socket(ai[0], ai[1], ai[2])
    try:
        s.connect(ai[-1])
        s = wrap_socket(s, server_hostname=host)
        s.write(b"%s /%s HTTP/1.0\r\n" % ('POST', path))
        if not "Host" in headers:
            s.write(b"Host: %s\r\n" % host)
        # Iterate over keys to avoid tuple alloc
        for k in headers:
            s.write(k)
            s.write(b": ")
            s.write(headers[k])
            s.write(b"\r\n")

        size = mylib.getFileSize(file)
        if size == None:
            raise ValueError("FileSize is None")
        s.write(b"Content-Length: %d\r\n" % size)
        s.write(b"\r\n")

        with open(file, 'rb') as fp:
            buffer = bytearray(FILEBUFSIZE)
            while True:
                if DBG_MEMORY_REPORT:
                    print(mylib.reportMemory())  # for debug
                size = fp.readinto(buffer, FILEBUFSIZE)
                if size == 0:
                    break
                else:
                    s.write(buffer, FILEBUFSIZE)
            buffer = None
        l = s.readline()
        l = l.split(None, 2)
        status = int(l[1])
        reason = ""
        if len(l) > 2:
            reason = l[2].rstrip()
        while True:
            l = s.readline()
            if not l or l == b"\r\n":
                break
            if l.startswith(b"Transfer-Encoding:"):
                if b"chunked" in l:
                    raise ValueError("Unsupported " + l)
            elif l.startswith(b"Location:") and not 200 <= status <= 299:
                raise NotImplementedError("Redirects not yet supported")
    except OSError:
        s.close()
        raise

    resp = Response(s)
    resp.status_code = status
    resp.reason = reason
    return resp
Exemplo n.º 38
0
def request(method, url, data=None, json=None, headers={}, stream=None):
    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto == "http:":
        port = 80
    elif proto == "https:":
        import ussl
        port = 443
    else:
        raise ValueError("Unsupported protocol: " + proto)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)

    ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
    ai = ai[0]

    s = usocket.socket(ai[0], ai[1], ai[2])
    try:
        s.connect(ai[-1])
        if proto == "https:":
            s = ussl.wrap_socket(s, server_hostname=host)
        s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
        if not "Host" in headers:
            s.write(b"Host: %s\r\n" % host)
        # Iterate over keys to avoid tuple alloc
        for k in headers:
            s.write(k)
            s.write(b": ")
            s.write(headers[k])
            s.write(b"\r\n")
        if json is not None:
            assert data is None
            import ujson
            data = ujson.dumps(json)
            s.write(b"Content-Type: application/json\r\n")
        if data:
            s.write(b"Content-Length: %d\r\n" % len(data))
        s.write(b"\r\n")
        if data:
            s.write(data)

        l = s.readline()
        #print(l)
        l = l.split(None, 2)
        status = int(l[1])
        reason = ""
        if len(l) > 2:
            reason = l[2].rstrip()
        while True:
            l = s.readline()
            if not l or l == b"\r\n":
                break
            #print(l)
            if l.startswith(b"Transfer-Encoding:"):
                if b"chunked" in l:
                    raise ValueError("Unsupported " + l)
            elif l.startswith(b"Location:") and not 200 <= status <= 299:
                raise NotImplementedError("Redirects not yet supported")
    except OSError:
        s.close()
        raise

    resp = Response(s)
    resp.status_code = status
    resp.reason = reason
    return resp
Exemplo n.º 39
0
def ping(host, count=4, timeout=5000, interval=1000, quiet=False, size=64):
    raise Exception('Unsupported! Leaks memory!')
    # print('ping')
    import utime
    import uselect
    import uctypes
    import usocket
    import ustruct
    import machine

    # round up fractional values
    interval = max(1, int(interval))

    # avoid count==0
    count = max(count, 1)

    # prepare packet
    assert size >= 16, "pkt size too small"
    pkt = b'Q' * size
    pkt_desc = {
        "type": uctypes.UINT8 | 0,
        "code": uctypes.UINT8 | 1,
        "checksum": uctypes.UINT16 | 2,
        "id": uctypes.UINT16 | 4,
        "seq": uctypes.INT16 | 6,
        "timestamp": uctypes.UINT64 | 8,
    }  # packet header descriptor
    h = uctypes.struct(uctypes.addressof(pkt), pkt_desc, uctypes.BIG_ENDIAN)
    h.type = 8  # ICMP_ECHO_REQUEST
    h.code = 0
    h.checksum = 0
    h.id = machine.rng()
    h.seq = 1

    # init socket
    sock = usocket.socket(usocket.AF_INET, 3, 1)  # usocket.SOCK_RAW, 1)
    sock.setblocking(0)
    sock.settimeout(timeout / 1000)
    addr = usocket.getaddrinfo(host, 1)[0][-1][0]  # ip address
    sock.connect((addr, 1))
    not quiet and print("PING %s (%s): %u data bytes" % (host, addr, len(pkt)))

    seqs = list(range(1, count + 1))  # [1,2,...,count]
    c = 1
    t = 0
    n_trans = 0
    n_recv = 0
    time_s = 0
    finish = False
    # print('ping2')
    while t < timeout:
        if t == interval and c <= count:
            # send packet
            h.checksum = 0
            h.seq = c
            h.timestamp = utime.ticks_us()
            h.checksum = _checksum(pkt)
            if sock.send(pkt) == size:
                n_trans += 1
                t = 0  # reset timeout
            else:
                seqs.remove(c)
            c += 1

        # recv packet
        while 1:
            socks, _, _ = uselect.select([sock], [], [], 0)
            if socks:
                resp = socks[0].recv(4096)
                resp_mv = memoryview(resp)
                h2 = uctypes.struct(uctypes.addressof(resp_mv[20:]), pkt_desc,
                                    uctypes.BIG_ENDIAN)
                # TODO: validate checksum (optional)
                seq = h2.seq
                if h2.type == 0 and h2.id == h.id and (
                        seq in seqs):  # 0: ICMP_ECHO_REPLY
                    t_elasped = (utime.ticks_us() - h2.timestamp) / 1000
                    ttl = ustruct.unpack('!B', resp_mv[8:9])[0]  # time-to-live
                    n_recv += 1
                    not quiet and print(
                        "%u bytes from %s: icmp_seq=%u, ttl=%u, time=%.2f ms" %
                        (len(resp), addr, seq, ttl, t_elasped))
                    time_s += t_elasped
                    seqs.remove(seq)
                    if len(seqs) == 0:
                        finish = True
                        break
            else:
                break

        if finish:
            break

        #utime.sleep_ms(1)
        t += 1

    sock.close()
    loss = 0
    try:
        loss = (n_trans - n_recv) / n_trans * 100
    except:
        pass
    avg_ms = 0
    try:
        avg_ms = time_s / n_recv
    except:
        pass
    ret = (n_trans, n_recv, loss, avg_ms)
    not quiet and print(
        "%u packets transmitted, %u packets received, %.2f%% packet loss, %.2f ms avg"
        % ret)
    return ret
Exemplo n.º 40
0
    def get_data(self,
                 req,
                 dest_path=None,
                 hash=False,
                 hasher=uhashlib.sha512):
        # board firmware download is disabled as it needs to
        # be rewritten to not ignore the file hash
        firmware = False

        h = None

        # Connect to server
        print("Requesting: {}".format(req))
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                          socket.IPPROTO_TCP)
        s.settimeout(self.sockettimeout)
        s.connect((self.ip, self.port))

        # Request File
        s.sendall(self._http_get(req, "{}:{}".format(self.ip, self.port)))

        try:
            content = bytearray()
            fp = None
            if dest_path is not None:
                if firmware:
                    raise Exception("Cannot write firmware to a file")
                fp = open(dest_path, 'wb')

            if firmware:
                pycom.ota_start()

            h = hasher()

            # Get data from server
            result = s.recv(100)

            start_writing = False
            while (len(result) > 0):
                # Ignore the HTTP headers
                if not start_writing:
                    if "\r\n\r\n" in result:
                        start_writing = True
                        result = result.decode().split("\r\n\r\n")[1].encode()

                if start_writing:
                    if firmware:
                        pycom.ota_write(result)
                    elif fp is None:
                        content.extend(result)
                    else:
                        fp.write(result)

                    if hash:
                        h.update(result)

                result = s.recv(100)

            s.close()

            if fp is not None:
                fp.close()
            if firmware:
                pycom.ota_finish()

        except Exception as e:
            # Since only one hash operation is allowed at Once
            # ensure we close it if there is an error
            if h is not None:
                h.digest()
            raise e

        hash_val = ubinascii.hexlify(h.digest()).decode()

        if dest_path is None:
            if hash:
                return (bytes(content), hash_val)
            else:
                return bytes(content)
        elif hash:
            return hash_val
Exemplo n.º 41
0
def new_config(logger, arg):
    """
    Thread that turns on access point on the device to modify configurations. Name of access point: PmSensor
    Password: pmsensor Enter 192.168.4.10 on device browser to get configuration form. Indicator LEDs:
    Blue - Access point turned on, not connected, Green - Connected, configuration is open on browser,
    Red - An error has occured
    The device automatically reboots and applies modifications upon successful configuration.
    :param thread_name: Thread id
    :type thread_name: str
    :param logger: status logger
    :type logger: LoggerFactory object
    :param timeout: timeout (in seconds) for user configuration
    :type timeout: int
    """

    #  Only one of this thread is allowed to run at a time
    if not wifi_lock.locked():
        with wifi_lock:

            logger.info("New configuration setup started")

            # Config uses LED colours to indicate the state of the connection - lock is necessary to disable error pings
            led_lock.acquire(1)

            # set pycom up as access point
            wlan = network.WLAN(mode=WLAN.AP,
                                ssid=config.get_config("device_name"))
            # Connect to PmSensor using password set by the user
            wlan.init(mode=WLAN.AP,
                      ssid=config.get_config("device_name"),
                      auth=(WLAN.WPA2, config.get_config("password")),
                      channel=1,
                      antenna=WLAN.INT_ANT)
            # Load HTML via entering 192,168.4.10 to browser
            wlan.ifconfig(id=1,
                          config=('192.168.4.10', '255.255.255.0',
                                  '192.168.4.1', '192.168.4.1'))

            logger.info('Access point turned on as {}'.format(
                config.get_config("device_name")))
            logger.info(
                'Configuration website can be accessed at 192.168.4.10')

            address = socket.getaddrinfo(
                '0.0.0.0', 80)[0][-1]  # Accept stations from all addresses
            sct = socket.socket()  # Create socket for communication
            sct.settimeout(config.get_config(
                "config_timeout"))  # session times out after x seconds
            gc.collect(
            )  # frees up unused memory if there was a previous connection
            sct.bind(address)  # Bind address to socket
            sct.listen(1)  # Allow one station to connect to socket

            pycom.rgbled(0x000055)  # Blue LED - waiting for connection

            get_new_config(sct, logger)

            wlan.deinit()  # turn off wifi
            gc.collect()

            logger.info('rebooting...')
            machine.reset()
Exemplo n.º 42
0
def app_proc():

    # Start up delay to allow REPL message
    utime.sleep_ms(1000)

    # Print info
    print('GSM connection started...\r\n')

    # Configure the GSM parameters
    nic.config(user='******', pwd='gprs', apn='internet', pin='1234')

    # Connect to the gsm network
    nic.connect()

    # Wait till connection
    while not nic.isconnected():
        utime.sleep_ms(10)

    # Status info
    ifconfig = nic.ifconfig()
    print('GSM connection done: %s' % ifconfig[0])

    # GSM info
    print('IMEI Number: %s' % nic.imei())
    print('IMSI Number: %s' % nic.imsi())
    qos = nic.qos()
    print('Signal Quality: %d,%d' % (qos[0], qos[1]))

    # Get the IP address of host
    addr = usocket.getaddrinfo('ardusimple.com', 80)[0][-1]
    print('Host: %s:%d' % (addr[0], addr[1]))

    # Create the socket
    sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)

    # Connect to the host
    sock.connect(addr)
    print('Socket connected\r\n')

    # Send data to the host
    sock.send(b'GET / HTTP/1.1\r\nHost: ardusimple.com\r\n\r\n')
    print('Packet sent\r\n')

    # Get data from the host
    sock.settimeout(10.0)
    try:
        data = sock.recv(1000)
        print(data)
    except Exception as e:
        print(e)

    # Close the socket
    sock.close()
    print('Socket closed\r\n')

    # Disconnect from the gsm network
    nic.disconnect()

    print(
        'This is simple socket application based on GSM NIC with CMUX support\r\n'
    )
Exemplo n.º 43
0
def net():
    import network
    import usocket as socket
    import uselect

    wlan = network.WLAN(network.STA_IF)

    def client_mode():
        
        wlan.active(True)
        if not wlan.isconnected():
            print('connecting to network...')
            wlan.connect('rohr2', '0394747aHeKs')
            while not wlan.isconnected():
                pass
        print('network config:', wlan.ifconfig())
    
    def ap_mode():
        ap = network.WLAN(network.AP_IF)
        ap.active(True)
        ap.config(essid='ESP-3D',password='******')

    client_mode()
    #send socket
    add = ("192.168.128.29",4445)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setblocking(False)
    #rx socket
    rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    rsock.bind(('0.0.0.0',4440))
    rsock.setblocking(False)

    print('listening on 4440')

    _c=0

    poller=uselect.poll()
    poller.register(rsock,uselect.POLLIN)
    def sendudp(data):
        print ('send')
       
        sock.sendto(data,add)

    def rxudp(buf):
        try:
            rsock.readinto(buf)
            #print('rx:')

        except OSError:
            pass

        return

    def get_add():
      return wlan.ifconfig()

    def pole():
         e = poller.poll(1)
         return e

    return rxudp,sendudp,pole,get_add
Exemplo n.º 44
0
    # Start streaming images
    # NOTE: Disable IDE preview to increase streaming FPS.
    while (True):
        clock.tick() # Track elapsed milliseconds between snapshots().
        frame = sensor.snapshot()
        cframe = frame.compressed(quality=35)
        header = "\r\n--openmv\r\n" \
                 "Content-Type: image/jpeg\r\n"\
                 "Content-Length:"+str(cframe.size())+"\r\n\r\n"
        client.send(header)
        client.send(cframe)
        print(clock.fps())

while (True):
    # Create server socket
    s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    try:
        # Bind and listen
        s.bind([HOST, PORT])
        s.listen(5)

        # Set server socket timeout
        # NOTE: Due to a WINC FW bug, the server socket must be closed and reopened if
        # the client disconnects. Use a timeout here to close and re-create the socket.
        s.settimeout(3)
        start_streaming(s)
    except OSError as e:
        s.close()
        print("socket error: ", e)
        #sys.print_exception(e)
Exemplo n.º 45
0
# -*- coding: utf-8 -*-
import usocket as socket

import config
import machine

from lib import logging
from nce.network.network_connector import NetworkConnector

logging.basic_config(level=logging.INFO)
logger = logging.get_logger("__main__")

if __name__ == '__main__':
    message = "Hello, UDP. Can you hear me?".encode()

    logger.info("Opening UDP Socket")
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    addr = socket.getaddrinfo(config.UDP_ENDPOINT_ADDRESS,
                              config.UDP_ENDPOINT_PORT)[0][-1]
    logger.info("Resolved Address [{}]".format(addr))
    logger.info("Sending UDP message to {}:{} with body {}".format(
        config.UDP_ENDPOINT_ADDRESS, config.UDP_ENDPOINT_PORT, message))
    s.sendto(message, addr)
    logger.info("Sent UDP Message to the UDP Broker")

    logger.info("Closing the network connection")
    NetworkConnector().disconnect()
    machine.idle()
Exemplo n.º 46
0
def webServer():
    print('------------------------- Setup Ap End -------------')
    print('Files:{}'.format(os.listdir()))
    html_org = ''
    with open('seju.html', 'r') as f:
        html_org = f.read()

    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
    # addr = socket.getaddrinfo('192.168.185.14', 80)[0][-1]
    # addr = socket.getaddrinfo('192.168.4.1', 80)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # s.bind(('', 80))
    s.bind(addr)
    s.listen(1)
    print('My Addr:{}'.format(addr))
    count = 0
    dispList = ['SeJu FA', '20180425', 'Red  Off', 'Blue Off', 'Ex   Off']
    dispOled(dispList)

    fileSize = 2048
    while True:
        html = html_org
        conn, addr = s.accept()
        request = conn.recv(fileSize)
        # request = myReceive(conn)
        count += 1
        if count % 2:
            print("connection from %s" % str(addr))
            print("Content = %s" % str(request))
        request = str(request)
        LEDON_RED = request.find('/?LED=ON_R')
        LEDOFF_RED = request.find('/?LED=OFF_R')
        LEDON_BLUE = request.find('/?LED=ON_B')
        LEDOFF_BLUE = request.find('/?LED=OFF_B')
        LEDON_EX = request.find('/?LED=ON_E')
        LEDOFF_EX = request.find('/?LED=OFF_E')
        EXIT = request.find('/?LED=Exit')
        # print('LEDON_RED:{}'.format(LEDON_RED))
        if LEDON_RED == 6:
            print('Red Led ON')
            dispList[2] = 'Red   On'
        if LEDOFF_RED == 6:
            print('Red Led OFF')
            dispList[2] = 'Red  Off'

        if LEDON_BLUE == 6:
            print('Blue Led ON')
            dispList[3] = 'Blue  On'
        if LEDOFF_BLUE == 6:
            print('Blue Led OFF')
            dispList[3] = 'Blue Off'

        if LEDON_EX == 6:
            print('External Led ON')
            dispList[4] = 'Ex    On'
            # LED_EX.on()
        if LEDOFF_EX == 6:
            print('External Led OFF')
            dispList[4] = 'Ex   Off'
            # LED_EX.off()
        if EXIT == 6:
            print('Bye Bye Seju Demo')

            response = html
            mySend(conn, response, len(response))
            conn.close()
            break

        response = html
        mySend(conn, response, len(response))
        conn.close()
        dispOled(dispList)
Exemplo n.º 47
0
def request(method,
            url,
            data=None,
            json=None,
            files=None,
            headers={},
            auth=None,
            stream=None):
    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        proto, dummy, host = url.split("/", 2)
        path = ""
    if proto == "http:":
        port = 80
    elif proto == "https:":
        import ussl
        port = 443
    else:
        raise ValueError("Unsupported protocol: " + proto)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)

    if auth:
        headers['Authorization'] = b'Basic %s' % (ubinascii.b2a_base64(
            '%s:%s' % (auth[0], auth[1]))[0:-1])

    resp_code = 0
    resp_reason = None
    resp_headers = []

    ai = usocket.getaddrinfo(host, port)[0]
    s = usocket.socket(ai[0], ai[1], ai[2])
    try:
        s.connect(ai[-1])
        s.settimeout(5.0)
        if proto == "https:":
            s = ussl.wrap_socket(s, server_hostname=host)

        s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))

        if not "Host" in headers:
            s.write(b"Host: %s\r\n" % host)

        # Iterate over keys to avoid tuple alloc
        for k in headers:
            s.write(k)
            s.write(b": ")
            s.write(headers[k])
            s.write(b"\r\n")

        if json is not None:
            import ujson
            data = ujson.dumps(json)
            s.write(b"Content-Type: application/json\r\n")

        if files is not None:
            data = bytearray()
            boundary = b"37a4bcce91521f74142f1868e328a6b9"
            s.write(b"Content-Type: multipart/form-data; boundary=%s\r\n" %
                    (boundary))
            for name, fileobj in files.items():
                data += b"--%s\r\n" % (boundary)
                data += b'Content-Disposition: form-data; name="%s"; filename="%s"\r\n\r\n' % (
                    name, fileobj[0])
                data += fileobj[1].read()
                data += b"\r\n"
            data += b"\r\n--%s--\r\n" % (boundary)

        if data:
            s.write(b"Content-Length: %d\r\n\r\n" % len(data))
            s.write(data)
        else:
            s.write(b"\r\n")

        response = socket_readall(s).split(b"\r\n")
        while response:
            l = response.pop(0).strip()
            if not l or l == b"\r\n":
                break
            if l.startswith(b"Transfer-Encoding:"):
                if b"chunked" in l:
                    raise ValueError("Unsupported " + l)
            elif l.startswith(b"Location:") and not 200 <= status <= 299:
                raise NotImplementedError("Redirects not yet supported")
            if 'HTTPS' in l or 'HTTP' in l:
                sline = l.split(None, 2)
                resp_code = int(sline[1])
                resp_reason = sline[2].decode().rstrip(
                ) if len(sline) > 2 else ""
                continue
            resp_headers.append(l)
        resp_headers = b'\r\n'.join(resp_headers)
        content = b'\r\n'.join(response)
    except OSError:
        s.close()
        raise

    return Response(resp_code, resp_reason, resp_headers, content)
Exemplo n.º 48
0
def sync_clock(Force=False):
    global _TimerInfo, ScheduleList
    if _TimerInfo[
            2] == None or Force == True:  # Only sync NTP once to avoid float mis-align
        import ustruct, usocket
        try:
            f = open('System/config.json')
            gmt = ustruct.loads(f.read())['timezone']
        except:
            gmt = 7  # Default for Vietnam timezone

        try:
            NTP_QUERY = bytearray(48)
            NTP_QUERY[0] = 0x1b
            s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
            s.settimeout(2)
            res = s.sendto(NTP_QUERY,
                           usocket.getaddrinfo("pool.ntp.org", 123)[0][-1])
            msg = s.recv(48)
            s.close()
            ntp = ustruct.unpack("!I", msg[40:44])[0]
            ntp -= 3155673600
            if ntp > 0:  # Correct time
                from time import localtime

                ntp += gmt * 3600  #GMT time
                _TimerInfo[2] = (time(), ntp)
                print('Synced ', localtime(ntp))

        except:
            print('Redo')
            AddTask(function=sync_clock, mode='once', period=10000)
            return

    from time import mktime, ticks_ms
    for i in range(len(ScheduleList)):
        date, month, year = map(int, ScheduleList[i - 1]['date'].split('/'))
        hour, minute, second = map(int, ScheduleList[i - 1]['time'].split(':'))
        ntptime = mktime([year, month, date, hour, minute, second, 0, 0])
        print('Attttttttttttt', ntptime - clock())
        print('SCHEDULE TASK sex')
        if ntptime < _TimerInfo[2][1]:
            print('Too Late')
            continue
        print('SCHEDULE TASK F****D')
        AddTask(function=ScheduleList[i - 1]['function'],
                name=ScheduleList[i - 1]['name'],
                mode='once',
                period=(ntptime - clock()) * 1000)
        print('SCHEDULE TASK ADDED')
    ScheduleList.clear()
    TaskList.sort()

    if len(TaskList) == 0:
        _TimerInfo[3] = _TimerInfo[1] + 300000  # Call itself every 5 minutes
        _TimerInfo[4] = False
    else:
        if TaskList[0][0] - _TimerInfo[1] < 0:
            _TimerInfo[3] = _TimerInfo[1] + 1
            _TimerInfo[4] = True
        else:
            if TaskList[0][0] - _TimerInfo[1] > 300000:
                _TimerInfo[3] = _TimerInfo[1] + 300000
                _TimerInfo[4] = False
            else:
                _TimerInfo[3] = _TimerInfo[1] + (TaskList[0][0] -
                                                 _TimerInfo[1])
                _TimerInfo[4] = True
    global _Tasker
    _Tasker.deinit()
    _Tasker.init(period=_TimerInfo[3] - _TimerInfo[1],
                 mode=Timer.ONE_SHOT,
                 callback=_TaskHandler)
Exemplo n.º 49
0
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.ifconfig((myip, mysubnet, myrouter, mydns))
    sta_if.connect(Wifi_SSID, Wifi_Pass)
    while not sta_if.isconnected():
        pass

    print('WiFi connected:')
    print('IP-Address: ' + str(sta_if.ifconfig()[0]))
    print('Subnet Mask: ' + str(sta_if.ifconfig()[1]))
    print('Gateway: ' + str(sta_if.ifconfig()[2]))
    print('DNS: ' + str(sta_if.ifconfig()[3]))
    print()

    # Start Webserver
    s = usocket.socket()
    ai = usocket.getaddrinfo("0.0.0.0", 80)
    print("Bind address info:", ai)
    addr = ai[0][-1]

    s.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(5)
    print("Webserver ready.")

    # Endless-Loop for Webserver hosting Website
    outputheader = 'HTTP/1.0 200 OK\r\n\r\n'
    while True:
        res = s.accept()
        client_sock = res[0]
        client_addr = res[1]
def captive_portal(essid_name):
	existing_config = False
	try:
		f = open("config.json", "r")
		configs = f.read()
		j = ujson.loads(configs)
		print(j)
		f.close()
		con = connection(j['network_name'], j['network_password'])
		if con is True:
			existing_config = True
			print("Network connected")
			ap = network.WLAN(network.AP_IF)
			ap.active(False)    # turn off AP SSID
		else:
			existing_config = False
			print("Incorrect network configuration")
	except:
		print("No saved network")

	if existing_config is False:
		ap = network.WLAN(network.AP_IF)
		ap.active(True)
		ap.config(essid=essid_name, authmode=1)
		ip = ap.ifconfig()[0]
		print("DNS Server: dom.query. 60 in A {:s}".format(ip))

		udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		udps.setblocking(False)
		udps.bind(('',53))

		s = socket.socket()
		ai = socket.getaddrinfo(ip, 80)
		print("Web Server: Bind address information: ", ai)
		addr = ai[0][-1]

		s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		s.bind(addr)
		s.listen(1)
		s.settimeout(2)
		print("Web Server: Listening http://{}:80/".format(ip))

		regex = ure.compile("network\?ssid=(.*?)&password=(.*?)\sHTTP")

		set_connection = False
		while set_connection is False:
			try:
				data, addr = udps.recvfrom(4096)
				print("Incoming data...")
				DNS = DNSQuery(data)
				udps.sendto(DNS.response(ip), addr)
				print("Replying: {:s} -> {:s}".format(DNS.domain, ip))
			except:
				print("No DNS")

			try:
				res = s.accept()
				client_sock = res[0]
				client_addr = res[1]

				req = client_sock.recv(4096)
				print("Request:")
				print(req)
				client_sock.send(CONTENT)
				client_sock.close()
				print()
				search_result = regex.search(req)
				if search_result:
					incoming_network_name = search_result.group(1)
					incoming_network_pass = search_result.group(2)
					con = connection(incoming_network_name, incoming_network_pass)
					if con is True:
						d = {"network_name": incoming_network_name, "network_password": incoming_network_pass}
						f = open("config.json", "w")
						f.write(ujson.dumps(d))
						f.close()
						set_connection = True



			except:
				print("Timeout")
			time.sleep_ms(1000)

		udps.close()
Exemplo n.º 51
0
def socket(af=usocket.AF_INET):
    s = usocket.socket(af, usocket.SOCK_DGRAM)
    s.setblocking(False)
    return s
Exemplo n.º 52
0
def request_with_ssl_cert_patch(method,
                                url,
                                data=None,
                                json=None,
                                headers={},
                                stream=None,
                                parse_headers=True,
                                cert=None):
    redir_cnt = 1
    if json is not None:
        assert data is None
        import ujson
        data = ujson.dumps(json)

    while True:
        try:
            proto, dummy, host, path = url.split("/", 3)
        except ValueError:
            proto, dummy, host = url.split("/", 2)
            path = ""
        if proto == "http:":
            port = 80
        elif proto == "https:":
            import ussl
            port = 443
        else:
            raise ValueError("Unsupported protocol: " + proto)

        if ":" in host:
            host, port = host.split(":", 1)
            port = int(port)

        ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
        ai = ai[0]

        resp_d = None
        if parse_headers is not False:
            resp_d = {}

        s = usocket.socket(ai[0], ai[1], ai[2])
        try:
            s.connect(ai[-1])
            if proto == "https:":
                if cert is not None:  # Here's the patch
                    key = open(cert[1])
                    cert = open(cert[0])
                    s = ussl.wrap_socket(s,
                                         server_hostname=host,
                                         cert=cert.read(),
                                         key=key.read())
                    cert.close()
                    key.close()
                else:
                    s = ussl.wrap_socket(s, server_hostname=host)
            s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
            if not "Host" in headers:
                s.write(b"Host: %s\r\n" % host)
            # Iterate over keys to avoid tuple alloc
            for k in headers:
                s.write(k)
                s.write(b": ")
                s.write(headers[k])
                s.write(b"\r\n")
            if json is not None:
                s.write(b"Content-Type: application/json\r\n")
            if data:
                s.write(b"Content-Length: %d\r\n" % len(data))
            s.write(b"Connection: close\r\n\r\n")
            if data:
                s.write(data)

            l = s.readline()
            #print(l)
            l = l.split(None, 2)
            status = int(l[1])
            reason = ""
            if len(l) > 2:
                reason = l[2].rstrip()
            while True:
                l = s.readline()
                if not l or l == b"\r\n":
                    break
                #print(l)

                if l.startswith(b"Transfer-Encoding:"):
                    if b"chunked" in l:
                        raise ValueError("Unsupported " + l)
                elif l.startswith(b"Location:") and 300 <= status <= 399:
                    if not redir_cnt:
                        raise ValueError("Too many redirects")
                    redir_cnt -= 1
                    url = l[9:].decode().strip()
                    #print("redir to:", url)
                    status = 300
                    break

                if parse_headers is False:
                    pass
                elif parse_headers is True:
                    l = l.decode()
                    k, v = l.split(":", 1)
                    resp_d[k] = v.strip()
                else:
                    parse_headers(l, resp_d)
        except OSError:
            s.close()
            raise

        if status != 300:
            break

    resp = Response(s)
    resp.status_code = status
    resp.reason = reason
    if resp_d is not None:
        resp.headers = resp_d
    return resp
Exemplo n.º 53
0
def sendtcp(host, port):
    data = b'token here'
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))
    sock.send(data)
    sock.close()
Exemplo n.º 54
0
    def start(self):
        """
        Starts the nano gateway.
        """

        self.log('Starting nano gateway with id {}', self.gateway_id)

        # Change WiFi to STA mode and connect
        self.wlan = WLAN(mode=WLAN.STA)
        self._connect_to_wifi()

        # Get a time sync
        self.log('Syncing time with {} ...', self.ntp_server)
        self.rtc.ntp_sync(self.ntp_server, update_period=self.ntp_period)
        while not self.rtc.synced():
            utime.sleep_ms(50)
        self.log('RTC NTP sync complete')

        # Get the server IP and create an UDP socket
        self.server_ip = usocket.getaddrinfo(self.server, self.port)[0][-1]
        self.log('Opening UDP socket to {} ({}) port {}...', self.server,
                 self.server_ip[0], self.server_ip[1])
        self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM,
                                   usocket.IPPROTO_UDP)
        self.sock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
        self.sock.setblocking(False)

        # Push the first time stat immediately
        self._push_data(self._make_stat_packet())

        # Create the alarms
        self.stat_alarm = machine.Timer.Alarm(
            handler=lambda t: self._push_data(self._make_stat_packet()),
            s=60,
            periodic=True)
        self.pull_alarm = machine.Timer.Alarm(
            handler=lambda u: self._pull_data(), s=25, periodic=True)

        # Start the UDP receive thread
        self.udp_stop = False
        _thread.start_new_thread(self._udp_thread, ())

        # Initialize the LoRa radio in LORA mode
        self.log('Setting up LoRa socket on {:.1f} Mhz using {}',
                 self._freq_to_float(self.frequency), self.datarate)
        self.lora = LoRa(mode=LoRa.LORA,
                         frequency=self.frequency,
                         bandwidth=self.bw,
                         sf=self.sf,
                         preamble=8,
                         coding_rate=LoRa.CODING_4_5,
                         tx_iq=True)

        # Create a raw LoRa socket
        self.lora_sock = usocket.socket(usocket.AF_LORA, usocket.SOCK_RAW)
        self.lora_sock.setblocking(False)

        self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT
                                    | LoRa.TX_PACKET_EVENT),
                           handler=self._lora_cb)
        self.log('Nano gateway online')
Exemplo n.º 55
0
 def __init__(self):
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.sock.bind(('0.0.0.0', 80))
     self.sock.listen(5)
     #sock.settimeout(30)
     self.vistas = {}
Exemplo n.º 56
0
 def __init__(self, addr='0.0.0.0', port=80, maxQ=5):
     address = socket.getaddrinfo(addr, port)[0][-1]
     self.m_Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.m_Socket.bind(address)
     self.m_Socket.listen(maxQ)
     self.m_Socket.setblocking(True)
Exemplo n.º 57
0
# This is your main script.
import machine
import time
import network
import usocket as socket

pin = machine.Pin(0, machine.Pin.OUT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)


def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('ssid', 'password')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())


def start_server():
    while True:
        conn, addr = s.accept()
        request = conn.recv(1024)
        request = str(request)
        if "GET /?led=on" in request:
            pin.on()
        if "GET /?led=off" in request:
Exemplo n.º 58
0
 def _create_connection(self, addr, timeout=None):
     sock = socket.socket(socket.AF_INET)
     sock.connect(addr)
     if timeout not in [None, _GLOBAL_DEFAULT_TIMEOUT]:
         sock.settimeout(timeout)
     return sock
Exemplo n.º 59
0
 def __init__(self):
     self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self._server.bind(('', 80))
     self._server.listen(5)
Exemplo n.º 60
0
def request(method, url, data=None, json=None, headers={}, stream=None,
            verify=None, cert=None):
    try:
        scheme, _, host, path = url.split("/", 3)
    except ValueError:
        scheme, _, host = url.split("/", 2)
        path = ""
    if scheme == "http:":
        port = 80
        proto = usocket.IPPROTO_TCP
    elif scheme == "https:":
        import ussl
        port = 443
        proto = usocket.IPPROTO_SEC
    else:
        raise ValueError("Unsupported scheme: " + scheme)

    if ":" in host:
        host, port = host.split(":", 1)
        port = int(port)

    s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM, proto)
    try:
        if proto == usocket.IPPROTO_SEC:
            wrap_params = {'server_hostname':host}
            if cert is not None:
                wrap_params['certfile'] = cert[0]
                wrap_params['keyfile'] = cert[1]
            if verify is not None:
                wrap_params['ca_certs'] = verify
            s = ussl.wrap_socket(s, **wrap_params)
        s.connect((host, port))
        s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
        if not "Host" in headers:
            s.write(b"Host: %s\r\n" % host)
        # Iterate over keys to avoid tuple alloc
        for k in headers:
            s.write(k)
            s.write(b": ")
            s.write(headers[k])
            s.write(b"\r\n")
        if json is not None:
            assert data is None
            import ujson
            data = ujson.dumps(json)
            s.write(b"Content-Type: application/json\r\n")
        if data:
            s.write(b"Content-Length: %d\r\n" % len(data))
        s.write(b"\r\n")
        if data:
            s.write(data)

        l = s.readline()
        #print(l)
        l = l.split(None, 2)
        status = int(l[1])
        reason = ""
        if len(l) > 2:
            reason = l[2].rstrip()
        while True:
            l = s.readline()
            if not l or l == b"\r\n":
                break
            #print(l)
            if l.startswith(b"Transfer-Encoding:"):
                if b"chunked" in l:
                    raise ValueError("Unsupported " + l)
            elif l.startswith(b"Location:") and not 200 <= status <= 299:
                raise NotImplementedError("Redirects not yet supported")
    except OSError:
        s.close()
        raise

    resp = Response(s)
    resp.status_code = status
    resp.reason = reason
    return resp