Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
christianstrauch authored Feb 20, 2024
1 parent 6ecde64 commit e1de5dc
Show file tree
Hide file tree
Showing 2 changed files with 125 additions and 7 deletions.
85 changes: 78 additions & 7 deletions install/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,27 @@
import machine
import json
import sys
import utils
from utime import sleep
from micropyserver import MicroPyServer
import time
import usocket as socket
import ustruct as struct

NTP_HOST = 'pool.ntp.org'
userconfig = {}
wifi = {}

outlets = [
{ 'pin': machine.Pin(18, mode=machine.Pin.OUT), 'on': False },
{ 'pin': machine.Pin(19, mode=machine.Pin.OUT), 'on': False },
{ 'pin': machine.Pin(20, mode=machine.Pin.OUT), 'on': False },
{ 'pin': machine.Pin(21, mode=machine.Pin.OUT), 'on': False },
{ 'pin': machine.Pin(22, mode=machine.Pin.OUT), 'on': False }
]

def asbool(s):
return s.lower() in {'true', 'yes', '1', 'on'}

def blink(timer):
led.toggle()
Expand Down Expand Up @@ -42,13 +56,17 @@ def setup_ap(config):
print(wap.ifconfig())

def run(config):
network.country = config.user["country"]
userconfig = config.user
network.country(config.user["country"])
wifi = network.WLAN(network.STA_IF)
wifi.config(pm = 0xa11140)
wifi.active(True)
wifi.connect(config.user["ssid"], config.user["pwd"], hostname=config.user["device_name"])
while not wifi.isconnected() and wifi.status() >= 0:
time.sleep(1)
for wait_counter in range(10):
if not wifi.isconnected() and wifi.status() >= 0:
time.sleep(1)
else:
break
setTimeRTC()
return

Expand All @@ -59,7 +77,11 @@ def getmachineid():
return mid

def setup(request):
server.send("<html />")
file = open('setup.html.txt', 'r')
html = file.read()
file.close()
server.send(html)
return

def save_config(request):
if utils.get_request_method(request) != 'POST':
Expand Down Expand Up @@ -96,13 +118,59 @@ def status(request):
server.send("")

def control(request):
qparams = utils.get_request_query_params(request)
pparams = utils.get_request_post_params(request)
key = userconfig.user['id_key']
if key != '' and not ('id_key' in pparams or pparams['id_key'] != key):
server.send("invalid key")
return
if \
'plug' in qparams \
and qparams['plug'].isnumeric() \
and (i := int(params['plug'])) >= 0 \
and i <= 5:
if 'on' in pparams:
control_plug(i, asbool(pparams['on']))
server.send(json.dumps(get_states()))
return
else:
server.send("Invalid state")
return
else:
server.send("invalid plug id")
return


server.send("")

def get_states():
states = {
'plugs': {
'1': { 'on': outlets[0]['on'] },
'2': { 'on': outlets[1]['on'] },
'3': { 'on': outlets[2]['on'] },
'4': { 'on': outlets[3]['on'] },
'5': { 'on': outlets[4]['on'] }
},
'ip': wifi.ifconfig()[0],
'device_name': userconfig['device_name']
}
return states

def control_plug(plug_index, val):

i = plug_index - 1
if plug_index == -1:
for j in range(5):
control_plug(j, val)
return
else:
if val:
outlets[i]['pin'].on()
else:
outlets[i]['pin'].off()
outlets[i]['on'] = val

led = machine.Pin("LED", machine.Pin.OUT)
plugs = [False, False, False, False, False]

server = MicroPyServer()
try:
Expand All @@ -115,13 +183,16 @@ def control_plug(plug_index, val):
server.add_route("/control", control)
timer.deinit()

except:
except ImportError:
timer = machine.Timer()
timer.init(freq=.5, mode=machine.Timer.PERIODIC, callback=blink)
import initial_config
setup_ap(initial_config)
server.add_route("/", setup)
server.add_route("/save_config", save_config)

except Exception as err:
print(f"Unexpected {err=}, {type(err)=}")

server.start()

47 changes: 47 additions & 0 deletions install/setup.html.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<html>
<head>
<style>
body { font-family: sans-serif }
form { display: block; border: 1px solid #c0c0c0; padding: 20px; margin: 100px;}
input { display: block; width: 100%; height: 30px; margin-bottom: 30px }
</style>
</head>
<body>
<form method='post' action='/save_config'>
<h1>PiPlug Config</h1>
<hr />
<h2>Wifi</h2>
<label for='ssid'>SSID</label>
<input type='text' name='ssid' />
<label for='pwd'>Password</label>
<input type='password' name='pwd' />
<label for='country'>Country (e.g., US, DE, FR, CH...)</label>
<input type='text' name='country' />
<hr />
<h2>Name</h2>
<label for='device_name'>Name for this device</label>
<input type='text' name='device_name' />
<hr />
<h2>Identification</h2>
<label for='id_key'>Identification string for a simple, clear text authentication (leave empty if not needed)</label>
<input type='text' name='id_key' />
<hr />
<h2>Status updates</h2>
<label for='u'>Update URL, posts <i>{ 'id': 'xyz', 'plug': 0, 'on': true }</i> (leave empty for no update)</label>
<input type='text' name='u'/>
<hr />
<input type='submit' value='Save'>
<hr />
<p>To use, find out the device IP address on your router, then post the following body to <u>http://&lt;ip-address&gt;/control</u></p>
<pre>
{
'id_key': '&lt;the id you defined above, omit if none&gt;',
'plug': &lt;the index of the plug, 0 for all&gt;,
'on': &lt;true for on, false, for off&gt;
}
</pre>
<p>To check the current power status, GET <u>http://&lt;ip-address&gt;/status?plug=&lt;the index of the plug&gt;</u></p>

</form>
</body>
</html>

0 comments on commit e1de5dc

Please sign in to comment.