aboutsummaryrefslogtreecommitdiff
path: root/public/simple-iot-application.html
blob: 2027c1c7bb7f9f3f12034825bba1c45e313d80f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<!doctype html><html lang=en-us><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><link href="data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL69vf8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv76+/8LBwQkAAAAAAAAAAAAAAAC+vb3/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL+9vf/Bv78JAAAAAAAAAAAAAAAAu7q6/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC7ubr/vr29CAAAAAAAAAAAy8nJAZ6foP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAnqGj/6GipAoAAAAAHLjU/xcXHf/BwsL/I8XY/yPK3v8XGiD/IbjL/yPF2f8XGiD/Fxkf/yLF2f8gnK3/Fxog/62ztv8fwNf/FRcd/x271v8mz93/GRsi/xkXHf8p097/GiIp/xobIv8p0t3/KdPe/xocIv8fYmr/KNPe/xoZH/8aHCL/J87c/xy81/8VFxz/IsPZ/8zS0/8XGiD/Ir/R/yPH2/8XGiD/Fxkf/yPH2/8dd4T/GBog/yPJ3f8jyNr/uru9/xcUGv8cudb/EhITDKi5vRKlvMP/RUpOERwcHRAdOj4QHTk8EBwdHRAdNTgQHTo/EBwcHRAcHB0QSGduEKW4vf+koqQfHzg+EBqz0ewSFRv7EyMr/xq51vsTERb7ExUb+xq41fsau9j7ExUb+xiPp/sZudb7ExUb+xMVG/sZuNX/GKvI/BIUGfMdvdn/IrfL/xcaIP8n1eb/J9Dh/xkcIf8ZGR7/J8/f/xxCSv8ZGyH/J9Dg/ybQ4P8ZHCL/FSQs/yPK3/8UExj/GE1b/ybS5P8ZGB7/Ghwj/ynW5P8p2Ob/Ghwi/yWrtv8p1eH/Ghwi/xocIv8p1uT/J8XT/xkcIv8m1un/Hb7d/xUYH/8hzOr/HtHu/xcaIf8XGB//I8vi/xgxOv8XGSD/I8rg/yPK4P8XGiD/GUFL/yPP6f8SERj/Fhkh/x3A4f8AAAAAJ2f9/ydr//8mZPH/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlYu38J2v//ydo/f8AAAAAAAAAAAd8/fkFqf//Iob8sAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMY39awWr//8FfP3/AAAAAAAAAAAFm/7/SfD//wR+/f8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOB/f9B7v//BaX+/wAAAAAAAAAAQ878SAyZ/v9n1v4KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADu9v8DDJb+/z3N/XgAAAAA3/sAAN/7AADf+wAA3/sAAAAAAAAAAAAAAAAAAN/7AAAAAAAAAAAAAAAAAAAAAAAAj/EAAI/5AACP8QAA3/sAAA==" rel=icon type=image/x-icon><title>Simple IOT application supported by real-time monitoring and data history</title><meta name=description content="Initial thoughtsI have been developing these kind of application for the better part of my last5 years and people keep asking me how to approach developing such applicationand I will give a try explaining it here."><link rel=alternate type=application/rss+xml title="Mitja Felicijan's posts" href=https://mitjafelicijan.com/index.xml><link rel=alternate type=application/rss+xml title="Mitja Felicijan's notes" href=https://mitjafelicijan.com/notes.xml><style>body{padding:1rem;max-width:760px;background:#fff;font-family:times new roman,Times,serif;line-height:1.35rem}hr{margin-block-start:1.5rem}h1,h2,h3{line-height:initial}footer{margin-block-start:3rem}table{max-width:100%;border-collapse:separate;border-spacing:2px;border:1px solid #000;border-left:1px solid #999;border-top:1px solid #999}blockquote{font-style:italic}table thead{background:#eee}td,th{border:1px solid #000;padding:4px;border-right:1px solid #999;border-bottom:1px solid #999;text-align:left}pre{text-wrap:nowrap;overflow-x:auto;margin-block-start:1.5rem;margin-block-end:1.5rem;padding:.5rem 0;border-top:1px solid #000;border-bottom:1px solid #000}pre code{line-height:1.3em}pre,code,pre *,code *{font-family:monospace;font-size:initial!important}img,video,audio{max-width:100%}header{display:flex;flex-direction:row;gap:3rem}nav{display:flex;gap:.75rem}.pstatus-orange{background:gold}.pstatus-green{background:#9acd32}.pstatus-red{background:#cd5c5c}@media only screen and (max-width:600px){header{flex-direction:column;gap:1rem}a{word-wrap:break-word}}</style><header><nav class=main><a href=/>Home</a>
<a href=https://git.mitjafelicijan.com/ target=_blank>Git</a>
<a href=https://files.mitjafelicijan.com/ target=_blank>Files</a>
<a href=/mitjafelicijan.pgp.pub.txt target=_blank>PGP</a>
<a href=/curriculum-vitae.html>CV</a>
<a href=/index.xml target=_blank>RSS</a></nav></header><main><div><h1>Simple IOT application supported by real-time monitoring and data history</h1><p>Aug 11, 2017<div><h2 id=initial-thoughts>Initial thoughts</h2><p>I have been developing these kind of application for the better part of my last
5 years and people keep asking me how to approach developing such application
and I will give a try explaining it here.<p>IOT applications are really no different than any other kind of applications.
We have data that needs to be collected and visualized in some form of tables or
charts. The main difference here is that most of the times these data is
collected by some kind of device foreign to developer that mainly operates in
web domain. But fear not, it's not that different than writing some JavaScript.<p>There are many devices able to transmit data via wireless or wired network by
default but for the sake of example we will be using commonly known Arduino with
wireless module already on the board → <a href=https://store.arduino.cc/arduino-mkr1000>Arduino
MKR1000</a>.<p>In order to make this little project as accessible to others as possible I will
try to make it as inexpensive as possible. And by this I mean that I will avoid
using hosted virtual servers and will be using my own laptop as a server. But
you must buy Arduino MKR1000 to follow steps below. But if you would want to
deploy this software I would suggest using
<a href=https://www.digitalocean.com>DigitalOcean</a> → smallest VPS is only per month
making this one of the most affordable option out there. Please notice that this
software will not run on stock web hosting that only supports LAMP (Linux,
Apache, MySQL, and PHP).<p>But before we begin please take notice that this is strictly experimental code
and not well optimized and there are much better ways in handling some aspects
of the application but that requires much deeper knowledge of technology that is
not needed for an example like this.<p><strong>Development steps</strong><ol><li>Simple Python API that will receive and store incoming data.<li>Prototype C++ code that will read "sensor data" and transmit it to API.<li>Data visualization with charts → extends Python web application.</ol><p>Step 1. and 3. will share the same web application. One route will be dedicated
to API and another to serving HTML with chart.<p>Schema below represents what we will try to achieve and how different parts
correlates to each other.<p><img src=/assets/iot-application/simple-iot-application-overview.svg alt=Overview><h2 id=simple-python-api>Simple Python API</h2><p>I have always been a fan of simplicity so we will be using <a href=https://bottlepy.org/docs/dev/>Bottle: Python Web
Framework</a>. It is a single file web framework
that seriously simplifies working with routes, templating and has built-in web
server that satisfies our need in this case.<p>First we need to install bottle package. This can be done by downloading
<code>bottle.py</code> and placing it in the root of your application or by using pip
software <code>pip install bottle --user</code>.<p>If you are using Linux or MacOS then Python is already installed. If you will
try to test this on Windows please install <a href=https://www.python.org/downloads/windows/>Python for
Windows</a>. There may be some problems
with path when you will try to launch <code>python webapp.py</code> so please take care
of this before you continue.<h3 id=basic-web-application>Basic web application</h3><p>Most basic bottle application is quite simple. Paste code below in
<code>webapp.py</code> file and save.<pre tabindex=0 style=background-color:#fff><code><span style=display:flex><span><span style=color:green># -*- coding: utf-8 -*-</span>
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:#00f>import</span> bottle
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># initializing bottle app</span>
</span></span><span style=display:flex><span>app = bottle.Bottle()
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># triggered when / is accessed from browser</span>
</span></span><span style=display:flex><span><span style=color:green># only accepts GET → no POST allowed</span>
</span></span><span style=display:flex><span>@app.route(<span style=color:#a31515>&#34;/&#34;</span>, method=[<span style=color:#a31515>&#34;GET&#34;</span>])
</span></span><span style=display:flex><span><span style=color:#00f>def</span> route_default():
</span></span><span style=display:flex><span>  <span style=color:#00f>return</span> <span style=color:#a31515>&#34;howdy from python&#34;</span>
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># starting server on http://0.0.0.0:5000</span>
</span></span><span style=display:flex><span><span style=color:#00f>if</span> __name__ == <span style=color:#a31515>&#34;__main__&#34;</span>:
</span></span><span style=display:flex><span>  bottle.run(
</span></span><span style=display:flex><span>    app = app,
</span></span><span style=display:flex><span>    host = <span style=color:#a31515>&#34;0.0.0.0&#34;</span>,
</span></span><span style=display:flex><span>    port = 5000,
</span></span><span style=display:flex><span>    debug = <span style=color:#00f>True</span>,
</span></span><span style=display:flex><span>    reloader = <span style=color:#00f>True</span>,
</span></span><span style=display:flex><span>    catchall = <span style=color:#00f>True</span>,
</span></span><span style=display:flex><span>  )
</span></span></code></pre><p>To run this simple application you should open command prompt or terminal on
your machine and go to the folder containing your file and type <code>python webapp.py</code>. If everything goes ok then open your web browser and point it to
<code>http://0.0.0.0:5000</code>.<p>If you would like change the port of your application (like port 80) and not use
root to run your app this will present a problem. The TCP/IP port numbers below
1024 are privileged ports → this is a security feature. So in order of
simplicity and security use a port number above 1024 like I have used port 5000.<p>If this fails at any time please fix it before you continue, because nothing
below will work otherwise.<p>We use 0.0.0.0 as default host so that this app is available over your local
network. If you find your local ip <code>ifconfig</code> and try accessing this site
with your phone (if on same network/router as your machine) this should work as
well (example of such ip <code>http://192.168.1.15:5000</code>). This is a must have
because Arduino will be accessing this application to send it's data.<h3 id=web-application-security>Web application security</h3><p>There is a lot to be said about security and is a topic of many books. Of course
all this can not be written here but to just establish some basic security → you
should always use SSL with your application. Some fantastic free certificates
are available by <a href=https://letsencrypt.org>Let's Encrypt - Free SSL/TLS
Certificates</a>. With SSL certificate installed you
should then make use of HTTP headers and send your "API key" via a header. If
your key is send via header then this key is encrypted by SSL and send encrypted
over the network. Never send your api keys by GET parameter like
<code>http://example.com/?api_key=somekeyvalue</code>. The problem that this kind of
sending presents is that this key is visible in logs and by network sniffers.<p>There is a fantastic article describing some aspects about security: <a href=https://www.keycdn.com/blog/web-application-security-best-practices/>11 Web
Application Security Best
Practices</a>. Please
check it out.<h3 id=simple-api-for-writing-data-points>Simple API for writing data-points</h3><p>We will now be using boilerplate code from example above and extend it to be
SQLite3 because it plays well with Python and can store quite large amount of
able to write data received by API to local storage. For example use I will use
data. I have been using it to collect gigabytes of data in a single database
without any corruption or problems → your experience may vary.<p>To avoid learning SQLite I will be using <a href=https://dataset.readthedocs.io/en/latest/index.html>Dataset: databases for lazy
people</a>. This package
abstracts SQL and simplifies writing and reading data from database. You should
install this package with pip software <code>pip install dataset --user</code>.<p>Because API will use POST method I will be testing if code works correctly by
using <a href=https://chrome.google.com/webstore/detail/restlet-client-rest-api-t/aejoelaoggembcahagimdiliamlcdmfm>Restlet Client for Google
Chrome</a>.
This software also allows you to set headers → for basic security with API_KEY.<p>To quickly generate passwords or API keys I usually use this nifty website
<a href=https://randomkeygen.com/>RandomKeygen</a>.<p>Copy and paste code below over your previous code in file <code>webapp.py</code>.<pre tabindex=0 style=background-color:#fff><code><span style=display:flex><span><span style=color:green># -*- coding: utf-8 -*-</span>
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:#00f>import</span> time
</span></span><span style=display:flex><span><span style=color:#00f>import</span> bottle
</span></span><span style=display:flex><span><span style=color:#00f>import</span> random
</span></span><span style=display:flex><span><span style=color:#00f>import</span> dataset
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># initializing bottle app</span>
</span></span><span style=display:flex><span>app = bottle.Bottle()
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># connects to sqlite database</span>
</span></span><span style=display:flex><span><span style=color:green># check_same_thread=False allows using it in multi-threaded mode</span>
</span></span><span style=display:flex><span>app.config[<span style=color:#a31515>&#34;dsn&#34;</span>] = dataset.connect(<span style=color:#a31515>&#34;sqlite:///data.db?check_same_thread=False&#34;</span>)
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># api key that will be used in Arduino code</span>
</span></span><span style=display:flex><span>app.config[<span style=color:#a31515>&#34;api_key&#34;</span>] = <span style=color:#a31515>&#34;JtF2aUE5SGHfVJBCG5SH&#34;</span>
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># triggered when /api is accessed from browser</span>
</span></span><span style=display:flex><span><span style=color:green># only accepts POST → no GET allowed</span>
</span></span><span style=display:flex><span>@app.route(<span style=color:#a31515>&#34;/api&#34;</span>, method=[<span style=color:#a31515>&#34;POST&#34;</span>])
</span></span><span style=display:flex><span><span style=color:#00f>def</span> route_default():
</span></span><span style=display:flex><span>  status = 400
</span></span><span style=display:flex><span>  ts = int(time.time()) <span style=color:green># current timestamp</span>
</span></span><span style=display:flex><span>  value = bottle.request.body.read() <span style=color:green># data from device</span>
</span></span><span style=display:flex><span>  api_key = bottle.request.get_header(<span style=color:#a31515>&#34;Api_Key&#34;</span>) <span style=color:green># api key from header</span>
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green># outputs to console received data for debug reason</span>
</span></span><span style=display:flex><span>  print <span style=color:#a31515>&#34;&gt;&gt;&gt; </span><span style=color:#a31515>{}</span><span style=color:#a31515> :: </span><span style=color:#a31515>{}</span><span style=color:#a31515>&#34;</span>.format(value, api_key)
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green># if api_key is correct and value is present</span>
</span></span><span style=display:flex><span>  <span style=color:green># then writes attribute to point table</span>
</span></span><span style=display:flex><span>  <span style=color:#00f>if</span> api_key == app.config[<span style=color:#a31515>&#34;api_key&#34;</span>] <span style=color:#00f>and</span> value:
</span></span><span style=display:flex><span>    app.config[<span style=color:#a31515>&#34;dsn&#34;</span>][<span style=color:#a31515>&#34;point&#34;</span>].insert(dict(ts=ts, value=value))
</span></span><span style=display:flex><span>    status = 200
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green># we only need to return status</span>
</span></span><span style=display:flex><span>  <span style=color:#00f>return</span> bottle.HTTPResponse(status=status, body=<span style=color:#a31515>&#34;&#34;</span>)
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># starting server on http://0.0.0.0:5000</span>
</span></span><span style=display:flex><span><span style=color:#00f>if</span> __name__ == <span style=color:#a31515>&#34;__main__&#34;</span>:
</span></span><span style=display:flex><span>  bottle.run(
</span></span><span style=display:flex><span>    app = app,
</span></span><span style=display:flex><span>    host = <span style=color:#a31515>&#34;0.0.0.0&#34;</span>,
</span></span><span style=display:flex><span>    port = 5000,
</span></span><span style=display:flex><span>    debug = <span style=color:#00f>True</span>,
</span></span><span style=display:flex><span>    reloader = <span style=color:#00f>True</span>,
</span></span><span style=display:flex><span>    catchall = <span style=color:#00f>True</span>,
</span></span><span style=display:flex><span>  )
</span></span></code></pre><p>To run this simply go to folder containing python file and run <code>python webapp.py</code> from terminal. If everything goes ok you should have simple API
available via POST method on /api route.<p>After testing the service with Restlet Client you should be able to view your
data in a database file <code>data.db</code>.<p><img src=/assets/iot-application/iot-rest-example.png alt="REST settings example"><p>You can also check the contents of new database file by using desktop client
for SQLite → <a href=http://sqlitebrowser.org/>DB Browser for SQLite</a>.<p><img src=/assets/iot-application/iot-sqlite-db.png alt="SQLite database example"><p>Table structure is as simple as it can be. We have ts (timestamp) and value
(value from Arduino). As you can see timestamp is generated on API side. If you
would happen to have atomic clock on Arduino it would be then better to generate
and send timestamp with the value. This would be particularity useful if we
would be collecting sensor data at a higher frequency and then sending this data
in bulk to API.<p>If you will deploy this app with uWSGI and multi-threaded, use DSN (Data Source
Name) url with <code>?check_same_thread=False</code>.<p>Ok, now that we have some sort of a working API with some basic security so
unwanted people can not post data to your database can we proceed further and
try to program Arduino to send data to API.<h2 id=sending-data-to-api-with-arduino-mkr1000>Sending data to API with Arduino MKR1000</h2><p>First of all you should have MKR1000 module and microUSB cable to proceed. If
you have ever done any work with Arduino you should know that you also need
<a href=https://www.arduino.cc/en/Main/Software>Arduino IDE</a>. On provided link you
should be able to download and install IDE. Once that task is completed and you
have successfully run blink example you should proceed to the next step.<p>In order to use wireless capabilities of MKR1000 you need to first install
<a href=https://www.arduino.cc/en/Reference/WiFi101>WiFi101 library</a> in Arduino IDE.
Please check before you install, you may already have it installed.<p>Code below is a working example that sends data to API. Before you try to test
your code make sure you have run Python web application. Then change settings
for wifi, api endpoint and api_key. If by some reason code bellow doesn't work
for you please leave a comment and I'll try to help.<p>Once you have opened IDE and copied this code try to compile and upload it.
Then open "Serial monitor" to see if any output is presented by Arduino.<pre tabindex=0 style=background-color:#fff><code><span style=display:flex><span><span style=color:#00f>#include</span> <span style=color:#00f>&lt;WiFi101.h&gt;</span><span style=color:#00f>
</span></span></span><span style=display:flex><span><span style=color:#00f></span>
</span></span><span style=display:flex><span><span style=color:green>// wifi settings
</span></span></span><span style=display:flex><span><span style=color:green></span><span style=color:#2b91af>char</span> ssid[] = <span style=color:#a31515>&#34;ssid-name&#34;</span>;
</span></span><span style=display:flex><span><span style=color:#2b91af>char</span> pass[] = <span style=color:#a31515>&#34;ssid-password&#34;</span>;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green>// api server enpoint
</span></span></span><span style=display:flex><span><span style=color:green></span><span style=color:#2b91af>char</span> server[] = <span style=color:#a31515>&#34;192.168.6.22&#34;</span>;
</span></span><span style=display:flex><span><span style=color:#2b91af>int</span> port = 5000;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green>// api key that must be the same as the one in Python code
</span></span></span><span style=display:flex><span><span style=color:green></span>String api_key = <span style=color:#a31515>&#34;JtF2aUE5SGHfVJBCG5SH&#34;</span>;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green>// frequency data is sent in ms - every 5 seconds
</span></span></span><span style=display:flex><span><span style=color:green></span><span style=color:#2b91af>int</span> timeout = 1000 * 5;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:#2b91af>int</span> status = WL_IDLE_STATUS;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:#2b91af>void</span> setup() {
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green>// initialize serial and wait for port to open:
</span></span></span><span style=display:flex><span><span style=color:green></span>  Serial.begin(9600);
</span></span><span style=display:flex><span>  delay(1000);
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green>// check for the presence of the shield
</span></span></span><span style=display:flex><span><span style=color:green></span>  <span style=color:#00f>if</span> (WiFi.status() == WL_NO_SHIELD) {
</span></span><span style=display:flex><span>    Serial.println(<span style=color:#a31515>&#34;WiFi shield not present&#34;</span>);
</span></span><span style=display:flex><span>    <span style=color:#00f>while</span> (true);
</span></span><span style=display:flex><span>  }
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green>// attempt to connect to wifi network
</span></span></span><span style=display:flex><span><span style=color:green></span>  <span style=color:#00f>while</span> (status != WL_CONNECTED) {
</span></span><span style=display:flex><span>    Serial.print(<span style=color:#a31515>&#34;Attempting to connect to SSID: &#34;</span>);
</span></span><span style=display:flex><span>    Serial.println(ssid);
</span></span><span style=display:flex><span>    status = WiFi.begin(ssid, pass);
</span></span><span style=display:flex><span>    <span style=color:green>// wait 10 seconds for connection
</span></span></span><span style=display:flex><span><span style=color:green></span>    delay(10000);
</span></span><span style=display:flex><span>  }
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green>// output wifi status to serial monitor
</span></span></span><span style=display:flex><span><span style=color:green></span>  Serial.print(<span style=color:#a31515>&#34;SSID: &#34;</span>);
</span></span><span style=display:flex><span>  Serial.println(WiFi.SSID());
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  IPAddress ip = WiFi.localIP();
</span></span><span style=display:flex><span>  Serial.print(<span style=color:#a31515>&#34;IP Address: &#34;</span>);
</span></span><span style=display:flex><span>  Serial.println(ip);
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:#2b91af>long</span> rssi = WiFi.RSSI();
</span></span><span style=display:flex><span>  Serial.print(<span style=color:#a31515>&#34;signal strength (RSSI):&#34;</span>);
</span></span><span style=display:flex><span>  Serial.print(rssi);
</span></span><span style=display:flex><span>  Serial.println(<span style=color:#a31515>&#34; dBm&#34;</span>);
</span></span><span style=display:flex><span>}
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:#2b91af>void</span> loop() {
</span></span><span style=display:flex><span>  WiFiClient client;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:#00f>if</span> (client.connect(server, port)) {
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    <span style=color:green>// I use random number generator for this example
</span></span></span><span style=display:flex><span><span style=color:green></span>    <span style=color:green>// but you can use analog or digital inputs from arduino
</span></span></span><span style=display:flex><span><span style=color:green></span>    String content = String(random(1000));
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    client.println(<span style=color:#a31515>&#34;POST /api HTTP/1.1&#34;</span>);
</span></span><span style=display:flex><span>    client.println(<span style=color:#a31515>&#34;Connection: close&#34;</span>);
</span></span><span style=display:flex><span>    client.println(<span style=color:#a31515>&#34;Api-Key: &#34;</span> + api_key);
</span></span><span style=display:flex><span>    client.println(<span style=color:#a31515>&#34;Content-Length: &#34;</span> + String(content.length()));
</span></span><span style=display:flex><span>    client.println();
</span></span><span style=display:flex><span>    client.println(content);
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    delay(100);
</span></span><span style=display:flex><span>    client.stop();
</span></span><span style=display:flex><span>    Serial.println(<span style=color:#a31515>&#34;Data sent successfully ...&#34;</span>);
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  } <span style=color:#00f>else</span> {
</span></span><span style=display:flex><span>    Serial.println(<span style=color:#a31515>&#34;Problem sending data ...&#34;</span>);
</span></span><span style=display:flex><span>  }
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green>// waits for x seconds and continue looping
</span></span></span><span style=display:flex><span><span style=color:green></span>  delay(timeout);
</span></span><span style=display:flex><span>}
</span></span></code></pre><p>As seen from example you can notice that Arduino is generating random integer
between [ 0 .. 1000 ]. You can easily replace this with a temperature sensor or
any other kind of sensor.<p>Now that we have API under the hood and Arduino is sending demo data we can now
focus on data visualization.<h2 id=data-visualization>Data visualization</h2><p>Before we continue we should examine our project folder structure. Currently we
only have two files in our project:<p><em>simple-iot-app/</em><ul><li><em>webapp.py</em><li><em>data.db</em></ul><p>We will now add HTML template that will contain CSS and JavaScript code inline
for the simplicity reason. And for the bottle framework to be able to scan root
application folder for templates we will add <code>bottle.TEMPLATE_PATH.insert(0, "./")</code> in <code>webapp.py</code>. By default bottle framework uses <code>views/</code>
subfolder to store templates. This is not the ideal situation and if you will
use bottle to develop web applications you should use native behavior and store
templates in it's predefined folder. But for the sake of example we will
over-ride this. Be careful to fully replace your code with new code that is
provided below. Avoid partially replacing code in file :) Also new code for
reading data-points is provided in Python example below.<p>First we add new route to our web application. It should be trigger when browser
hits root of application <code>http://0.0.0.0:5000/</code>. This route will do nothing
more than render <code>frontend.html</code> template. This is done by <code>return bottle.template("frontend.html")</code>. Check code below to further examine how
exactly this is done.<p>Now we will expand <code>/api</code> route and use different methods to write or read
data-points. For writing data-point we will use POST method and for reading
points we will use GET method. GET method will return JSON object with latest
readings and historical data.<p>There is a fantastic JavaScript library for plotting time-series charts called
<a href=https://www.metricsgraphicsjs.org>MetricsGraphics.js</a> that is based on
<a href=https://d3js.org/>D3.js</a> library for visualizing data.<p>Data schema required by MetricsGraphics.js → to achieve this we need to
transform data from database into this format:<pre tabindex=0 style=background-color:#fff><code><span style=display:flex><span>[
</span></span><span style=display:flex><span>  {
</span></span><span style=display:flex><span>    &#34;date&#34;: <span style=color:#a31515>&#34;2017-08-11 01:07:20&#34;</span>,
</span></span><span style=display:flex><span>    &#34;value&#34;: 933
</span></span><span style=display:flex><span>  },
</span></span><span style=display:flex><span>  {
</span></span><span style=display:flex><span>    &#34;date&#34;: <span style=color:#a31515>&#34;2017-08-11 01:07:30&#34;</span>,
</span></span><span style=display:flex><span>    &#34;value&#34;: 743
</span></span><span style=display:flex><span>  }
</span></span><span style=display:flex><span>]
</span></span></code></pre><p>Web application is now complete and we only need <code>frontend.html</code> that we
will develop now. If you would try to start web app now and go to root app this
will return error because we don't have frontend.html yet.<pre tabindex=0 style=background-color:#fff><code><span style=display:flex><span><span style=color:green># -*- coding: utf-8 -*-</span>
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:#00f>import</span> time
</span></span><span style=display:flex><span><span style=color:#00f>import</span> bottle
</span></span><span style=display:flex><span><span style=color:#00f>import</span> json
</span></span><span style=display:flex><span><span style=color:#00f>import</span> datetime
</span></span><span style=display:flex><span><span style=color:#00f>import</span> random
</span></span><span style=display:flex><span><span style=color:#00f>import</span> dataset
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># initializing bottle app</span>
</span></span><span style=display:flex><span>app = bottle.Bottle()
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># adds root directory as template folder</span>
</span></span><span style=display:flex><span>bottle.TEMPLATE_PATH.insert(0, <span style=color:#a31515>&#34;./&#34;</span>)
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># connects to sqlite database</span>
</span></span><span style=display:flex><span><span style=color:green># check_same_thread=False allows using it in multi-threaded mode</span>
</span></span><span style=display:flex><span>app.config[<span style=color:#a31515>&#34;db&#34;</span>] = dataset.connect(<span style=color:#a31515>&#34;sqlite:///data.db?check_same_thread=False&#34;</span>)
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># api key that will be used in Arduino code</span>
</span></span><span style=display:flex><span>app.config[<span style=color:#a31515>&#34;api_key&#34;</span>] = <span style=color:#a31515>&#34;JtF2aUE5SGHfVJBCG5SH&#34;</span>
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># triggered when / is accessed from browser</span>
</span></span><span style=display:flex><span><span style=color:green># only accepts GET → no POST allowed</span>
</span></span><span style=display:flex><span>@app.route(<span style=color:#a31515>&#34;/&#34;</span>, method=[<span style=color:#a31515>&#34;GET&#34;</span>])
</span></span><span style=display:flex><span><span style=color:#00f>def</span> route_default():
</span></span><span style=display:flex><span>  <span style=color:#00f>return</span> bottle.template(<span style=color:#a31515>&#34;frontend.html&#34;</span>)
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># triggered when /api is accessed from browser</span>
</span></span><span style=display:flex><span><span style=color:green># accepts POST and GET</span>
</span></span><span style=display:flex><span>@app.route(<span style=color:#a31515>&#34;/api&#34;</span>, method=[<span style=color:#a31515>&#34;GET&#34;</span>, <span style=color:#a31515>&#34;POST&#34;</span>])
</span></span><span style=display:flex><span><span style=color:#00f>def</span> route_default():
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green># if method is POST then we write datapoint</span>
</span></span><span style=display:flex><span>  <span style=color:#00f>if</span> bottle.request.method == <span style=color:#a31515>&#34;POST&#34;</span>:
</span></span><span style=display:flex><span>    status = 400
</span></span><span style=display:flex><span>    ts = int(time.time()) <span style=color:green># current timestamp</span>
</span></span><span style=display:flex><span>    value = bottle.request.body.read() <span style=color:green># data from device</span>
</span></span><span style=display:flex><span>    api_key = bottle.request.get_header(<span style=color:#a31515>&#34;Api-Key&#34;</span>) <span style=color:green># api key from header</span>
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    <span style=color:green># outputs to console recieved data for debug reason</span>
</span></span><span style=display:flex><span>    print <span style=color:#a31515>&#34;&gt;&gt;&gt; </span><span style=color:#a31515>{}</span><span style=color:#a31515> :: </span><span style=color:#a31515>{}</span><span style=color:#a31515>&#34;</span>.format(value, api_key)
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    <span style=color:green># if api_key is correct and value is present</span>
</span></span><span style=display:flex><span>    <span style=color:green># then writes attribute to point table</span>
</span></span><span style=display:flex><span>    <span style=color:#00f>if</span> api_key == app.config[<span style=color:#a31515>&#34;api_key&#34;</span>] <span style=color:#00f>and</span> value:
</span></span><span style=display:flex><span>      app.config[<span style=color:#a31515>&#34;db&#34;</span>][<span style=color:#a31515>&#34;point&#34;</span>].insert(dict(ts=ts, value=value))
</span></span><span style=display:flex><span>      status = 200
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>      <span style=color:green># we only need to return status</span>
</span></span><span style=display:flex><span>      <span style=color:#00f>return</span> bottle.HTTPResponse(status=status, body=<span style=color:#a31515>&#34;&#34;</span>)
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  <span style=color:green># if method is GET then we read datapoint</span>
</span></span><span style=display:flex><span>  <span style=color:#00f>else</span>:
</span></span><span style=display:flex><span>    response = []
</span></span><span style=display:flex><span>    datapoints = app.config[<span style=color:#a31515>&#34;db&#34;</span>][<span style=color:#a31515>&#34;point&#34;</span>].all()
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    <span style=color:#00f>for</span> point <span style=color:#00f>in</span> datapoints:
</span></span><span style=display:flex><span>      response.append({
</span></span><span style=display:flex><span>        <span style=color:#a31515>&#34;date&#34;</span>: datetime.datetime.fromtimestamp(int(point[<span style=color:#a31515>&#34;ts&#34;</span>])).strftime(<span style=color:#a31515>&#34;%Y-%m-</span><span style=color:#a31515>%d</span><span style=color:#a31515> %H:%M:%S&#34;</span>),
</span></span><span style=display:flex><span>        <span style=color:#a31515>&#34;value&#34;</span>: point[<span style=color:#a31515>&#34;value&#34;</span>]
</span></span><span style=display:flex><span>      })
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    bottle.response.content_type = <span style=color:#a31515>&#34;application/json&#34;</span>
</span></span><span style=display:flex><span>    <span style=color:#00f>return</span> json.dumps(response)
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span><span style=color:green># starting server on http://0.0.0.0:5000</span>
</span></span><span style=display:flex><span><span style=color:#00f>if</span> __name__ == <span style=color:#a31515>&#34;__main__&#34;</span>:
</span></span><span style=display:flex><span>  bottle.run(
</span></span><span style=display:flex><span>    app = app,
</span></span><span style=display:flex><span>    host = <span style=color:#a31515>&#34;0.0.0.0&#34;</span>,
</span></span><span style=display:flex><span>    port = 5000,
</span></span><span style=display:flex><span>    debug = <span style=color:#00f>True</span>,
</span></span><span style=display:flex><span>    reloader = <span style=color:#00f>True</span>,
</span></span><span style=display:flex><span>    catchall = <span style=color:#00f>True</span>,
</span></span><span style=display:flex><span>  )
</span></span></code></pre><p>And now finally we can implement <code>frontend.html</code>. Create file with this name
and copy code below. When you are done you can start web application. Steps for
this part are listed below the code.<pre tabindex=0 style=background-color:#fff><code><span style=display:flex><span><span style=color:#00f>&lt;!DOCTYPE html&gt;</span>
</span></span><span style=display:flex><span>&lt;html&gt;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  &lt;head&gt;
</span></span><span style=display:flex><span>    &lt;meta charset=<span style=color:#a31515>&#34;utf-8&#34;</span>&gt;
</span></span><span style=display:flex><span>    &lt;title&gt;Simple IOT application&lt;/title&gt;
</span></span><span style=display:flex><span>  &lt;/head&gt;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  &lt;body&gt;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    &lt;h1&gt;Simple IOT application&lt;/h1&gt;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    &lt;div class=<span style=color:#a31515>&#34;chart-placeholder&#34;</span>&gt;
</span></span><span style=display:flex><span>      &lt;div id=<span style=color:#a31515>&#34;chart&#34;</span>&gt;&lt;/div&gt;
</span></span><span style=display:flex><span>    &lt;/div&gt;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    <span style=color:green>&lt;!-- application main script --&gt;</span>
</span></span><span style=display:flex><span>    &lt;script src=<span style=color:#a31515>&#34;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js&#34;</span>&gt;&lt;/script&gt;
</span></span><span style=display:flex><span>    &lt;script src=<span style=color:#a31515>&#34;https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js&#34;</span>&gt;&lt;/script&gt;
</span></span><span style=display:flex><span>    &lt;script src=<span style=color:#a31515>&#34;https://cdnjs.cloudflare.com/ajax/libs/metrics-graphics/2.11.0/metricsgraphics.min.js&#34;</span>&gt;&lt;/script&gt;
</span></span><span style=display:flex><span>    &lt;script&gt;
</span></span><span style=display:flex><span>      <span style=color:#00f>function</span> fetch_and_render() {
</span></span><span style=display:flex><span>        d3.json(<span style=color:#a31515>&#34;/api&#34;</span>, <span style=color:#00f>function</span>(data) {
</span></span><span style=display:flex><span>          data = MG.convert.date(data, <span style=color:#a31515>&#34;date&#34;</span>, <span style=color:#a31515>&#34;%Y-%m-%d %H:%M:%S&#34;</span>);
</span></span><span style=display:flex><span>          MG.data_graphic({
</span></span><span style=display:flex><span>            data: data,
</span></span><span style=display:flex><span>            chart_type: <span style=color:#a31515>&#34;line&#34;</span>,
</span></span><span style=display:flex><span>            full_width: <span style=color:#00f>true</span>,
</span></span><span style=display:flex><span>            height: 270,
</span></span><span style=display:flex><span>            target: document.getElementById(<span style=color:#a31515>&#34;chart&#34;</span>),
</span></span><span style=display:flex><span>            x_accessor: <span style=color:#a31515>&#34;date&#34;</span>,
</span></span><span style=display:flex><span>            y_accessor: <span style=color:#a31515>&#34;value&#34;</span>
</span></span><span style=display:flex><span>          });
</span></span><span style=display:flex><span>        });
</span></span><span style=display:flex><span>      }
</span></span><span style=display:flex><span>      window.onload = <span style=color:#00f>function</span>() {
</span></span><span style=display:flex><span>        <span style=color:green>// initial call for rendering
</span></span></span><span style=display:flex><span><span style=color:green></span>        fetch_and_render();
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>        <span style=color:green>// updates chart every 5 seconds
</span></span></span><span style=display:flex><span><span style=color:green></span>        setInterval(<span style=color:#00f>function</span>() {
</span></span><span style=display:flex><span>          fetch_and_render();
</span></span><span style=display:flex><span>        }, 5000);
</span></span><span style=display:flex><span>      }
</span></span><span style=display:flex><span>    &lt;/script&gt;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>    <span style=color:green>&lt;!-- application styles --&gt;</span>
</span></span><span style=display:flex><span>    &lt;style&gt;
</span></span><span style=display:flex><span>      body {
</span></span><span style=display:flex><span>        <span style=color:#00f>font</span>: 13<span style=color:#2b91af>px</span> <span style=color:#00f>sans-serif</span>;
</span></span><span style=display:flex><span>        <span style=color:#00f>padding</span>: 20<span style=color:#2b91af>px</span> 50<span style=color:#2b91af>px</span>;
</span></span><span style=display:flex><span>      }
</span></span><span style=display:flex><span>      .<span style=color:#2b91af>chart-placeholder</span> {
</span></span><span style=display:flex><span>        <span style=color:#00f>border</span>: 2<span style=color:#2b91af>px</span> <span style=color:#00f>solid</span> #ccc;
</span></span><span style=display:flex><span>        <span style=color:#00f>width</span>: 100<span style=color:#2b91af>%</span>;
</span></span><span style=display:flex><span>        <span style=color:#00f>user-select</span>: <span style=color:#00f>none</span>;
</span></span><span style=display:flex><span>      }
</span></span><span style=display:flex><span>      <span style=color:green>/* chart styles */</span>
</span></span><span style=display:flex><span>      .<span style=color:#2b91af>mg-line1-color</span> {
</span></span><span style=display:flex><span>        stroke: <span style=color:#00f>red</span>;
</span></span><span style=display:flex><span>        stroke-width: 2;
</span></span><span style=display:flex><span>      }
</span></span><span style=display:flex><span>      .<span style=color:#2b91af>mg-main-area</span>, .<span style=color:#2b91af>mg-main-line</span> {
</span></span><span style=display:flex><span>        fill: #fff;
</span></span><span style=display:flex><span>      }
</span></span><span style=display:flex><span>      .<span style=color:#2b91af>mg-x-axis</span> line, .<span style=color:#2b91af>mg-y-axis</span> line {
</span></span><span style=display:flex><span>        stroke: #b3b2b2;
</span></span><span style=display:flex><span>        stroke-width: 1<span style=color:#2b91af>px</span>;
</span></span><span style=display:flex><span>      }
</span></span><span style=display:flex><span>    &lt;/style&gt;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>  &lt;/body&gt;
</span></span><span style=display:flex><span>
</span></span><span style=display:flex><span>&lt;/html&gt;
</span></span></code></pre><p>Now the folder structure should look like:<p><em>simple-iot-app/</em><ul><li><em>webapp.py</em><li><em>data.db</em><li><em>frontend.html</em></ul><p>Ok, lets now start application and start feeding it data.<ol><li><code>python webapp.py</code><li>connect Arduino MKR1000 to power source<li>open browser and go to <code>http://0.0.0.0:5000</code></ol><p>If everything goes well you should be seeing new data-points rendered on chart
every 5 seconds.<p>If you navigate to <code>http://0.0.0.0:5000</code> you should see rendered chart as
shown on picture below.<p><img src=/assets/iot-application/iot-app-output.png alt="Application output"><p>Complete application with all the code is available for
<a href=/assets/iot-application/simple-iot-application.zip>download</a>.<h2 id=conclusion>Conclusion</h2><p>I hope this clarifies some aspects of IOT application development. Of course
this is a minimal example and is far from what can be done in real life with
some further dive into other technologies.<p>If you would like to continue exploring IOT world here are some interesting
resources for you to examine:<ul><li><a href=https://www.allaboutcircuits.com/projects/reading-sensors-with-an-arduino/>Reading Sensors with an Arduino</a><li><a href=http://www.hivemq.com/blog/how-to-get-started-with-mqtt>MQTT 101 – How to Get Started with the lightweight IoT Protocol</a><li><a href=https://www.html5rocks.com/en/tutorials/eventsource/basics/>Stream Updates with Server-Sent Events</a><li><a href=http://www.tutorialspoint.com/internet_of_things/>Internet of Things (IoT) Tutorials</a></ul><p>Any comment or additional ideas are welcomed in comments below.</div></div></main><footer><hr><div><h3>Want to comment or have something to add?</h3>You can write me an email at
<a href=mailto:m@mitjafelicijan.com>m@mitjafelicijan.com</a> or catch up
with me
<a href=https://telegram.me/mitjafelicijan target=_blank>on Telegram</a>.</div><hr><p>This website does not track you. Content is made available under
the <a href=https://creativecommons.org/licenses/by/4.0/ target=_blank rel=noreferrer>CC BY 4.0 license</a> unless specified
otherwise. Blog feed is available as <a href=/index.xml target=_blank>RSS feed</a>.</footer><script src=https://cdn.usefathom.com/script.js data-site=XHQARKXP defer></script>