src/eric7/MicroPython/Devices/RP2040Devices.py

branch
mpy_network
changeset 9878
a82014a9e57b
parent 9870
0399d3607829
child 9880
f425c58cf8e9
equal deleted inserted replaced
9877:dad1f6d37366 9878:a82014a9e57b
20 from eric7 import Globals, Preferences 20 from eric7 import Globals, Preferences
21 from eric7.EricGui.EricOverrideCursor import EricOverrideCursor 21 from eric7.EricGui.EricOverrideCursor import EricOverrideCursor
22 from eric7.EricWidgets import EricMessageBox 22 from eric7.EricWidgets import EricMessageBox
23 from eric7.EricWidgets.EricApplication import ericApp 23 from eric7.EricWidgets.EricApplication import ericApp
24 24
25 from ..EthernetDialogs import WiznetUtilities
25 from ..MicroPythonWidget import HAS_QTCHART 26 from ..MicroPythonWidget import HAS_QTCHART
26 from . import FirmwareGithubUrls 27 from . import FirmwareGithubUrls
27 from .DeviceBase import BaseDevice 28 from .DeviceBase import BaseDevice
28 29
29 30
66 5: self.tr("connection lost"), 67 5: self.tr("connection lost"),
67 6: self.tr("disconnected"), 68 6: self.tr("disconnected"),
68 7: self.tr("AP listening"), 69 7: self.tr("AP listening"),
69 8: self.tr("AP connected"), 70 8: self.tr("AP connected"),
70 9: self.tr("AP failed"), 71 9: self.tr("AP failed"),
72 },
73 "picowiz": {
74 0: self.tr("switched off"),
75 1: self.tr("switched on, inactive"),
76 2: self.tr("switched on, active"),
71 }, 77 },
72 } 78 }
73 79
74 self.__securityTranslations = { 80 self.__securityTranslations = {
75 "picow": { 81 "picow": {
1173 1179
1174 clientsList = ast.literal_eval(out.decode("utf-8")) 1180 clientsList = ast.literal_eval(out.decode("utf-8"))
1175 return clientsList, "" 1181 return clientsList, ""
1176 1182
1177 ################################################################## 1183 ##################################################################
1184 ## Methods below implement Ethernet related methods
1185 ##################################################################
1186
1187 def hasEthernet(self):
1188 """
1189 Public method to check the availability of Ethernet.
1190
1191 @return flag indicating the availability of Ethernet
1192 @rtype bool
1193 @exception OSError raised to indicate an issue with the device
1194 """
1195 command = """
1196 def has_eth():
1197 try:
1198 import network
1199 if hasattr(network, 'WIZNET5K'):
1200 return True, 'picowiz'
1201 except ImportError:
1202 pass
1203
1204 return False, ''
1205
1206 print(has_eth())
1207 del has_eth
1208 """
1209
1210 out, err = self._interface.execute(
1211 command, mode=self._submitMode, timeout=10000
1212 )
1213 if err:
1214 if not err.startswith(b"Timeout "):
1215 raise OSError(self._shortError(err))
1216 else:
1217 return False # pimoroni firmware loaded but no pico wireless present
1218 return ast.literal_eval(out.decode("utf-8"))
1219
1220 def getEthernetStatus(self):
1221 """
1222 Public method to get Ethernet status data of the connected board.
1223
1224 @return list of tuples containing the translated status data label and
1225 the associated value
1226 @rtype list of tuples of (str, str)
1227 @exception OSError raised to indicate an issue with the device
1228 """
1229 command = """{0}
1230 def ethernet_status():
1231 import network
1232 import ubinascii
1233 import ujson
1234
1235 w5x00_init()
1236
1237 res = {{
1238 'active': nic.active(),
1239 'connected': nic.isconnected(),
1240 'status': nic.status(),
1241 'ifconfig': nic.ifconfig(),
1242 'mac': ubinascii.hexlify(nic.config('mac'), ':').decode(),
1243 'hostname': network.hostname(),
1244 }}
1245 print(ujson.dumps(res))
1246
1247 ethernet_status()
1248 del ethernet_status, w5x00_init
1249 """.format(
1250 WiznetUtilities.wiznetInit()
1251 )
1252
1253 out, err = self._interface.execute(command, mode=self._submitMode)
1254 if err:
1255 raise OSError(self._shortError(err))
1256
1257 status = []
1258 ethStatus = json.loads(out.decode("utf-8"))
1259 status.append((self.tr("Active"), self.bool2str(ethStatus["active"])))
1260 status.append((self.tr("Connected"), self.bool2str(ethStatus["connected"])))
1261 status.append(
1262 (
1263 self.tr("Status"),
1264 self.__statusTranslations["picowiz"][ethStatus["status"]],
1265 )
1266 )
1267 status.append((self.tr("Hostname"), ethStatus["hostname"]))
1268 status.append((self.tr("IPv4 Address"), ethStatus["ifconfig"][0]))
1269 status.append((self.tr("Netmask"), ethStatus["ifconfig"][1]))
1270 status.append((self.tr("Gateway"), ethStatus["ifconfig"][2]))
1271 status.append((self.tr("DNS"), ethStatus["ifconfig"][3]))
1272 status.append((self.tr("MAC-Address"), ethStatus["mac"]))
1273
1274 return status
1275
1276 def connectToLan(self, config):
1277 """
1278 Public method to connect the connected device to the LAN.
1279
1280 @param config configuration for the connection (either the string 'dhcp'
1281 for a dynamic address or a tuple of four strings with the IPv4 parameters.
1282 @type str or tuple of (str, str, str, str)
1283 @return tuple containing a flag indicating success and an error message
1284 @rtype tuple of (bool, str)
1285 """
1286 command = """{0}
1287 def connect_lan(config):
1288 import time
1289
1290 w5x00_init()
1291
1292 nic.active(False)
1293 nic.active(True)
1294 nic.ifconfig(config)
1295 max_wait = 140
1296 while max_wait:
1297 if nic.isconnected():
1298 break
1299 max_wait -= 1
1300 time.sleep(0.1)
1301 print(nic.isconnected())
1302
1303 connect_lan({1})
1304 del connect_lan, w5x00_init
1305 """.format(
1306 WiznetUtilities.wiznetInit(), repr(config) if config == "dhcp" else config
1307 )
1308
1309 with EricOverrideCursor():
1310 out, err = self._interface.execute(
1311 command, mode=self._submitMode, timeout=15000
1312 )
1313 if err:
1314 return False, err
1315
1316 return out.strip() == b"True", ""
1317
1318 def disconnectFromLan(self):
1319 """
1320 Public method to disconnect from the LAN.
1321
1322 @return tuple containing a flag indicating success and an error message
1323 @rtype tuple of (bool, str)
1324 """
1325 command = """{0}
1326 def disconnect_lan():
1327 import time
1328
1329 w5x00_init()
1330
1331 nic.active(False)
1332 time.sleep(0.1)
1333 print(not nic.isconnected())
1334
1335 disconnect_lan()
1336 del disconnect_lan, w5x00_init
1337 """.format(
1338 WiznetUtilities.wiznetInit(),
1339 )
1340
1341 with EricOverrideCursor():
1342 out, err = self._interface.execute(
1343 command, mode=self._submitMode, timeout=15000
1344 )
1345 if err:
1346 return False, err
1347
1348 return out.strip() == b"True", ""
1349
1350 def checkInternetViaLan(self):
1351 """
1352 Public method to check, if the internet can be reached (LAN variant).
1353
1354 @return tuple containing a flag indicating reachability and an error string
1355 @rtype tuple of (bool, str)
1356 """
1357 command = """{0}
1358 def check_internet():
1359 import network
1360 import socket
1361
1362 w5x00_init()
1363
1364 if nic.isconnected():
1365 s = socket.socket()
1366 try:
1367 s.connect(socket.getaddrinfo('quad9.net', 80)[0][-1])
1368 s.close()
1369 print(True)
1370 except:
1371 print(False)
1372 else:
1373 print(False)
1374
1375 check_internet()
1376 del check_internet, w5x00_init
1377 """.format(
1378 WiznetUtilities.wiznetInit(),
1379 )
1380
1381 out, err = self._interface.execute(
1382 command, mode=self._submitMode, timeout=10000
1383 )
1384 if err:
1385 return False, err
1386
1387 return out.strip() == b"True", ""
1388
1389 def deactivateEthernet(self):
1390 """
1391 Public method to deactivate the Ethernet interface of the connected device.
1392
1393 @return tuple containg a flag indicating success and an error message
1394 @rtype tuple of (bool, str)
1395 """
1396 # The WIZnet 5x00 interface cannot be switched off explicitly. That means,
1397 # disconnect from the LAN is all we can do.
1398
1399 return self.disconnectFromLan()
1400
1401 def writeLanAutoConnect(self, config):
1402 """
1403 Public method to generate a script and associated configuration to connect the
1404 device to the LAN during boot time.
1405
1406 @param config configuration for the connection (either the string 'dhcp'
1407 for a dynamic address or a tuple of four strings with the IPv4 parameters.
1408 @type str or tuple of (str, str, str, str)
1409 @return tuple containing a flag indicating success and an error message
1410 @rtype tuple of (bool, str)
1411 """
1412 command = """
1413 def modify_boot():
1414 add = True
1415 try:
1416 with open('/boot.py', 'r') as f:
1417 for ln in f.readlines():
1418 if 'wiznet_connect' in ln:
1419 add = False
1420 break
1421 except:
1422 pass
1423 if add:
1424 with open('/boot.py', 'a') as f:
1425 f.write('\\nimport wiznet_connect\\n')
1426 f.write('nic = wiznet_connect.connectLan()\\n')
1427 print(True)
1428
1429 modify_boot()
1430 del modify_boot
1431 """
1432 ifconfig = "ifconfig = {0}\n".format("'dhcp'" if config == "dhcp" else config)
1433 try:
1434 # write secrets file
1435 self.putData("/wiznet_config.py", ifconfig.encode("utf-8"))
1436 # copy auto-connect file
1437 self.put(
1438 os.path.join(
1439 os.path.dirname(__file__), "MCUScripts", "picoWiznetConnect.py"
1440 ),
1441 "/wiznet_connect.py",
1442 )
1443 except OSError as err:
1444 return False, str(err)
1445
1446 # modify boot.py
1447 out, err = self._interface.execute(command, mode=self._submitMode)
1448 if err:
1449 return False, err
1450
1451 return out.decode("utf-8").strip() == "True", ""
1452
1453 def removeLanAutoConnect(self):
1454 """
1455 Public method to remove the saved IPv4 parameters from the connected device.
1456
1457 Note: This disables the LAN auto-connect feature.
1458
1459 @return tuple containing a flag indicating success and an error message
1460 @rtype tuple of (bool, str)
1461 """
1462 try:
1463 self.rm("/wiznet_config.py")
1464 except OSError as err:
1465 return False, str(err)
1466
1467 return True, ""
1468
1469 ##################################################################
1178 ## Methods below implement NTP related methods 1470 ## Methods below implement NTP related methods
1179 ################################################################## 1471 ##################################################################
1180 1472
1181 def hasNetworkTime(self): 1473 def hasNetworkTime(self):
1182 """ 1474 """
1222 def set_ntp_time(server, tz_offset, timeout): 1514 def set_ntp_time(server, tz_offset, timeout):
1223 import network 1515 import network
1224 import ntptime 1516 import ntptime
1225 import machine 1517 import machine
1226 1518
1227 if not network.WLAN(network.STA_IF).isconnected(): 1519 if hasattr(network, 'WLAN') and not network.WLAN(network.STA_IF).isconnected():
1228 return False 1520 return False
1521 elif hasattr(network, 'WIZNET5K'):
1522 try:
1523 if not nic.isconnected():
1524 return False
1525 except NameError:
1526 return False
1229 1527
1230 ntptime.host = server 1528 ntptime.host = server
1231 ntptime.timeout = timeout 1529 ntptime.timeout = timeout
1232 ntptime.settime() 1530 ntptime.settime()
1233 1531

eric ide

mercurial