def connect(self, clean_session=True): if not self.sock: self.sock = socket.socket() addr = socket.getaddrinfo(self.server, self.port)[0][-1] self.sock.settimeout(10) self.sock.connect(addr, conntype=TCP_MODE) if self.ssl: import ussl self.sock = ussl.wrap_socket(self.sock, **self.ssl_params) premsg = bytearray(b"\x10\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) #self.sock.write(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
def open_socket(): # If socket connects then we should get NOKEY or 4 byte hash key print("In open_socket") print(esp.socket_status(0)) #print(cmd_socket.connected()) try: # sockaddr is 32 bit packed IP address sockaddr = socket.getaddrinfo(WLAN_PJ_IP, ADCP_PORT)[0][-1] # VPL Client mode cmd_socket.connect(sockaddr) print(esp.socket_status(0)) except RuntimeError as e: print("In open_socket err, ", e) print() # Give the socket time to connect before readline in auth_check ## ESP32 reliability??? ## time.sleep(.1)
def request(method, url, data=None, json=None, headers=None, stream=False): """Perform an HTTP request to the given url which we will parse to determine whether to use SSL ('https://') or not. We can also send some provided 'data' or a json dictionary which we will stringify. 'headers' is optional HTTP headers sent along. 'stream' will determine if we buffer everything, or whether to only read only when requested """ global _the_interface # pylint: disable=global-statement, invalid-name if not headers: headers = {} try: proto, dummy, host, path = url.split("/", 3) # replace spaces in path path = path.replace(" ", "%20") except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "http:": port = 80 elif proto == "https:": port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) addr_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0] sock = socket.socket(addr_info[0], addr_info[1], addr_info[2]) resp = Response(sock) # our response sock.settimeout(1) # 1 second timeout try: if proto == "https:": conntype = _the_interface.TLS_MODE sock.connect((host, port), conntype) # for SSL we need to know the host name else: conntype = _the_interface.TCP_MODE sock.connect(addr_info[-1], conntype) sock.write(b"%s /%s HTTP/1.0\r\n" % (method, path)) if "Host" not in headers: sock.write(b"Host: %s\r\n" % host) if "User-Agent" not in headers: sock.write(b"User-Agent: Adafruit CircuitPython\r\n") # Iterate over keys to avoid tuple alloc for k in headers: sock.write(k.encode()) sock.write(b": ") sock.write(headers[k].encode()) sock.write(b"\r\n") if json is not None: assert data is None try: import json as json_module except ImportError: import ujson as json_module data = json_module.dumps(json) sock.write(b"Content-Type: application/json\r\n") if data: sock.write(b"Content-Length: %d\r\n" % len(data)) sock.write(b"\r\n") if data: sock.write(bytes(data, 'utf-8')) line = sock.readline() #print(line) line = line.split(None, 2) status = int(line[1]) reason = "" if len(line) > 2: reason = line[2].rstrip() while True: line = sock.readline() if not line or line == b"\r\n": break #print("**line: ", line) header_tuple = line.split(b': ', 1) if len(header_tuple) == 2: # sometimes there aren't two values? title, content = header_tuple if title and content: title = str(title.lower(), 'utf-8') content = str(content, 'utf-8') resp.headers[title] = content if line.startswith(b"Transfer-Encoding:"): if b"chunked" in line: raise ValueError("Unsupported " + line) elif line.startswith(b"Location:") and not 200 <= status <= 299: raise NotImplementedError("Redirects not yet supported") except OSError: sock.close() raise resp.status_code = status resp.reason = reason return resp
# PyPortal or similar; edit pins as needed spi = board.SPI() esp32_cs = DigitalInOut(board.ESP_CS) esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_reset = DigitalInOut(board.ESP_RESET) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) # connect to wifi AP esp.connect(secrets) # test for connectivity to server print("Server ping:", esp.ping(HOST), "ms") # create the socket socket.set_interface(esp) socketaddr = socket.getaddrinfo(HOST, PORT)[0][4] s = socket.socket(type=socket.SOCK_DGRAM) s.settimeout(TIMEOUT) print("Sending") s.connect(socketaddr, conntype=esp.UDP_MODE) packet = bytearray(48) packet[0] = 0b00100011 # Not leap second, NTP version 4, Client mode s.send(packet) print("Receiving") packet = s.recv(48) seconds = struct.unpack_from("!I", packet, offset=len(packet) - 8)[0] print("Time:", time.localtime(seconds - NTP_TO_UNIX_EPOCH))
esp32_ready, esp32_reset, debug=False) print("Connecting to Wifi") esp.connect(secrets) print("IP Address", esp.pretty_ip(esp.ip_address)) print("Server ping", esp.ping(HOST), "ms") socket.set_interface(esp) while True: print("Create TCP Client Socket") s = socket.socket() s.settimeout(TIMEOUT) print("Connecting") socketaddr = socket.getaddrinfo(HOST, PORT, 0, socket.SOCK_STREAM)[0][4] s.connect(socketaddr) s.send(b'Hello, world') print("Sent") buf = s.recv(MAXBUF) print("Receied", buf) s.close() time.sleep(INTERVAL)
switch = DigitalInOut(board.D7) switch.direction = Direction.OUTPUT switch.value = False transistorOutput = AnalogIn(board.A5) requests.set_socket(socket, esp) #if esp.status == adafruit_esp32spi.WL_IDLE_STATUS: # print("ESP32 found and in idle mode") #print("Firmware vers.", esp.firmware_version) #print("MAC addr:", [hex(i) for i in esp.MAC_address]) #for ap in esp.scan_networks(): # print("\t%s\t\tRSSI: %d" % (str(ap["ssid"], "utf-8"), ap["rssi"])) ADDR = socket.getaddrinfo("192.168.0.188", 8080)[0][-1] class State: def __init__(self, interval=0.01): self.interval = interval self.time = time.monotonic() def intervalPassed(self): return time.monotonic() - self.time > self.interval class Sensor(State): def __init__(self, interval, analogInput, actionResetInterval): self.input = analogInput self.value = self.input.value