Merge pull request #316 from pycom/network-examples

Network examples
This commit is contained in:
gijsio
2020-09-18 12:50:18 +02:00
committed by GitHub
20 changed files with 140 additions and 93 deletions

View File

@@ -22,7 +22,7 @@ The datasheet of the GPy is available as a [PDF File](/gitbook/assets/specsheets
The drawing of the LTE-M antenna is available as a [PDF File](/gitbook/assets/lte-m-antenna-drawing.pdf)
The Gpy is certified for [CE RED](/gitbook/assets/c03-b0-red-gpy.pdf) and [FCC DSS](/gitbook/assets/pycom-2ajmtgpy01r-fcc-grant-dss.pdf) [FCC DTS](/gitbook/assets/pycom-2ajmtgpy01r-fcc-grant-dts.pdf) [FCC TNB](//gitbook/assets/pycom-2ajmtgpy01r-fcc-grant-tnb.pdf)
The Gpy is certified for [CE RED](/gitbook/assets/c03-b0-red-gpy.pdf) and [FCC DSS](/gitbook/assets/pycom-2ajmtgpy01r-fcc-grant-dss.pdf) [FCC DTS](/gitbook/assets/pycom-2ajmtgpy01r-fcc-grant-dts.pdf) [FCC TNB](/gitbook/assets/pycom-2ajmtgpy01r-fcc-grant-tnb.pdf)
[RCM](/gitbook/assets/RCM-Gpy.pdf)
[ROHS certification](/gitbook/assets/RoHs_declarations/RoHS-for-GPy(8217-00090P)-20190523.pdf)

View File

@@ -46,5 +46,5 @@ Always attach the appropriate antenna when using a wireless connection (LoRa / S
### Power
Do not use the 3.3V pin **in combination with** the Vin pin to supply the device as this will damage the voltage regulator on the board.
### Antennas
### Antenna placement
Always attach the appropriate antenna when using a wireless connection (LoRa / LTE). For WiFi / BLE, it is not mandatory to use an external antenna when you did not explicitly specify this in your code.

View File

@@ -239,7 +239,7 @@ Enable the Mesh network. Only after Mesh enabling the `lora.cli()` and `socket`
### lora.cli()
Send OpenThread CLI commands, the list is [here](https://github.com/openthread/openthread/blob/master/src/cli/README). The output is multiline string, having as line-endings the `\r\n`.
Send OpenThread CLI commands, the list is [here](https://github.com/openthread/openthread/tree/master/src/cli/). The output is multiline string, having as line-endings the `\r\n`.
```bash
>>> print(lora.cli("ipaddr"))

View File

@@ -47,7 +47,7 @@ Create a WLAN object, and optionally configure it. See init for params of config
## Methods
#### wlan.init(mode, [ssid=None, auth=None, channel=1, antenna=WLAN.INT_ANT, power_save=False, hidden=False, bandwidth=HT40, max_tx_pwr=20, country=NA, protocol=(1,1,1)])
#### wlan.init(mode, [ssid=None, auth=None, channel=1, antenna=WLAN.INT_ANT, power_save=False, hidden=False, bandwidth=WLAN.HT40, max_tx_pwr, country=NA, protocol=(1,1,1)])
Set or get the WiFi network processor configuration.
@@ -218,24 +218,11 @@ Each element of the returned list is a tuple, containing the MAC address and IP
### wlan.max_tx_power([power])
Gets or Sets the maximum allowable transmission power for wifi.
Gets or Sets the maximum allowable transmission power for wifi. This is also related to the country setting.
Packets of different rates are transmitted in different powers according to the configuration in phy init data. This API only sets maximum WiFi transmiting power. If this API is called, the transmiting power of every packet will be less than or equal to the value set by this API. Default is Level 0.
Packets of different rates are transmitted in different powers according to the configuration in phy init data. This API only sets maximum WiFi transmiting power. If this API is called, the transmiting power of every packet will be less than or equal to the value set by this API.
Values passed in power are mapped to transmit power levels as follows:
* [78, 127]: level0
* [76, 77]: level1
* [74, 75]: level2
* [68, 73]: level3
* [60, 67]: level4
* [52, 59]: level5
* [44, 51]: level5 - 2dBm
* [34, 43]: level5 - 4.5dBm
* [28, 33]: level5 - 6dBm
* [20, 27]: level5 - 8dBm
* [8, 19]: level5 - 11dBm
* [-128, 7]: level5 - 14dBm
Values passed in the `power` argument are mapped to transmit power level in dBm. Possible values are between 8 and 78, where 8 corresponds to 2dBm and 78 to 20dBm. All values in between increase the maximum output power in 0.25dBm increments.
### wlan.country([country, schan, nchan, max_tx_pwr, policy])

View File

@@ -58,9 +58,9 @@ If you are registering multiple devices you can generate more Applications Keys
Once you have the three identifiers for your device you need to register them on the Objenius portal.
Follow "Importer des capteurs" under "Statuc do Parc" and select "Provisioning Unitaire":
![](//gitbook/assets/objeniousprovision1.jpg)
![](/gitbook/assets/objeniousprovision1.jpg)
Once there give your device a name and enter the DevEUI, AppEUI, and AppKey obtained from the steps above:
![](//gitbook/assets/objeniousprovision2.jpg)
![](/gitbook/assets/objeniousprovision2.jpg)

View File

@@ -10,15 +10,15 @@ This Micropython library is included as frozen scripts in the Pymesh firmware re
The code is open-sourced in [pycom-libraries repository](https://github.com/pycom/pycom-libraries/blob/master/pymesh/pymesh_frozen/lib/pymesh.py).
It is easily customisable and contributions are welcome using [Github PRs](https://github.com/pycom/pycom-libraries/pulls).
It is easily customisable and contributions are welcome using [Github PRs](https://github.com/pycom/pycom-libraries/pulls/).
### Main features
* Start Pymesh over LoRa on 863Mhz, bandwidth 250kHz, spreading-factor 7 (please check `pymesh_config.py` defaults for exact values).
* Pymesh parameters are automatically saved in NVM, so in the next restart/deepsleep, the node will try to maintain its IP addresses and connections with neighbour nodes.
* Start Bluetooth LE server with name `PyGo <LoRa MAC>`
* BLE is used with an RPC protocol, presented int [Pymesh library BLE RPC](/pymesh/lib-ble-rpc)
* Internal CLI for controlling/triggering Pymesh features, as explained in [Pymesh library CLI](/pymesh/lib-cli).
* BLE is used with an RPC protocol, presented int [Pymesh library BLE RPC](/pymesh/lib-ble-rpc/)
* Internal CLI for controlling/triggering Pymesh features, as explained in [Pymesh library CLI](/pymesh/lib-cli/).
### Color coding LED
@@ -40,17 +40,17 @@ A simple example of usage is in the [main.py](https://github.com/pycom/pycom-lib
## Specifications
It can be easily customised, by modifying any file from [/lib folder](https://github.com/pycom/pycom-libraries/tree/master/lib/pymesh/lib) and flashing it to the board. The uploaded file will automatically be executed instead of the _frozen_ one, which is already embedded into the binary firmware.
It can be easily customised, by modifying any file from [/lib folder](https://github.com/pycom/pycom-libraries/tree/master/pymesh/lib/) and flashing it to the board. The uploaded file will automatically be executed instead of the _frozen_ one, which is already embedded into the binary firmware.
### Structure
* `pymesh.py`
* contains all the methods accessible from `main.py`
* `cli.py`
* [Pymesh library CLI](/pymesh/lib-cli)
* [Pymesh library CLI](/pymesh/lib-cli/)
* BLE services
* `ble_rpc.py`
* [Pymesh library BLE RPC](/pymesh/lib-ble-rpc)
* [Pymesh library BLE RPC](/pymesh/lib-ble-rpc/)
* `ble_services.py`
* setting BLE server
* auxiliary files:

View File

@@ -10,8 +10,6 @@ The Pymesh mobile application is available [here for both iOS and Android platfo
## RPC protocol
It is implemented in [ble_rpc.py](https://github.com/pycom/pycom-libraries/blob/master/lib/pymesh/lib/ble_rpc.py).
In the class `RPCHandler` methods can be added to expand RPC set.
The internal RPC are calling methods from file `mesh_interface.py`.

View File

@@ -0,0 +1,18 @@
---
title: "MDNS"
---
On this page, we will explore the Multicast DNS feature. MDNS is very useful for connecting to a device of which you do not know the IP address, and works similar to the Domain Name System, on a local network without the need for a DNS server. You can use the `hostname.local` url to connect. To be able to use MDNS on your computer, you might need some additional software.
* Windows:
* MacOS: built in!
* Linux:
## Use MDNS for a Telnet connection
```python
from network import MDNS
MDNS.init()
MDNS.set_name(hostname ="pycom", instance_name="pycom")
MDNS.add_service("_http",MDNS.PROTO_TCP, 80)
MDNS.add_service("_telnetd", MDNS.PROTO_TCP, 23)
```
When this is running on your development board, you can go to your terminal and try `ping pycom.local`. The second service activate the telnet link, so you can also try `telnet pycom.local` and connect to the REPL through this method!

View File

@@ -6,7 +6,7 @@ title: 'Networks'
The Pycom devices support several different types of networks.
We have the WiFi and Bluetooth connections:
* [WiFi](../networks/wifi/)
* [WiFi](../networks/wlan/)
* [Bluetooth Low Energy](../networks/ble/)
* [LoRa](../networks/lora/)
* [Sigfox]( ../networks/sigfox/)

View File

@@ -6,7 +6,11 @@ aliases:
- chapter/tutorials/all/ble
---
At present, basic BLE functionality is available. More features will be implemented in the near future, such as pairing. This page will be updated in line with these features.
On this page we cover
1. [Scanning for BLE devices](#scan-for-ble-devices)
2. [Connecting to a BLE device](#connect-to-a-ble-device)
1. [Retrieve data](#connect-to-a-ble-device-and-retrieve-data)
2. [Retrieve manufacturer](#connect-to-a-ble-device-and-get-name-and-manufacturer-data)
## Scan for BLE devices
@@ -47,7 +51,7 @@ while True:
print("Connected to device with addr = {}".format(ubinascii.hexlify(adv.mac)))
```
## Connect to a BLE Device and retrieve data
### Connect to a BLE Device and retrieve data
Connecting to a device named 'Heart Rate' and receiving data from it's services.
@@ -81,7 +85,7 @@ while True:
time.sleep(0.050)
```
## Connect to a BLE device and get name and manufacturer data
### Connect to a BLE device and get name and manufacturer data
Using `resolve_adv_data()` to attempt to retrieve the name and manufacturer data from the advertiser.

View File

@@ -6,6 +6,12 @@ aliases:
The following tutorials demonstrate the use of the LoRa functionality on the LoPy. LoRa can work in 2 different modes; **LoRa-MAC** (which we also call Raw-LoRa) and **LoRaWAN** mode.
> Note: LoRa will not work with Pygate firmware loaded on your device. It will return a `/event_groups.c:498 (xEventGroupClearBits)- assert failed!` error.
When using Lora, **Always** connect the appropriate LoRa antenna to your device. See the figures below for the correct antenna placement
| Lopy / Fipy | Lopy4 |
|:---|:---|
| ![](/gitbook/assets/lora_pigtail_lopy.png) | ![](/gitbook/assets/lora_sigfox_pigtail_lopy4.png) |
* **LoRaWAN mode** implements the full LoRaWAN stack for a class A device. It supports both OTAA and ABP connection methods, as well as advanced features like adding and removing custom channels to support "special" frequencies plans like the those used in New Zealand. There are two basic ways of accessing the LoraWAN network:
* [LoRaWAN ABP](../lora/lorawan-abp/)
* [LoRaWAN OTAA](../lora/lorawan-otaa/)

View File

@@ -6,49 +6,46 @@ aliases:
- chapter/tutorials/lora/module-module
---
This example shows how to connect two Pycode LoRa capable modules (nodes) via raw LoRa.
This example shows how to connect two Pycom LoRa capable modules (nodes) via raw LoRa. **Node A** will continuously send a packet containing `Ping`. Once **Node B** receives such a packet, it will respond with `Pong`. You will see the count messages appear in the REPL. You can adapt this example to have mutual communication between two LoRa nodes.
## Node A
```python
from network import LoRa
import socket
import time
# Please pick the region that matches where you are using the device:
# Asia = LoRa.AS923
# Australia = LoRa.AU915
# Europe = LoRa.EU868
# United States = LoRa.US915
# Please pick the region that matches where you are using the device
lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)
i = 0
while True:
if s.recv(64) == b'Ping':
s.send('Pong')
s.send('Ping')
print('Ping {}'.format(i))
i= i+1
time.sleep(5)
```
## Node B
```python
from network import LoRa
import socket
import time
# Please pick the region that matches where you are using the device:
# Asia = LoRa.AS923
# Australia = LoRa.AU915
# Europe = LoRa.EU868
# United States = LoRa.US915
# Please pick the region that matches where you are using the device
lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)
i = 0
while True:
s.send('Ping')
if s.recv(64) == b'Ping':
s.send('Pong')
print('Pong {}'.format(i))
i = i+1
time.sleep(5)
```

View File

@@ -6,6 +6,15 @@ aliases:
The following tutorial demonstrates the use of the LTE CAT-M1 and NB-IoT functionality on cellular enabled Pycom modules.
> Before you start, make sure that your Simcard is registered and activated with your carrier.
When using the SigFox network, **Always** connect the appropriate LoRa antenna to your device. See the figures below for the correct antenna placement
| Gpy | Fipy |
|---|---|
| ![](/gitbook/assets/lte_ant_gpy.png) | ![](/gitbook/assets/lte_ant_fipy.png) |
GPy and FiPy support both LTE CAT-M1 and NB-IoT. These are newer, low power, long range, cellular protocols. They are not the same as the full version of 2G/3G/LTE supported by cell phones, and require your local carriers to support them. At the time of writing, CAT-M1 and NB-IoT connectivity is not widely available so be sure to check with local carriers if support is available where you are. Together with the SIM card, the provider will supply you with configuration details: Usually band and APN. Use these in the example code below.
```python

View File

@@ -6,8 +6,20 @@ aliases:
- chapter/tutorials/sigfox
---
Before you start, make sure that your device was registered with [Sigfox](/gettingstarted/registration/sigfox).
> Before you start, make sure that your device was registered with [Sigfox](/gettingstarted/registration/sigfox).
When using the SigFox network, **Always** connect the appropriate LoRa antenna to your device. See the figures below for the correct antenna placement
| Lopy4 | Fipy |
|---|---|
| ![](/gitbook/assets/lora_sigfox_pigtail_lopy4.png) | ![](/gitbook/assets/lora_sigfox_pigtail_fipy.png) |
On this page we cover
1. [Connecting to Sigfox](#connecting-to-sigfox)
2. [Disengaging Sequence Numbers](#disengaging-sequence-numbers)
## Connecting to SigFox
The following tutorials demonstrate how to register and get started with the SiPy. The board can be configured for operation in various countries based upon specified RCZ zones (see the `Sigfox` class for more info). The SiPy, LoPy 4, and FiPy supports both uplink and downlink `Sigfox` messages as well as device to device communication via its FSK Mode `Sigfox`.
```python
@@ -30,10 +42,8 @@ s.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False)
s.send(bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]))
```
> Please ensure that there is an antenna connected to your device before sending/receiving Sigfox messages as in proper use (e.g. without an antenna), may damage the device.
## Disengage Sequence Number
## Disengaging Sequence Numbers
If your are experiencing issues with Sigfox connectivity, this could be due to the sequence number being out of sync. To prevent replay on the network, the Sigfox protocol uses sequence numbers. If there is a large difference between the sequence number sent by the device and the one expected by the backend, your message is dropped by the network.

View File

@@ -6,13 +6,19 @@ aliases:
- chapter/tutorials/networks/wlan
---
The WLAN (WiFi) is a system feature of all Pycom devices, therefore it is enabled by default.
The WLAN (WiFi) is a system feature of all Pycom devices, therefore it is enabled by default. The development boards include an on-board antenna by default, so no external antenna is needed to get started. When deploying your solution, you might want to consider using the external antenna to increase the wireless range.
>Note: Changing the WLAN settings while using the Telnet server might break the wireless connection to the device permanently. Please use caution or a USB cable :)
>Note: Changing the WLAN settings while using the Telnet server might break the wireless connection to the device permanently. Please use caution, or a USB cable :)
On this page, we cover:
1. [Connecting to the Device](#connecting-to-the-device)
2. [Connecting to a Router](#connecting-to-a-router)
2. [Connecting to a home Router](#connecting-to-a-router)
* [Scanning for networks](#scan-for-wifi-networks)
* [Assigning a static IP Address](#assigning-a-static-ip-address)
* [Connecting to multiple networks](#multiple-networks-using-a-static-ip-address)
* [Connecting to a WPA2 Enterprise Network](#connecting-to-a-wpa2-enterprise-network)
3. [Using an external Antenna](#using-an-external-antenna)
>Note: Generally, code in either sections is applicable to both WLAN modes.
@@ -48,7 +54,7 @@ print(wlan.ifconfig())
>Note: If the device hangs in the `while` loop, probably your network is out of reach, or you made a mistake entering your WiFi credentials.
### Scan
## Scan for WiFi networks
If you are not always in reach of your network (maybe you have a moving device), you can also scan for the network using the example below.
```python
@@ -67,17 +73,14 @@ for net in nets:
break
```
### Assigning a Static IP Address at Boot Up
If you want to connect your device to a wireless router, and access it from a telnet terminal, you can use the following example to assign a fixed ip address (`192.168.1.10`, check with your wifi network for possibilities), use the following script as `/boot.py`:
# Assigning a Static IP Address
If you want to connect your device to a wireless router, and access it from a telnet terminal, you can use the following example to assign a fixed ip address (192.168.1.10, check with your wifi network for possibilities), use the following script:
```python
import machine
from network import WLAN
wlan = WLAN() # get current object, without changing the mode
if machine.reset_cause() != machine.SOFT_RESET: #do not reset the wireless connection on soft reset.
if machine.reset_cause() != machine.SOFT_RESET:
wlan.init(mode=WLAN.STA)
# configuration below MUST match your home router settings!!
wlan.ifconfig(config=('192.168.178.107', '255.255.255.0', '192.168.1.10', '8.8.8.8')) # (ip, subnet_mask, gateway, DNS_server)
@@ -85,20 +88,18 @@ if machine.reset_cause() != machine.SOFT_RESET: #do not reset the wireless conne
if not wlan.isconnected():
# change the line below to match your network ssid, security and password
wlan.connect('mywifi', auth=(WLAN.WPA2, 'mywifikey'), timeout=5000)
print("connecting",end='')
while not wlan.isconnected():
machine.idle() # save power while waiting
time.sleep(1)
print(".",end='')
print("connected")
```
{{% hint style="info" %}}
Notice how we check for the reset cause and the connection status, this is crucial in order to be able to soft reset the LoPy during a telnet session without breaking the connection.
{{% /hint %}}
> Notice how we check for the reset cause and the connection status, this is crucial in order to be able to soft reset the LoPy during a telnet session without breaking the connection.
### Multiple Networks using a Static IP Address
The following script holds a list with nets and an optional list of `wlan_config` to set a fixed IP
The following script holds a list with nets and an optional list of wlan_config to set a fixed IP
```python
import os
import machine
@@ -113,13 +114,13 @@ known_nets = {
if machine.reset_cause() != machine.SOFT_RESET:
from network import WLAN
wl = WLAN()
wl.mode(WLAN.STA)
original_ssid = wl.ssid()
original_auth = wl.auth()
wlan = WLAN()
wlan.mode(WLAN.STA)
original_ssid = wlan.ssid()
original_auth = wlan.auth()
print("Scanning for known wifi nets")
available_nets = wl.scan()
available_nets = wlan.scan()
nets = frozenset([e.ssid for e in available_nets])
known_nets_names = frozenset([key for key in known_nets])
@@ -130,37 +131,54 @@ if machine.reset_cause() != machine.SOFT_RESET:
pwd = net_properties['pwd']
sec = [e.sec for e in available_nets if e.ssid == net_to_use][0]
if 'wlan_config' in net_properties:
wl.ifconfig(config=net_properties['wlan_config'])
wl.connect(net_to_use, (sec, pwd), timeout=10000)
while not wl.isconnected():
wlan.ifconfig(config=net_properties['wlan_config'])
wlan.connect(net_to_use, (sec, pwd), timeout=10000)
while not wlan.isconnected():
machine.idle() # save power while waiting
print("Connected to "+net_to_use+" with IP address:" + wl.ifconfig()[0])
print("Connected to "+net_to_use+" with IP address:" + wlan.ifconfig()[0])
except Exception as e:
print("Failed to connect to any known network, going into AP mode")
wl.init(mode=WLAN.AP, ssid=original_ssid, auth=original_auth, channel=6, antenna=WLAN.INT_ANT)
wlan.init(mode=WLAN.AP, ssid=original_ssid, auth=original_auth, channel=6, antenna=WLAN.INT_ANT)
```
## Connecting to a WPA2-Enterprise network
### Connecting to a WPA2-Enterprise network
There are two types of WPA2-Enterprise networks.
* **Connecting with EAP-TLS:**
Before connecting, obtain and copy the public and private keys to the device, e.g. under location `/flash/cert`. If it is required to validate the server's public key, an appropriate CA certificate (chain) must also be provided.
```python
from network import WLAN
```python
from network import WLAN
wlan = WLAN(mode=WLAN.STA)
wlan.connect(ssid='mywifi', auth=(WLAN.WPA2_ENT,), identity='myidentity', ca_certs='/flash/cert/ca.pem', keyfile='/flash/cert/client.key', certfile='/flash/cert/client.crt')
```
wlan = WLAN(mode=WLAN.STA)
wlan.connect(ssid='mywifi', auth=(WLAN.WPA2_ENT,), identity='myidentity', ca_certs='/flash/cert/ca.pem', keyfile='/flash/cert/client.key', certfile='/flash/cert/client.crt')
```
* **Connecting with EAP-PEAP or EAP-TTLS:**
In case of EAP-PEAP (or EAP-TTLS), the client key and certificate are not necessary, only a username and password pair. If it is required to validate the server's public key, an appropriate CA certificate (chain) must also be provided.
```python
from network import WLAN
wlan = WLAN(mode=WLAN.STA)
wlan.connect(ssid='mywifi', auth=(WLAN.WPA2_ENT, 'username', 'password'), [identity='myidentity', ca_certs='/flash/cert/ca.pem'])
```
## Using an external antenna
Connect a WiFi antenna to this U.FL connector on your development board. This works the same on all variants. The antenna switch is connected to `P12`.
![](/gitbook/assets/wifi_pigtail_ant_lopy4.png)
To switch the signal towards the external antenna, use
```python
from network import WLAN
wlan = WLAN(mode=WLAN.STA)
wlan.connect(ssid='mywifi', auth=(WLAN.WPA2_ENT, 'username', 'password'), identity='myidentity', ca_certs='/flash/cert/ca.pem')
wlan = WLAN()
wlan.antenna(WLAN.EXT_ANT)
```

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -293,7 +293,7 @@ img {
table {
display: table;
width: 100%;
max-width: 100%;
border-collapse: collapse;
border-spacing: 0;
overflow: auto;