Tutorial Network

From Sketching with Hardware at LMU Wiki
Revision as of 13:48, 14 June 2024 by Mayersven (talk | contribs) (→‎Using the uPyCraft IDE to upload files)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Write and Read Network Variables

In this part of the tutorial, we explain how to write variables to the server and how to read them again. This is a very simple module/library with very basic functionality to connect objects by using shared variables in the network

Success criteria

  • you can write a variable to the network
  • you can read a variable from the network
  • you understand how the network variables work
  • you understand the limitations of the module (only strings, everyone can read and write all variables, naming conditions)

Required Module and Files

Related Components

The components are related to the LMUBox. For more components, see the Hardware List. Many of the pages on actuators and sensor include additional examples.

Microcontroller

Instructional Videos

Connecting to WiFI and using Network Variables

In this video on youtube (8:52) we show how to Connect the ESP32/ESP8266 to the Internet and how to use the netvars.py module to use variables stored on the server.

Using the uPyCraft IDE to upload files

In this video on youtube (6:48), we show how to upload an run python files with the uPyCraft IDE: https://youtu.be/MXfj_gWf0z4

Code Examples

Code Example: using netvars.py

Variable names can only be strings of letters and numbers without space Variable values can only be strings of letters and numbers without space (numbers will be converted to strings), spaces will give an error You are welcome to improve the module!

 1 #Example usage
 2 
 3 #import module
 4 from netvars import setNetVar, getNetVar, initNet
 5 
 6 # # assuming there is a network with ssid hotspot1 and password 123456789
 7 # connect to wifi
 8 initNet("hotspot1", "123456789")
 9 
10 # set the variale with the name test222 to the value valTest222
11 setNetVar("test222", "valTest222")
12 
13 # read the variable test222 from the server and print it
14 a=getNetVar("test222")
15 print(a) # will print valTest222

Code Example for use in Jupyter Notebook: updated netvars.py

This has our server address hard coded - if you run it on your server you have to adapt the URLs.

Note: connecting to public Wifis might not be possible, see https://github.com/micropython/micropython/issues/9016.

 1 import network, socket
 2 
 3 def initNet(ssid, passwd=None):
 4     wlan = network.WLAN(network.STA_IF)
 5     wlan.active(True)
 6     if not wlan.isconnected():
 7         print('connecting to network...')
 8         if passwd == None:
 9             wlan.connect(ssid)
10         else:
11             wlan.connect(ssid, passwd)
12         while not wlan.isconnected():
13 
14             pass
15     print('network config:', wlan.ifconfig())
16 
17 def http_get(url):
18     #print(url)
19     #print("............")
20     _, _, host, path = url.split('/', 3)
21     addr = socket.getaddrinfo(host, 80)[0][-1]
22     print ("fetch from: ", addr)
23     s = socket.socket()
24     s.connect(addr)
25     s.send(bytes('GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
26     #print(s)
27     retStr =""
28     while True:
29         data = s.recv(1024)
30         #print(data)
31         
32         if data:
33             # this would be all
34             #retStr = retStr +str(data, 'utf8') 
35             # Only the last line
36             retStr = str(data, 'utf8') 
37             #print(str(data, 'utf8'), end='')
38             #print(retStr)
39             break
40         else:
41             print("---data")
42             #print(retStr)
43             break
44     s.close()
45     return retStr
46 
47 
48 def setNetVar(varName, varVal):
49     urlStr = "https://ubicomp.net/sw/db1/var2db.php?varName=" + str(varName) + "&varValue=" + str(varVal)
50     #print(urlStr)
51     # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test3&varValue=14")
52     # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test222&varValue=valTest222")
53     http_get(urlStr)
54 
55 
56 def getNetVar(varName):
57     urlStr = "https://ubicomp.net/sw/db1/var2db.php?varName=" + str(varName) 
58     #print(urlStr)
59     # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test3&varValue=14")
60     # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test222&varValue=valTest222")
61     resStr = http_get(urlStr)
62     # import re # standrad python
63     import ure
64     #_, retVar0 = ure.split('\r\n\r\n|\n\n',resStr)
65     # retVar = ure.split(' |\n|\r',retVar0)
66     reg1 = ure.compile('\r\n\r\n|\n\n')
67     reg2 = ure.compile(' |\n|\r')
68     #print(reg1)
69     #print(reg1.split(resStr))
70     _, retVar0, _ = reg1.split(resStr)
71     #print(retVar0)
72     retVar = reg2.split(retVar0)
73     #print(retVar)
74     return retVar[2]
75 
76 #Example usage
77 # from netvars import setNetVar, getNetVar, http_get, initNet
78 # # assuming there is a network with ssid hotspot1 and password 123456789
79 # initNet("hotspot1", "123456789")
80 # setNetVar("test222", "valTest222")
81 # a=getNetVar("test222")
82 # print(a) # will print valTest222
83 
84 # # assuming there is a network with ssid hotspot1 and password 123456789
85 # connect to wifi
86 initNet("as62", "VivienPetraAlbrecht")
87 # set the variale with the name test222 to the value valTest222
88 setNetVar("1000_albrecht_test222", "XXXalbrecht_valTest222")
89 # read the variable test222 from the server and print it
90 a=getNetVar("1000_albrecht_test222")
91 print(a) # will print valTest222

Code Example: netvars.py

This has our server address hard coded - if you run it on your server you have to adapt the URLs.

 1 import network
 2 
 3 def initNet(ssid, passwd):
 4     wlan = network.WLAN(network.STA_IF)
 5     wlan.active(True)
 6     if not wlan.isconnected():
 7         print('connecting to network...')
 8         wlan.connect(ssid, passwd)
 9         while not wlan.isconnected():
10 
11             pass
12     print('network config:', wlan.ifconfig())
13 
14 def http_get(url):
15     #print(url)
16     #print("............")
17     import socket
18     _, _, host, path = url.split('/', 3)
19     addr = socket.getaddrinfo(host, 80)[0][-1]
20     s = socket.socket()
21     s.connect(addr)
22     s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
23     retStr =""
24     while True:
25         data = s.recv(500)
26         if data:
27             # this would be all
28             # retStr = retStr +str(data, 'utf8') 
29             # Only the last line
30             retStr = str(data, 'utf8') 
31             #print(str(data, 'utf8'), end='')
32         else:
33             break
34     s.close()
35     return retStr
36 
37 
38 def setNetVar(varName, varVal):
39     urlStr = "https://ubicomp.net/sw/db1/var2db.php?varName=" + str(varName) + "&varValue=" + str(varVal)
40     # print(urlStr)
41     # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test3&varValue=14")
42     # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test222&varValue=valTest222")
43     http_get(urlStr)
44 
45 
46 def getNetVar(varName):
47     urlStr = "https://ubicomp.net/sw/db1/var2db.php?varName=" + str(varName) 
48     # print(urlStr)
49     # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test3&varValue=14")
50     # http_get("https://ubicomp.net/sw/db1/var2db.php?varName=test222&varValue=valTest222")
51     resStr = http_get(urlStr)
52     # import re # standrad python
53     import ure
54     #_, retVar0 = ure.split('\r\n\r\n|\n\n',resStr)
55     # retVar = ure.split(' |\n|\r',retVar0)
56     reg1 = ure.compile('\r\n\r\n|\n\n')
57     reg2 = ure.compile(' |\n|\r')
58     _, retVar0 = reg1.split(resStr)
59     retVar = reg2.split(retVar0)
60     return retVar[0]
61 
62 #Example usage
63 # from netvars import setNetVar, getNetVar, http_get, initNet
64 # # assuming there is a network with ssid hotspot1 and password 123456789
65 # initNet("hotspot1", "123456789")
66 # setNetVar("test222", "valTest222")
67 # a=getNetVar("test222")
68 # print(a) # will print valTest222


Debugging Network Variables

For debugging you can see all the variables in our test installation by accessing: https://ubicomp.net/sw/db1/var2db.php