Skip to content

Commit 298901d

Browse files
committed
Changed some stuff around--connect() not working
1 parent ad624da commit 298901d

File tree

5 files changed

+82
-146
lines changed

5 files changed

+82
-146
lines changed

api_connect.py

+2-28
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,11 @@
22
import json
33
import requests
44

5-
# api_functions.py -> api_connect.py
6-
75
class ApiConnect():
86
def __init__(self):
97
self.token = None
108
self.error = None
119

12-
# token_handling() --> errors for token
13-
# request_handling() --> errors for request
14-
15-
# get_token()
16-
# check_token()
17-
18-
# request()
19-
# get() --> get endpoint info
20-
# post() --> overwrite/new endpoint info
21-
# patch() --> edit endpoint info
22-
# delete() --> delete endpoint info
23-
2410
def token_handling(self, response):
2511
"""Handle errors relating to bad user auth token requests."""
2612

@@ -76,12 +62,9 @@ def get_token(self, email, password, server):
7662
response = requests.post(f'{server}/api/tokens', headers=headers, json=user)
7763

7864
if self.token_handling(response) == 200:
79-
token_obj = response.json()
80-
token_str = json.dumps(token_obj)
81-
# token_dict = json.loads(token_str)
82-
self.token = token_str
65+
token_data = response.json()
8366
self.error = None
84-
return token_str
67+
return token_data
8568
else:
8669
return self.error
8770

@@ -92,15 +75,6 @@ def check_token(self):
9275
print("ERROR: You have no token, please call `get_token` using your login credentials and the server you wish to connect to.")
9376
sys.exit(1)
9477

95-
# save response as JSON object: json_obj = response.json()
96-
# json.dumps(json_obj)
97-
98-
# save response as a string: json_str = response.text
99-
100-
# access JSON object fields: json_obj = response.json()
101-
# data = json.dumps(json_obj)
102-
# name = data["name"]
103-
10478
def request(self, method, endpoint, id, payload):
10579
"""Send requests from user-accessible functions via API."""
10680

api_functions.py

+14-22
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,49 @@
11
from api_connect import ApiConnect
22

3-
# main.py -> api_functions.py -> api_connect.py
4-
53
class ApiFunctions():
64
def __init__(self):
7-
self.connect = ApiConnect()
8-
5+
self.api_connect = ApiConnect()
96
self.token = None
10-
self.error = None
117

128
def get_token(self, email, password, server='https://my.farm.bot'):
13-
# when get_token() is called, set self.token
14-
self.token = self.connect.get_token(email, password, server)
15-
16-
# when get_token() is called, set api.token
17-
self.connect.token = self.token
18-
# when get_token() is called, set broker.token
19-
self.broker.token = self.token
9+
token_str = self.api_connect.get_token(email, password, server)
10+
return token_str
2011

21-
return self.token
12+
# data = get_info() and like functions will assign 'data' JSON object
13+
# data["name"] will access the field "name" and return the field value
2214

2315
def get_info(self, endpoint, id=None):
24-
return self.connect.get(endpoint, id)
25-
# return self.connect.get(endpoint, id)...
16+
return self.api_connect.get(endpoint, id)
17+
# return self.api_connect.get(endpoint, id)...
2618

2719
def set_info(self, endpoint, field, value, id=None):
2820
new_value = {
2921
field: value
3022
}
3123

32-
self.connect.patch(endpoint, id, new_value)
33-
return self.connect.get(endpoint, id)
34-
# return self.connect.get(endpoint, id)...
24+
self.api_connect.patch(endpoint, id, new_value)
25+
return self.api_connect.get(endpoint, id)
26+
# return self.api_connect.get(endpoint, id)...
3527

3628
def env(self, id=None, field=None, new_val=None):
3729
if id is None:
38-
data = self.connect.get('farmware_envs', id=None)
30+
data = self.api_connect.get('farmware_envs', id=None)
3931
print(data)
4032
else:
41-
data = self.connect.get('farmware_envs', id)
33+
data = self.api_connect.get('farmware_envs', id)
4234
print(data)
4335

4436
def log(self, message, type=None, channel=None):
4537
log_message = {
4638
"message": message,
47-
"type": type,
39+
"type": type, # https://software.farm.bot/v15/app/intro/jobs-and-logs#log-types
4840
"channel": channel # Specifying channel does not do anything
4941
}
5042

5143
endpoint = 'logs'
5244
id = None
5345

54-
self.connect.post(endpoint, id, log_message)
46+
self.api_connect.post(endpoint, id, log_message)
5547
# return ...
5648

5749
def safe_z(self):

broker_connect.py

+3-47
Original file line numberDiff line numberDiff line change
@@ -3,56 +3,13 @@
33
from datetime import datetime
44
import paho.mqtt.client as mqtt
55

6-
# broker_functions.py -> broker_connect.py
7-
86
class BrokerConnect():
97
def __init__(self):
108
self.token = None
119
self.client = None
1210

13-
# connect() --> establish connection to message broker
14-
# disconnect() --> disconnect from message broker
15-
16-
# publish()
17-
18-
# on_connect() --> subscribe to channel
19-
# on_message() --> print channel/message
20-
21-
# def on_connect(self, client, *_args):
22-
# # subscribe to all channels
23-
# self.client.subscribe(f"bot/{self.token['token']['unencoded']['bot']}/#")
24-
# print('connected')
25-
26-
# def status_connect(self, client, *_args):
27-
# # Subscribe to specific channel
28-
# device_info = self.api.get('device')
29-
# device_id = device_info['id']
30-
31-
# client.subscribe("bot/device_4652/status")
32-
# print('connected via status_connect()')
33-
34-
def sub_all(self, client, *_args):
35-
"""Subscribe to all message broker channels."""
36-
37-
self.client.subscribe(f"bot/{self.token['token']['unencoded']['bot']}/#")
38-
print("Connected to all channels.")
39-
40-
def sub_single(self, client, *_args, channel):
41-
"""Subscribe to specific message broker channel."""
42-
43-
self.client.subscribe("bot/{device_id}/{channel}")
44-
print("Connected to "+channel+".")
45-
46-
def on_message(self, _client, _userdata, msg):
47-
print('-' * 100)
48-
# print channel
49-
print("Channel:")
50-
print(f'{msg.topic} ({datetime.now().strftime("%Y-%m-%d %H:%M:%S")})\n')
51-
# print message
52-
print("Message:")
53-
print(json.dumps(json.loads(msg.payload), indent=4))
54-
5511
def connect(self):
12+
"""Establish persistent connection with message broker."""
5613
self.client = mqtt.Client()
5714
self.client.username_pw_set(
5815
username=self.token['token']['unencoded']['bot'],
@@ -65,17 +22,16 @@ def connect(self):
6522
keepalive=60
6623
)
6724

68-
# self.client.on_connect = status_connect
69-
# self.client.on_message = on_message
70-
7125
self.client.loop_start()
7226

7327
def disconnect(self):
28+
"""Disconnect from the message broker."""
7429
if self.client is not None:
7530
self.client.loop_stop()
7631
self.client.disconnect()
7732

7833
def publish(self, message):
34+
"""Send Celery Script messages via message broker."""
7935
if self.client is None:
8036
self.connect()
8137

0 commit comments

Comments
 (0)