Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.75 KB | None | 0 0
  1. import gc
  2. import network
  3. gc.collect()
  4. import machine
  5. gc.collect()
  6. import ubinascii
  7. gc.collect()
  8. import ujson
  9. gc.collect()
  10. import uos
  11. gc.collect()
  12. import utime
  13. gc.collect()
  14. import socket
  15. gc.collect()
  16. import select
  17. gc.collect()
  18.  
  19. html = """<!DOCTYPE html>
  20. <html>
  21. <head> <title>Ouroboros IoT Login</title> </head>
  22. <body>
  23. <form action="configure.html" method="POST">
  24. Username : <input type="text" name="username"></br>
  25. Password: <input type="password" name="password" ></br>
  26. <input type="submit" value="submit" name="submit">
  27. </form>
  28. </body>
  29. </html>
  30. """
  31.  
  32. login_fail_html = """<!DOCTYPE html>
  33. <html>
  34. <head> <title>Ouroboros IoT Login</title> </head>
  35. <body>
  36. <h2>Incorrect Credentials!</h2><br>Please login<br>
  37. <form action="configure.html" method="POST">
  38. Username : <input type="text" name="username"></br>
  39. Password: <input type="password" name="password" ></br>
  40. <input type="submit" value="submit" name="submit">
  41. </form>
  42. </body>
  43. </html>
  44. """
  45.  
  46. # Check if file exists
  47. def fileExists(fileName):
  48. try:
  49. uos.stat(fileName)
  50. print("File " + fileName + " found!")
  51. return True
  52. except OSError:
  53. print("No file " + fileName + " found!")
  54. return False
  55.  
  56. # Turns WiFi ON for configuration
  57. def turn_wifi_on():
  58. # Setup the AP interface
  59. ap_if = network.WLAN(network.AP_IF)
  60. ap_if.active(False)
  61. ap_if.active(True)
  62. # Get the MACADDRESS - without any spaces
  63. macaddress = ubinascii.hexlify(ap_if.config('mac'),'').decode()
  64. ap_if.config(essid="OUB1_"+macaddress, password="12345678")
  65. #ap_if.config(essid="OUB1_"+macaddress)
  66. ap_if.ifconfig(('192.168.0.1', '255.255.255.0', '192.168.0.1', '192.168.0.1'))
  67. # Configure the AP to static IPs
  68.  
  69. def turn_wifi_off():
  70. ap_if = network.WLAN(network.AP_IF)
  71. ap_if.active(False)
  72.  
  73. # Find out the stored IoT secret content
  74. def get_iot_secret():
  75. fileName = 'alpha.txt'
  76. if fileExists(fileName):
  77. f = open(fileName)
  78. content_str = f.read()
  79. f.close()
  80. return content_str
  81. else:
  82. return 'asdasrefwefefergf9rerf3n4r23irn1n32f'
  83.  
  84. # Find out the stored home network credential if exist
  85. def get_wifi_config():
  86. fileName = 'wifi.conf'
  87. if fileExists(fileName):
  88. f = open(fileName)
  89. content_str = f.read()
  90. f.close()
  91. content = ujson.loads(content_str)
  92. return content
  93. else:
  94. return None
  95.  
  96. # Set the home network credentials
  97. def save_wifi_config(essid, passphrase):
  98. f = open('wifi.conf', 'w')
  99. config = {'essid':essid, 'passphrase':passphrase}
  100. config_str = ujson.dumps(config)
  101. f.write(config_str)
  102. f.close()
  103.  
  104.  
  105. # Find out the stored login credentials
  106. def get_login_config():
  107. fileName = 'login.conf'
  108. if fileExists(fileName):
  109. f = open(fileName)
  110. content_str = f.read()
  111. f.close()
  112. content = ujson.loads(content_str)
  113. return content
  114. else:
  115. # No file exists so far, so use the admin/admin credentials
  116. return {'user':'admin','password':'admin'}
  117.  
  118. # Set the login credentials
  119. def save_login_config(user, password):
  120. f = open('login.conf', 'w')
  121. config = {'user':user, 'password':password}
  122. config_str = ujson.dumps(config)
  123. f.write(config_str)
  124. f.close()
  125.  
  126. def turn_gpio_on(device_num):
  127. # Device Num to Pin Mapping
  128. if device_num == 0:
  129. pin_num = 0
  130. elif device_num == 1:
  131. pin_num = 2
  132. # Check Pin
  133. pin = machine.Pin(pin_num)
  134. if pin.value() == 0:
  135. pin.on()
  136. # else it is already at HIGH state, nothing to do
  137.  
  138. def turn_gpio_off(device_num):
  139. # Device Num to Pin Mapping
  140. if device_num == 0:
  141. pin_num = 0
  142. elif device_num == 1:
  143. pin_num = 2
  144. # Check Pin
  145. pin = machine.Pin(pin_num)
  146. if pin.value() == 1:
  147. pin.off()
  148. # else it is already at LOW state, nothing to do
  149.  
  150. def init_pin(device_num):
  151. # Device Num to Pin Mapping
  152. if device_num == 0:
  153. pin_num = 0
  154. elif device_num == 1:
  155. pin_num = 2
  156. #open GPIO0 in output mode & turn it off by default
  157. pin = machine.Pin(pin_num, machine.Pin.OUT)
  158. # Turn off both GPIO initially
  159. turn_gpio_off(device_num)
  160.  
  161. # Find out the post parameters in a dictionary
  162. def get_post_params(req):
  163. print("Inside GET POST PARAMS : req = " + req)
  164. post_params = req.split('rn')[-1:][0]
  165. # Check if the post body contains the necessary fields
  166. # Split the post_params by &
  167. # params : ['username=', 'password=', 'method=POST', 'url=http%3A%2F%2Ftwig-me.com%2Fv1%2Fusergroups%2FWKMUYXELA9LCC', 'jsondata=', 'submit=submit']
  168. print("post_params : " + post_params)
  169. params = post_params.split('&')
  170. print("Params")
  171. print(params)
  172. # Initialize the key value pair dict
  173. post_dict = {}
  174. # Iterate on each param
  175. for param in params:
  176. # Each param would be like 'method=POST', etc
  177. key_val = param.split('=')
  178. print("Key Val :")
  179. print(key_val)
  180. key = key_val[0]
  181. val = key_val[1]
  182. # Update post_dict
  183. post_dict[key] = val
  184. return post_dict
  185.  
  186. # This web server takes care of the WiFi configuration
  187. # max_run_sec
  188. def web_server(max_run_sec = None):
  189. # Turn wifi interface ON
  190. turn_wifi_on()
  191. # Create server socket
  192. addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
  193. s = socket.socket()
  194. # TODO : If both the wifi and sta are operating simultaneously, then bind only to WiFi
  195. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  196. s.bind(addr)
  197. s.listen(1)
  198. # s.settimeout(1)
  199.  
  200. poller = select.poll()
  201. poller.register(s, select.POLLIN)
  202.  
  203. # Get the current time since epoch
  204. startTimeEpoch = utime.time()
  205.  
  206. while True:
  207. events = poller.poll(200) # time in milliseconds
  208. if events:
  209. try:
  210. gc.collect()
  211. res = s.accept()
  212. client_s = res[0]
  213. client_addr = res[1]
  214. req = ''
  215. #while True:
  216. # data = client_s.recv(200)
  217. # if data:
  218. # req += str(data, 'utf8')
  219. # else:
  220. # break
  221. # utime.sleep_ms(50)
  222. req = client_s.recv(4096)
  223. req = req.decode()
  224. print(req)
  225. req = str(req)
  226. # Came here means that there has been some connection!
  227. # Reset the start time epoch in such a case:
  228. startTimeEpoch = utime.time()
  229. # Check route now
  230. if req.find('configure.html') != -1:
  231. print("Got configure request!rn")
  232. # Check if the username and password are correct, if not, configure:
  233. login_config = get_login_config()
  234. username = login_config['user']
  235. pwd = login_config['password']
  236. print("Username : " + username + ", pwd : " + pwd)
  237. # Find the POST PARAMETERS sent
  238. # There would be just one entry in the array, so get the 0th index directly
  239. # post_params : 'username=&password=&method=POST&url=http%3A%2F%2Ftwig-me.com%2Fv1%2Fusergroups%2FWKMUYXELA9LCC&jsondata=&submit=submit'
  240. print("Came here A")
  241. post_dict = get_post_params(req)
  242.  
  243. # Now check if the post_dict has the key and value for username and password as needed?
  244. username_post = post_dict['username']
  245. password_post = post_dict['password']
  246.  
  247. print("Came here B")
  248.  
  249. # Check if the password is same as expected
  250. if (username_post == username) and (password_post == pwd):
  251. hidden_input = '<input type="hidden" name="username" value="' + username + '"><input type="hidden" name="passphrase" value="' + pwd + '">'
  252. # Send the login username and password inside the hidden input field
  253. configure_html = "<!DOCTYPE html><html><head> <title>Ouroboros IoT WiFi Configuration Page</title> </head><body><form action="configure_wifi.html" method="POST">WiFi SSID : <input type="text" name="essid"></br>WiFi Password: <input type="password" name="passphrase" ></br>" + hidden_input + "<input type="submit" value="submit" name="submit"></form></body></html>"
  254. # TODO : Also show link to webpage, where from we can change the login credentials
  255. client_s.send(configure_html)
  256. else:
  257. client_s.send(login_fail_html)
  258. elif req.find('configure_wifi.html') != -1:
  259. # Check if the username and password are correct, if not, configure:
  260. login_config = get_login_config()
  261. username = login_config['user']
  262. pwd = login_config['password']
  263. # Get post parameters
  264. post_dict = get_post_params(req)
  265. # Now check if the post_dict has the key and value for username and password as needed?
  266. username_post = post_dict['username']
  267. password_post = post_dict['password']
  268.  
  269. # Check if the password is same as expected
  270. if (username_post == username) and (password_post == pwd):
  271. # Do some sanity check for handling the new wifi ssid and password
  272. new_wifi_ssid = post_dict['essid']
  273. new_wifi_passphrase = post_dict['passphrase']
  274. # Set the wifi credentials
  275. save_wifi_config(new_wifi_ssid, new_wifi_passphrase)
  276. client_s.send('<!DOCTYPE html><html><head> <title>Ouroboros IoT WiFi Configuration Success</title> </head><body>Configuration successful!<br>Device would go into reboot now!</body></html>')
  277. # Reboot device now
  278. machine.reset()
  279. else:
  280. client_s.send(login_fail_html)
  281. elif req.find('index.html') != -1:
  282. print("Got index.html request!rn")
  283. client_s.send(html)
  284. else :
  285. # Do nothing
  286. print("Invalid request received! Show the login page again!rn")
  287. client_s.send(html)
  288.  
  289. client_s.close()
  290. machine.idle()
  291. except OSError:
  292. # Got no request and it timedout!
  293. print("Timed-out, no request received!rn")
  294. except Exception as e:
  295. print("Got some exceptionrn")
  296. print(str(e))
  297. finally:
  298. if max_run_sec is not None:
  299. elapsedTime = utime.time() - startTimeEpoch
  300. if elapsedTime > max_run_sec:
  301. # Max run time of web server has elapsed, time to exit this mode!
  302. break
  303. utime.sleep_ms()
  304. machine.idle()
  305.  
  306. # When while loop ends!
  307. s.close()
  308. # Turn wifi interface OFF
  309. turn_wifi_off()
  310.  
  311. # Starts a thread which runs the web server to handle WiFi
  312. def start_web_server(max_run_sec = None):
  313. # start_new_thread(web_server, (max_run_sec))
  314. web_server(max_run_sec)
  315.  
  316.  
  317.  
  318. ############# MAIN ##########################
  319. # Initialize two pins to INPUT and OFF by default
  320. init_pin(0)
  321. init_pin(1)
  322. #turn_wifi_off()
  323.  
  324. # Check if the home wifi network has been setup
  325. # Check if home wifi config is valid, if so, connect to it
  326. # If home wifi is not configured, then use the Web server all the time.
  327. if get_wifi_config() is None:
  328. # Came here means the wifi is not configured
  329. # Start the web server
  330. print("Starting web server")
  331. start_web_server()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement