Page 1 of 1

How to check gpio pin input, when http-server is running?

Posted: Fri Aug 31, 2018 1:26 pm
by Zolee
Hello!

I have a mini project at home.
I want to send a notification, when motion sensor is active.
My problem is, how can i check the input value, when http server is running.
Is checks, and send the message to my phone, but only at once.
My program ask the User, from the wifi connection settings.
Board: Wemos D1 Mini
Motion sensor: hc-sr501
Here is my code:

Code: Select all

import time
import usocket as socket
import network
from machine import Pin
import urequests
import machine
import os

time.sleep(5)

#SZERVER
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)

ap_if = network.WLAN(network.AP_IF)
ap_if.active(True)


#szerver beállítások:
SSID='mozgaserzekelo'
JELSZO='12345678'
IPCIM='192.168.4.1'
ATJARO='192.168.4.1'
#szerver beállítások vége
ap_if.config(essid=SSID, channel=11, password=JELSZO)
ap_if.ifconfig((IPCIM,'255.255.255.0',ATJARO,'208.67.222.222'))
#SZERVER VÉGE
###########################################
wlan_list = sta_if.scan()
time.sleep(2)

mozgas = Pin(15, Pin.IN)#d8
hozzaferes = ["default","default","default"]
reset=0
tovabblepes=0
ido=time.ticks_ms()
elso_ertesites=0
idokoz=60000
bekapcs=0
jelzes=0

listazas='''<!DOCTYPE html><html>
<head><title>MOZGÁSÉRZÉKELŐ</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="about:blank">
<style>
td{padding: 15px;text-align: left;border: 1px solid #ddd;}
th {background-color: #4CAF50;color: white;}
table {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;border: 1px solid #ddd;}
</style>
</head>
<body>
<TABLE align="center">
<form>
<tr>
<th>Wifi hálózatok</th>
<th>Kiválaszt</th>
</tr>%s 
<tr>
<td></td>
<td><input type="submit" value="Tovább"></td>
</tr>
</form>
</table>
</body>
</html>'''

jelszobekeres='''<!DOCTYPE html><html>
<head><title>MOZGÁSÉRZÉKELŐ</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="about:blank">
<style>
td{padding: 15px;text-align: left;border: 1px solid #ddd;}
th {background-color: #4CAF50;color: white;}
table {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;border: 1px solid #ddd;}
</style>
</head>
<body>
<TABLE align="center">
<form>
<tr>
<th>Wifi hálózat jelszava</th>
<th>Mentés</th>
</tr>
<tr>
<td><input type="text" name="jelszo"></td>
<td><input type="submit" value="Mentés"></td>
</tr>
</form>
</table>
</body>
</html>'''

erzekelo_neve='''<!DOCTYPE html><html>
<head><title>MOZGÁSÉRZÉKELŐ</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="about:blank">
<style>
td{padding: 15px;text-align: left;border: 1px solid #ddd;}
th {background-color: #4CAF50;color: white;}
table {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;border: 1px solid #ddd;}
</style>
</head>
<body>
<TABLE align="center">
<form>
<tr>
<th>Mozgásérzékelő elnevezése</th>
<th>Mentés</th>
</tr>
<tr>
<td><input type="text" name="m_neve"></td>
<td><input type="submit" value="Mentés"></td>
</tr>
</form>
</table>
</body>
</html>'''


befejezes='''<!DOCTYPE html><html>
<head><title>MOZGÁSÉRZÉKELŐ</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="about:blank">
<style>
td{padding: 15px;text-align: center;border: 1px solid #ddd;}
th {padding: 15px;background-color: #4CAF50;color: white;}
table {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;border: 1px solid #ddd;}
</style>
</head>
<body>
<TABLE align="center">
<form>
<tr>
<th colspan="2">Mozgásérzékelő</th>
</tr>
<tr>
<td><input type="button" value="BE" onclick="location.href='http://192.168.4.1/?be'"></td>
<td><input type="button" value="KI" onclick="location.href='http://192.168.4.1/?ki'"></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="RESET" onclick="location.href='http://192.168.4.1/?reset'"></td>
</tr>
</form>
</table>
</body>
</html>'''

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 80))

s.listen(5)
while True:
	try:
		conn, addr = s.accept()
		
		print("Got a connection from %s" % str(addr))
		request = conn.recv(2048)
		#print("Content = %s" % str(request))
		request = str(request)
		print (request)
		
		#print (request[8:11])
		#parancsget = request[8:11]
		if hozzaferes[0]=="default" or reset==1:
			eleje=request.find("ssidk")
			elsoszam=eleje+6
			vege=request.find("HTTP/1.1")
			vegeszam=vege-1
			#print(request[elsoszam:vegeszam])
				
			rows = ['<tr><td>%s</td><td><input type="radio" name="ssidk" value="%s"></td></tr>' % (str(i[0], 'utf8'), str(i[0], 'utf8')) for i in wlan_list]
			response = listazas % '\n'.join(rows)

			if eleje!=-1:
				valasztott_ssid=request[elsoszam:vegeszam]
				tovabblepes=1
				hozzaferes[0]=str(valasztott_ssid)
				response = jelszobekeres
			print(hozzaferes)
			print("hozzaferes_default")
			conn.sendall(response)
			time.sleep(0.2)
			conn.close()

		if tovabblepes==1:
			eleje=request.find("jelszo")
			elsoszam=eleje+7
			vege=request.find("HTTP/1.1")
			vegeszam=vege-1
			print(request[elsoszam:vegeszam])
			ssid_jelszava=request[elsoszam:vegeszam]
			if eleje!=-1:
				hozzaferes[1]=str(ssid_jelszava)
				tovabblepes=2
				response = erzekelo_neve
			print(hozzaferes)
			print("tovabblepes1")
			conn.sendall(response)
			conn.close()

		if tovabblepes==2:
			eleje=request.find("m_neve")
			elsoszam=eleje+7
			vege=request.find("HTTP/1.1")
			vegeszam=vege-1
			erzekelo_nev=request[elsoszam:vegeszam]
			if eleje!=-1:
				hozzaferes[2]=str(erzekelo_nev)
				tovabblepes=3
				response = befejezes
			print(hozzaferes)
			print("tovabblepes2")
			conn.sendall(response)
			conn.close()

		if tovabblepes==3:
			print("tovabblepes3")
			response = befejezes
			bekapcs=1
			tovabblepes=0
			conn.sendall(response)
			conn.close()
		if bekapcs==1:
			print("Mozgásérzékelő bekapcsolva...")
			ido2=time.ticks_ms()
			eltelt_ido=ido2-ido
			response = befejezes
			conn.sendall(response)
			conn.close()
			if mozgas.value()==1:
				print("mozgás")
				jelzes=1
			if jelzes==1:
				if elso_ertesites==0 or eltelt_ido>=idokoz:
					sta_if.active(True)
					SSIDWIFI=hozzaferes[0]
					JELSZOWIFI=hozzaferes[1]
					hely=hozzaferes[2]
					sta_if.connect(SSIDWIFI, JELSZOWIFI)
					for x in range(1,15):
						time.sleep(1)
						if x ==14 and sta.isconnected()!=True:
							machine.reset()
						else:
							break
					ertesites = '***************'
					response = urequests.post("http://api.pushingbox.com/pushingbox?devid="+ertesites+"&hely="+hely)
					time.sleep_ms(250)
					elso_ertesites=1
					sta_if.active(False)
					time.sleep_ms(500)
					#ap_if.active(True)
					#time.sleep_ms(500)
					elso_ertesites=1
					jelzes=0
	except:
		print('')

Re: How to check gpio pin input, when http-server is running?

Posted: Fri Aug 31, 2018 3:18 pm
by deonis
You will need to wrap your request and socket server with uasyncio library or use _thread library. This way two processes will run independently of one another. For esp8266 use uasyncio:

https://github.com/micropython/micropyt ... r/uasyncio

Use help("Modules") to see if you have it on the board.

Also, it is generally a bad idea to enable the board in both the Station and Access Point modes (AP). Your board might be unstable.

Re: How to check gpio pin input, when http-server is running?

Posted: Fri Aug 31, 2018 3:35 pm
by Zolee
Thanks!
The Client mode is not active always, only when the request sending.
Then disabling it in the code.
My first problem is this statement:

Code: Select all

if mozgas.value()==1:
	print("mozgás")
	jelzes=1
This wont be executed in the loop.
How i want to make it:
-starting the AP.
-user set the wifi connection.
-saving it in a txt file
loop:
-run the AP server (user can switching on/off the notification and reseting the wifi settings)
-check the input on the motion sensor
-when high is, start the wifi connection
-send the notification
-closing the wifi connection

Re: How to check gpio pin input, when http-server is running?

Posted: Fri Aug 31, 2018 9:24 pm
by deonis
I see. The only way, to my knowledge, to read the value in the loop while running the socket server is to use _thread or uasyncio library. Please take a look at this example by Peter:

https://github.com/peterhinch/micropyth ... /aqtest.py

An alternative way would be to use ajax request in the loop on the client side and post value from the server. In this case your browser will be doing looping.

Also, you might want to use:

Code: Select all

 
try:
   # stuff to do 
except Exception as exc:
      print("Error", exc.args[0])   
This way you can see what errors you might have in the loop. For instance, there is a typo in line 252,

Code: Select all

if x ==14 and sta.isconnected()!=True:
needs to be sta_if

More here:
viewtopic.php?f=16&t=5061&p=28963&hilit=uasyncio#p28963

Re: How to check gpio pin input, when http-server is running?

Posted: Sun Sep 02, 2018 10:31 am
by Zolee
Thanks!
I writed a code with asyncio, but only one loop called.

Code: Select all

loop = asyncio.get_event_loop()

try:
	asyncio.ensure_future(server())
	asyncio.ensure_future(erzekelo())
	
	loop.run_forever()
except KeyboardInterrupt:
	pass
finally:
	print("Closing Loop")
	loop.close()
Only the server loop is running.

Code: Select all

loop = asyncio.get_event_loop()

try:
	asyncio.ensure_future(erzekelo())
	asyncio.ensure_future(server())
	
	
	loop.run_forever()
except KeyboardInterrupt:
	pass
finally:
	print("Closing Loop")
	loop.close()
Only the erzekelo loop is running.
The full code:

Code: Select all

import time
import usocket as socket
import network
from machine import Pin
import urequests
import machine
import os
import uasyncio as asyncio


time.sleep(5)


#SZERVER
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)

ap_if = network.WLAN(network.AP_IF)
ap_if.active(True)


#szerver beállítások:
SSID='mozgaserzekelo'
JELSZO='12345678'
IPCIM='192.168.4.1'
ATJARO='192.168.4.1'
#szerver beállítások vége
ap_if.config(essid=SSID, channel=11, password=JELSZO)
ap_if.ifconfig((IPCIM,'255.255.255.0',ATJARO,'208.67.222.222'))
#SZERVER VÉGE
###########################################
wlan_list = sta_if.scan()
time.sleep(2)

mozgas = Pin(15, Pin.IN)#d8
hozzaferes = ["default","default","default"]
reset=0
tovabblepes=0
ido=time.ticks_ms()
elso_ertesites=0
idokoz=60000
bekapcs=0
jelzes=0


listazas='''<!DOCTYPE html><html>
<head><title>MOZGÁSÉRZÉKELŐ</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="about:blank">
<style>
td{padding: 15px;text-align: left;border: 1px solid #ddd;}
th {background-color: #4CAF50;color: white;}
table {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;border: 1px solid #ddd;}
</style>
</head>
<body>
<TABLE align="center">
<form>
<tr>
<th>Wifi hálózatok</th>
<th>Kiválaszt</th>
</tr>%s 
<tr>
<td></td>
<td><input type="submit" value="Tovább"></td>
</tr>
</form>
</table>
</body>
</html>'''

jelszobekeres='''<!DOCTYPE html><html>
<head><title>MOZGÁSÉRZÉKELŐ</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="about:blank">
<style>
td{padding: 15px;text-align: left;border: 1px solid #ddd;}
th {background-color: #4CAF50;color: white;}
table {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;border: 1px solid #ddd;}
</style>
</head>
<body>
<TABLE align="center">
<form>
<tr>
<th>Wifi hálózat jelszava</th>
<th>Mentés</th>
</tr>
<tr>
<td><input type="text" name="jelszo"></td>
<td><input type="submit" value="Mentés"></td>
</tr>
</form>
</table>
</body>
</html>'''

erzekelo_neve='''<!DOCTYPE html><html>
<head><title>MOZGÁSÉRZÉKELŐ</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="about:blank">
<style>
td{padding: 15px;text-align: left;border: 1px solid #ddd;}
th {background-color: #4CAF50;color: white;}
table {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;border: 1px solid #ddd;}
</style>
</head>
<body>
<TABLE align="center">
<form>
<tr>
<th>Mozgásérzékelő elnevezése</th>
<th>Mentés</th>
</tr>
<tr>
<td><input type="text" name="m_neve"></td>
<td><input type="submit" value="Mentés"></td>
</tr>
</form>
</table>
</body>
</html>'''


befejezes='''<!DOCTYPE html><html>
<head><title>MOZGÁSÉRZÉKELŐ</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="about:blank">
<style>
td{padding: 15px;text-align: center;border: 1px solid #ddd;}
th {padding: 15px;background-color: #4CAF50;color: white;}
table {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;border: 1px solid #ddd;}
</style>
</head>
<body>
<TABLE align="center">
<form>
<tr>
<th colspan="2">Mozgásérzékelő</th>
</tr>
<tr>
<td><input type="button" value="BE" onclick="location.href='http://192.168.4.1/?be'"></td>
<td><input type="button" value="KI" onclick="location.href='http://192.168.4.1/?ki'"></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="RESET" onclick="location.href='http://192.168.4.1/?reset'"></td>
</tr>
</form>
</table>
</body>
</html>'''
async def erzekelo():
	while True:
		try:
			global jelzes
			jelzes=0
			global ido
			global elso_ertesites
			global bekapcs
			print("érzékelő")
			print(idokoz)
			if mozgas.value()==1:
				print("mozgás")
				jelzes=1
				ido2=time.ticks_ms()
				eltelt_ido=ido2-ido
			else:
				pass
			print(jelzes)
			if jelzes==1  and bekapcs==1:
				print("jelzés")
				if elso_ertesites==0 or eltelt_ido>=idokoz:
					sta_if.active(True)
					with open("access.txt", "r") as file2:
						data2 = eval(file2.readline())
						file2.close()
					SSIDWIFI=data2[0]
					JELSZOWIFI=data2[1]
					hely=data2[2]
					print(SSIDWIFI)
					print(JELSZOWIFI)
					sta_if.connect(SSIDWIFI, JELSZOWIFI)
					for x in range(1,15):
						if x ==14 and sta_if.isconnected()!=True:
							machine.reset()
						else:
							break
						time.sleep(1)
					ertesites = 'xxxxxxxxxxxxxxxxxxxxxx'
					response = urequests.post("http://api.pushingbox.com/pushingbox?devid="+ertesites+"&hely="+hely)
					time.sleep_ms(250)
					elso_ertesites=1
					sta_if.active(False)
					time.sleep_ms(500)
					#ap_if.active(True)
					#time.sleep_ms(500)
					elso_ertesites=1
					jelzes=0
				print("lefutott")
			else:
				pass
				print("pass")
		except Exception as exc:
			print("Error_érzékelő", exc.args[0])
		time.sleep(1)


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 80))

s.listen(5)
async def server():
	while True:
		try:
			global bekapcs
			global tovabblepes
			conn, addr = s.accept()
			print("Got a connection from %s" % str(addr))
			request = conn.recv(2048)
			#print("Content = %s" % str(request))
			request = str(request)
			print (request)
			#print (request[8:11])
			#parancsget = request[8:11]
			if hozzaferes[0]=="default" or reset==1:
				eleje=request.find("ssidk")
				elsoszam=eleje+6
				vege=request.find("HTTP/1.1")
				vegeszam=vege-1
				#print(request[elsoszam:vegeszam])
					
				rows = ['<tr><td>%s</td><td><input type="radio" name="ssidk" value="%s"></td></tr>' % (str(i[0], 'utf8'), str(i[0], 'utf8')) for i in wlan_list]
				response = listazas % '\n'.join(rows)

				if eleje!=-1:
					valasztott_ssid=request[elsoszam:vegeszam]
					tovabblepes=1
					hozzaferes[0]=str(valasztott_ssid)
					response = jelszobekeres
				print(hozzaferes)
				print("hozzaferes_default")
				conn.sendall(response)
				conn.close()

			if tovabblepes==1:
				eleje=request.find("jelszo")
				elsoszam=eleje+7
				vege=request.find("HTTP/1.1")
				vegeszam=vege-1
				print(request[elsoszam:vegeszam])
				ssid_jelszava=request[elsoszam:vegeszam]
				if eleje!=-1:
					hozzaferes[1]=str(ssid_jelszava)
					tovabblepes=2
					response = erzekelo_neve
				print(hozzaferes)
				print("tovabblepes1")
				conn.sendall(response)
				conn.close()

			if tovabblepes==2:
				eleje=request.find("m_neve")
				elsoszam=eleje+7
				vege=request.find("HTTP/1.1")
				vegeszam=vege-1
				erzekelo_nev=request[elsoszam:vegeszam]
				if eleje!=-1:
					hozzaferes[2]=str(erzekelo_nev)
					tovabblepes=3
					response = befejezes
					with open("access.txt", "w") as file:
					#f.write('%s' % (szam2))
						file.write(str(hozzaferes))
						file.close()
				print(hozzaferes)
				print("tovabblepes2")
				conn.sendall(response)
				conn.close()

			if tovabblepes==3:
				print("tovabblepes3")
				response = befejezes
				bekapcs=1
				tovabblepes=0
				conn.sendall(response)
				conn.close()
			if bekapcs==1:
				print("Mozgásérzékelő bekapcsolva...")
				response = befejezes
				conn.sendall(response)
				conn.close()
		except Exception as exc:
			print("Error", exc.args[0])

loop = asyncio.get_event_loop()

try:
	asyncio.ensure_future(server())
	asyncio.ensure_future(erzekelo())
	
	loop.run_forever()
except KeyboardInterrupt:
	pass
finally:
	print("Closing Loop")
	loop.close()

Re: How to check gpio pin input, when http-server is running?

Posted: Sun Sep 02, 2018 11:56 am
by Zolee
Ok, i think this setup never will working, because the server loop not a "real" loop.
The server loop recognised only, if the client send a request.
If the request is sended, the another function is called, but only at once. Same problem as before.
The output:

Code: Select all

Got a connection from ('192.168.4.2', 38957)
b'GET /?be HTTP/1.1\r\nHost: 192.168.4.1\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\nSave-Data: on\r\nUser-Agent: Mozilla/5.0 (Linux; Android 7.0; HUAWEI VNS-L21 Build/HUAWEIVNS-L21) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.91 Mobile Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\nReferer: http://192.168.4.1/?be\r\nAccept-Encoding: gzip, deflate\r\nAccept-Language: en-US,en;q=0.9,de;q=0.8,hu;q=0.7\r\n\r\n'
Mozgásérzékelő bekapcsolva...
érzékelő
60000
mozgás
1
jelzés
#7 ets_task(4020f474, 28, 3fff9ed8, 10)
*SSID*
*PASSWORD*
lefutott
Got a connection from ('192.168.4.2', 38958)
I think with two Esp8266 will working.
On the first esp. running the AP server
On the second esp. running the motion sensor loop.

Re: How to check gpio pin input, when http-server is running?

Posted: Wed Sep 05, 2018 4:50 am
by deonis
Asynchronous socket server :

Code: Select all

import uasyncio as asyncio


async def dummyloop():
    while True:
        print("Hello World")
        await  asyncio.sleep(0.01)
        # await asyncio.sleep(1)
        print("Bye Bye")

@asyncio.coroutine
def serve(reader, writer):
    try:
        with open("index.html", "r") as fhtml:
            html = fhtml.readlines()
    except OSError:
        pass
    print(reader, writer)
    print("================")
    print((yield from reader.read()))
    for lines in html:
        yield from writer.awrite(lines+"\r\n\r\n")
    print("After response write")
    yield from writer.aclose()
    print((yield from reader.read()))
    del html, reader
    print("Finished processing request")


#import logging
#logging.basicConfig(level=logging.INFO)
#logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
loop.call_soon(asyncio.start_server(serve, "192.168.0.12", 80))
loop.create_task(dummyloop())
loop.run_forever()
loop.close()

index.html is taken from here https://github.com/deonis1/nphttpd
more here:
https://github.com/micropython/micropyt ... _server.py

Re: How to check gpio pin input, when http-server is running?

Posted: Wed Sep 05, 2018 11:36 pm
by devnull
Why not use a timer instead ?

Re: How to check gpio pin input, when http-server is running?

Posted: Thu Sep 06, 2018 1:37 am
by deonis
I assume you mean machine.Timer ? It might be worth trying.

from machine import Timer

tim = Timer(-1)
tim.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(1))
tim.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(2))