Skip to content

Commit

Permalink
Added IS_DEBUG env, added try catch for listening
Browse files Browse the repository at this point in the history
  • Loading branch information
niemijoe committed Aug 9, 2022
1 parent e7c0b28 commit 513dd94
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
IS_DEBUG=True
TENANT_ID=<secret>
CLIENT_ID=<secret>
CLIENT_SECRET=<secret>
Expand Down
27 changes: 23 additions & 4 deletions mqtt_data_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@

load_dotenv()

IS_DEBUG = os.getenv('IS_DEBUG')

# How long to listen to the topics until we send data to Azure. Should be 60 in production
MONITOR_PERIOD_IN_SECONDS = 60
MONITOR_PERIOD_IN_SECONDS = 60 if IS_DEBUG == False else 3

def main():
"""
Expand Down Expand Up @@ -51,8 +53,11 @@ def listen_topic_thread(topic_data_string):
for i in range(len(threads)):
threads[i].join()

send_mqtt_msg_count_into_azure(topic_data_collection)
print(f'Mqtt metrics sent: {datetime.now().strftime("%Y-%m-%dT%H:%M:%S")}')
if IS_DEBUG == False:
send_mqtt_msg_count_into_azure(topic_data_collection)
print(f'Mqtt metrics sent: {datetime.now().strftime("%Y-%m-%dT%H:%M:%S")}')
else:
print(topic_data_collection)

def listen_topic(topic_data_collection, address, topic, port):
"""
Expand All @@ -63,8 +68,14 @@ def listen_topic(topic_data_collection, address, topic, port):
client = mqtt.Client()
client.on_connect = on_connect_callback(topic)
client.on_message = on_message_callback(topic_data_collection, topic)
# Enable debugging if needed
# client.on_log = on_log_callback
# client.on_disconnect = on_disconnect_callback

client.connect(address, int(port), MONITOR_PERIOD_IN_SECONDS)
try:
client.connect(address, int(port), MONITOR_PERIOD_IN_SECONDS)
except:
print(f'Error: could not connect to {address} {topic} {port}')

# Call that processes network traffic, dispatches callbacks and
# handles reconnecting.
Expand Down Expand Up @@ -93,6 +104,14 @@ def on_message(client, userdata, msg):

return on_message

# Enable debugging if needed
# def on_log_callback(client, userdata, level, buf):
# print(buf)

# Enable debugging if needed
# def on_disconnect_callback(client, userdata, rc):
# print("Disconnected")

def send_mqtt_msg_count_into_azure(topic_data_collection):
"""
Send custom metrics into azure. Documentation for the required format can be found from here:
Expand Down

0 comments on commit 513dd94

Please sign in to comment.