src/eric7/MicroPython/Devices/CircuitPythonDevices.py

branch
eric7
changeset 10153
ffe7432f716b
parent 10144
45a9177c8e77
child 10170
6cf1ee737d8f
diff -r 33e7b9d3f91c -r ffe7432f716b src/eric7/MicroPython/Devices/CircuitPythonDevices.py
--- a/src/eric7/MicroPython/Devices/CircuitPythonDevices.py	Wed Aug 02 17:22:20 2023 +0200
+++ b/src/eric7/MicroPython/Devices/CircuitPythonDevices.py	Thu Aug 03 17:33:07 2023 +0200
@@ -796,7 +796,6 @@
             str(r.ipv4_dns) if r.ipv4_dns else'0.0.0.0',
         ),
         'mac': binascii.hexlify(r.mac_address, ':').decode(),
-        'hostname': r.hostname,
     }
     try:
         station['txpower'] = r.tx_power
@@ -831,7 +830,6 @@
             str(r.ipv4_dns) if r.ipv4_dns else'0.0.0.0',
         ),
         'mac': binascii.hexlify(r.mac_address_ap, ':').decode(),
-        'hostname': r.hostname,
     }
     try:
         ap['txpower'] = r.tx_power
@@ -840,7 +838,8 @@
     print(json.dumps(ap))
 
     overall = {
-        'active': r.enabled
+        'active': r.enabled,
+        'hostname': r.hostname,
     }
     print(json.dumps(overall))
 
@@ -868,7 +867,7 @@
 
         return station, ap, overall
 
-    def connectWifi(self, ssid, password):
+    def connectWifi(self, ssid, password, hostname):
         """
         Public method to connect a device to a WiFi network.
 
@@ -876,16 +875,20 @@
         @type str
         @param password password needed to connect
         @type str
+        @param hostname host name of the device
+        @type str
         @return tuple containing the connection status and an error string
         @rtype tuple of (bool, str)
         """
         command = """
-def connect_wifi(ssid, password):
+def connect_wifi(ssid, password, hostname):
     import json
     import wifi
 
     r = wifi.radio
     try:
+        if hostname:
+            r.hostname = hostname
         r.start_station()
         r.connect(ssid, password)
         status = 'connected'
@@ -894,11 +897,12 @@
 
     print(json.dumps({{'connected': r.ipv4_address is not None, 'status': status}}))
 
-connect_wifi({0}, {1})
+connect_wifi({0}, {1}, {2})
 del connect_wifi
 """.format(
             repr(ssid),
             repr(password if password else ""),
+            repr(hostname),
         )
 
         with EricOverrideCursor():
@@ -990,7 +994,7 @@
 
         return out.strip() == b"True"
 
-    def writeCredentials(self, ssid, password):
+    def writeCredentials(self, ssid, password, hostname, country):  # noqa: U100
         """
         Public method to write the given credentials to the connected device and modify
         the start script to connect automatically.
@@ -999,6 +1003,10 @@
         @type str
         @param password password needed to authenticate
         @type str
+        @param hostname host name of the device
+        @type str
+        @param country WiFi country code (unused)
+        @type str
         @return tuple containing a flag indicating success and an error message
         @rtype tuple of (bool, str)
         """
@@ -1010,9 +1018,8 @@
         if Globals.versionToTuple(self._deviceData["release"]) >= (8, 0, 0):
             # CircuitPython >= 8.0.0: generate 'settings.toml' file
             contents = (
-                'CIRCUITPY_WIFI_SSID = "{0}"\nCIRCUITPY_WIFI_PASSWORD = "{1}"\n'.format(
-                    ssid, password
-                )
+                'CIRCUITPY_WIFI_SSID = "{0}"\nCIRCUITPY_WIFI_PASSWORD = "{1}"\n'
+                'CIRCUITPY_WIFI_HOSTNAME = "{2}"\n'.format(ssid, password, hostname)
             )
             filename = os.path.join(workspace, "settings.toml")
             if os.path.exists(filename):
@@ -1038,9 +1045,8 @@
             # CircuitPython < 8.0.0: generate a secrets.py script
             # step 1: generate the secrets.py file
             contents = (
-                'secrets = {{\n    "ssid": "{0}",\n    "password": "{1}",\n}}\n'.format(
-                    ssid, password
-                )
+                'secrets = {{\n    "ssid": "{0}",\n    "password": "{1}",\n'
+                '    "hostname": "{2}",\n}}\n'.format(ssid, password, hostname)
             )
             filename = os.path.join(workspace, "secrets.py")
             if os.path.exists(filename):
@@ -1211,7 +1217,14 @@
         else:
             return out.decode("utf-8").strip() == "True", ""
 
-    def startAccessPoint(self, ssid, security=None, password=None, ifconfig=None):
+    def startAccessPoint(
+        self,
+        ssid,
+        security=None,
+        password=None,
+        hostname=None,
+        ifconfig=None,
+    ):
         """
         Public method to start the access point interface.
 
@@ -1221,6 +1234,8 @@
         @type int (optional)
         @param password password (defaults to None)
         @type str (optional)
+        @param hostname host name of the device (defaults to None)
+        @type str (optional)
         @param ifconfig IPv4 configuration for the access point if not default
             (IPv4 address, netmask, gateway address, DNS server address)
         @type tuple of (str, str, str, str)
@@ -1242,19 +1257,22 @@
             )
 
         command = """
-def start_ap(ssid, password):
+def start_ap(ssid, password, hostname):
     import wifi
 
     r = wifi.radio
+    r.enabled = True
+    if hostname:
+        r.hostname = hostname
     try:
-        r.start_ap(ssid, password, authmode={2})
-    except ValueError as exc:
+        r.start_ap(ssid, password, authmode={3})
+    except (NotImplementedError, ValueError) as exc:
         print('Error:', str(exc))
 
-start_ap({0}, {1})
+start_ap({0}, {1}, {2})
 del start_ap
 """.format(
-            repr(ssid), repr(password), authmode
+            repr(ssid), repr(password), repr(hostname), authmode
         )
 
         out, err = self.executeCommands(command, mode=self._submitMode, timeout=15000)
@@ -1396,7 +1414,7 @@
 
         return status
 
-    def connectToLan(self, config):
+    def connectToLan(self, config, hostname):
         """
         Public method to connect the connected device to the LAN.
 
@@ -1405,18 +1423,20 @@
         @param config configuration for the connection (either the string 'dhcp'
             for a dynamic address or a tuple of four strings with the IPv4 parameters.
         @type str or tuple of (str, str, str, str)
+        @param hostname host name of the device
+        @type str
         @return tuple containing a flag indicating success and an error message
         @rtype tuple of (bool, str)
         """
         command = """{0}
-def connect_lan(config):
+def connect_lan(config, hostname):
     from adafruit_wiznet5k import adafruit_wiznet5k
 
     w5x00_init()
 
     nic.mac_address = adafruit_wiznet5k._DEFAULT_MAC
     if config == 'dhcp':
-        nic.set_dhcp(response_timeout=14)
+        nic.set_dhcp(hostname=hostname)
     else:
         nic.ifconfig = (
             nic.unpretty_ip(config[0]),
@@ -1426,10 +1446,12 @@
         )
     print(nic.ifconfig[0] != b'\x00\x00\x00\x00')
 
-connect_lan({1})
+connect_lan({1}, {2})
 del connect_lan, w5x00_init
 """.format(
-            WiznetUtilities.cpyWiznetInit(), "'dhcp'" if config == "dhcp" else config
+            WiznetUtilities.cpyWiznetInit(),
+            "'dhcp'" if config == "dhcp" else config,
+            repr(hostname) if hostname else "''",
         )
 
         with EricOverrideCursor():
@@ -1545,7 +1567,7 @@
 
         return self.disconnectFromLan()
 
-    def writeLanAutoConnect(self, config):
+    def writeLanAutoConnect(self, config, hostname):
         """
         Public method to generate a script and associated configuration to connect the
         device to the LAN during boot time.
@@ -1553,6 +1575,8 @@
         @param config configuration for the connection (either the string 'dhcp'
             for a dynamic address or a tuple of four strings with the IPv4 parameters.
         @type str or tuple of (str, str, str, str)
+        @param hostname host name of the device
+        @type str
         @return tuple containing a flag indicating success and an error message
         @rtype tuple of (bool, str)
         """
@@ -1569,6 +1593,7 @@
                     "WIZNET_IFCONFIG_1": "",
                     "WIZNET_IFCONFIG_2": "",
                     "WIZNET_IFCONFIG_3": "",
+                    "WIZNET_HOSTNAME": '"{0}"'.format(hostname) if hostname else '""',
                 }
                 if config == "dhcp"
                 else {
@@ -1588,8 +1613,9 @@
 
         else:
             # step 1: generate the wiznet_config.py file
-            ifconfig = "ifconfig = {0}\n".format(
-                "'dhcp'" if config == "dhcp" else config
+            ifconfig = "ifconfig = {0}\nhostname={1}\n".format(
+                "'dhcp'" if config == "dhcp" else config,
+                repr(hostname) if hostname else "''",
             )
             filename = os.path.join(workspace, "wiznet_config.py")
             if os.path.exists(filename):

eric ide

mercurial