浏览代码

added webapp and autostart handling

Tobias Simetsreiter 4 年之前
父节点
当前提交
ef78196700

+ 1 - 0
.gitignore

@@ -1,3 +1,4 @@
 src/blob
+src/runtime
 build
 __pycache__

+ 38 - 0
src/bootstrap_captive/api/__init__.py

@@ -0,0 +1,38 @@
+
+
+def process_json(inp):
+    if "set_wifi" in inp:
+        return set_wifi(inp["set_wifi"])
+    if "disable_portal" in inp:
+        disable_portal(inp["disable_portal"])
+        return {
+            "ok":True,
+        }
+    return {
+        "ok":False,
+        "api_err":"Request Handler not fond"
+    }
+
+def disable_portal(inp):
+    import subprocess
+    p = subprocess.Popen(['bootstrap_captive','stop'],
+                     cwd="/",
+                     stdout=subprocess.PIPE,
+                     stderr=subprocess.STDOUT)
+
+def set_wifi(inp):
+    import re
+    wifi_file = "/etc/wpa_supplicant/wpa_supplicant.conf"
+    with open(wifi_file) as fd:
+        wifi_conf = fd.read()
+
+    wifi_conf = re.sub(r'ssid=".*','ssid="'+inp["ssid"]+'"', wifi_conf)
+    wifi_conf = re.sub(r'psk=".*','psk="'+inp["pw"]+'"', wifi_conf)
+
+    with open(wifi_file, "w") as fd:
+        fd.write(wifi_conf)
+
+    return {
+        "ok":True,
+        "wifi_conf": wifi_conf
+    }

+ 8 - 0
src/bootstrap_captive/gpio.py

@@ -0,0 +1,8 @@
+
+switch_pin = 40
+
+def switch(args):
+    from RPi import GPIO
+    GPIO.setmode(GPIO.BOARD)
+    GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
+    return GPIO.input(switch_pin) == 0

+ 20 - 19
src/bootstrap_captive/install.py

@@ -1,11 +1,5 @@
 
-def com_install(args):
-    import os
-    if not "UNSHARXZ_INSTALLER" in os.environ:
-        print("hostapt_captive is already installed")
-        if args.enable:
-            com_enable(args)
-        return
+def com_unpack(args):
     COM="""
 set -e
 set -x
@@ -13,8 +7,26 @@ pwd
 ls -alsh .
 ls -alsh blob/
 
-dpkg -l hostapd dnsmasq 2>&1 1> /dev/null || dpkg -i -R blob/
+mkdir -p "{0}"
+rm -rf "{0}"
+cp -a "." "{0}"
+printf "#!/usr/bin/env sh\n\ncd {0} && ./main.py \\$@" > "/usr/local/bin/bootstrap_captive"
+chmod +x "/usr/local/bin/bootstrap_captive"
+""".format(args.install_dir)
+    from subprocess import run
+    run(COM, shell=True, check=True)
+
 
+def com_install(args):
+    import os
+    if not "UNSHARXZ_INSTALLER" in os.environ:
+        print("hostapt_captive is already installed")
+        return
+    com_unpack(args)
+    COM="""
+set -e
+set -x
+dpkg -l hostapd dnsmasq python3-rpi.gpio 2>&1 1> /dev/null || dpkg -i -R blob/
 systemctl unmask hostapd.service
 systemctl disable hostapd.service dnsmasq.service
 sed -i 's/^source-directory.*$/source \/etc\/network\/interfaces.d\/*/' /etc/network/interfaces
@@ -23,11 +35,6 @@ rm -f /etc/hostapd/hostapd.conf
 ln -s "{0}/hostapd.conf" /etc/hostapd/hostapd.conf
 mv /etc/dnsmasq.conf /etc/dnsmasq.orig || true
 ln -s "{0}/dnsmasq.conf" /etc/dnsmasq.conf
-mkdir -p "{0}"
-rm -rf "{0}"
-cp -a "." "{0}"
-printf "#!/usr/bin/env sh\n\ncd {0} && ./main.py \\$@" > "/usr/local/bin/bootstrap_captive"
-chmod +x "/usr/local/bin/bootstrap_captive"
 rm -f /lib/systemd/system/bootstrap_captive@.service
 ln -s "{0}/bootstrap_captive@.service" /lib/systemd/system/
 systemctl daemon-reload
@@ -36,9 +43,3 @@ systemctl disable bootstrap_captive@server.service
 """.format(args.install_dir)
     from subprocess import run
     run(COM, shell=True, check=True)
-    if args.remove_installer:
-        inst_file = os.environ["UNSHARXZ_INSTALLER"]
-        os.unlink(inst_file)
-    if args.enable:
-        com_enable(args)
-

+ 5 - 5
src/bootstrap_captive/server.py

@@ -42,13 +42,17 @@ class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
     def do_POST(self):
         import traceback
         import json
+        from .api import process_json
         self.send_response(200)
         self.send_header('Content-type', 'application/json')
         self.end_headers()
         try:
             length = int(self.headers['Content-Length'])
             data = json.loads(self.rfile.read(length).decode("utf-8"))
-            resp_data = self.process_json(data)
+            print("Req:", data)
+            resp_data = process_json(data)
+            print("Res:", resp_data)
+            resp_data["input"] = data
         except Exception as ex:
             print(traceback.format_exc())
             resp_data = {
@@ -59,10 +63,6 @@ class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
         self.wfile.write(json.dumps(resp_data).encode("utf-8")+b"\n")
         return
 
-    def process_json(self, data):
-        return data
-
-
 
 def start_http_service(args):
     from subprocess import run

文件差异内容过多而无法显示
+ 5 - 0
src/http/bootstrap.bundle.min.js


文件差异内容过多而无法显示
+ 5 - 0
src/http/bootstrap.min.css


+ 12 - 6
src/http/index.html

@@ -1,13 +1,19 @@
 <html>
  <head>
- <script src="portal.js">
- </script>
+   <script src="bootstrap.bundle.min.js"></script>
+   <link rel="stylesheet" style="text/css" href="bootstrap.min.css" />
+   <script src="portal.js"></script>
  </head>
  <body>
-   <h1>Hello World<h1>
-   <input id="input_ssid" placeholder="SSID">
-   <input id="input_pw" placeholder="Password">
-   <button onclick="portal.setWifi()">set</button>
+   <h1>Welcome to Raspi Bootstrap Captive<h1>
+   <div class="form-group">
+     <input id="input_ssid" placeholder="SSID" class="form-control">
+     <input id="input_pw" placeholder="Password" class="form-control">
+     <button onclick="portal.setWifi()" class="btn btn-primary">set</button>
+   </div>
+   <div class="form-group">
+     <button onclick="portal.disablePortal()" class="btn btn-warning">Disable Portal</button>
+   </div>
    <textarea id="input_resp" name="message" rows="10" cols="30">
    </textarea>
  </body>

+ 10 - 2
src/http/portal.js

@@ -4,8 +4,16 @@ portal = new function(){
         const pw   = getId("input_pw").value;
         const resp_div   = getId("input_resp");
         const resp = await postData("", {
-            "ssid":ssid,
-            "pw":pw,
+            "set_wifi":{
+                "ssid":ssid,
+                "pw":pw,
+            }
+        })
+        resp_div.value = JSON.stringify(resp, null, 2);
+    }
+    this.disablePortal = async () => {
+        const resp = await postData("", {
+            "disable_portal":true
         })
         resp_div.value = JSON.stringify(resp, null, 2);
     }

+ 28 - 9
src/main.py

@@ -2,7 +2,7 @@
 
 import os
 import sys
-from bootstrap_captive.install import com_install
+from bootstrap_captive.install import com_install,com_unpack
 from bootstrap_captive.wificonfig import set_wifi
 realp = os.path.realpath(os.path.dirname(__file__))
 
@@ -24,18 +24,37 @@ def parser():
     p_server.add_argument("-p", "--port", type=int, default=80)
     p_server.add_argument("-s", "--ssl_port", type=int, default=443)
     p_server.add_argument("-n", "--portal_name", default="portal.raspi.tsimnet.eu")
+
+    p_unpack = sub.add_parser("unpack")
+    p_unpack.set_defaults(func=com_unpack)
+    p_unpack.add_argument("-i", "--install_dir", default="/opt/eu.tsimnet.git/dasimmet/bootstrap_captive")
+
+    p_autostart = sub.add_parser("autostart")
+    p_autostart.set_defaults(func=com_autostart)
+    p_autostart.add_argument("-i", "--install_dir", default="/opt/eu.tsimnet.git/dasimmet/bootstrap_captive")
+
     p_install = sub.add_parser("install")
     p_install.set_defaults(func=com_install)
     p_install.add_argument("-i", "--install_dir", default="/opt/eu.tsimnet.git/dasimmet/bootstrap_captive")
-    p_install.add_argument("-r", "--remove_installer", action="store_true")
-    p_install.add_argument("-e", "--enable", action="store_true")
-    p_enable = sub.add_parser("enable")
-    p_enable.set_defaults(func=com_enable)
-    p_enable = sub.add_parser("disable")
-    p_enable.set_defaults(func=com_disable)
+
+    p_start = sub.add_parser("start")
+    p_start.set_defaults(func=com_start)
+
+    p_stop = sub.add_parser("stop")
+    p_stop.set_defaults(func=com_stop)
     return p
 
-def com_enable(args):
+def com_autostart(args):
+    com_install(args)
+    with open("/etc/cron.d/42-bootstrap_captive", "w") as fd:
+        fd.write('''
+@reboot /usr/local/bin/bootstrap_captive autostart
+''')
+    from bootstrap_captive.gpio import switch
+    if switch(args):
+        com_start(args)
+
+def com_start(args):
     from subprocess import run
     set_wifi(True)
     COM="""
@@ -51,7 +70,7 @@ iptables -t nat -A PREROUTING -d 0/0 -p tcp --dport 80 -j DNAT --to-destination
 """
     run(COM, shell=True)
 
-def com_disable(args):
+def com_stop(args):
     from subprocess import run
     set_wifi(False)
     COM="""

+ 0 - 0
src/runtime/.gitignore


部分文件因为文件数量过多而无法显示