Skip to content

Commit eb0ef7c

Browse files
fix formatting
1 parent a3226b6 commit eb0ef7c

File tree

14 files changed

+404
-171
lines changed

14 files changed

+404
-171
lines changed

farmbot_sidecar_starter_pack/functions/api.py

+29-11
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
class HTMLResponseParser(HTMLParser):
1717
"""Response parser for HTML content."""
18+
1819
def __init__(self):
1920
super().__init__()
2021
self.is_header = False
@@ -42,6 +43,7 @@ def handle_data(self, data):
4243

4344
class ApiConnect():
4445
"""Connect class for FarmBot API."""
46+
4547
def __init__(self, state):
4648
self.state = state
4749

@@ -52,19 +54,25 @@ def get_token(self, email, password, server="https://my.farm.bot"):
5254
headers = {'content-type': 'application/json'}
5355
user = {'user': {'email': email, 'password': password}}
5456
timeout = self.state.timeout["api"]
55-
response = requests.post(f'{server}/api/tokens', headers=headers, json=user, timeout=timeout)
57+
response = requests.post(
58+
url=f'{server}/api/tokens',
59+
headers=headers,
60+
json=user,
61+
timeout=timeout)
5662
# Handle HTTP status codes
5763
if response.status_code == 200:
5864
self.state.token = response.json()
5965
self.state.error = None
60-
self.state.print_status(description=f"Successfully fetched token from {server}.")
66+
description = f"Successfully fetched token from {server}."
67+
self.state.print_status(description=description)
6168
return response.json()
6269
elif response.status_code == 404:
6370
self.state.error = "HTTP ERROR: The server address does not exist."
6471
elif response.status_code == 422:
6572
self.state.error = "HTTP ERROR: Incorrect email address or password."
6673
else:
67-
self.state.error = f"HTTP ERROR: Unexpected status code {response.status_code}"
74+
code = response.status_code
75+
self.state.error = f"HTTP ERROR: Unexpected status code {code}"
6876
# Handle DNS resolution errors
6977
except requests.exceptions.RequestException as e:
7078
if isinstance(e, requests.exceptions.ConnectionError):
@@ -74,7 +82,7 @@ def get_token(self, email, password, server="https://my.farm.bot"):
7482
elif isinstance(e, requests.exceptions.RequestException):
7583
self.state.error = "DNS ERROR: There was a problem with the request."
7684
except Exception as e:
77-
self.state.error = f"DNS ERROR: An unexpected error occurred: {str(e)}"
85+
self.state.error = f"DNS ERROR: An unexpected error occurred: {e}"
7886

7987
self.state.token = None
8088
self.state.print_status(description=self.state.error)
@@ -109,16 +117,18 @@ def request_handling(self, response, make_request):
109117
self.state.print_status(description=description)
110118
return 200
111119
if 400 <= response.status_code < 500:
112-
self.state.error = f"CLIENT ERROR {response.status_code}: {error_messages.get(response.status_code, response.reason)}"
120+
err = error_messages.get(response.status_code, response.reason)
121+
self.state.error = f"CLIENT ERROR {response.status_code}: {err}"
113122
elif 500 <= response.status_code < 600:
114123
self.state.error = f"SERVER ERROR {response.status_code}: {text}"
115124
else:
116-
self.state.error = f"UNEXPECTED ERROR {response.status_code}: {text}"
125+
code = response.status_code
126+
self.state.error = f"UNEXPECTED ERROR {code}: {text}"
117127

118128
try:
119129
response.json()
120130
except requests.exceptions.JSONDecodeError:
121-
self.state.error += f" ({text})"
131+
self.state.error += f" ({text})"
122132
else:
123133
self.state.error += f" ({json.dumps(response.json(), indent=2)})"
124134

@@ -142,19 +152,27 @@ def request(self, method, endpoint, database_id, payload=None):
142152
http_part = "https" if self.state.ssl else "http"
143153
url = f'{http_part}:{iss}/api/{endpoint}{id_part}'
144154

145-
headers = {'authorization': token['encoded'], 'content-type': 'application/json'}
155+
headers = {'authorization': token['encoded'],
156+
'content-type': 'application/json'}
146157
make_request = not self.state.dry_run or method == "GET"
147158
if make_request:
148159
timeout = self.state.timeout["api"]
149-
response = requests.request(method, url, headers=headers, json=payload, timeout=timeout)
160+
response = requests.request(
161+
method=method,
162+
url=url,
163+
headers=headers,
164+
json=payload,
165+
timeout=timeout)
150166
else:
151167
response = requests.Response()
152168
response.status_code = 200
153169
response._content = b'{"edit_requests_disabled": true}'
154170

155171
if self.request_handling(response, make_request) == 200:
156172
self.state.error = None
157-
self.state.print_status(description="Successfully returned request contents.")
173+
description = "Successfully fetched request contents."
174+
self.state.print_status(description=description)
158175
return response.json()
159-
self.state.print_status(description="There was an error processing the request...")
176+
description = "There was an error processing the request..."
177+
self.state.print_status(description=description)
160178
return self.state.error

farmbot_sidecar_starter_pack/functions/basic_commands.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,19 @@
1111

1212
from .broker import BrokerConnect
1313

14+
1415
class BasicCommands():
1516
"""Basic commands class."""
17+
1618
def __init__(self, state):
1719
self.broker = BrokerConnect(state)
1820
self.state = state
1921

2022
def wait(self, duration):
2123
"""Pauses execution for a certain number of milliseconds."""
2224

23-
self.state.print_status(description=f"Waiting for {duration} milliseconds...")
25+
description = f"Waiting for {duration} milliseconds..."
26+
self.state.print_status(description=description)
2427

2528
wait_message = {
2629
"kind": "wait",
@@ -54,7 +57,9 @@ def unlock(self):
5457
"args": {}
5558
}
5659

57-
unlock_message = self.broker.wrap_message(unlock_message, priority=9000)
60+
unlock_message = self.broker.wrap_message(
61+
unlock_message,
62+
priority=9000)
5863
self.broker.publish(unlock_message)
5964

6065
def reboot(self):

farmbot_sidecar_starter_pack/functions/broker.py

+45-17
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,10 @@
1717
from datetime import datetime
1818
import paho.mqtt.client as mqtt
1919

20+
2021
class BrokerConnect():
2122
"""Broker connection class."""
23+
2224
def __init__(self, state):
2325
self.state = state
2426
self.client = None
@@ -50,7 +52,8 @@ def disconnect(self):
5052
if self.client is not None:
5153
self.client.loop_stop()
5254
self.client.disconnect()
53-
self.state.print_status(description="Disconnected from message broker.")
55+
description = "Disconnected from message broker."
56+
self.state.print_status(description=description)
5457

5558
def wrap_message(self, message, priority=None):
5659
"""Wrap message in CeleryScript format."""
@@ -78,22 +81,31 @@ def publish(self, message):
7881
rpc = self.wrap_message(rpc)
7982

8083
if rpc["args"]["label"] == "":
81-
rpc["args"]["label"] = uuid.uuid4().hex if not self.state.test_env else "test"
84+
if self.state.test_env:
85+
rpc["args"]["label"] = "test"
86+
else:
87+
rpc["args"]["label"] = uuid.uuid4().hex
8288

8389
self.state.print_status(description="Publishing to 'from_clients'")
8490
self.state.print_status(endpoint_json=rpc, update_only=True)
8591
if self.state.dry_run:
86-
self.state.print_status(description="Sending disabled, message not sent.", update_only=True)
92+
self.state.print_status(
93+
description="Sending disabled, message not sent.",
94+
update_only=True)
8795
else:
8896
self.listen("from_device", publish_payload=rpc)
8997

9098
response = self.state.last_messages.get("from_device", [])
9199
if len(response) > 0:
92100
if response[-1]["kind"] == "rpc_ok":
93-
self.state.print_status(description="Success response received.", update_only=True)
101+
self.state.print_status(
102+
description="Success response received.",
103+
update_only=True)
94104
self.state.error = None
95105
else:
96-
self.state.print_status(description="Error response received.", update_only=True)
106+
self.state.print_status(
107+
description="Error response received.",
108+
update_only=True)
97109
self.state.error = "RPC error response received."
98110

99111
self.state.last_published = rpc
@@ -131,8 +143,8 @@ def on_message(_client, _userdata, msg):
131143

132144
if diff_only:
133145
diff = payload
134-
prev_channel_key = path_channel if len(path) > 0 else channel_key
135-
last_messages = self.state.last_messages.get(prev_channel_key, [])
146+
key = path_channel if len(path) > 0 else channel_key
147+
last_messages = self.state.last_messages.get(key, [])
136148
if len(last_messages) > 1:
137149
current = last_messages[-1]
138150
previous = last_messages[-2]
@@ -175,9 +187,15 @@ def stop_listen(self):
175187

176188
self.client.loop_stop()
177189

178-
self.state.print_status(description="Stopped listening to all message broker channels.")
190+
self.state.print_status(
191+
description="Stopped listening to all message broker channels.")
179192

180-
def listen(self, channel="#", duration=None, publish_payload=None, stop_count=1, message_options=None):
193+
def listen(self,
194+
channel="#",
195+
duration=None,
196+
publish_payload=None,
197+
stop_count=1,
198+
message_options=None):
181199
"""Listen to a message broker channel for the provided duration in seconds."""
182200
publish = publish_payload is not None
183201
message = (publish_payload or {}).get("body", [{}])[0]
@@ -220,14 +238,16 @@ def listen(self, channel="#", duration=None, publish_payload=None, stop_count=1,
220238
self.start_listen(channel, message_options)
221239
if not self.state.test_env:
222240
if channel == "#":
223-
self.state.last_messages = {"#" : []}
241+
self.state.last_messages = {"#": []}
224242
else:
225243
self.state.last_messages[channel] = []
226244
if publish:
227-
time.sleep(0.1) # wait for start_listen to be ready
245+
time.sleep(0.1) # wait for start_listen to be ready
228246
device_id_str = self.state.token["token"]["unencoded"]["bot"]
229-
publish_topic = f"bot/{device_id_str}/from_clients"
230-
self.client.publish(publish_topic, payload=json.dumps(publish_payload))
247+
publish_topic = f"bot/{device_id_str}/from_clients"
248+
self.client.publish(
249+
publish_topic,
250+
payload=json.dumps(publish_payload))
231251
self.state.print_status(update_only=True, description="", end="")
232252
while (datetime.now() - start_time).seconds < duration_seconds:
233253
self.state.print_status(update_only=True, description=".", end="")
@@ -240,20 +260,26 @@ def listen(self, channel="#", duration=None, publish_payload=None, stop_count=1,
240260
continue
241261
if len(last_messages) > (stop_count - 1):
242262
seconds = (datetime.now() - start_time).seconds
243-
prefix = "Message" if stop_count == 1 else f"{stop_count} messages"
263+
prefix = f"{stop_count} messages"
264+
if stop_count == 1:
265+
prefix = "Message"
266+
description = f"{prefix} received after {seconds} seconds"
244267
self.state.print_status(
245-
description=f"{prefix} received after {seconds} seconds",
268+
description=description,
246269
update_only=True)
247270
break
248271
if len(self.state.last_messages.get(channel, [])) == 0:
249272
self.state.print_status(description="", update_only=True)
273+
secs = duration_seconds
274+
description = f"Did not receive message after {secs} seconds"
250275
self.state.print_status(
251-
description=f"Did not receive message after {duration_seconds} seconds",
276+
description=description,
252277
update_only=True)
253278
self.state.error = "Timed out waiting for RPC response."
254279

255280
self.stop_listen()
256281

282+
257283
def difference(next_state, prev_state):
258284
"""Find the difference between two states."""
259285
is_different = False
@@ -267,7 +293,9 @@ def difference(next_state, prev_state):
267293
prev_value = prev_state[key]
268294
if next_value != prev_value:
269295
if isinstance(next_value, dict) and isinstance(prev_value, dict):
270-
nested_diff, nested_is_different = difference(next_value, prev_value)
296+
nested_diff, nested_is_different = difference(
297+
next_value,
298+
prev_value)
271299
if nested_is_different:
272300
diff[key] = nested_diff
273301
is_different = True

farmbot_sidecar_starter_pack/functions/camera.py

+2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@
99

1010
from .broker import BrokerConnect
1111

12+
1213
class Camera():
1314
"""Camera class."""
15+
1416
def __init__(self, state):
1517
self.broker = BrokerConnect(state)
1618
self.state = state

0 commit comments

Comments
 (0)