Skip to content

Commit

Permalink
Refactoring Connection.py to be according to PEP.
Browse files Browse the repository at this point in the history
  • Loading branch information
tomekmalek committed Apr 4, 2022
1 parent 3453547 commit 03445fa
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 108 deletions.
4 changes: 2 additions & 2 deletions 1_send_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

while True:
if (time.time()) >= last + MESSAGE_RATE:
lo.addToPayload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.sendData() # Sending data to cloud
lo.add_to_payload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.send_data() # Sending data to cloud
last = time.time()
lo.loop() # Check for incoming messages and if connection is still active
8 changes: 4 additions & 4 deletions 2_simple_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@

# Main program
# Available types: INT, BINARY, STRING, FLOAT
lo.addParameter("messageRate", 5, LiveObjects.INT) # Add parameter: Name - Value - Type
lo.add_parameter("message_rate", 5, LiveObjects.INT) # Add parameter: Name - Value - Type

lo.connect() # Connect to LiveObjects
last = uptime = time.time()

while True:
if time.time() >= last + lo.getParameter("messageRate"): # Get the parameter using its name
lo.addToPayload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.sendData() # Sending data to cloud
if time.time() >= last + lo.get_parameter("message_rate"): # Get the parameter using its name
lo.add_to_payload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.send_data() # Sending data to cloud
last = time.time()
lo.loop() # Check for incoming messages and if connection is still active
12 changes: 6 additions & 6 deletions 3_parameter_with_callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@


# Callback for a parameter change
def callback(parameterName, newValue):
print("Changed value of the parameter " + parameterName + " to " + str(newValue))
def callback(parameter_name, new_value):
print("Changed value of the parameter " + parameter_name + " to " + str(new_value))


# Main program
# Available types: INT, BINARY, STRING, FLOAT
lo.addParameter("messageRate", 5, LiveObjects.INT, callback) # Add parameter: Name - Value - Type - Callback
lo.add_parameter("message_rate", 5, LiveObjects.INT, callback) # Add parameter: Name - Value - Type - Callback
lo.connect() # Connect to LiveObjects
last = uptime = time.time()

while True:
if time.time() >= last + lo.getParameter("messageRate"): # Get the parameter using its name
lo.addToPayload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.sendData() # Sending data to cloud
if time.time() >= last + lo.get_parameter("message_rate"): # Get the parameter using its name
lo.add_to_payload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.send_data() # Sending data to cloud
last = time.time()
lo.loop() # Check for incoming messages and if connection is still active
8 changes: 4 additions & 4 deletions 4_simple_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@

# Define command function
def foo(arg={}):
lo.outputDebug(LiveObjects.INFO, "Called function foo")
lo.output_debug(LiveObjects.INFO, "Called function foo")
return {}


# Main program
lo.addCommand("foo", foo) # Add command to LiveObjects: name - function
lo.add_command("foo", foo) # Add command to LiveObjects: name - function
lo.connect() # Connect to LiveObjects
last = uptime = time.time()

while True:
if time.time() >= last + MESSAGE_RATE:
lo.addToPayload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.sendData() # Sending data to cloud
lo.add_to_payload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.send_data() # Sending data to cloud
last = time.time()
lo.loop() # Check for incoming messages and if connection is still active
10 changes: 5 additions & 5 deletions 5_command_with_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,22 @@

# Define command function with arguments handling
def foo(args={}):
lo.outputDebug(LiveObjects.INFO, "Called function foo with args", json.dumps(args))
lo.output_debug(LiveObjects.INFO, "Called function foo with args", json.dumps(args))
counter = 0
for i in range(args["repetitions"]):
print("Repetition nr " + str(i))
counter += 1
return {"Repeated": str(counter) + " times"}
return {"Repeated": str(counter) + " times."}


# Main program
lo.addCommand("foo", foo) # Add command to LiveObjects: name - function
lo.add_command("foo", foo) # Add command to LiveObjects: name - function
lo.connect() # Connect to LiveObjects
last = uptime = time.time()

while True:
if time.time() >= last + MESSAGE_RATE:
lo.addToPayload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.sendData() # Sending data to cloud
lo.add_to_payload("uptime", int(time.time() - uptime)) # Add value to payload: name - value
lo.send_data() # Sending data to cloud
last = time.time()
lo.loop() # Check for incoming messages and if connection is still active
123 changes: 60 additions & 63 deletions LiveObjects/Connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,114 +62,111 @@ def __init__(self, debug=True):
elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON:
self.ssl = self.__port == SSL
self.__mqtt = MQTTClient(self.__device_id, self.__server, self.__port, "json+device",
self.__apiKey, 0, self.ssl, {'server_hostname': self.__server})
self.__apiKey, 0, self.ssl, {'server_hostname': self.__server})

def loop(self):
if self.mode == LiveObjects.BoardsInterface.MICROPYTHON:
self.__mqtt.check_msg()

def __onMessage(self, client="", userdata="", msg=""):
def __on_message(self, client="", userdata="", msg=""):
if self.mode == LiveObjects.BoardsInterface.PYTHON:
if msg.topic == "dev/cfg/upd":
self.__parameterManager(msg)
self.__parameter_manager(msg)
elif msg.topic == "dev/cmd":
self.__commandManager(msg)
self.__command_manager(msg)
elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON:
if client == b"dev/cfg/upd":
self.__parameterManager(userdata)
self.__parameter_manager(userdata)
elif client == b"dev/cmd":
self.__commandManager(userdata)
self.__command_manager(userdata)

def __onConnect(self, client="", userdata="", flags="", rc=""):
def __on_connect(self, client="", userdata="", flags="", rc=""):
if self.mode == LiveObjects.BoardsInterface.PYTHON:
if rc == 0:
self.outputDebug(INFO, "Connected!")
self.output_debug(INFO, "Connected!")
if len(self.__commands) > 0:
self.outputDebug(INFO, "Subscribing commands")
self.output_debug(INFO, "Subscribing commands")
self.__mqtt.subscribe("dev/cmd")
if len(self.__parameters) > 0:
self.outputDebug(INFO, "Subscribing parameters")
self.output_debug(INFO, "Subscribing parameters")
self.__mqtt.subscribe("dev/cfg/upd")
self.__sendConfig()
self.__send_config()
else:
self.outputDebug(ERROR, "Check your api key")
self.quit=True
self.output_debug(ERROR, "Check your api key")
self.quit = True
sys.exit()
#else:
#self.outputDebug(ERROR,"Unknown error while connecting,quitting...")
#sys.exit()
elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON:
self.outputDebug(INFO, "Connected, sending config")
self.output_debug(INFO, "Connected, sending config")
if len(self.__commands) > 0:
self.outputDebug(INFO, "Subscribing commands")
self.output_debug(INFO, "Subscribing commands")
self.__mqtt.subscribe(b"dev/cmd")
if len(self.__parameters) > 0:
self.outputDebug(INFO, "Subscribing parameters")
self.output_debug(INFO, "Subscribing parameters")
self.__mqtt.subscribe(b"dev/cfg/upd")
self.__sendConfig()
self.__send_config()

def connect(self):
self.__board.connect()
if self.mode == LiveObjects.BoardsInterface.PYTHON:
self.__mqtt.username_pw_set("json+device", self.__apiKey)
self.__mqtt.on_connect = self.__onConnect
self.__mqtt.on_message = self.__onMessage
self.__mqtt.on_connect = self.__on_connect
self.__mqtt.on_message = self.__on_message
if self.__port == SSL:
self.__mqtt.tls_set(self.__board.get_store_cert_filename())
self.__mqtt.connect(self.__server, self.__port, 60)
self.__mqtt.loop_start()
elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON:
self.__mqtt.set_callback(self.__onMessage)
self.__mqtt.set_callback(self.__on_message)
self.__mqtt.connect()
time.sleep(1)
self.__onConnect()
self.__on_connect()

def disconnect(self):
self.__mqtt.disconnect()
self.outputDebug(INFO, "Disconnected")
self.output_debug(INFO, "Disconnected")

def outputDebug(self, info, *args):
def output_debug(self, info, *args):
if self.__doLog:
print("[", info, "]", end=" ", sep="")
for arg in args:
print(arg, end=" ")
print("")

def addCommand(self, name, cmd):
def add_command(self, name, cmd):
self.__commands[name] = cmd

def __commandManager(self, msg):
def __command_manager(self, msg):
if self.mode == LiveObjects.BoardsInterface.PYTHON:
msgDict = json.loads(msg.payload)
self.outputDebug(INFO, "Received message:\n", json.dumps(msgDict, sort_keys=True, indent=4))
msg_dict = json.loads(msg.payload)
self.output_debug(INFO, "Received message:\n", json.dumps(msg_dict, sort_keys=True, indent=4))
elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON:
msgDict = json.loads(msg)
self.outputDebug(INFO, "Received message:", json.dumps(msgDict))
outputMsg = {}
outputMsg["cid"] = msgDict["cid"]
response = self.__commands.get(msgDict["req"], self.__default)(msgDict["arg"])
msg_dict = json.loads(msg)
self.output_debug(INFO, "Received message:", json.dumps(msg_dict))
output_msg = {}
output_msg["cid"] = msg_dict["cid"]
response = self.__commands.get(msg_dict["req"], self.__default)(msg_dict["arg"])
if len(response) > 0:
outputMsg["res"] = response
self.__publishMessage("dev/cmd/res", outputMsg)
output_msg["res"] = response
self.__publish_message("dev/cmd/res", output_msg)

def __default(self, req=""):
self.outputDebug(INFO, "Command not found!")
self.output_debug(INFO, "Command not found!")
return {"info": "Command not found"}

def __sendConfig(self):
outMsg = {"cfg": {}}
def __send_config(self):
out_msg = {"cfg": {}}
for param in self.__parameters:
outMsg["cfg"][param] = {"t": self.__parameters[param].type, "v": self.__parameters[param].value}
self.__publishMessage("dev/cfg", outMsg)
out_msg["cfg"][param] = {"t": self.__parameters[param].type, "v": self.__parameters[param].value}
self.__publish_message("dev/cfg", out_msg)

def __parameterManager(self, msg):
def __parameter_manager(self, msg):
if self.mode == LiveObjects.BoardsInterface.PYTHON:
self.outputDebug(INFO, "Received message: ")
self.outputDebug(INFO, json.loads(msg.payload))
self.output_debug(INFO, "Received message: ")
self.output_debug(INFO, json.loads(msg.payload))
params = json.loads(msg.payload)
elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON:
self.outputDebug(INFO, "Received message: ")
self.outputDebug(INFO, json.loads(msg))
self.output_debug(INFO, "Received message: ")
self.output_debug(INFO, json.loads(msg))
params = json.loads(msg)

for param in params["cfg"]:
Expand All @@ -187,9 +184,9 @@ def __parameterManager(self, msg):
self.__parameters[param].value = params["cfg"][param]["v"]
if self.__parameters[param].callback is not None:
self.__parameters[param].callback(param, params["cfg"][param]["v"])
self.__publishMessage("dev/cfg", params)
self.__publish_message("dev/cfg", params)

def addParameter(self, name, val, type_, cb=None):
def add_parameter(self, name, val, type_, cb=None):
if type_ == INT:
val = int(val)
elif type_ == STRING:
Expand All @@ -202,7 +199,7 @@ def addParameter(self, name, val, type_, cb=None):
val = float(val)
self.__parameters[name] = LiveObjectsParameter(val, type_, cb)

def getParameter(self, name):
def get_parameter(self, name):
if self.__parameters[name].type == INT:
return int(self.__parameters[name].value)
elif self.__parameters[name].type == STRING:
Expand All @@ -215,39 +212,39 @@ def getParameter(self, name):
return float(self.__parameters[name].value)
return 0

def addToPayload(self, name, val):
def add_to_payload(self, name, val):
self.__payload[self.__value][name] = val

def setObjectAsPayload(self, val):
def set_object_as_payload(self, val):
self.__payload[self.__value] = val

def addModel(self, model):
def add_model(self, model):
self.__payload["model"] = model

def addTag(self, tag):
if not "tags" in self.__payload:
def add_tag(self, tag):
if "tags" not in self.__payload:
self.__payload["tags"] = []
self.__payload["tags"].append(tag)

def addTags(self, tags):
if not "tags" in self.__payload:
def add_tags(self, tags):
if "tags" not in self.__payload:
self.__payload["tags"] = []
for tag in tags:
self.__payload["tags"].append(tag)

def sendData(self):
def send_data(self):
if self.quit:
sys.exit()
self.__publishMessage("dev/data", self.__payload)
self.__publish_message("dev/data", self.__payload)
self.__payload = {}
self.__payload[self.__value] = {}

def __publishMessage(self, topic, msg):
self.outputDebug(INFO, "Publishing message on topic: ", topic)
def __publish_message(self, topic, msg):
self.output_debug(INFO, "Publishing message on topic: ", topic)

if self.mode == LiveObjects.BoardsInterface.PYTHON:
self.outputDebug(INFO, "\n", json.dumps(msg, sort_keys=True, indent=4))
self.output_debug(INFO, "\n", json.dumps(msg, sort_keys=True, indent=4))
elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON:
self.outputDebug(INFO, json.dumps(msg))
self.output_debug(INFO, json.dumps(msg))

self.__mqtt.publish(topic, json.dumps(msg))
Loading

0 comments on commit 03445fa

Please sign in to comment.