GrowSystem/gs/grow_system_api.py

70 lines
2.3 KiB
Python

from gs.http_client import HTTPClient
from gs.device_info import DeviceInfo
from gs.wlan_client import WlanClient
import json
import gs.config.initial_config as ic
import helper.token_helper as th
class GrowSystemApi:
http_client = HTTPClient()
device_info = DeviceInfo()
base_url = ''
def __init__(self):
self.base_url = self.device_info.server_url()
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):
print("ACtivate config:", config)
data = self._get_device_data()
data.update({
'user_id': 1,
'pin': config['pin']
})
print("activate ...", data)
response = self.http_client.post(self.base_url + "/api/device/activate", data)
print("REsponse ...", response.content)
return self._get_json_encoded(response.text)
def update_device_info(self, config):
device_id = self.device_info.get_device_id()
token = self.device_info.get_token()
print("update device info. Token ...", token)
url = self.base_url + "/api/device/" + str(device_id) + "/update-device-info/" + token
response = self.http_client.get(url)
print("Device Info Update Response ...", response.text)
return self._get_json_encoded(response.text)
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)
try:
return json.loads(response.text)
except ValueError as e:
print("JSON Value error raised after sending measurements")
except Exception as e:
print("Exception raised while sending measurements", e)
return response
def _get_device_data(self):
return self.device_info.get_all_device_infos()
def _get_json_encoded(self, text):
return json.loads(text)
def connect_wifi(self, ssid, password):
print("Connect WLAN")
self.wlan_client = WlanClient(ssid, password)
self.wlan_client.connect()