Skip to content

Commit 64ff603

Browse files
committed
Organized into separate files
1 parent a3fae43 commit 64ff603

File tree

6 files changed

+514
-470
lines changed

6 files changed

+514
-470
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
.coverage
22
__pycache__
3+
DO_NOT_COMMIT

api.py api_connect.py

+18-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import sys
2-
import os
32
import json
43
import requests
54

6-
class ApiFunctions():
5+
class ApiConnect():
76
def __init__(self):
87
self.token = None
98
self.error = None
@@ -21,6 +20,8 @@ def __init__(self):
2120
# delete() --> delete endpoint info
2221

2322
def token_handling(self, response):
23+
"""Handle errors relating to bad user auth token requests."""
24+
2425
# Handle HTTP status codes
2526
if response.status_code == 200:
2627
return 200
@@ -44,6 +45,8 @@ def token_handling(self, response):
4445
return 0
4546

4647
def request_handling(self, response):
48+
"""Handle errors relating to bad endpoints and user requests."""
49+
4750
error_messages = {
4851
404: "The specified endpoint does not exist.",
4952
400: "The specified ID is invalid or you do not have access to it.",
@@ -64,22 +67,30 @@ def request_handling(self, response):
6467
return 0
6568

6669
def get_token(self, email, password, server):
70+
"""Fetch user authentication token via API."""
71+
6772
headers = {'content-type': 'application/json'}
6873
user = {'user': {'email': email, 'password': password}}
6974
response = requests.post(f'{server}/api/tokens', headers=headers, json=user)
7075

7176
if self.token_handling(response) == 200:
77+
user_data = response.json()
78+
user_token = user_data['token']
7279
self.error = None
73-
return response.json()
80+
return user_token
7481
else:
7582
return self.error
7683

7784
def check_token(self):
85+
"""Ensure user authentication token has been generated and persists."""
86+
7887
if self.token is None:
7988
print("ERROR: You have no token, please call `get_token` using your login credentials and the server you wish to connect to.")
8089
sys.exit(1)
8190

8291
def request(self, method, endpoint, id, payload):
92+
"""Send requests from user-accessible functions via API."""
93+
8394
self.check_token()
8495

8596
if id is None:
@@ -98,13 +109,17 @@ def request(self, method, endpoint, id, payload):
98109
return self.error
99110

100111
def get(self, endpoint, id):
112+
"""METHOD: 'get' allows user to view endpoint data."""
101113
return self.request('GET', endpoint, id, payload=None)
102114

103115
def post(self, endpoint, id, payload):
116+
"""METHOD: 'post' allows user to overwrite/create new endpoint data."""
104117
return self.request('POST', endpoint, id, payload)
105118

106119
def patch(self, endpoint, id, payload):
120+
"""METHOD: 'patch' allows user to edit endpoint data (used for new logs)."""
107121
return self.request('PATCH', endpoint, id, payload)
108122

109123
def delete(self, endpoint, id):
124+
"""METHOD: 'delete' allows user to delete endpoint data (hidden)."""
110125
return self.request('DELETE', endpoint, id, payload=None)

api_functions.py

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
from api_connect import ApiConnect
2+
3+
class ApiFunctions():
4+
def __init__(self):
5+
self.connect = ApiConnect()
6+
7+
self.token = None
8+
self.error = None
9+
10+
def get_token(self, email, password, server='https://my.farm.bot'):
11+
# when get_token() is called, set self.token
12+
self.token = self.connect.get_token(email, password, server)
13+
14+
# when get_token() is called, set api.token
15+
self.connect.token = self.token
16+
# when get_token() is called, set broker.token
17+
self.broker.token = self.token
18+
19+
return self.token
20+
21+
def get_info(self, endpoint, id=None):
22+
return self.connect.get(endpoint, id)
23+
# return self.connect.get(endpoint, id)...
24+
25+
def set_info(self, endpoint, field, value, id=None):
26+
new_value = {
27+
field: value
28+
}
29+
30+
self.connect.patch(endpoint, id, new_value)
31+
return self.connect.get(endpoint, id)
32+
# return self.connect.get(endpoint, id)...
33+
34+
def env(self, id=None, field=None, new_val=None):
35+
if id is None:
36+
data = self.connect.get('farmware_envs', id=None)
37+
print(data)
38+
else:
39+
data = self.connect.get('farmware_envs', id)
40+
print(data)
41+
42+
def log(self, message, type=None, channel=None):
43+
log_message = {
44+
"message": message,
45+
"type": type,
46+
"channel": channel # Specifying channel does not do anything
47+
}
48+
49+
endpoint = 'logs'
50+
id = None
51+
52+
self.connect.post(endpoint, id, log_message)
53+
# return ...
54+
55+
def safe_z(self):
56+
json_data = self.get_info('fbos_config')
57+
return json_data['safe_height']
58+
# return json_data['safe_height']...
59+
60+
def garden_size(self):
61+
json_data = self.get_info('firmware_config')
62+
63+
# Get x axis length in steps
64+
x_steps = json_data['movement_axis_nr_steps_x']
65+
66+
# Get number of steps per millimeter on the x axis
67+
x_mm = json_data['movement_step_per_mm_x']
68+
69+
# Get y axis length in steps
70+
y_steps = json_data['movement_axis_nr_steps_y']
71+
72+
# Get number of steps per millimeter on the y axis
73+
y_mm = json_data['movement_step_per_mm_y']
74+
75+
length_x = x_steps / x_mm
76+
length_y = y_steps / y_mm
77+
area = length_x * length_y
78+
79+
size_value = {'x': length_x, 'y': length_y, 'area': area}
80+
return size_value
81+
82+
def group(self, id):
83+
return self.get_info('point_groups', id)
84+
# return self.get_info('point_groups', id)...
85+
86+
def curve(self, id):
87+
return self.get_info('curves', id)
88+
# return self.get_info('curves', id)...

broker.py broker_connect.py

+16-4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1+
import json
2+
13
from datetime import datetime
24
import paho.mqtt.client as mqtt
35

4-
import json
5-
6-
class BrokerFunctions():
6+
class BrokerConnect():
77
def __init__(self):
88
self.token = None
99
self.client = None
@@ -29,6 +29,18 @@ def __init__(self):
2929
# client.subscribe("bot/device_4652/status")
3030
# print('connected via status_connect()')
3131

32+
def sub_all(self, client, *_args):
33+
"""Subscribe to all message broker channels."""
34+
35+
self.client.subscribe(f"bot/{self.token['token']['unencoded']['bot']}/#")
36+
print("Connected to all channels.")
37+
38+
def sub_single(self, client, *_args, channel):
39+
"""Subscribe to specific message broker channel."""
40+
41+
self.client.subscribe("bot/{device_id}/{channel}")
42+
print("Connected to "+channel+".")
43+
3244
def on_message(self, _client, _userdata, msg):
3345
print('-' * 100)
3446
# print channel
@@ -63,7 +75,7 @@ def disconnect(self):
6375

6476
def publish(self, message):
6577
if self.client is None:
66-
self.connect(self.token)
78+
self.connect()
6779

6880
self.client.publish(
6981
f'bot/{self.token["token"]["unencoded"]["bot"]}/from_clients',

0 commit comments

Comments
 (0)