diff --git a/1_send_data.py b/1_send_data.py index 2e05593..6ea86ca 100644 --- a/1_send_data.py +++ b/1_send_data.py @@ -4,24 +4,21 @@ # This software is distributed under the terms and conditions of the 'MIT' # license which can be found in the file 'LICENSE.md' in this package distribution -import os -import sys import time - import LiveObjects -#Create LiveObjects with parameters: ClientID - Security - APIKEY -lo = LiveObjects.Connection("PythonMQTT", LiveObjects.NONE, "") +# Create LiveObjects +lo = LiveObjects.Connection() + +MESSAGE_RATE = 5 -messageRate = 5 +# Main program +lo.connect() # Connect to LiveObjects +last = uptime = time.time() -#Main program -lo.connect() #Connect to LiveObjects -last = time.time() -uptime = time.time() while True: - if time.time()>=last+messageRate: - lo.addToPayload("uptime", int(time.time() - uptime) ) #Add value to payload: name - value - lo.sendData() #Sending data to cloud - lo.loop() #Check for incoming messages and if connection is still active - last = time.time() \ No newline at end of file + if (time.time()) >= last + MESSAGE_RATE: + 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 diff --git a/2_simple_parameters.py b/2_simple_parameters.py index 2cf9b7a..82dc716 100644 --- a/2_simple_parameters.py +++ b/2_simple_parameters.py @@ -4,24 +4,22 @@ # This software is distributed under the terms and conditions of the 'MIT' # license which can be found in the file 'LICENSE.md' in this package distribution -import os -import sys import time - import LiveObjects -#Create LiveObjects with parameters: ClientID - Security - APIKEY -lo = LiveObjects.Connection("PythonMQTT", LiveObjects.NONE, "") +# Create LiveObjects +lo = LiveObjects.Connection() + +# Main program +# Available types: INT, BINARY, STRING, FLOAT +lo.add_parameter("message_rate", 5, LiveObjects.INT) # Add parameter: Name - Value - Type + +lo.connect() # Connect to LiveObjects +last = uptime = time.time() -#Main program -lo.addParameter("messageRate", 5 , LiveObjects.INT) #Add parameter: Name - Value - Type -#Available types: INT BINARY STRING FLOAT -lo.connect() #Connect to LiveObjects -last = time.time() -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 - lo.loop() #Check for incoming messages and if connection is still active - last = time.time() \ No newline at end of file + 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 diff --git a/3_parameter_with_callback.py b/3_parameter_with_callback.py index a9858a1..09865f6 100644 --- a/3_parameter_with_callback.py +++ b/3_parameter_with_callback.py @@ -4,30 +4,28 @@ # This software is distributed under the terms and conditions of the 'MIT' # license which can be found in the file 'LICENSE.md' in this package distribution -import os -import sys import time - import LiveObjects -#Create LiveObjects with parameters: ClientID - Security - APIKEY -lo = LiveObjects.Connection("PythonMQTT", LiveObjects.NONE, "") +# Create LiveObjects +lo = LiveObjects.Connection() + + +# Callback for a parameter change +def callback(parameter_name, new_value): + print("Changed value of the parameter " + parameter_name + " to " + str(new_value)) -#Callback for a parameter change -def callback(parameterName, newValue): - print("Changed value of the parameter "+parameterName+" to " + str(newValue)) +# Main program +# Available types: INT, BINARY, STRING, FLOAT +lo.add_parameter("message_rate", 5, LiveObjects.INT, callback) # Add parameter: Name - Value - Type - Callback +lo.connect() # Connect to LiveObjects +last = uptime = time.time() -#Main program -lo.addParameter("messageRate", 5 , LiveObjects.INT, callback) #Add parameter: Name - Value - Type - Callback -#Available types: INT BINARY STRING FLOAT -lo.connect() #Connect to LiveObjects -last = time.time() -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 - lo.loop() #Check for incoming messages and if connection is still active - last = time.time() \ No newline at end of file + 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 diff --git a/4_simple_command.py b/4_simple_command.py index 65f649f..4003bb2 100644 --- a/4_simple_command.py +++ b/4_simple_command.py @@ -4,30 +4,29 @@ # This software is distributed under the terms and conditions of the 'MIT' # license which can be found in the file 'LICENSE.md' in this package distribution -import os -import sys import time - import LiveObjects -#Create LiveObjects with parameters: ClientID - Security - APIKEY -lo = LiveObjects.Connection("PythonMQTT", LiveObjects.NONE, "") +# Create LiveObjects +lo = LiveObjects.Connection() + +MESSAGE_RATE = 5 -messageRate = 5 -#Define command function +# 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.connect() #Connect to LiveObjects -last = time.time() -uptime = time.time() + +# Main program +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+messageRate: - lo.addToPayload("uptime", int(time.time() - uptime) ) #Add value to payload: name - value - lo.sendData() #Sending data to cloud - lo.loop() #Check for incoming messages and if connection is still active - last = time.time() \ No newline at end of file + if time.time() >= last + MESSAGE_RATE: + 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 diff --git a/5_command_with_arguments.py b/5_command_with_arguments.py index 12bc0b9..2b88d4c 100644 --- a/5_command_with_arguments.py +++ b/5_command_with_arguments.py @@ -4,34 +4,34 @@ # This software is distributed under the terms and conditions of the 'MIT' # license which can be found in the file 'LICENSE.md' in this package distribution -import os -import sys import time import json import LiveObjects -#Create LiveObjects with parameters: ClientID - Security - APIKEY -lo = LiveObjects.Connection("PythonMQTT", LiveObjects.NONE, "") +# Create LiveObjects +lo = LiveObjects.Connection() -messageRate = 5 +MESSAGE_RATE = 5 -#Define command function with arguments handling + +# Define command function with arguments handling def foo(args={}): - lo.outputDebug(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"} - -#Main program -lo.addCommand("foo",foo) #Add command to LiveObjects: name - function -lo.connect() #Connect to LiveObjects -last = time.time() -uptime = time.time() + 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."} + + +# Main program +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+messageRate: - lo.addToPayload("uptime", int(time.time() - uptime) ) #Add value to payload: name - value - lo.sendData() #Sending data to cloud - lo.loop() #Check for incoming messages and if connection is still active - last = time.time() \ No newline at end of file + if time.time() >= last + MESSAGE_RATE: + 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 diff --git a/LiveObjects/Connection.py b/LiveObjects/Connection.py index 415fcd2..0efa679 100644 --- a/LiveObjects/Connection.py +++ b/LiveObjects/Connection.py @@ -7,164 +7,167 @@ import sys import json import time -import os -INT="i32" -UINT="u32" -BINARY="bin" -STRING="str" -FLOAT="f64" -INFO="INFO" +import LiveObjects + +INT = "i32" +UINT = "u32" +BINARY = "bin" +STRING = "str" +FLOAT = "f64" +INFO = "INFO" WARNING = "WARNING" ERROR = "ERROR" SSL = 8883 NONE = 1883 + class LiveObjectsParameter: - def __init__(self,value,type_, cb = None): + def __init__(self, value, type_, cb=None): self.value = value self.type = type_ self.callback = cb + class Connection: - def __init__(self, deviceID, port, apiKey, debug = True): - try: - if sys.platform == "linux" or sys.platform=="win32": + def __init__(self, debug=True): + self.__board = LiveObjects.BoardsFactory(net_type=LiveObjects.BoardsInterface.DEFAULT_CARRIER) + self.mode = self.__board.get_lang_id() + + try: + if self.mode == LiveObjects.BoardsInterface.PYTHON: import paho.mqtt.client as paho import os - self.mode = 1 - else: + elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON: from umqttrobust import MQTTClient - self.mode = 0 except ImportError: - print("[ERROR] U have missing libraries Paho-mqtt(for Linux) or umqttrobust(for uPython)") + print("[ERROR] U have missing libraries 'Paho-mqtt' (for Python) or 'umqttrobust' (for uPython)") sys.exit() - self.__port = port - self.__apiKey = apiKey + + self.__port = self.__board.get_security_level() + self.__apiKey = self.__board.get_apikey() + self.__device_id = self.__board.get_client_id() self.__parameters = {} - self.__server = "liveobjects.orange-business.com" + self.__server = "mqtt.liveobjects.orange-business.com" self.__topic = "dev/data" self.__value = "value" self.__payload = {self.__value: {}} self.__commands = {} self.__doLog = debug - self.quit=False + self.quit = False - if self.mode == 1: - self.__mqtt = paho.Client(deviceID) - else: - self.ssl = port == 8883 - self.__mqtt = MQTTClient(deviceID, self.__server, self.__port, "json+device", self.__apiKey, 0, self.ssl, {}) + if self.mode == LiveObjects.BoardsInterface.PYTHON: + self.__mqtt = paho.Client(self.__device_id) + 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}) def loop(self): - if self.mode == 0: + if self.mode == LiveObjects.BoardsInterface.MICROPYTHON: self.__mqtt.check_msg() - def __onMessage(self,client="", userdata="", msg=""): - if self.mode == 1: + 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) - else: + 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) - - def __onConnect(self,client="", userdata="", flags="", rc=""): - if self.mode == 1: - if rc ==0: - self.outputDebug(INFO,"Connected!") - if len(self.__commands)>0: - self.outputDebug(INFO, "Subscribing commands") + self.__command_manager(userdata) + + def __on_connect(self, client="", userdata="", flags="", rc=""): + if self.mode == LiveObjects.BoardsInterface.PYTHON: + if rc == 0: + self.output_debug(INFO, "Connected!") + if len(self.__commands) > 0: + self.output_debug(INFO, "Subscribing commands") self.__mqtt.subscribe("dev/cmd") - if len(self.__parameters)>0: - self.outputDebug(INFO, "Subscribing parameters") + if len(self.__parameters) > 0: + 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() - else: - self.outputDebug(INFO, "Connected, sending config") + elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON: + 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): - if self.mode == 1: + 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 - if self.__port == 8883: - dirname = os.path.dirname(__file__) - filename = os.path.join(dirname, "./certfile.cer") - self.__mqtt.tls_set(filename) + 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() - else: - self.__mqtt.set_callback(self.__onMessage) + elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON: + 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): - if self.mode ==1: - msgDict = json.loads(msg.payload) - self.outputDebug(INFO, "Received message:\n", json.dumps(msgDict, sort_keys=True, indent=4)) - else: - 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"]) + def __command_manager(self, msg): + if self.mode == LiveObjects.BoardsInterface.PYTHON: + 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: + 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!") - return {"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): - if self.mode == 1: - self.outputDebug(INFO,"Received message: ") - self.outputDebug(INFO,json.loads(msg.payload)) + def __parameter_manager(self, msg): + if self.mode == LiveObjects.BoardsInterface.PYTHON: + self.output_debug(INFO, "Received message: ") + self.output_debug(INFO, json.loads(msg.payload)) params = json.loads(msg.payload) - else: - self.outputDebug(INFO, "Received message: ") - self.outputDebug(INFO, json.loads(msg)) + elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON: + self.output_debug(INFO, "Received message: ") + self.output_debug(INFO, json.loads(msg)) params = json.loads(msg) + for param in params["cfg"]: if params["cfg"][param]["t"] == "i32": self.__parameters[param].type = INT @@ -178,11 +181,11 @@ def __parameterManager(self, msg): self.__parameters[param].type = FLOAT self.__parameters[param].value = params["cfg"][param]["v"] - if self.__parameters[param].callback != None: - self.__parameters[param].callback(param, params["cfg"][param]["v"]) - self.__publishMessage("dev/cfg",params) + if self.__parameters[param].callback is not None: + self.__parameters[param].callback(param, params["cfg"][param]["v"]) + 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: @@ -195,7 +198,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: @@ -208,37 +211,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: - self.__payload["tags"]=[] + 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: - self.__payload["tags"]=[] + 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) - if self.mode == 1: - self.outputDebug(INFO, "\n", json.dumps(msg, sort_keys=True, indent=4)) - else: - self.outputDebug(INFO, json.dumps(msg)) + self.__payload[self.__value] = {} + + def __publish_message(self, topic, msg): + self.output_debug(INFO, "Publishing message on topic: ", topic) + + if self.mode == LiveObjects.BoardsInterface.PYTHON: + self.output_debug(INFO, "\n", json.dumps(msg, sort_keys=True, indent=4)) + elif self.mode == LiveObjects.BoardsInterface.MICROPYTHON: + self.output_debug(INFO, json.dumps(msg)) + self.__mqtt.publish(topic, json.dumps(msg)) diff --git a/LiveObjects/__init__.py b/LiveObjects/__init__.py index 56f73f8..af16118 100644 --- a/LiveObjects/__init__.py +++ b/LiveObjects/__init__.py @@ -1,5 +1,7 @@ from LiveObjects.Connection import * +from LiveObjects.hal import * +from LiveObjects.credentials import * import json import time import os -import sys \ No newline at end of file +import sys diff --git a/LiveObjects/certfile.cer b/LiveObjects/certfile.cer deleted file mode 100644 index fd4341d..0000000 --- a/LiveObjects/certfile.cer +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD -QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT -MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j -b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB -CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 -nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt -43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P -T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 -gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO -BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR -TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw -DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr -hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg -06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF -PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls -YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk -CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= ------END CERTIFICATE----- diff --git a/LiveObjects/credentials.py b/LiveObjects/credentials.py new file mode 100644 index 0000000..8ec19e5 --- /dev/null +++ b/LiveObjects/credentials.py @@ -0,0 +1,30 @@ +# +# Copyright (C) Orange +# +# This software is distributed under the terms and conditions of the 'MIT' +# license which can be found in the file 'LICENSE.md' in this package distribution +import LiveObjects + + +class Credentials: + + def __init__(self, net_type): + + self._apikey = '' + self._net_type = net_type + + if net_type == LiveObjects.BoardsInterface.WIFI: + self._wifi_ssid = '' + self._wifi_password = '' + elif net_type == LiveObjects.BoardsInterface.LTE: + self._pin = '' + self._apn = '' + + def get_apikey(self): + return self._apikey + + def get_creds(self): + if self._net_type == LiveObjects.BoardsInterface.WIFI: + return {'ssid': self._wifi_ssid, 'password': self._wifi_password} + elif self._net_type == LiveObjects.BoardsInterface.LTE: + return {'pin': self._pin, 'apn_name': self._apn} diff --git a/LiveObjects/hal.py b/LiveObjects/hal.py new file mode 100644 index 0000000..8bcdfde --- /dev/null +++ b/LiveObjects/hal.py @@ -0,0 +1,219 @@ +# +# Copyright (C) Orange +# +# This software is distributed under the terms and conditions of the 'MIT' +# license which can be found in the file 'LICENSE.md' in this package distribution + +import sys +import LiveObjects + + +class BoardsInterface: + + DEFAULT_CARRIER = 1 + EXISTING_NETWORK = 2 + WIFI = 3 + LTE = 4 + + PYTHON = 1 + MICROPYTHON = 2 + + @staticmethod + def create_credentials(net_type): + return LiveObjects.Credentials(net_type) + + def get_apikey(self): + return self._credentials.get_apikey() + + def get_client_id(self): + pass + + def get_lang_str(self): + lang_dict = {BoardsInterface.PYTHON: 'Python', + BoardsInterface.MICROPYTHON: 'microPython'} + return lang_dict[self._lang_id] + + def get_lang_id(self): + return self._lang_id + + def get_security_level(self): + pass + + def get_store_cert_filename(self): + pass + + def check_network_capabilities(self, net_type): + if net_type not in self._carrier_capability: + print('Carrier not supported.') + sys.exit() + + def connect(self): + pass + + def network_disconnect(self): + pass + + +class LoPy(BoardsInterface): + def __init__(self, net_type): + self._lang_id = BoardsInterface.MICROPYTHON + self._net_type = BoardsInterface.WIFI if net_type == BoardsInterface.DEFAULT_CARRIER else net_type + self._carrier_capability = (BoardsInterface.WIFI,) + self._wifi_tls_capability = False + self._credentials = super().create_credentials(self._net_type) + self._hostname = 'LoPy' + + def connect(self): + super().check_network_capabilities(self._net_type) + if self._net_type == BoardsInterface.WIFI: + from LiveObjects.services import pycom_wifi_connect + pycom_wifi_connect(self._credentials.get_creds()['ssid'], self._credentials.get_creds()['password'], + self._hostname) + + def get_security_level(self): + if self._net_type == BoardsInterface.WIFI: + return LiveObjects.SSL if self._wifi_tls_capability else LiveObjects.NONE + + def get_client_id(self): + from LiveObjects.services import get_pycom_mac + return self.get_lang_str() + 'MQTT_' + get_pycom_mac() + + +class GPy(BoardsInterface): + def __init__(self, net_type): + self._lang_id = BoardsInterface.MICROPYTHON + self._net_type = BoardsInterface.WIFI if net_type == BoardsInterface.DEFAULT_CARRIER else net_type + self._carrier_capability = (BoardsInterface.WIFI, BoardsInterface.LTE) + self._wifi_tls_capability = False + self._lte_tls_capability = False + self._credentials = super().create_credentials(self._net_type) + self._hostname = 'GPy' + + def connect(self): + super().check_network_capabilities(self._net_type) + if self._net_type == BoardsInterface.WIFI: + from LiveObjects.services import pycom_wifi_connect + pycom_wifi_connect(self._credentials.get_creds()['ssid'], self._credentials.get_creds()['password'], + self._hostname) + elif self._net_type == BoardsInterface.LTE: + from LiveObjects.services import lte_connect + lte_connect(self._credentials.get_creds()['pin']) + + def get_security_level(self): + if self._net_type == BoardsInterface.WIFI: + return LiveObjects.SSL if self._wifi_tls_capability else LiveObjects.NONE + elif self._net_type == BoardsInterface.LTE: + return LiveObjects.SSL if self._lte_tls_capability else LiveObjects.NONE + + def get_client_id(self): + if self._net_type == BoardsInterface.WIFI: + from LiveObjects.services import get_pycom_mac + return self.get_lang_str() + 'MQTT_' + get_pycom_mac() + elif self._net_type == BoardsInterface.LTE: + from LiveObjects.services import get_pycom_imei + return self.get_lang_str() + 'MQTT_' + get_pycom_imei() + + +class Esp8266(BoardsInterface): + def __init__(self, net_type): + self._lang_id = BoardsInterface.MICROPYTHON + self._net_type = BoardsInterface.WIFI if net_type == BoardsInterface.DEFAULT_CARRIER else net_type + self._carrier_capability = (BoardsInterface.WIFI,) + self._wifi_tls_capability = False + self._credentials = super().create_credentials(self._net_type) + + def connect(self): + from LiveObjects.services import wifi_connect + super().check_network_capabilities(self._net_type) + wifi_connect(self._credentials.get_creds()['ssid'], self._credentials.get_creds()['password']) + + def get_security_level(self): + return LiveObjects.SSL if self._wifi_tls_capability else LiveObjects.NONE + + def get_client_id(self): + from LiveObjects.services import get_esp_mac + return self.get_lang_str() + 'MQTT_' + get_esp_mac() + + +class Win32(BoardsInterface): + def __init__(self, net_type): + self._lang_id = BoardsInterface.PYTHON + self._net_type = BoardsInterface.EXISTING_NETWORK if net_type == BoardsInterface.DEFAULT_CARRIER else net_type + self._carrier_capability = (BoardsInterface.EXISTING_NETWORK,) + self._existing_network_tls_capability = True + self._credentials = super().create_credentials(self._net_type) + + def connect(self): + from LiveObjects.services import use_existing_network_connection + super().check_network_capabilities(self._net_type) + use_existing_network_connection() + + def get_security_level(self): + return LiveObjects.SSL if self._existing_network_tls_capability else LiveObjects.NONE + + def get_store_cert_filename(self): + try: + import certifi + return certifi.where() + except ImportError: + print("[ERROR] U have missing library 'python-certifi-win32'") + sys.exit() + + def get_client_id(self): + from LiveObjects.services import get_mac + return self.get_lang_str() + 'MQTT_' + get_mac() + + +class Esp32(BoardsInterface): + def __init__(self, net_type): + self._lang_id = BoardsInterface.MICROPYTHON + self._net_type = BoardsInterface.WIFI if net_type == BoardsInterface.DEFAULT_CARRIER else net_type + self._carrier_capability = (BoardsInterface.WIFI,) + self._wifi_tls_capability = True + self._credentials = super().create_credentials(self._net_type) + + def connect(self): + from LiveObjects.services import wifi_connect + super().check_network_capabilities(self._net_type) + wifi_connect(self._credentials.get_creds()['ssid'], self._credentials.get_creds()['password']) + + def get_security_level(self): + return LiveObjects.SSL if self._wifi_tls_capability else LiveObjects.NONE + + def get_client_id(self): + from LiveObjects.services import get_esp_mac + return self.get_lang_str() + 'MQTT_' + get_esp_mac() + + +class Linux(BoardsInterface): + def __init__(self, net_type): + self._lang_id = BoardsInterface.PYTHON + self._net_type = BoardsInterface.EXISTING_NETWORK if net_type == BoardsInterface.DEFAULT_CARRIER else net_type + self._carrier_capability = (BoardsInterface.EXISTING_NETWORK,) + self._existing_network_tls_capability = True + self._credentials = super().create_credentials(self._net_type) + self._cert_store_filename = "/etc/ssl/certs/ca-certificates.crt" + + def connect(self): + from LiveObjects.services import use_existing_network_connection + super().check_network_capabilities(self._net_type) + use_existing_network_connection() + + def get_security_level(self): + return LiveObjects.SSL if self._existing_network_tls_capability else LiveObjects.NONE + + def get_store_cert_filename(self): + return self._cert_store_filename + + def get_client_id(self): + from LiveObjects.services import get_mac + return self.get_lang_str() + 'MQTT_' + get_mac() + + +class BoardsFactory: + + def __new__(cls, net_type): + s = sys.platform + sn = s[0].upper() + s[1:] # capitalize first letter + board = eval(sn)(net_type) # instance of board w/ net type: WiFi, LTE, etc. + return board diff --git a/LiveObjects/services.py b/LiveObjects/services.py new file mode 100644 index 0000000..95d5913 --- /dev/null +++ b/LiveObjects/services.py @@ -0,0 +1,109 @@ +# +# Copyright (C) Orange +# +# This software is distributed under the terms and conditions of the 'MIT' +# license which can be found in the file 'LICENSE.md' in this package distribution + +import time +import sys + + +def use_existing_network_connection(): + print('Using existing network connection') + + +def get_mac(): + import uuid + return ''.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff) for ele in range(0, 8*6, 8)][::-1]).upper() + + +CONN_TIMEOUT = 20 + + +def wifi_connect(ssid, password): + from network import WLAN, STA_IF + + sta_if = WLAN(STA_IF) + sta_if.active(True) + start_time = time.time() + while True: + print('Connecting to network...') + try: + sta_if.connect(ssid, password) + time.sleep_ms(3000) + if sta_if.isconnected(): + print("WiFi connected successfully.") + print('Network config:', sta_if.ifconfig()) + break + elif time.time() - start_time > CONN_TIMEOUT: + print("[ERROR] Wi-Fi not connected. Stopped.") + sys.exit() + except OSError: + print("[ERROR] Wi-Fi not connected. Stopped.") + sys.exit() + + +def get_esp_mac(): + from network import WLAN + import binascii + return binascii.hexlify(WLAN().config('mac')).decode('ascii').upper() + + +def pycom_wifi_connect(ssid, password, hostname): + from network import WLAN + + wlan = WLAN(mode=WLAN.STA) + wlan.hostname(hostname) + start_time = time.time() + while True: + print("Trying to connect...") + wlan.connect(ssid=ssid, auth=(WLAN.WPA2, password)) + time.sleep_ms(3000) + if wlan.isconnected(): + print("WiFi connected successfully.") + print('IPs:', wlan.ifconfig(), 'Channel:', wlan.channel()) + break + elif time.time() - start_time > CONN_TIMEOUT: + print("[ERROR] Wi-Fi not connected. Stopped.") + sys.exit() + + +def get_pycom_mac(): + from network import WLAN + import binascii + return binascii.hexlify(WLAN().mac()[0]).decode('ascii').upper() + + +def lte_connect(pin): + from network import LTE + + def is_sim_waiting_for_pin(): + if lte.send_at_cmd('AT+CPIN?').strip() == '+CPIN: SIM PIN\r\n\r\nOK': + return True + else: + return False + + lte = LTE() + time.sleep(2) + + if is_sim_waiting_for_pin(): + print("PIN", (lte.send_at_cmd('AT+CPIN="%s"' % pin)).strip()) + else: + print("PIN PRESENT: OK") + + lte.attach() + print("Attaching... ", end='') + while not lte.isattached(): + time.sleep(1) + print("attached!") + + lte.connect() + print("Connecting... ", end='') + while not lte.isconnected(): + time.sleep(1) + print("connected!") + + +def get_pycom_imei(): + from network import LTE + return LTE().imei() diff --git a/README.md b/README.md index bcfc303..a5d9785 100644 --- a/README.md +++ b/README.md @@ -3,57 +3,59 @@ This code wraps all the functions necessary to make your object work with Live Objects. - You can declare parameters, which you can later update OTA from Live objects. You can also create commands to trigger actions remotely. - Only thing u must do yourself is connecting the board with internet. +You can declare parameters, which you can later update OTA from Live objects. You can also create commands to trigger actions remotely. +Only thing you must do yourself is connecting the board with internet. Code uses MQTT connection to exchange data with Live objects under the hood to keep your parameters up to date or execute the commands received without you having to take care of them (apart from writing the code of these commands, of course). ## Compatibility ## -| System | MQTT | MQTTS | -| :--- | :---: | :---: | -| Linux | OK |OK | -| Windows | OK |OK | -| Raspberry Pi | OK |OK | -| ESP8266 | OK | - | -| ESP32 | OK | OK | - -## Prerequisites/dependecies ## -This code needs a few libraries to run +| System | MQTT | MQTTS | +|:--------------|:----:|:-----:| +| Linux | OK | OK | +| Windows | OK | OK | +| Raspberry Pi | OK | OK | +| ESP8266 | OK | - | +| ESP32 | OK | OK | +| LoPy (Pycom) | OK | - | +| GPy (Pycom) | OK | - | + +## Prerequisites / dependencies ## +This code needs a few libraries to run: - Python needs [paho-mqtt](https://pypi.org/project/paho-mqtt/) + - Python for Windows needs [python-certifi-win32](https://pypi.org/project/python-certifi-win32/) - uPython needs [umqttsimple, umqttrobust and ssl](https://github.com/micropython/micropython-lib) ## How to use ## -1. Log in to [Live Objects](https://liveobjects.orange-business.com) or request a [trial account](https://liveobjects.orange-business.com/#/request_account) (up to 10 devices for 1 year) if you don't have one. -2. Create an [API key](https://liveobjects.orange-business.com/#/administration/apikeys) for your device. Give it a name, select the *Device access* role and validate. Copy the key. -3. Clone or download the directory from Github. -4. Change **\** in sketches to one you generated -5. Run script +1. Log in to [Live Objects](https://liveobjects.orange-business.com) or request a [trial account](https://liveobjects.orange-business.com/#/request_account) (up to 10 devices for 1 year) if you don't have one, +2. Create an [API key](https://liveobjects.orange-business.com/#/administration/apikeys) for your device. Give it a name, select the *Device access* role and validate. Copy the key, +3. Clone or download the directory from GitHub, +4. Change **\** in `credentials.py` to one you generated, +5. Run selected `.py` script ## Developer guide ## ### Constructor ### -Constructor of LiveObjects looks like this +Constructor of LiveObjects looks like below: ```Python -lo = LiveObjects.Connection("mqttID",LiveObjects.NONE,"", debug = True) +lo = LiveObjects.Connection() ``` -First parameter is ID of the device, second is type of connection security ( NONE / SSL), third is Api Key to LiveObjects and last is debug mode, if you don't want to output debug messages set it to False. You can also use `lo.setDebug(False)`. - ### Debug messages ### You can use LiveObjects to output debug messages. + ```Python -foo = 21 -#INFO / ERROR / WARNING -lo.outputDebug(LiveObjects.INFO,"example value", foo, ...) -#Output: [INFO] example value 21 ... +VALUE = 21 +# INFO / ERROR / WARNING +lo.output_debug(LiveObjects.INFO, "example value", VALUE, ...) +# Output: [INFO] example value 21 ... ``` ### Declare parameters ### -You can update over the air some parameters of your sketch using Live Objects's parameters. Parameters and Commands must be declared **before** your device connects to Live Objects. +You can update over the air some parameters of your script using Live Objects's parameters. Parameters and Commands must be declared **before** your device connects to Live Objects. You can declare parameters with the `addParameter()` instruction, which accepts the following arguments: - the label of your parameter as it will be displayed on Live Objects; @@ -65,56 +67,59 @@ To retrieve a parameter use function `getParameter()` which takes following argu - Parameter name Example: + ```Python -lo.addParameter("messageRate", 25, LiveObjects.INT); -lo.addParameter("sendDHTData", true ,LiveObjects.BINARY, myCallbackFunction); -... -if lo.getParameter("sendDHTData"): - lo.addToPayload("temperature",DHT.readTemeprature()) - lo.addToPayload("humidity",DHT.readHumidity()) +lo.add_parameter("message_rate", 25, LiveObjects.INT) +lo.add_parameter("send_DHT_data", true, LiveObjects.BINARY, my_callback_function) +# ... +if lo.get_parameter("send_DHT_data"): + lo.add_to_payload("temperature", DHT.read_temeprature()) + lo.add_to_payload("humidity", DHT.read_humidity()) ``` -The callback function takes 2 arguments +The callback function takes 2 arguments: ```Python -def myCallbackFunction(parameterName, newValue): - // do stuff +def my_callback_function(parameter_name, new_value): + # do stuff ``` Further reading on Live Objects' [Parameters](https://liveobjects.orange-business.com/doc/html/lo_manual.html#_configuration). ### Declare commands ### -Commands lets you trigger specific actions on your device from Live Objects. Parameters and Commands must be declared _before_ your device connects to Live Objects. +Commands let you trigger specific actions on your device from Live Objects. Parameters and Commands must be declared _before_ your device connects to Live Objects. Commands can be declared using the `addcommand()` instruction, which accepts the following arguments: - the label of your command - the callback function that will execute the command. + ```Python -lo.addParameter("a command", myCallback); +lo.add_parameter("a command", my_callback, ); ``` -The callback function should take 1 parameter and return dictonary +The callback function should take 1 parameter and return dictionary: ```Python -def myCallback(args={}): - // do stuff - return {} +def my_callback(args={}): + # do stuff + return {} ``` Arguments and response are optional when using commands, but they can be useful if you want to pass parameters to your function. For instance, you could define a `play tone` command that will use some parameters like the frequency of the tone, or its duration. -- Any incoming arguments will be passed as member of a dictonary -- You can pass response arguments in the form of a dictonary by returning them +- Any incoming arguments will be passed as member of a dictionary +- You can pass response arguments in the form of a dictionary by returning them + ```Python -def playTone(args={}): - duration = args["duration"] - frequency = args["frequency"] - // play the tone accordingly to arguments - ... - return {"I played":"the tone"} -} +def play_tone(args={}): + duration = args["duration"] + frequency = args["frequency"] + # play the tone accordingly to arguments + # ... + return {"I played": "the tone"} + def setup(): - lo.addCommand("play tone", playTone) + lo.add_command("play tone", play_tone) ``` -> :warning: **Command name and arguments are case-sensitive when creating the command on Live Objects.**: On the opposite, there is no specific order for specifying the command arguments. +> Warning: **Command name and arguments are case-sensitive when creating the command on Live Objects.**: On the opposite, there is no specific order for specifying the command arguments. Further reading on Live Objects' [Commands](https://liveobjects.orange-business.com/doc/html/lo_manual.html#MQTT_DEV_CMD). @@ -122,34 +127,37 @@ Further reading on Live Objects' [Commands](https://liveobjects.orange-business. You can send data very easily to Live Objects. #### Dead simple method #### -Compose your payload using the `addToPayload()` instruction. You will need to provide a label for your value, and the data itself. You data can be of any simple type. +Compose your payload using the `addToPayload()` instruction. You will need to provide a label for your value, and the data itself. Your data can be of any simple type. Data is added on each call to `addToPayload()`, so repeat the instruction if you have multiple data to send. When your payload is ready, send it using `sendData()`. That simple. + ```Python -value=21 -myOtherValue=37 +VALUE = 21 +MY_OTHER_VALUE = 37 + def foo(): - // collect data - lo.addToPayload("my data", value) - lo.addToPayload("my other data", myOtherValue) - lo.sendData() # send to LiveObjects + # collect data + lo.add_to_payload("my data", VALUE) + lo.add_to_payload("my other data", MY_OTHER_VALUE) + lo.send_data() # send to LiveObjects ``` -As soon the data is send, your payload is cleared and waiting for the next sending. +As soon the data is sent, your payload is cleared and waiting for the next sending. + +### Advanced payload features ### -### Advanced payload feautres ### ```Python - #add "model" property to your message - lo.addModel("exampleName") +# Add "model" property to your message +lo.add_model("example_name") - #Add "tag" property to your message - lo.addTag("kitchen") - lo.addTags(["humidity","bathroom"]) +# Add "tag" property to your message +lo.add_tag("kitchen") +lo.add_tags(["humidity", "bathroom"]) - #Use your object as payload (this function doesn't append current paylod) - obj = ["example":"value", "example2":"value2" ] - lo.setObjectAsPayload(obj) +# Use your object as payload (this function doesn't append current payload) +obj = {"example": "value", "example2": "value2"} +lo.set_object_as_payload(obj) ``` @@ -157,88 +165,134 @@ As soon the data is send, your payload is cleared and waiting for the next sendi You can control the connection and disconnection of your device using `connect()` and `disconnect()`. - In order to check for any incoming configuration update or command, you need to keep the `loop()` instruction in your main loop. ```Python def foo(): - lo.connect(); - while True: - #Do some stuff - #... - lo.loop(); #Keep this in main loop - lo.disconnect() + lo.connect(); + while True: + # Do some stuff + #... + lo.loop(); #Keep this in main loop + lo.disconnect() ``` +### Changing default carrier to connect to the network ### + +Every board has its own default carrier for connection to the network (see below). + +| System | Default carrier | Optional carrier | +|:--------------|:---------------:|:----------------:| +| Linux | Delivered by OS | - | +| Windows | Delivered by OS | - | +| Raspberry Pi | Delivered by OS | - | +| ESP8266 | Wi-Fi | - | +| ESP32 | Wi-Fi | - | +| LoPy (Pycom) | Wi-Fi | - | +| GPy (Pycom) | Wi-Fi | LTE | + +For GPy you can switch connectivity to optional carrier. You need to do change in `Connection` class in `Connection.py` +from: +```Python +def __init__(self, debug=True): + self.__board = LiveObjects.BoardsFactory(net_type=LiveObjects.BoardsInterface.DEFAULT_CARRIER) +... +``` +to: +```Python +def __init__(self, debug=True): + self.__board = LiveObjects.BoardsFactory(net_type=LiveObjects.BoardsInterface.LTE) +... +``` +Then GPy will connect via LTE network. + +### Adding new boards ### + +There is possibility to add your new type of board supporting Python/uPython. +You need to add your own class in `hal.py`. Name of this class has to be the same as output of `sys.platform` +and has to start from capital letter. +```commandline +>>> sys.platform +'GPy' +>>> +``` +Below code shows basic constructor: +```Python +def __init__(self, net_type): + self._lang_id = BoardsInterface.MICROPYTHON + self._net_type = BoardsInterface.WIFI if net_type == BoardsInterface.DEFAULT_CARRIER else net_type + self._carrier_capability = (BoardsInterface.WIFI,) + self._wifi_tls_capability = False + self._credentials = super().create_credentials(self._net_type) +``` +Basic fields meaning: +- **_lang_id**: used Python dialect: PYTHON / MICROPYTHON, +- **_net_type**: used type of network: WIFI / LTE / network delivered by OS / ... +- **_carrier_capability**: _tuple_ containing supported type(s) of network, +- **_wifi_tls_capability**: _True_ if TLS is supported and MQTTS could be used, +- **_credentials**: required credentials depended on network type: SSID/PASS for Wi-Fi, PIN/APN for LTE etc. + +If other specific fields are necessary you need to define them. +You need to override specific methods - e.g. `connect` which is depended on type of board. +All specific functions are placed in `services.py`. +If your board needs function supporting its equipment you need to put it in this file. + # Installation guide for uPython # -## Example for ESP8266 ## -## Requirements ## +## Example for ESP32 / ESP8266 ## +### Requirements ### 1. [ampy](https://learn.adafruit.com/micropython-basics-load-files-and-run-code/install-ampy) 2. [umqttsimple, umqttrobust and ssl](https://github.com/micropython/micropython-lib) 3. [PuTTY](https://www.putty.org/) (for Windows) -## Installation steps ## -1. Copy files into device - ``` - ampy -pCOMXX put umqttrobus.py - ampy -pCOMXX put umqttsimple.py - ampy -pCOMXX put ssl.py - ampy -pCOMXX put LiveObjects //It will copy directory with its content - ``` -2. Prepare your sketch and save it as main.py then copy file into device -``` -ampy -pCOMXX put main.py +### Installation steps ### + +1. Preparation + +Change **\** in `credentials.py` to one you generated.\ +Change **\** and **\** suitable to your Wi-Fi or +change **\** and **\** suitable to your SIM card. + +2. Copy files into device +```commandline +> ampy -pCOMXX put umqttrobust.py +> ampy -pCOMXX put simple.py +> ampy -pCOMXX put LiveObjects // It will copy directory with its content ``` -3. Setup internet connection in boot.py file and upload it into device. -```Python -# This file is executed on every boot (including wake-boot from deepsleep) -#import esp -#esp.osdebug(None) -import uos, machine -#uos.dupterm(None, 1) # disable REPL on UART(0) -import gc -#import webrepl -#webrepl.start() -gc.collect() - - -#Network connection -import network -sta_if = network.WLAN(network.STA_IF) -if not sta_if.isconnected(): - print('connecting to network...') - sta_if.active(True) - sta_if.connect('SSID', 'PASS') - while not sta_if.isconnected(): - pass -print('network config:', sta_if.ifconfig()) -``` -You may want to get content of file first, then use -``` -ampy -pCOMXX get boot.py +3. Prepare your script and save it as `main.py` then copy file into device. +You can use one of example ones (`1_send_data.py`, ...) renaming it to `main.py` +```Shell +> ampy -pCOMXX put main.py ``` + 4. Connect to device and check if it's working using PuTTY - Crtl + D soft resets device - + Ctrl + D soft resets device + Ctrl + C Stops currently running script -## Summary ## -After all steps content of the device should look like this -``` ->ampy -pCOMXX ls +### Summary ### + +After all steps content of the device should look like below: +```commandline +> ampy -pCOMXX ls /LiveObjects /boot.py /main.py -/ssl.py /umqttrobust.py -/umqttsimple.py +/simple.py ->ampy -pCOMXX ls LiveObjects +> ampy -pCOMXX ls LiveObjects /LiveObjects/Connection.py /LiveObjects/__init__.py -/LiveObjects/certfile.cer +/LiveObjects/hal.py +/LiveObjects/credentials.py +/LiveObjects/services.py ``` +## Example for LoPy / GPy ## + +You can do the steps as above but better is to use [Pymakr plug-in](https://pycom.io/products/supported-networks/pymakr/) for **Visual Studio Code** or **Atom** delivered by [Pycom](https://pycom.io/). +Plug-in supports code development, its upload to the board and communication with board. + ## Troubleshooting ## If you are getting 'MQTT exception: 5' check your api key \ No newline at end of file diff --git a/setup.py b/setup.py index c1dd677..14285a6 100644 --- a/setup.py +++ b/setup.py @@ -5,14 +5,14 @@ name='LiveObjects', url='https://github.com/DatavenueLiveObjects/LiveObjects_SDK_for_Python', - author='Kacper Sawicki, Krzysztof Krześlak', + author='Kacper Sawicki, Krzysztof Krześlak, Tomasz Malek', #author_email='', packages=['LiveObjects'], include_package_data=True, install_requires=['paho-mqtt'], - version='1.0.0', + version='2.0.0', license='MIT',