network.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. ****************************************
  2. :mod:`network` --- network configuration
  3. ****************************************
  4. .. module:: network
  5. :synopsis: network configuration
  6. This module provides network drivers and routing configuration. To use this
  7. module, a MicroPython variant/build with network capabilities must be installed.
  8. Network drivers for specific hardware are available within this module and are
  9. used to configure hardware network interface(s). Network services provided
  10. by configured interfaces are then available for use via the :mod:`usocket`
  11. module.
  12. For example::
  13. # connect/ show IP config a specific network interface
  14. # see below for examples of specific drivers
  15. import network
  16. import utime
  17. nic = network.Driver(...)
  18. if not nic.isconnected():
  19. nic.connect()
  20. print("Waiting for connection...")
  21. while not nic.isconnected():
  22. utime.sleep(1)
  23. print(nic.ifconfig())
  24. # now use usocket as usual
  25. import usocket as socket
  26. addr = socket.getaddrinfo('micropython.org', 80)[0][-1]
  27. s = socket.socket()
  28. s.connect(addr)
  29. s.send(b'GET / HTTP/1.1\r\nHost: micropython.org\r\n\r\n')
  30. data = s.recv(1000)
  31. s.close()
  32. Common network adapter interface
  33. ================================
  34. This section describes an (implied) abstract base class for all network
  35. interface classes implemented by `MicroPython ports <MicroPython port>`
  36. for different hardware. This means that MicroPython does not actually
  37. provide ``AbstractNIC`` class, but any actual NIC class, as described
  38. in the following sections, implements methods as described here.
  39. .. class:: AbstractNIC(id=None, ...)
  40. Instantiate a network interface object. Parameters are network interface
  41. dependent. If there are more than one interface of the same type, the first
  42. parameter should be `id`.
  43. .. method:: active([is_active])
  44. Activate ("up") or deactivate ("down") the network interface, if
  45. a boolean argument is passed. Otherwise, query current state if
  46. no argument is provided. Most other methods require an active
  47. interface (behavior of calling them on inactive interface is
  48. undefined).
  49. .. method:: connect([service_id, key=None, \*, ...])
  50. Connect the interface to a network. This method is optional, and
  51. available only for interfaces which are not "always connected".
  52. If no parameters are given, connect to the default (or the only)
  53. service. If a single parameter is given, it is the primary identifier
  54. of a service to connect to. It may be accompanied by a key
  55. (password) required to access said service. There can be further
  56. arbitrary keyword-only parameters, depending on the networking medium
  57. type and/or particular device. Parameters can be used to: a)
  58. specify alternative service identifer types; b) provide additional
  59. connection parameters. For various medium types, there are different
  60. sets of predefined/recommended parameters, among them:
  61. * WiFi: *bssid* keyword to connect to a specific BSSID (MAC address)
  62. .. method:: disconnect()
  63. Disconnect from network.
  64. .. method:: isconnected()
  65. Returns ``True`` if connected to network, otherwise returns ``False``.
  66. .. method:: scan(\*, ...)
  67. Scan for the available network services/connections. Returns a
  68. list of tuples with discovered service parameters. For various
  69. network media, there are different variants of predefined/
  70. recommended tuple formats, among them:
  71. * WiFi: (ssid, bssid, channel, RSSI, authmode, hidden). There
  72. may be further fields, specific to a particular device.
  73. The function may accept additional keyword arguments to filter scan
  74. results (e.g. scan for a particular service, on a particular channel,
  75. for services of a particular set, etc.), and to affect scan
  76. duration and other parameters. Where possible, parameter names
  77. should match those in connect().
  78. .. method:: status([param])
  79. Query dynamic status information of the interface. When called with no
  80. argument the return value describes the network link status. Otherwise
  81. *param* should be a string naming the particular status parameter to
  82. retrieve.
  83. The return types and values are dependent on the network
  84. medium/technology. Some of the parameters that may be supported are:
  85. * WiFi STA: use ``'rssi'`` to retrieve the RSSI of the AP signal
  86. * WiFi AP: use ``'stations'`` to retrieve a list of all the STAs
  87. connected to the AP. The list contains tuples of the form
  88. (MAC, RSSI).
  89. .. method:: ifconfig([(ip, subnet, gateway, dns)])
  90. Get/set IP-level network interface parameters: IP address, subnet mask,
  91. gateway and DNS server. When called with no arguments, this method returns
  92. a 4-tuple with the above information. To set the above values, pass a
  93. 4-tuple with the required information. For example::
  94. nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))
  95. .. method:: config('param')
  96. config(param=value, ...)
  97. Get or set general network interface parameters. These methods allow to work
  98. with additional parameters beyond standard IP configuration (as dealt with by
  99. `ifconfig()`). These include network-specific and hardware-specific
  100. parameters. For setting parameters, the keyword argument
  101. syntax should be used, and multiple parameters can be set at once. For
  102. querying, a parameter name should be quoted as a string, and only one
  103. parameter can be queried at a time::
  104. # Set WiFi access point name (formally known as ESSID) and WiFi channel
  105. ap.config(essid='My AP', channel=11)
  106. # Query params one by one
  107. print(ap.config('essid'))
  108. print(ap.config('channel'))
  109. .. only:: port_pyboard
  110. class CC3K
  111. ==========
  112. This class provides a driver for CC3000 WiFi modules. Example usage::
  113. import network
  114. nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3)
  115. nic.connect('your-ssid', 'your-password')
  116. while not nic.isconnected():
  117. pyb.delay(50)
  118. print(nic.ifconfig())
  119. # now use socket as usual
  120. ...
  121. For this example to work the CC3000 module must have the following connections:
  122. - MOSI connected to Y8
  123. - MISO connected to Y7
  124. - CLK connected to Y6
  125. - CS connected to Y5
  126. - VBEN connected to Y4
  127. - IRQ connected to Y3
  128. It is possible to use other SPI busses and other pins for CS, VBEN and IRQ.
  129. Constructors
  130. ------------
  131. .. class:: CC3K(spi, pin_cs, pin_en, pin_irq)
  132. Create a CC3K driver object, initialise the CC3000 module using the given SPI bus
  133. and pins, and return the CC3K object.
  134. Arguments are:
  135. - *spi* is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the CC3000 is
  136. connected to (the MOSI, MISO and CLK pins).
  137. - *pin_cs* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 CS pin.
  138. - *pin_en* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 VBEN pin.
  139. - *pin_irq* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 IRQ pin.
  140. All of these objects will be initialised by the driver, so there is no need to
  141. initialise them yourself. For example, you can use::
  142. nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3)
  143. Methods
  144. -------
  145. .. method:: cc3k.connect(ssid, key=None, \*, security=WPA2, bssid=None)
  146. Connect to a WiFi access point using the given SSID, and other security
  147. parameters.
  148. .. method:: cc3k.disconnect()
  149. Disconnect from the WiFi access point.
  150. .. method:: cc3k.isconnected()
  151. Returns True if connected to a WiFi access point and has a valid IP address,
  152. False otherwise.
  153. .. method:: cc3k.ifconfig()
  154. Returns a 7-tuple with (ip, subnet mask, gateway, DNS server, DHCP server,
  155. MAC address, SSID).
  156. .. method:: cc3k.patch_version()
  157. Return the version of the patch program (firmware) on the CC3000.
  158. .. method:: cc3k.patch_program('pgm')
  159. Upload the current firmware to the CC3000. You must pass 'pgm' as the first
  160. argument in order for the upload to proceed.
  161. Constants
  162. ---------
  163. .. data:: CC3K.WEP
  164. .. data:: CC3K.WPA
  165. .. data:: CC3K.WPA2
  166. security type to use
  167. class WIZNET5K
  168. ==============
  169. This class allows you to control WIZnet5x00 Ethernet adaptors based on
  170. the W5200 and W5500 chipsets. The particular chipset that is supported
  171. by the firmware is selected at compile-time via the MICROPY_PY_WIZNET5K
  172. option.
  173. Example usage::
  174. import network
  175. nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4)
  176. print(nic.ifconfig())
  177. # now use socket as usual
  178. ...
  179. For this example to work the WIZnet5x00 module must have the following connections:
  180. - MOSI connected to X8
  181. - MISO connected to X7
  182. - SCLK connected to X6
  183. - nSS connected to X5
  184. - nRESET connected to X4
  185. It is possible to use other SPI busses and other pins for nSS and nRESET.
  186. Constructors
  187. ------------
  188. .. class:: WIZNET5K(spi, pin_cs, pin_rst)
  189. Create a WIZNET5K driver object, initialise the WIZnet5x00 module using the given
  190. SPI bus and pins, and return the WIZNET5K object.
  191. Arguments are:
  192. - *spi* is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the WIZnet5x00 is
  193. connected to (the MOSI, MISO and SCLK pins).
  194. - *pin_cs* is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nSS pin.
  195. - *pin_rst* is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nRESET pin.
  196. All of these objects will be initialised by the driver, so there is no need to
  197. initialise them yourself. For example, you can use::
  198. nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4)
  199. Methods
  200. -------
  201. .. method:: wiznet5k.isconnected()
  202. Returns ``True`` if the physical Ethernet link is connected and up.
  203. Returns ``False`` otherwise.
  204. .. method:: wiznet5k.ifconfig([(ip, subnet, gateway, dns)])
  205. Get/set IP address, subnet mask, gateway and DNS.
  206. When called with no arguments, this method returns a 4-tuple with the above information.
  207. To set the above values, pass a 4-tuple with the required information. For example::
  208. nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))
  209. .. method:: wiznet5k.regs()
  210. Dump the WIZnet5x00 registers. Useful for debugging.
  211. .. _network.WLAN:
  212. .. only:: port_esp8266
  213. Functions
  214. =========
  215. .. function:: phy_mode([mode])
  216. Get or set the PHY mode.
  217. If the *mode* parameter is provided, sets the mode to its value. If
  218. the function is called without parameters, returns the current mode.
  219. The possible modes are defined as constants:
  220. * ``MODE_11B`` -- IEEE 802.11b,
  221. * ``MODE_11G`` -- IEEE 802.11g,
  222. * ``MODE_11N`` -- IEEE 802.11n.
  223. class WLAN
  224. ==========
  225. This class provides a driver for WiFi network processor in the ESP8266. Example usage::
  226. import network
  227. # enable station interface and connect to WiFi access point
  228. nic = network.WLAN(network.STA_IF)
  229. nic.active(True)
  230. nic.connect('your-ssid', 'your-password')
  231. # now use sockets as usual
  232. Constructors
  233. ------------
  234. .. class:: WLAN(interface_id)
  235. Create a WLAN network interface object. Supported interfaces are
  236. ``network.STA_IF`` (station aka client, connects to upstream WiFi access
  237. points) and ``network.AP_IF`` (access point, allows other WiFi clients to
  238. connect). Availability of the methods below depends on interface type.
  239. For example, only STA interface may `connect()` to an access point.
  240. Methods
  241. -------
  242. .. method:: wlan.active([is_active])
  243. Activate ("up") or deactivate ("down") network interface, if boolean
  244. argument is passed. Otherwise, query current state if no argument is
  245. provided. Most other methods require active interface.
  246. .. method:: wlan.connect(ssid=None, password=None, \*, bssid=None)
  247. Connect to the specified wireless network, using the specified password.
  248. If *bssid* is given then the connection will be restricted to the
  249. access-point with that MAC address (the *ssid* must also be specified
  250. in this case).
  251. .. method:: wlan.disconnect()
  252. Disconnect from the currently connected wireless network.
  253. .. method:: wlan.scan()
  254. Scan for the available wireless networks.
  255. Scanning is only possible on STA interface. Returns list of tuples with
  256. the information about WiFi access points:
  257. (ssid, bssid, channel, RSSI, authmode, hidden)
  258. *bssid* is hardware address of an access point, in binary form, returned as
  259. bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form.
  260. There are five values for authmode:
  261. * 0 -- open
  262. * 1 -- WEP
  263. * 2 -- WPA-PSK
  264. * 3 -- WPA2-PSK
  265. * 4 -- WPA/WPA2-PSK
  266. and two for hidden:
  267. * 0 -- visible
  268. * 1 -- hidden
  269. .. method:: wlan.status([param])
  270. Return the current status of the wireless connection.
  271. When called with no argument the return value describes the network link status.
  272. The possible statuses are defined as constants:
  273. * ``STAT_IDLE`` -- no connection and no activity,
  274. * ``STAT_CONNECTING`` -- connecting in progress,
  275. * ``STAT_WRONG_PASSWORD`` -- failed due to incorrect password,
  276. * ``STAT_NO_AP_FOUND`` -- failed because no access point replied,
  277. * ``STAT_CONNECT_FAIL`` -- failed due to other problems,
  278. * ``STAT_GOT_IP`` -- connection successful.
  279. When called with one argument *param* should be a string naming the status
  280. parameter to retrieve. Supported parameters in WiFI STA mode are: ``'rssi'``.
  281. .. method:: wlan.isconnected()
  282. In case of STA mode, returns ``True`` if connected to a WiFi access
  283. point and has a valid IP address. In AP mode returns ``True`` when a
  284. station is connected. Returns ``False`` otherwise.
  285. .. method:: wlan.ifconfig([(ip, subnet, gateway, dns)])
  286. Get/set IP-level network interface parameters: IP address, subnet mask,
  287. gateway and DNS server. When called with no arguments, this method returns
  288. a 4-tuple with the above information. To set the above values, pass a
  289. 4-tuple with the required information. For example::
  290. nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))
  291. .. method:: wlan.config('param')
  292. .. method:: wlan.config(param=value, ...)
  293. Get or set general network interface parameters. These methods allow to work
  294. with additional parameters beyond standard IP configuration (as dealt with by
  295. `wlan.ifconfig()`). These include network-specific and hardware-specific
  296. parameters. For setting parameters, keyword argument syntax should be used,
  297. multiple parameters can be set at once. For querying, parameters name should
  298. be quoted as a string, and only one parameter can be queries at time::
  299. # Set WiFi access point name (formally known as ESSID) and WiFi channel
  300. ap.config(essid='My AP', channel=11)
  301. # Query params one by one
  302. print(ap.config('essid'))
  303. print(ap.config('channel'))
  304. Following are commonly supported parameters (availability of a specific parameter
  305. depends on network technology type, driver, and `MicroPython port`).
  306. ============= ===========
  307. Parameter Description
  308. ============= ===========
  309. mac MAC address (bytes)
  310. essid WiFi access point name (string)
  311. channel WiFi channel (integer)
  312. hidden Whether ESSID is hidden (boolean)
  313. authmode Authentication mode supported (enumeration, see module constants)
  314. password Access password (string)
  315. dhcp_hostname The DHCP hostname to use
  316. ============= ===========
  317. .. only:: port_wipy
  318. class WLAN
  319. ==========
  320. This class provides a driver for the WiFi network processor in the WiPy. Example usage::
  321. import network
  322. import time
  323. # setup as a station
  324. wlan = network.WLAN(mode=WLAN.STA)
  325. wlan.connect('your-ssid', auth=(WLAN.WPA2, 'your-key'))
  326. while not wlan.isconnected():
  327. time.sleep_ms(50)
  328. print(wlan.ifconfig())
  329. # now use socket as usual
  330. ...
  331. Constructors
  332. ------------
  333. .. class:: WLAN(id=0, ...)
  334. Create a WLAN object, and optionally configure it. See `init()` for params of configuration.
  335. .. note::
  336. The ``WLAN`` constructor is special in the sense that if no arguments besides the id are given,
  337. it will return the already existing ``WLAN`` instance without re-configuring it. This is
  338. because ``WLAN`` is a system feature of the WiPy. If the already existing instance is not
  339. initialized it will do the same as the other constructors an will initialize it with default
  340. values.
  341. Methods
  342. -------
  343. .. method:: wlan.init(mode, \*, ssid, auth, channel, antenna)
  344. Set or get the WiFi network processor configuration.
  345. Arguments are:
  346. - *mode* can be either ``WLAN.STA`` or ``WLAN.AP``.
  347. - *ssid* is a string with the ssid name. Only needed when mode is ``WLAN.AP``.
  348. - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
  349. ``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password.
  350. If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal
  351. values (e.g. 'ABC1DE45BF'). Only needed when mode is ``WLAN.AP``.
  352. - *channel* a number in the range 1-11. Only needed when mode is ``WLAN.AP``.
  353. - *antenna* selects between the internal and the external antenna. Can be either
  354. ``WLAN.INT_ANT`` or ``WLAN.EXT_ANT``.
  355. For example, you can do::
  356. # create and configure as an access point
  357. wlan.init(mode=WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2,'www.wipy.io'), channel=7, antenna=WLAN.INT_ANT)
  358. or::
  359. # configure as an station
  360. wlan.init(mode=WLAN.STA)
  361. .. method:: wlan.connect(ssid, \*, auth=None, bssid=None, timeout=None)
  362. Connect to a WiFi access point using the given SSID, and other security
  363. parameters.
  364. - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
  365. ``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password.
  366. If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal
  367. values (e.g. 'ABC1DE45BF').
  368. - *bssid* is the MAC address of the AP to connect to. Useful when there are several
  369. APs with the same ssid.
  370. - *timeout* is the maximum time in milliseconds to wait for the connection to succeed.
  371. .. method:: wlan.scan()
  372. Performs a network scan and returns a list of named tuples with (ssid, bssid, sec, channel, rssi).
  373. Note that channel is always ``None`` since this info is not provided by the WiPy.
  374. .. method:: wlan.disconnect()
  375. Disconnect from the WiFi access point.
  376. .. method:: wlan.isconnected()
  377. In case of STA mode, returns ``True`` if connected to a WiFi access point and has a valid IP address.
  378. In AP mode returns ``True`` when a station is connected, ``False`` otherwise.
  379. .. method:: wlan.ifconfig(if_id=0, config=['dhcp' or configtuple])
  380. With no parameters given returns a 4-tuple of *(ip, subnet_mask, gateway, DNS_server)*.
  381. if ``'dhcp'`` is passed as a parameter then the DHCP client is enabled and the IP params
  382. are negotiated with the AP.
  383. If the 4-tuple config is given then a static IP is configured. For instance::
  384. wlan.ifconfig(config=('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))
  385. .. method:: wlan.mode([mode])
  386. Get or set the WLAN mode.
  387. .. method:: wlan.ssid([ssid])
  388. Get or set the SSID when in AP mode.
  389. .. method:: wlan.auth([auth])
  390. Get or set the authentication type when in AP mode.
  391. .. method:: wlan.channel([channel])
  392. Get or set the channel (only applicable in AP mode).
  393. .. method:: wlan.antenna([antenna])
  394. Get or set the antenna type (external or internal).
  395. .. method:: wlan.mac([mac_addr])
  396. Get or set a 6-byte long bytes object with the MAC address.
  397. .. method:: wlan.irq(\*, handler, wake)
  398. Create a callback to be triggered when a WLAN event occurs during ``machine.SLEEP``
  399. mode. Events are triggered by socket activity or by WLAN connection/disconnection.
  400. - *handler* is the function that gets called when the IRQ is triggered.
  401. - *wake* must be ``machine.SLEEP``.
  402. Returns an IRQ object.
  403. Constants
  404. ---------
  405. .. data:: WLAN.STA
  406. .. data:: WLAN.AP
  407. selects the WLAN mode
  408. .. data:: WLAN.WEP
  409. .. data:: WLAN.WPA
  410. .. data:: WLAN.WPA2
  411. selects the network security
  412. .. data:: WLAN.INT_ANT
  413. .. data:: WLAN.EXT_ANT
  414. selects the antenna type