|
| 1 | +--- |
| 2 | +title: Configuring Manual Devices |
| 3 | +description: Connect to the Arduino IoT Cloud any kind of device that uses Python, MicroPython or JavaScript (Node.js) |
| 4 | +author: Karl Söderby |
| 5 | +tags: [IoT Cloud, Device API, JavaScript, Node.js, Python, MicroPython] |
| 6 | +--- |
| 7 | + |
| 8 | +Authentication & data synchronisation is automatically handled when you choose the automatic configuration option in the [Arduino IoT Cloud](https://create.arduino.cc/iot/). |
| 9 | + |
| 10 | +You can during the setup of your device instead choose the manual configuration option. This allows you to connect to the cloud using the **Device API** (MicroPython, Python or Node.js). |
| 11 | + |
| 12 | +This opens up possibilities for more kinds of devices, mainly Linux based, to connect to the Arduino IoT Cloud. |
| 13 | + |
| 14 | +***Manual configuration is recommended for more advanced users, mainly those that are looking to integrate existing projects with the Arduino IoT Cloud.*** |
| 15 | + |
| 16 | +## Goals |
| 17 | + |
| 18 | +In this article you will learn how to configure a manual device, and how to connect to the Arduino IoT Cloud with: |
| 19 | +- MicroPython |
| 20 | +- Python |
| 21 | +- JavaScript (Node.js) |
| 22 | + |
| 23 | +## Hardware & Software Needed |
| 24 | + |
| 25 | +Depending on what framework you choose to connect with, you will need various requirements. |
| 26 | +- To connect using Python you need to have a [version of Python](https://www.python.org/) installed on your machine (check `python --version`). This has been tested with Python version **3.11**. |
| 27 | +- To connect using MicroPython you need to have a [GIGA R1 WiFi](https://store.arduino.cc/products/giga-r1-wifi) / [Portenta H7](https://store.arduino.cc/products/portenta-h7), with MicroPython => 1.2 installed. |
| 28 | +- To connect using JavaScript, you will need to install [Node.js](https://nodejs.org/en) is required to be installed to connect via JS. |
| 29 | + |
| 30 | +Each method of interaction with the Device API requires various levels of complexity. |
| 31 | + |
| 32 | +## Device API |
| 33 | + |
| 34 | +The **Device API** allows you to interact with the Arduino IoT Cloud MQTT broker, by sending/receiving updates from your IoT Cloud variables. |
| 35 | + |
| 36 | +This API is ideal for you who'd like to integrate existing Python or JavaScript projects with Arduino. |
| 37 | + |
| 38 | +This API is currently split between two repositories: |
| 39 | +- [arduino-iot-js](https://github.com/arduino/arduino-iot-js) - for Node.js / JavaScript |
| 40 | +- [arduino-iot-cloud-py](https://github.com/arduino/arduino-iot-cloud-py) for Python / MicroPython |
| 41 | + |
| 42 | +Note that the Device API is designed to interact with the MQTT broker. To manage devices, Things etc., please refer to the [Application API](https://www.arduino.cc/reference/en/iot/api) which can be interacted with using HTTP requests. |
| 43 | + |
| 44 | +## Configure Manual Devices |
| 45 | + |
| 46 | +To configure a manual device, go to [devices in the IoT Cloud](https://create.arduino.cc/iot/devices), and click the **"Add"** button. This will open a new window, where you will be asked to either configure automatically, or manually. Choose the **"Manual"** option. |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +Follow the steps (name your device), and at the end of the wizard you will receive your credentials, which you can also download as a PDF. |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | +***Make sure to save the credentials, as the Secret Key will no longer be obtainable after completing the installation.*** |
| 55 | + |
| 56 | +After you have created your device, you need to link it to a Thing before using it. This is done in the Thing interface, under **"Associated Devices"**. |
| 57 | + |
| 58 | +## MicroPython |
| 59 | + |
| 60 | +The pre-requisities for connecting the the IoT Cloud via MicroPython are: |
| 61 | +- A [GIGA R1 WiFi](https://store.arduino.cc/products/giga-r1-wifi) / [Portenta H7](https://store.arduino.cc/products/portenta-h7) board with MicroPython installed, |
| 62 | +- [Arduino Lab for MicroPython](https://labs.arduino.cc/en/labs/micropython) code editor, |
| 63 | +- [arduino-iot-cloud-py](https://github.com/arduino/arduino-iot-cloud-py) installed, |
| 64 | + |
| 65 | + |
| 66 | +To install MicroPython, you can check out the [Installation Guide](/micropython/basics/board-installation#giga-r1-wifi). The installation process is the same for both boards as they are based on the same MCU (STM32H7). |
| 67 | + |
| 68 | +To connect with MicroPython, you will need to have a manual device created in the IoT Cloud. When you create it, you will receive a **Device ID** and a **Secret Key**. |
| 69 | + |
| 70 | +### MicroPython Example |
| 71 | + |
| 72 | +Below is a script that connects to the cloud, and allows you to control the onboard LED from a dashboard in the cloud. You will need to have exactly matching variables created inside your Thing in the cloud for this to work. For example: |
| 73 | +- `client.register("led", value=None)` requires a variable named `led`. |
| 74 | + |
| 75 | +```python |
| 76 | +from machine import Pin |
| 77 | +import time |
| 78 | +import network |
| 79 | +import logging |
| 80 | +from arduino_iot_cloud import ArduinoCloudClient |
| 81 | + |
| 82 | +WIFI_SSID = "WIFI_NETWORK" |
| 83 | +WIFI_PASSWORD = "WIFI_PASSWORD" |
| 84 | +DEVICE_ID = "YOUR_DEVICE_ID" |
| 85 | +SECRET_KEY = "YOUR_SECRET_KEY" |
| 86 | + |
| 87 | +led = Pin("LEDB", Pin.OUT) # Configure the desired LED pin as an output. |
| 88 | + |
| 89 | +def on_switch_changed(client, value): |
| 90 | + # Toggles the hardware LED on or off. |
| 91 | + led.value(not value) |
| 92 | + |
| 93 | + # Sets the value of the cloud variable "led" to the current state of the LED |
| 94 | + # and thus mirrors the hardware state in the cloud. |
| 95 | + client["led"] = value |
| 96 | + |
| 97 | +def wifi_connect(): |
| 98 | + if not WIFI_SSID or not WIFI_PASSWORD: |
| 99 | + raise (Exception("Network is not configured. Set SSID and passwords in secrets.py")) |
| 100 | + wlan = network.WLAN(network.STA_IF) |
| 101 | + wlan.active(True) |
| 102 | + wlan.connect(WIFI_SSID, WIFI_PASSWORD) |
| 103 | + while not wlan.isconnected(): |
| 104 | + logging.info("Trying to connect. Note this may take a while...") |
| 105 | + time.sleep_ms(500) |
| 106 | + logging.info(f"WiFi Connected {wlan.ifconfig()}") |
| 107 | + |
| 108 | +if __name__ == "__main__": |
| 109 | + # Configure the logger. |
| 110 | + # All message equal or higher to the logger level are printed. |
| 111 | + # To see more debugging messages, set level=logging.DEBUG. |
| 112 | + logging.basicConfig( |
| 113 | + datefmt="%H:%M:%S", |
| 114 | + format="%(asctime)s.%(msecs)03d %(message)s", |
| 115 | + level=logging.INFO, |
| 116 | + ) |
| 117 | + |
| 118 | + # NOTE: Add networking code here or in boot.py |
| 119 | + wifi_connect() |
| 120 | + |
| 121 | + # Create a client object to connect to the Arduino IoT cloud. |
| 122 | + # For MicroPython, the key and cert files must be stored in DER format on the filesystem. |
| 123 | + # Alternatively, a username and password can be used to authenticate: |
| 124 | + client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=SECRET_KEY) |
| 125 | + |
| 126 | + # Register cloud objects. |
| 127 | + # Note: The following objects must be created first in the dashboard and linked to the device. |
| 128 | + # This cloud object is initialized with its last known value from the cloud. When this object is updated |
| 129 | + # from the dashboard, the on_switch_changed function is called with the client object and the new value. |
| 130 | + client.register("ledSwitch", value=None, on_write=on_switch_changed, interval=0.250) |
| 131 | + |
| 132 | + # This cloud object is updated manually in the switch's on_write_change callback to update the LED state in the cloud. |
| 133 | + client.register("led", value=None) |
| 134 | + |
| 135 | + # Start the Arduino IoT cloud client. |
| 136 | + client.start() |
| 137 | +``` |
| 138 | + |
| 139 | +For a more details, you can visit a more complete guide at [Connecting to Arduino IoT Cloud using MicroPython](/arduino-cloud/getting-started/iot-cloud-micropython). |
| 140 | + |
| 141 | +## Python |
| 142 | + |
| 143 | +The pre-requisities for connecting with Python is: |
| 144 | +- [Python](https://www.python.org/) installed on your machine (this is tested and confirmed to work with v3.11), |
| 145 | +- [arduino-iot-cloud-py](https://github.com/arduino/arduino-iot-cloud-py) installed, |
| 146 | +- a Thing + device created in the Arduino IoT Cloud. |
| 147 | + |
| 148 | +Connection to the cloud via Python uses the same API as the MicroPython example listed in this article. To install the [arduino-iot-cloud-py](https://github.com/arduino/arduino-iot-cloud-py) module, we can use `pip`. |
| 149 | + |
| 150 | +```py |
| 151 | +pip install arduino-iot-cloud-py |
| 152 | +``` |
| 153 | + |
| 154 | +You will also need to have configured a manual device in the cloud. The **Device ID** and **Secret Key** are required in your script to authenticate. To connect, we use the following command: |
| 155 | + |
| 156 | +```python |
| 157 | +client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=SECRET_KEY) |
| 158 | +``` |
| 159 | + |
| 160 | +To use the script further below, you will need to create a Thing with the following variables: |
| 161 | +- `ledSwitch` - boolean |
| 162 | +- `temperature` - float |
| 163 | + |
| 164 | +The variables are set up to test bi-directional communication between the cloud and the manual device. The `temperature` variable will send just a dummy value to the cloud, and the `ledSwitch` will send data from the cloud to the manual device. |
| 165 | + |
| 166 | +In the script, we need register the variables to use them, and set some parameters. |
| 167 | + |
| 168 | +```python |
| 169 | +# register and send "temperature" data |
| 170 | +client.register("temperature") |
| 171 | +client["temperature"] = 20 |
| 172 | + |
| 173 | +# register and set callback (on_switch_changed) |
| 174 | +client.register("ledSwitch", value=None, on_write=on_switch_changed) |
| 175 | +``` |
| 176 | + |
| 177 | +### Python Example |
| 178 | + |
| 179 | +Below is a script that you can use to test out the API. Make sure to replace the `DEVICE_ID` and `SECRET_KEY` entries with your own credentials. |
| 180 | + |
| 181 | +```python |
| 182 | +import time |
| 183 | +import logging |
| 184 | + |
| 185 | +import sys |
| 186 | +sys.path.append("lib") |
| 187 | + |
| 188 | +from arduino_iot_cloud import ArduinoCloudClient |
| 189 | + |
| 190 | +DEVICE_ID = b"YOUR_DEVICE_ID" |
| 191 | +SECRET_KEY = b"YOUR_SECRET_KEY" |
| 192 | + |
| 193 | +def logging_func(): |
| 194 | + logging.basicConfig( |
| 195 | + datefmt="%H:%M:%S", |
| 196 | + format="%(asctime)s.%(msecs)03d %(message)s", |
| 197 | + level=logging.INFO, |
| 198 | + ) |
| 199 | + |
| 200 | +# This function is executed each time the "ledSwitch" variable changes |
| 201 | +def on_switch_changed(client, value): |
| 202 | + print("Switch Pressed! Status is: ", value) |
| 203 | + |
| 204 | +if __name__ == "__main__": |
| 205 | + |
| 206 | + logging_func() |
| 207 | + client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=SECRET_KEY) |
| 208 | + |
| 209 | + client.register("temperature") |
| 210 | + client["temperature"] = 20 |
| 211 | + client.register("ledSwitch", value=None, on_write=on_switch_changed) |
| 212 | + |
| 213 | + client.start() |
| 214 | +``` |
| 215 | + |
| 216 | +Once you run the script, you will start the client and you will be able to interact with it from a dashboard. The script is setup so that anytime the `ledSwitch` changes, we will print the current state of the variable (true/false) in the REPL. |
| 217 | + |
| 218 | +## JavaScript/Node.js |
| 219 | + |
| 220 | +The pre-requisities for connecting with Node.js is: |
| 221 | +- [Node.js](https://nodejs.org/en) installed on your machine (this is tested and confirmed to work with v20.2.0), |
| 222 | +- [arduino-iot-js](https://github.com/arduino/arduino-iot-js) installed, |
| 223 | +- a Thing created in the Arduino IoT Cloud. |
| 224 | + |
| 225 | +Connection to the cloud via Node.js/Javascript requires you to first install the [arduino-iot-js](https://github.com/arduino/arduino-iot-js) package. |
| 226 | + |
| 227 | +```sh |
| 228 | +npm install arduino-iot-js |
| 229 | +``` |
| 230 | + |
| 231 | +After installation, you can use the example below to connect and send variable updates to the cloud. Replace the following variables with your credentials: |
| 232 | + |
| 233 | +- `THING_ID` - obtained from your Thing, |
| 234 | +- `NAME_OF_VARIABLE` - name of your variable, obtained from your Thing, |
| 235 | +- `CLIENT_ID` - obtained from [API key section](https://cloud.arduino.cc/home/api-keys), |
| 236 | +- `CLIENT_SECRET` - only obtainable during creation of your API key. |
| 237 | + |
| 238 | + |
| 239 | +### JavaScript Example |
| 240 | + |
| 241 | +This example connects to the cloud (MQTT broker), and sends a variable update with `sendProperty()`. The parameters of `sendProperty()` are `thingId`, `variableName` and `value`. |
| 242 | + |
| 243 | +***Please note: the variable name you enter in the script needs to match the variable name in the cloud.*** |
| 244 | + |
| 245 | +```js |
| 246 | +const { ArduinoIoTCloud } = require('arduino-iot-js'); |
| 247 | +const thingId = "THING_ID" |
| 248 | +const variableName = "NAME_OF_VARIABLE" |
| 249 | + |
| 250 | +const options = { |
| 251 | + clientId: "CLIENT_ID", |
| 252 | + clientSecret: "CLIENT_SECRET", |
| 253 | + onDisconnect: message => { |
| 254 | + console.error(message); |
| 255 | + } |
| 256 | +} |
| 257 | + |
| 258 | +ArduinoIoTCloud.connect(options).then(() => { |
| 259 | + console.log("Connected to Arduino IoT Cloud broker"); |
| 260 | + ArduinoIoTCloud.sendProperty(thingId, variableName, 40).then(() => { |
| 261 | + console.log("Property value correctly sent: ", variableName, 40); |
| 262 | + }); |
| 263 | + |
| 264 | +}); |
| 265 | +``` |
| 266 | + |
| 267 | +On success, we should see the following: |
| 268 | + |
| 269 | +```sh |
| 270 | +Property value correctly sent: test_variable 40 |
| 271 | +``` |
| 272 | + |
| 273 | +This means you have successfully updated the `test_variable` with a value of `40`. |
| 274 | + |
| 275 | +## Summary |
| 276 | + |
| 277 | +In this article, you have learned about the Arduino IoT Cloud's **Device API**, and how to connect to it using MicroPython, Python & JavaScript (Node.js). |
| 278 | + |
| 279 | +This API makes it easier to integrate existing software projects written in Python & JavaScript. |
| 280 | + |
| 281 | + |
| 282 | + |
| 283 | + |
0 commit comments