main #3
|
|
@ -1,38 +0,0 @@
|
||||||
from http_client import HTTPClient
|
|
||||||
from device_info import DeviceInfo
|
|
||||||
import json
|
|
||||||
|
|
||||||
|
|
||||||
class GrowSystemApi:
|
|
||||||
|
|
||||||
http_client = HTTPClient()
|
|
||||||
|
|
||||||
device_info = DeviceInfo()
|
|
||||||
|
|
||||||
base_url = ''
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.base_url = self.device_info.server_url
|
|
||||||
|
|
||||||
def activate(self, config):
|
|
||||||
response = self.http_client.post(self.base_url + "/api/device/activate", self._get_device_data())
|
|
||||||
return self_get_json_encoded(response.text)
|
|
||||||
|
|
||||||
def say_hello(self):
|
|
||||||
response = self.http_client.post(self.base_url + "/api/device", self._get_device_data())
|
|
||||||
print(response.text)
|
|
||||||
jsonResult = json.loads(response.text)
|
|
||||||
print(jsonResult)
|
|
||||||
return jsonResult;
|
|
||||||
|
|
||||||
def send_measurements(self, device_id, data):
|
|
||||||
url = self.base_url + "/api/device/" + str(device_id) + "/sensor-log"
|
|
||||||
response = self.http_client.post(url, data)
|
|
||||||
return json.loads(response.text)
|
|
||||||
|
|
||||||
def _get_device_data(self):
|
|
||||||
return self.device_info.get_all_device_infos()
|
|
||||||
|
|
||||||
def _get_json_encoded(self, text):
|
|
||||||
return json.loads(text)
|
|
||||||
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
from gs.setup import Setup
|
|
||||||
import os
|
|
||||||
|
|
||||||
|
|
||||||
class GrowSystem:
|
|
||||||
|
|
||||||
version = "1.0"
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
print("Initialize Growsystem", self.version)
|
|
||||||
if self._is_config_existing():
|
|
||||||
print("Skip Setup. Config existing.")
|
|
||||||
elif self._is_initial_config_existing():
|
|
||||||
self._activate()
|
|
||||||
else:
|
|
||||||
print("No config existing. Start setup ...")
|
|
||||||
self._setup()
|
|
||||||
|
|
||||||
def _setup(self):
|
|
||||||
setup = Setup()
|
|
||||||
setup.setup_pico()
|
|
||||||
|
|
||||||
def _activate(self):
|
|
||||||
print("Start activation!")
|
|
||||||
|
|
||||||
def _is_config_existing(self):
|
|
||||||
return self._is_file_existing('/gs/config/config.py')
|
|
||||||
|
|
||||||
def _is_initial_config_existing(self):
|
|
||||||
return self._is_file_existing('/gs/config/initial_config.py')
|
|
||||||
|
|
||||||
def _is_file_existing(self, filepath):
|
|
||||||
try:
|
|
||||||
f = open(filepath, "r")
|
|
||||||
f.close()
|
|
||||||
# continue with the file.
|
|
||||||
return True
|
|
||||||
except OSError: # open failed
|
|
||||||
# handle the file open cas
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
sensors = [{"pin_int_sda": 8, "type": "ambilight", "pin_int": 8, "pin_int_scl": 9}, {"pin_int": 15, "type": "dht22"}, {"pin_int": 26, "type": "moisture"}]
|
||||||
|
|
@ -1 +1 @@
|
||||||
config = {"pin": "4628", "password": "95%04-MM", "ssid": "Oppa-95.lan"}
|
config = {"pin": "1234", "password": "95%04-MM", "ssid": "Oppa-95.lan"}
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import network
|
import network
|
||||||
|
import json
|
||||||
|
|
||||||
|
|
||||||
class DeviceInfo:
|
class DeviceInfo:
|
||||||
|
|
@ -58,6 +59,9 @@ class DeviceInfo:
|
||||||
'ip_address': self.get_ipaddress(),
|
'ip_address': self.get_ipaddress(),
|
||||||
'token': self.token}
|
'token': self.token}
|
||||||
|
|
||||||
|
def config(self):
|
||||||
|
return self._loadConfig()
|
||||||
|
|
||||||
def _format_mac(self, mac):
|
def _format_mac(self, mac):
|
||||||
# Split the MAC address into pairs of two characters each
|
# Split the MAC address into pairs of two characters each
|
||||||
pairs = [mac[i:i+2] for i in range(0, len(mac), 2)]
|
pairs = [mac[i:i+2] for i in range(0, len(mac), 2)]
|
||||||
|
|
@ -65,4 +69,10 @@ class DeviceInfo:
|
||||||
formatted_mac = ":".join(pairs)
|
formatted_mac = ":".join(pairs)
|
||||||
return formatted_mac
|
return formatted_mac
|
||||||
|
|
||||||
|
def _loadConfig(self):
|
||||||
|
with open('/gs/config/sensors.py', 'r') as file:
|
||||||
|
json_content = file.read()
|
||||||
|
return json.loads(json_content)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -17,6 +17,10 @@ class GrowSystemApi:
|
||||||
self.base_url = self.device_info.server_url
|
self.base_url = self.device_info.server_url
|
||||||
self.connect_wifi(ic.config['ssid'], ic.config['password'])
|
self.connect_wifi(ic.config['ssid'], ic.config['password'])
|
||||||
|
|
||||||
|
# config = self.device_info.config()
|
||||||
|
# print("Config:", config)
|
||||||
|
# print("Test", config['test'])
|
||||||
|
|
||||||
def activate(self, config):
|
def activate(self, config):
|
||||||
data = self._get_device_data()
|
data = self._get_device_data()
|
||||||
data.update({
|
data.update({
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
from gs.setup import Setup
|
from gs.setup import Setup
|
||||||
import os
|
import os
|
||||||
|
import ujson
|
||||||
|
|
||||||
|
|
||||||
class GrowSystem:
|
class GrowSystem:
|
||||||
|
|
@ -34,7 +35,14 @@ class GrowSystem:
|
||||||
import gs.config.initial_config as ic
|
import gs.config.initial_config as ic
|
||||||
self.initial_config = ic.config
|
self.initial_config = ic.config
|
||||||
device_config = self.gsapi.activate(self.initial_config)
|
device_config = self.gsapi.activate(self.initial_config)
|
||||||
print("Device Config:", device_config)
|
#print("Device Config:", device_config['data'])
|
||||||
|
sensors = device_config['data']['sensors']
|
||||||
|
sensor_configs = []
|
||||||
|
for sensor in sensors:
|
||||||
|
sensor_configs.append(sensor['config'])
|
||||||
|
print(sensor['config'])
|
||||||
|
with open("/gs/config/device_config.py", "w") as f:
|
||||||
|
f.write("sensors = " + ujson.dumps(sensor_configs))
|
||||||
|
|
||||||
def _is_config_existing(self):
|
def _is_config_existing(self):
|
||||||
return self._is_file_existing('/gs/config/config.py')
|
return self._is_file_existing('/gs/config/config.py')
|
||||||
|
|
|
||||||
110
little_apache.py
110
little_apache.py
|
|
@ -1,110 +0,0 @@
|
||||||
import socket
|
|
||||||
from gs.classes.http_request import HttpRequest
|
|
||||||
|
|
||||||
|
|
||||||
class LittleApache():
|
|
||||||
|
|
||||||
available_wifis = []
|
|
||||||
keep_webserver_alive = True
|
|
||||||
|
|
||||||
|
|
||||||
def __init__(self, net):
|
|
||||||
self.net = net
|
|
||||||
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
|
|
||||||
self.s = socket.socket()
|
|
||||||
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
||||||
self.s.bind(addr)
|
|
||||||
self.s.listen()
|
|
||||||
# print('Listening on', addr)
|
|
||||||
|
|
||||||
def start(self):
|
|
||||||
print("Webserver started. Connect to: " + self.net.ifconfig()[0])
|
|
||||||
print(self.net.ifconfig())
|
|
||||||
|
|
||||||
while self.keep_webserver_alive:
|
|
||||||
try:
|
|
||||||
conn, addr = self.s.accept()
|
|
||||||
#print('Got a connection from', addr)
|
|
||||||
|
|
||||||
# Receive and parse the request
|
|
||||||
request = conn.recv(1024)
|
|
||||||
# print("Request (RAW)", request)
|
|
||||||
http_request = HttpRequest(request)
|
|
||||||
self.http_request = http_request
|
|
||||||
request = str(request)
|
|
||||||
# print('Request content = %s' % request)
|
|
||||||
#try:
|
|
||||||
# request = request.split()[1]
|
|
||||||
# print('Request:', request)
|
|
||||||
#except IndexError:
|
|
||||||
# pass
|
|
||||||
response = self.response(http_request)
|
|
||||||
# Send the HTTP response and close the connection
|
|
||||||
conn.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
|
|
||||||
conn.send(response)
|
|
||||||
conn.close()
|
|
||||||
except OSError as e:
|
|
||||||
conn.close()
|
|
||||||
print('Connection closed')
|
|
||||||
return self
|
|
||||||
|
|
||||||
def response(self, request: HttpRequest):
|
|
||||||
#print("Webpage: ", request)
|
|
||||||
print("Request method: ", request.method, "Request path: ", request.path)
|
|
||||||
|
|
||||||
header = f"""
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<title>Growsystem</title>
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
"""
|
|
||||||
|
|
||||||
footer = f"""
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
"""
|
|
||||||
|
|
||||||
body = ""
|
|
||||||
|
|
||||||
if self.is_path_match(request, '/test1'):
|
|
||||||
body = f"""
|
|
||||||
<div>Test 1!!!</div>
|
|
||||||
"""
|
|
||||||
elif (self.is_path_match(request, '') or self.is_path_match(request, '/')):
|
|
||||||
options = []
|
|
||||||
for w in self.available_wifis:
|
|
||||||
options.append('<option value="{}">{}</option>'.format(w, w))
|
|
||||||
body = """
|
|
||||||
<h1>Setup Pico</h1>
|
|
||||||
<form method="post" action="save">
|
|
||||||
SSID: <select name="ssid">{}</select><br>
|
|
||||||
Password: <input type="password" name="password"><br>
|
|
||||||
PIN: <input type="text" name="pin" maxlength="4"><br>
|
|
||||||
<input type="submit" value="Submit">
|
|
||||||
</form>
|
|
||||||
"""
|
|
||||||
body = body.format(''.join(options))
|
|
||||||
elif self.is_path_match(request, '/save', 'POST'):
|
|
||||||
print("Save config path: ", request)
|
|
||||||
self.keep_webserver_alive = False
|
|
||||||
body = """
|
|
||||||
<h1>Setup Pico</h1>
|
|
||||||
<div>Setup abgeschlossen. Bitte ein paar Sekunden warten, dann neu starten.</div>
|
|
||||||
"""
|
|
||||||
else:
|
|
||||||
body = f"""
|
|
||||||
<div>Unknown page</div>
|
|
||||||
"""
|
|
||||||
|
|
||||||
html = ''
|
|
||||||
html_arr = [header, body, footer]
|
|
||||||
html = html.join(html_arr)
|
|
||||||
return str(html)
|
|
||||||
|
|
||||||
def is_path_match(self, request, path, method='GET'):
|
|
||||||
return path == request.path and method == request.method
|
|
||||||
|
|
||||||
|
|
||||||
84
setup.py
84
setup.py
|
|
@ -1,84 +0,0 @@
|
||||||
import network
|
|
||||||
import ujson
|
|
||||||
import ure as re
|
|
||||||
import usocket as socket
|
|
||||||
import time
|
|
||||||
from gs.little_apache import LittleApache
|
|
||||||
|
|
||||||
|
|
||||||
class Setup:
|
|
||||||
|
|
||||||
wlans = []
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.ap_ssid = "Growsystem 1.0"
|
|
||||||
self.ap_password = "password"
|
|
||||||
self.wlans = []
|
|
||||||
self.selected_ssid = ""
|
|
||||||
self.wlan_password = ""
|
|
||||||
self.pin = ""
|
|
||||||
|
|
||||||
def scan_wlans(self):
|
|
||||||
print("Scan for WiFis")
|
|
||||||
wlan = network.WLAN(network.STA_IF)
|
|
||||||
wlan.active(True)
|
|
||||||
self.wlans = [w[0].decode() for w in wlan.scan()]
|
|
||||||
print("Detected WiFis: ", self.wlans)
|
|
||||||
wlan.active(False)
|
|
||||||
|
|
||||||
def start_ap_mode(self):
|
|
||||||
wlan = network.WLAN(network.STA_IF)
|
|
||||||
wlan.active(False)
|
|
||||||
wlan_config = {
|
|
||||||
"ssid": self.ap_ssid,
|
|
||||||
"pw": self.ap_password
|
|
||||||
}
|
|
||||||
print("Switch to ap mode with data:", wlan_config)
|
|
||||||
ap = network.WLAN(network.AP_IF)
|
|
||||||
ap.config(essid=self.ap_ssid, password=self.ap_password)
|
|
||||||
ap.active(True)
|
|
||||||
self.net = ap
|
|
||||||
print("Connect with your browser to:", ap.ifconfig()[0])
|
|
||||||
|
|
||||||
def stop_ap_mode(self):
|
|
||||||
print("Stop ap mode")
|
|
||||||
ap = network.WLAN(network.AP_IF)
|
|
||||||
ap.active(False)
|
|
||||||
|
|
||||||
def get_initial_config_webserver(self):
|
|
||||||
self.la = LittleApache(self.net)
|
|
||||||
self.la.available_wifis = self.wlans
|
|
||||||
self.la.start()
|
|
||||||
config = self.la.http_request.get_content_json()
|
|
||||||
print("start webserver end:", config)
|
|
||||||
return config
|
|
||||||
|
|
||||||
def save_config(self, config):
|
|
||||||
config = {
|
|
||||||
"ssid": config['ssid'],
|
|
||||||
"password": config['password'],
|
|
||||||
"pin": config['pin']
|
|
||||||
}
|
|
||||||
print("Save config:", config)
|
|
||||||
with open("/gs/config/initial_config.py", "w") as f:
|
|
||||||
f.write("config = " + ujson.dumps(config))
|
|
||||||
|
|
||||||
def switch_to_client_mode(self):
|
|
||||||
print("Switch to client mode")
|
|
||||||
ap = network.WLAN(network.AP_IF)
|
|
||||||
ap.active(False)
|
|
||||||
wlan = network.WLAN(network.STA_IF)
|
|
||||||
wlan.active(True)
|
|
||||||
wlan.connect(self.selected_ssid, self.wlan_password)
|
|
||||||
while not wlan.isconnected():
|
|
||||||
time.sleep(1)
|
|
||||||
print("Connected to", self.selected_ssid)
|
|
||||||
|
|
||||||
def setup_pico(self):
|
|
||||||
self.scan_wlans()
|
|
||||||
self.start_ap_mode()
|
|
||||||
config = self.get_initial_config_webserver()
|
|
||||||
self.save_config(config)
|
|
||||||
# self.stop_ap_mode()
|
|
||||||
# self.switch_to_client_mode()
|
|
||||||
|
|
||||||
Loading…
Reference in New Issue