Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • viteks/nsi-lectures
1 result
Show changes
Commits on Source (3)
lec02/figs/Comparison-of-Majore-IOT-Protocols.png

64.1 KiB

lec02/figs/iot-04.png

69.3 KiB

%% Cell type:markdown id: tags:
# NSI - 2. přednáška
%% Cell type:code id: tags:
``` python
# jeste trochu Pythonu :-)
for i in range(1, 10):
print(i)
def ahoj(p1 = 10):
print('p1 = ', p1)
ahoj(120)
```
%% Output
1
2
3
4
5
6
7
8
9
p1 = 120
%% Cell type:markdown id: tags:
## REST architektura
### Metoda GET
%% Cell type:code id: tags:
``` python
import requests
# koncový bod aplikace
api_url = "https://jsonplaceholder.typicode.com/todos/1"
# požadavek na získání zdroje
response = requests.get(api_url)
```
%% Cell type:code id: tags:
``` python
# data zdroje
response.json()
```
%% Output
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
%% Cell type:code id: tags:
``` python
# status kód
response.status_code
```
%% Output
200
%% Cell type:code id: tags:
``` python
# hlavička odpovědi
response.headers["Content-Type"]
```
%% Output
'application/json; charset=utf-8'
%% Cell type:markdown id: tags:
### Metoda POST
%% Cell type:code id: tags:
``` python
api_url = "https://jsonplaceholder.typicode.com/todos"
todo = {"userId": 1, "title": "Buy milk", "completed": False}
response = requests.post(api_url, json=todo)
response.json()
```
%% Cell type:code id: tags:
``` python
response.status_code
```
%% Cell type:markdown id: tags:
### Metoda DELETE
%% Cell type:code id: tags:
``` python
api_url = "https://jsonplaceholder.typicode.com/todos/10"
response = requests.delete(api_url)
response.json()
```
%% Cell type:code id: tags:
``` python
response.status_code
```
%% Cell type:markdown id: tags:
### Metoda PUT
%% Cell type:code id: tags:
``` python
api_url = "https://jsonplaceholder.typicode.com/todos/10"
response = requests.get(api_url)
response.json()
```
%% Cell type:code id: tags:
``` python
todo = {"userId": 1, "title": "Wash car", "completed": True}
response = requests.put(api_url, json=todo)
response.json()
```
%% Cell type:code id: tags:
``` python
response.status_code
```
%% Cell type:markdown id: tags:
### Metoda PATCH
%% Cell type:code id: tags:
``` python
api_url = "https://jsonplaceholder.typicode.com/todos/10"
todo = {"title": "Mow lawn"}
response = requests.patch(api_url, json=todo)
response.json()
```
%% Cell type:code id: tags:
``` python
response.status_code
```
%% Cell type:markdown id: tags:
## RPC architektura
%% Cell type:code id: tags:
``` python
from xmlrpc.server import SimpleXMLRPCServer
def factorial(n):
fact = 1
for i in range(1,n+1):
fact=fact*i
return fact
server = SimpleXMLRPCServer(("localhost", 8000), logRequests=True)
server.register_function(factorial, "factorial_rpc")
try:
print("Starting and listening on port 8000...")
print("Press Ctrl + C to exit.")
server.serve_forever()
except:
print("Exit.")
```
%% Cell type:code id: tags:
``` python
import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
print("factorial of 3 is : %s" % str(proxy.factorial_rpc(3)))
print("factorial of 5 is : %s" % str(proxy.factorial_rpc(5)))
```
%% Cell type:markdown id: tags:
## MQTT protokol
%% Cell type:markdown id: tags:
### MQTT consumer
%% Cell type:code id: tags:
``` python
import paho.mqtt.client as paho
def on_message(mosq, obj, msg):
print ("%-20s %d %s" % (msg.topic, msg.qos, msg.payload))
# mosq.publish('pong', 'ack', 0)
def on_publish(mosq, obj, mid):
pass
if __name__ == '__main__':
client = paho.Client()
client.on_message = on_message
# client.on_publish = on_publish
#client.tls_set('root.ca', certfile='c1.crt', keyfile='c1.key')
client.connect("127.0.0.1", 1883, 60)
# client.subscribe("kids/yolo", 0)
# client.subscribe("adult/#", 0)
client.subscribe("#", 0)
while client.loop() == 0:
pass
```
%% Output
poslucharna/teplota 0 b'25'
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
Cell In[10], line 22
18 # client.subscribe("kids/yolo", 0)
19 # client.subscribe("adult/#", 0)
20 client.subscribe("#", 0)
---> 22 while client.loop() == 0:
23 pass
File c:\Python310\lib\site-packages\paho\mqtt\client.py:1120, in Client.loop(self, timeout, max_packets)
1117 self._reset_sockets(sockpair_only=True)
1118 self._sockpairR, self._sockpairW = _socketpair_compat()
-> 1120 return self._loop(timeout)
File c:\Python310\lib\site-packages\paho\mqtt\client.py:1150, in Client._loop(self, timeout)
1147 rlist = [self._sock, self._sockpairR]
1149 try:
-> 1150 socklist = select.select(rlist, wlist, [], timeout)
1151 except TypeError:
1152 # Socket isn't correct type, in likelihood connection is lost
1153 return MQTT_ERR_CONN_LOST
KeyboardInterrupt:
%% Cell type:markdown id: tags:
### MQTT publisher
%% Cell type:code id: tags:
``` python
import paho.mqtt.publish as publish
msgs = [{'topic': "CVUT/FEL/209/Temperature", 'payload': "23"},
{'topic': "CVUT/FEL/209/Humidity", 'payload': "60"}]
host = "localhost"
if __name__ == '__main__':
# publish a single message
publish.single(topic="CVUT/FEL/209/test", payload="test", hostname=host)
# publish multiple messages
publish.multiple(msgs, hostname=host)
```
......
......@@ -37,43 +37,126 @@ Katedra radioelektroniky
---
# Formáty výměny dat - JSON
# Formáty výměny dat
---
# XML
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<book>
<title>Python Basics</title>
<page_count>635</page_count>
<pub_date>2021-03-16</pub_date>
<authors>
<author>
<name>David Amos</name>
</author>
<author><name>Joanna Jablonski</name></author>
<author><name>Dan Bader</name></author>
<author><name>Fletcher Heisler</name></author>
</authors>
<isbn13>978-1775093329</isbn13>
<genre>Education</genre>
</book>
```
---
## JavaScript Object Notification
# JSON - JavaScript Object Notation
* kolekce párů název:hodnota
* 4 primitivní datové typy (řetězec, číslo, log. hodnota, NULL)
* 2 strukturované datové typy (objekt, pole)
* Založen na podmnožině standardu programovacího jazyka JavaScript ECMA-262 3rd Edition.
* JSON je způsob ukládání a komunikace dat se specifickými pravidly (jako např. XML, YAML atd.)
* Soubory JSON mají příponu .json
* Používá dvojice klíč-hodnota
* Navržen tak, aby byl čitelný pro lidi i stroje a nezávislý na jazyce
```json
{"members":[
{
"name": "John Lennon",
"birthdate": ["year": 1940, "month": 10, "day": 9]
},
{
"name": "Paul McCartney",
"birthdate": ["year": 1942, "month": 6, "day": 18]
}
]}
http://json.org
https://json-schema.org/
https://jsonformatter.curiousconcept.com/
---
# JSON příklad
```json
{
"members":[
{
"name":"Ringo Star",
"alive":true,
"birth":1940
},
{
"name":"John Lennon",
"alive":false,
"birth":1940
},
{
"name":"Paul McCartney",
"alive":true,
"birth":1942
},
{
"name":"George Harrison",
"alive":false,
"birth":1943
}
]
}
```
---
# # Formáty výměny dat - Binary JSON (BSON)
# JSON - datové typy
* Řetězec
* <span style="color:red; font=samily: courier;">"Hello world!"</span>
* sekvence znaků v kódování Unicode
* znak je reprezentován jako jednoznakový řetězec
* Číslo
* <span style="color:blue; font=samily: courier;">10 1.5 1.3e20</span>
* čísla typu integer, float, včetně čísel v exponenciálním tvaru
* Logický datový typ (boolean)
* <span style="color:green; font=samily: courier;">true false</span>
* Null
* hodnota může být <span style="color:green; font=samily: courier;">null</span>
---
# JSON - datové typy
* Pole
* [1, 2 3] ["Hello", "World"]
* položky oddělené čárkou
* položky nemusí být stejného datového typu
* Objekt
* {"name": "John", "age": 43}
* páry klíč-hodnota oddělené čárkou
---
# BSON - Binary JSON
![center](figs/iot-04-15.png)
---
# Protokoly relační/aplikační vrstvy
# Protokoly vyšších vrstev
## Aplikační, prezentační a relační
---
# Role protokolů vyšších vrstev
1. Poskytování abstrakce "zprávy" (elementární jednotky dat)komunikace mezi koncovými body internetu věcí).
1. Poskytování abstrakce "zprávy" (elementární jednotky dat), komunikace mezi koncovými body.
2. Poskytování primitiv pro datovou komunikaci/výměnu zpráv aplikacím vyšší vrstvy internetu věcí.
2. Poskytování primitiv pro datovou komunikaci/výměnu zpráv aplikacím vyšší vrstvy.
3. Implementace specifických síťových paradigmat (např. Publish-Subscribe nebo Request-Response).
3. Implementace specifických síťových paradigmat.
4. Poskytování dodatečných mechanismů spolehlivosti nebo zabezpečení.
......@@ -87,7 +170,8 @@ Katedra radioelektroniky
* HTTP
* CoAP
2. **Publish-Subscribe**
* MQTT, AMQP
* MQTT
* AMQP
3. **Push-Pull**
4. **Exclusive Pair**
......@@ -279,6 +363,12 @@ Katedra radioelektroniky
---
# COAP - Constrained Application Protocol
![h:500px center](figs/iot-04.png)
---
# COAP protokol
* Rozdělen do dvou dílčích vrstev
......@@ -299,7 +389,7 @@ Katedra radioelektroniky
## Příklad komunikace
![h:330px](figs/coap-fig1.svg) ![h:330px](figs/coap-fig1.svg)
![h:300px](figs/coap-fig1.svg) ![h:300px](figs/coap-fig2.svg)
---
......@@ -534,3 +624,9 @@ Mechanismus OBSERVE umožňuje implementovat mechanismus odběru dat
* Klient a server mohou po navázání spojení navzájem posílat zprávy .
![h:280px center](figs/nsi-fig05.drawio.svg)
---
# Porovnání komunikačních IoT protokolů
![h:550px center](figs/Comparison-of-Majore-IOT-Protocols.png)
\ No newline at end of file
File deleted
import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://localhost:8000')
print(s.len("Tutorialspoint"))
print(s.rmndr(12,5))
print(s.modl(7,3))
# Print list of available methods
print(s.system.listMethods())
\ No newline at end of file
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
with SimpleXMLRPCServer(('localhost', 8000),
requestHandler=RequestHandler) as server:
server.register_introspection_functions()
# Register len() function;
server.register_function(len)
# Register a function under a different name
@server.register_function(name='rmndr')
def remainder_function(x, y):
return x // y
# Register a function under function.__name__.
@server.register_function
def modl(x, y):
return x % y
server.serve_forever()
\ No newline at end of file
%% Cell type:code id: tags:
``` python
# NSI - 3. přednáška
## Třídy a objekty
```
%% Cell type:code id: tags:
``` python
import random
import matplotlib.pyplot as plt
last = 100
data = []
for i in range (1, 100):
rnd = random.random()-0.5
last += rnd
data.append(last)
plt.plot(data)
# fig, ax = plt.subplots()
# ax.set_ylim([0, 110])
# ax.plot(data)
```
%% Output
[<matplotlib.lines.Line2D at 0x131ef181510>]