Skip to content

Commit b11cf2a

Browse files
authored
Merge pull request #159 from Neradoc/staticIP-hostname-and-dns
Static ip hostname and dns
2 parents ef26881 + ab41a20 commit b11cf2a

File tree

3 files changed

+149
-15
lines changed

3 files changed

+149
-15
lines changed

adafruit_esp32spi/adafruit_esp32spi.py

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@
3737

3838
_SET_NET_CMD = const(0x10)
3939
_SET_PASSPHRASE_CMD = const(0x11)
40+
_SET_IP_CONFIG = const(0x14)
41+
_SET_DNS_CONFIG = const(0x15)
42+
_SET_HOSTNAME = const(0x16)
4043
_SET_AP_NET_CMD = const(0x18)
4144
_SET_AP_PASSPHRASE_CMD = const(0x19)
4245
_SET_DEBUG_CMD = const(0x1A)
@@ -405,6 +408,46 @@ def scan_networks(self):
405408
return APs
406409
return None
407410

411+
def set_ip_config(self, ip_address, gateway, mask="255.255.255.0"):
412+
"""Tells the ESP32 to set ip, gateway and network mask b"\xFF"
413+
414+
:param str ip_address: IP address (as a string).
415+
:param str gateway: Gateway (as a string).
416+
:param str mask: Mask, defaults to 255.255.255.0 (as a string).
417+
"""
418+
resp = self._send_command_get_response(
419+
_SET_IP_CONFIG,
420+
params=[
421+
b"\x00",
422+
self.unpretty_ip(ip_address),
423+
self.unpretty_ip(gateway),
424+
self.unpretty_ip(mask),
425+
],
426+
sent_param_len_16=False,
427+
)
428+
return resp
429+
430+
def set_dns_config(self, dns1, dns2):
431+
"""Tells the ESP32 to set DNS
432+
433+
:param str dns1: DNS server 1 IP as a string.
434+
:param str dns2: DNS server 2 IP as a string.
435+
"""
436+
resp = self._send_command_get_response(
437+
_SET_DNS_CONFIG, [b"\x00", self.unpretty_ip(dns1), self.unpretty_ip(dns2)]
438+
)
439+
if resp[0][0] != 1:
440+
raise RuntimeError("Failed to set dns with esp32")
441+
442+
def set_hostname(self, hostname):
443+
"""Tells the ESP32 to set hostname for DHCP.
444+
445+
:param str hostname: The new host name.
446+
"""
447+
resp = self._send_command_get_response(_SET_HOSTNAME, [hostname.encode()])
448+
if resp[0][0] != 1:
449+
raise RuntimeError("Failed to set hostname with esp32")
450+
408451
def wifi_set_network(self, ssid):
409452
"""Tells the ESP32 to set the access point to the given ssid"""
410453
resp = self._send_command_get_response(_SET_NET_CMD, [ssid])
@@ -518,8 +561,7 @@ def connect(self, secrets):
518561
self.connect_AP(secrets["ssid"], secrets["password"])
519562

520563
def connect_AP(self, ssid, password, timeout_s=10): # pylint: disable=invalid-name
521-
"""
522-
Connect to an access point with given name and password.
564+
"""Connect to an access point with given name and password.
523565
Will wait until specified timeout seconds and return on success
524566
or raise an exception on failure.
525567
@@ -552,8 +594,7 @@ def connect_AP(self, ssid, password, timeout_s=10): # pylint: disable=invalid-n
552594
def create_AP(
553595
self, ssid, password, channel=1, timeout=10
554596
): # pylint: disable=invalid-name
555-
"""
556-
Create an access point with the given name, password, and channel.
597+
"""Create an access point with the given name, password, and channel.
557598
Will wait until specified timeout seconds and return on success
558599
or raise an exception on failure.
559600
@@ -814,8 +855,7 @@ def set_esp_debug(self, enabled):
814855
raise RuntimeError("Failed to set debug mode")
815856

816857
def set_pin_mode(self, pin, mode):
817-
"""
818-
Set the io mode for a GPIO pin.
858+
"""Set the io mode for a GPIO pin.
819859
820860
:param int pin: ESP32 GPIO pin to set.
821861
:param value: direction for pin, digitalio.Direction or integer (0=input, 1=output).
@@ -831,8 +871,7 @@ def set_pin_mode(self, pin, mode):
831871
raise RuntimeError("Failed to set pin mode")
832872

833873
def set_digital_write(self, pin, value):
834-
"""
835-
Set the digital output value of pin.
874+
"""Set the digital output value of pin.
836875
837876
:param int pin: ESP32 GPIO pin to write to.
838877
:param bool value: Value for the pin.
@@ -844,8 +883,7 @@ def set_digital_write(self, pin, value):
844883
raise RuntimeError("Failed to write to pin")
845884

846885
def set_analog_write(self, pin, analog_value):
847-
"""
848-
Set the analog output value of pin, using PWM.
886+
"""Set the analog output value of pin, using PWM.
849887
850888
:param int pin: ESP32 GPIO pin to write to.
851889
:param float value: 0=off 1.0=full on
@@ -858,8 +896,7 @@ def set_analog_write(self, pin, analog_value):
858896
raise RuntimeError("Failed to write to pin")
859897

860898
def set_digital_read(self, pin):
861-
"""
862-
Get the digital input value of pin. Returns the boolean value of the pin.
899+
"""Get the digital input value of pin. Returns the boolean value of the pin.
863900
864901
:param int pin: ESP32 GPIO pin to read from.
865902
"""
@@ -877,8 +914,7 @@ def set_digital_read(self, pin):
877914
)
878915

879916
def set_analog_read(self, pin, atten=ADC_ATTEN_DB_11):
880-
"""
881-
Get the analog input value of pin. Returns an int between 0 and 65536.
917+
"""Get the analog input value of pin. Returns an int between 0 and 65536.
882918
883919
:param int pin: ESP32 GPIO pin to read from.
884920
:param int atten: attenuation constant
@@ -914,6 +950,7 @@ def get_time(self):
914950
def set_certificate(self, client_certificate):
915951
"""Sets client certificate. Must be called
916952
BEFORE a network connection is established.
953+
917954
:param str client_certificate: User-provided .PEM certificate up to 1300 bytes.
918955
"""
919956
if self._debug:
@@ -936,6 +973,7 @@ def set_certificate(self, client_certificate):
936973
def set_private_key(self, private_key):
937974
"""Sets private key. Must be called
938975
BEFORE a network connection is established.
976+
939977
:param str private_key: User-provided .PEM file up to 1700 bytes.
940978
"""
941979
if self._debug:

adafruit_esp32spi/digitalio.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ def __init__(self, esp_pin, esp):
5050

5151
def init(self, mode=IN):
5252
"""Initalizes a pre-defined pin.
53+
5354
:param mode: Pin mode (IN, OUT, LOW, HIGH). Defaults to IN.
5455
"""
5556
if mode is not None:
@@ -64,6 +65,7 @@ def init(self, mode=IN):
6465

6566
def value(self, val=None):
6667
"""Sets ESP32 Pin GPIO output mode.
68+
6769
:param val: Pin output level (LOW, HIGH)
6870
"""
6971
if val is not None:
@@ -133,6 +135,7 @@ def deinit(self):
133135

134136
def switch_to_output(self, value=False, drive_mode=DriveMode.PUSH_PULL):
135137
"""Set the drive mode and value and then switch to writing out digital values.
138+
136139
:param bool value: Default mode to set upon switching.
137140
:param DriveMode drive_mode: Drive mode for the output.
138141
"""
@@ -142,6 +145,7 @@ def switch_to_output(self, value=False, drive_mode=DriveMode.PUSH_PULL):
142145

143146
def switch_to_input(self, pull=None):
144147
"""Sets the pull and then switch to read in digital values.
148+
145149
:param Pull pull: Pull configuration for the input.
146150
"""
147151
raise NotImplementedError(
@@ -156,6 +160,7 @@ def direction(self):
156160
@direction.setter
157161
def direction(self, pin_dir):
158162
"""Sets the direction of the pin.
163+
159164
:param Direction dir: Pin direction (Direction.OUTPUT or Direction.INPUT)
160165
"""
161166
self.__direction = pin_dir
@@ -176,6 +181,7 @@ def value(self):
176181
@value.setter
177182
def value(self, val):
178183
"""Sets the digital logic level of the pin.
184+
179185
:param type value: Pin logic level.
180186
:param int value: Pin logic level. 1 is logic high, 0 is logic low.
181187
:param bool value: Pin logic level. True is logic high, False is logic low.
@@ -195,8 +201,9 @@ def drive_mode(self):
195201
@drive_mode.setter
196202
def drive_mode(self, mode):
197203
"""Sets the pin drive mode.
204+
198205
:param DriveMode mode: Defines the drive mode when outputting digital values.
199-
Either PUSH_PULL or OPEN_DRAIN
206+
Either PUSH_PULL or OPEN_DRAIN
200207
"""
201208
if mode is DriveMode.OPEN_DRAIN:
202209
raise NotImplementedError(

examples/esp32spi_ipconfig.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
4+
import time
5+
import board
6+
import busio
7+
from digitalio import DigitalInOut
8+
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
9+
from adafruit_esp32spi import adafruit_esp32spi
10+
11+
# Get wifi details and more from a secrets.py file
12+
try:
13+
from secrets import secrets
14+
except ImportError:
15+
print("WiFi secrets are kept in secrets.py, please add them there!")
16+
raise
17+
18+
HOSTNAME = "esp32-spi-hostname-test"
19+
20+
IP_ADDRESS = "192.168.1.111"
21+
GATEWAY_ADDRESS = "192.168.1.1"
22+
SUBNET_MASK = "255.255.255.0"
23+
24+
UDP_IN_ADDR = "192.168.1.1"
25+
UDP_IN_PORT = 5500
26+
27+
UDP_TIMEOUT = 20
28+
29+
esp32_cs = DigitalInOut(board.CS1)
30+
esp32_ready = DigitalInOut(board.ESP_BUSY)
31+
esp32_reset = DigitalInOut(board.ESP_RESET)
32+
33+
spi = busio.SPI(board.SCK1, board.MOSI1, board.MISO1)
34+
35+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
36+
socket.set_interface(esp)
37+
38+
s_in = socket.socket(type=socket.SOCK_DGRAM)
39+
s_in.settimeout(UDP_TIMEOUT)
40+
print("set hostname:", HOSTNAME)
41+
esp.set_hostname(HOSTNAME)
42+
43+
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
44+
print("ESP32 found and in idle mode")
45+
print("Firmware vers.", esp.firmware_version)
46+
print("MAC addr:", [hex(i) for i in esp.MAC_address])
47+
48+
print("Connecting to AP...")
49+
while not esp.is_connected:
50+
try:
51+
esp.connect_AP(secrets["ssid"], secrets["password"])
52+
except RuntimeError as e:
53+
print("could not connect to AP, retrying: ", e)
54+
continue
55+
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
56+
ip1 = esp.ip_address
57+
58+
print("set ip dns")
59+
esp.set_dns_config("192.168.1.1", "8.8.8.8")
60+
61+
print("set ip config")
62+
esp.set_ip_config(IP_ADDRESS, GATEWAY_ADDRESS, SUBNET_MASK)
63+
64+
time.sleep(1)
65+
ip2 = esp.ip_address
66+
67+
time.sleep(1)
68+
info = esp.network_data
69+
print(
70+
"get network_data: ",
71+
esp.pretty_ip(info["ip_addr"]),
72+
esp.pretty_ip(info["gateway"]),
73+
esp.pretty_ip(info["netmask"]),
74+
)
75+
76+
IP_ADDR = esp.pretty_ip(esp.ip_address)
77+
print("ip:", IP_ADDR)
78+
print("My IP address is", esp.pretty_ip(esp.ip_address))
79+
print("udp in addr: ", UDP_IN_ADDR, UDP_IN_PORT)
80+
81+
socketaddr_udp_in = socket.getaddrinfo(UDP_IN_ADDR, UDP_IN_PORT)[0][4]
82+
s_in.connect(socketaddr_udp_in, conntype=esp.UDP_MODE)
83+
print("connected local UDP")
84+
85+
while True:
86+
data = s_in.recv(1205)
87+
if len(data) >= 1:
88+
data = data.decode("utf-8")
89+
print(len(data), data)

0 commit comments

Comments
 (0)