Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,8 +335,7 @@ If you don't specify a client_id, the SDK will use a random hex string.

There are a number of callback functions you may assign.
Typically, you want to set these callbacks before you connect to the broker.
This is a list of the function names and their expected parameters.
For more information about the individual callbacks, see the [paho-mqtt](https://github.com/eclipse/paho.mqtt.python#callbacks) documentation.
This is a list of the function names and their expected parameters:
- `on_connect(client, userdata, flags, rc)`
- `on_disconnect(client, userdata, rc)`
- `on_subscribe(client, userdata, mid, granted_qos)`
Expand All @@ -345,6 +344,11 @@ For more information about the individual callbacks, see the [paho-mqtt](https:/
- `on_message(client, userdata, mid)`
- `on_log(client, userdata, level, buf)`

The SDK provides attributes and methods needed for most applications. Occasionally, it may be useful to access the attributes and methods the underlying **paho-mqtt** client. This is available through this public attribute:
- `paho_client`

For more information about the individual callbacks and attributes, see the [paho-mqtt](https://github.com/eclipse/paho.mqtt.python#callbacks) documentation.

#### Connecting and Disconnecting
Before publishing or subscribing, you must connect your client to the broker.
After you're finished, it's good practice to disconnect from the broker before quitting your program.
Expand Down
24 changes: 24 additions & 0 deletions clearblade/ClearBladeCore.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def __init__(self, systemKey, systemSecret, url="https://platform.clearblade.com
#############

def User(self, email, password="", authToken=""):
"""Authenticate & return User"""
user = Users.User(self, email, password=password, authToken=authToken)
if authToken == "":
user.authenticate()
Expand All @@ -48,16 +49,19 @@ def User(self, email, password="", authToken=""):
cbErrors.handle(-1)

def AnonUser(self):
"""Authenticate & return Anon User"""
anon = Users.AnonUser(self)
anon.authenticate()
return anon

def registerUser(self, authenticatedUser, email, password):
"""Register User"""
n00b = Users.registerUser(self, authenticatedUser, email, password)
self.users.append(n00b)
return n00b

def ServiceUser(self, email, token):
"""Register & return new Service Account User"""
user = Users.ServiceUser(self, email, token)
if user.checkAuth():
return user
Expand All @@ -70,14 +74,17 @@ def ServiceUser(self, email, token):
###############

def getDevices(self, authenticatedUser, query=None):
"""Return Devices"""
self.devices = Devices.getDevices(self, authenticatedUser, query)
return self.devices

def getDevice(self, authenticatedUser, name):
"""Return Device by Name"""
dev = Devices.getDevice(self, authenticatedUser, name)
return dev

def Device(self, name, key="", authToken="", x509keyPair=None):
"""Authenticate & return Device"""
dev = Devices.Device(system=self, name=name, key=key, authToken=authToken, x509keyPair=x509keyPair)
# check if dev in self.devices?
return dev
Expand All @@ -87,6 +94,7 @@ def Device(self, name, key="", authToken="", x509keyPair=None):
############

def Collection(self, authenticatedUser, collectionID="", collectionName=""):
"""Return Collection by Name or ID"""
if not collectionID and not collectionName:
cbLogs.error("beep")
cbErrors.handle(-1)
Expand All @@ -99,6 +107,7 @@ def Collection(self, authenticatedUser, collectionID="", collectionName=""):
############

def Messaging(self, user, port=1883, keepalive=30, url="", client_id="", clean_session=None, use_tls=False):
"""Return Messaging Object"""
msg = Messaging.Messaging(user, port, keepalive, url, client_id=client_id, clean_session=clean_session, use_tls=use_tls)
self.messagingClients.append(msg)
return msg
Expand All @@ -108,6 +117,7 @@ def Messaging(self, user, port=1883, keepalive=30, url="", client_id="", clean_s
############

def Service(self, name):
"""Return Code Service"""
return Code.Service(self, name)


Expand All @@ -117,6 +127,13 @@ def __init__(self):
self.filters = []

def Or(self, query):
"""
Query 'Or' function.

# NOTE: you can't add filters after
# you Or two queries together.
# This function has to be the last step.
"""
# NOTE: you can't add filters after
# you Or two queries together.
# This function has to be the last step.
Expand All @@ -133,22 +150,29 @@ def __addFilter(self, column, value, operator):
self.filters[0].append({operator: [{column: value}]})

def equalTo(self, column, value):
"""'EQ' (Equal To) Query function"""
self.__addFilter(column, value, "EQ")

def greaterThan(self, column, value):
"""'GT' (Greater Than) Query function"""
self.__addFilter(column, value, "GT")

def lessThan(self, column, value):
"""'LT' (Less Than) Query function"""
self.__addFilter(column, value, "LT")

def greaterThanEqualTo(self, column, value):
"""'GTE' (Greater Than or Equal) Query function"""
self.__addFilter(column, value, "GTE")

def lessThanEqualTo(self, column, value):
"""'LTE' (Less Than or Equal) Query function"""
self.__addFilter(column, value, "LTE")

def notEqualTo(self, column, value):
"""'NEQ' (Not Equal To) Query function"""
self.__addFilter(column, value, "NEQ")

def matches(self, column, value):
"""'RE' (Matches) Query function"""
self.__addFilter(column, value, "RE")
1 change: 1 addition & 0 deletions clearblade/Code.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ def __init__(self, system, name):
self.sslVerify = system.sslVerify

def execute(self, authenticatedUser, params={}):
"""Execute Code Service as Authenticated User"""
cbLogs.info("Executing code service", self.name)
resp = restcall.post(self.url, headers=authenticatedUser.headers, data=params, sslVerify=self.sslVerify)
return resp
Expand Down
9 changes: 9 additions & 0 deletions clearblade/Collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def __init__(self, system, authenticatedUser, collectionID="", collectionName=""
self.sslVerify = system.sslVerify

def getItems(self, query=None, pagesize=100, pagenum=1, url=""):
"""Return Collection Items"""
url = self.url + url
params = {
"PAGESIZE": pagesize,
Expand All @@ -47,12 +48,14 @@ def getItems(self, query=None, pagesize=100, pagenum=1, url=""):
return self.items

def getNextPage(self):
"""Return Next Page"""
if self.nextPageURL:
return self.getItems(url=self.nextPageURL)
else:
cbLogs.info("No next page!")

def getPrevPage(self):
"""Return Previous Page"""
if self.prevPageURL:
return self.getItems(url=self.prevPageURL)
elif self.currentPage == 2:
Expand All @@ -62,16 +65,19 @@ def getPrevPage(self):
cbLogs.info("No previous page!")

def createItem(self, data):
"""Create Collection Item"""
return restcall.post(self.url, headers=self.headers, data=data, sslVerify=self.sslVerify)

def updateItems(self, query, data):
"""Update Collection Items"""
payload = {
"query": query.filters,
"$set": data
}
return restcall.put(self.url, headers=self.headers, data=payload, sslVerify=self.sslVerify)

def deleteItems(self, query):
"""Delete Collection Items"""
return restcall.delete(self.url, headers=self.headers, params={"query": json.dumps(query.filters)}, sslVerify=self.sslVerify)


Expand All @@ -80,6 +86,7 @@ def deleteItems(self, query):
###########################

def DEVgetAllCollections(developer, system):
"""Return all Collections as Developer"""
url = system.url + "/admin/allcollections"
params = {
"appid": system.systemKey
Expand All @@ -88,6 +95,7 @@ def DEVgetAllCollections(developer, system):
return resp

def DEVnewCollection(developer, system, name):
"""Create Collection as Developer"""
url = system.url + "/admin/collectionmanagement"
data = {
"appID": system.systemKey,
Expand All @@ -98,6 +106,7 @@ def DEVnewCollection(developer, system, name):
return Collection(system, developer, collectionID=resp["collectionID"])

def DEVaddColumnToCollection(developer, system, collection, columnName, columnType):
"""Add Column to Collection as Developer"""
if not collection.collectionID:
cbLogs.error("You must supply the collection id when adding a column to a collection.")
cbErrors.handle(-1)
Expand Down
12 changes: 12 additions & 0 deletions clearblade/Developers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from . import Permissions

def registerDev(fname, lname, org, email, password, url="https://platform.clearblade.com", registrationKey="", sslVerify=True):
"""Register Developer in environment"""
newDevCredentials = {
"fname": fname,
"lname": lname,
Expand Down Expand Up @@ -51,13 +52,15 @@ def __init__(self, email, password, url="https://platform.clearblade.com", sslVe
self.authenticate()

def authenticate(self):
"""Authenticate Developer"""
cbLogs.info("Authenticating", self.credentials["email"], "as a developer...")
resp = restcall.post(self.url + "/admin/auth", headers=self.headers, data=self.credentials, sslVerify=self.sslVerify)
self.token = str(resp["dev_token"])
self.headers["ClearBlade-DevToken"] = self.token
cbLogs.info("Successfully authenticated!")

def logout(self):
"""Logout Developer"""
restcall.post(self.url + "/admin/logout", headers=self.headers, sslVerify=self.sslVerify)
if self in self.system.users:
self.system.users.remove(self)
Expand All @@ -74,37 +77,46 @@ def logout(self):
#################

def getAllCollections(self, system):
"""Return all Collections as Developer"""
return Collections.DEVgetAllCollections(self, system)

def newCollection(self, system, name):
"""Create Collection as Developer"""
return Collections.DEVnewCollection(self, system, name)

def addColumnToCollection(self, system, collection, columnName, columnType):
"""Add Column to Collection as Developer"""
return Collections.DEVaddColumnToCollection(self, system, collection, columnName, columnType)

###############
# Devices #
###############

def newDevice(self, system, name, enabled=True, type="", state="", active_key="", allow_certificate_auth=False, allow_key_auth=True, certificate="", description="", keys=""):
"""Create Device as Developer"""
return Devices.DEVnewDevice(self, system, name, enabled, type, state, active_key, allow_certificate_auth, allow_key_auth, certificate, description, keys)

def getDevices(self, system, query=None):
"""Return Devices as Developer"""
return Devices.DEVgetDevices(self, system, query)

def getDevice(self, system, name):
"""Return Device as Developer"""
return Devices.DEVgetDevice(self, system, name)

def updateDevice(self, system, name, updates):
"""Update Device as Developer"""
return Devices.DEVupdateDevice(self, system, name, updates)

def deleteDevice(self, system, name):
"""Delete Device as Developer"""
return Devices.DEVdeleteDevice(self, system, name)

#################
# Permissions #
#################

def setPermissionsForCollection(self, system, collection, permissionsLevel, roleName):
"""Set Permissions for Collection as Developer"""
return Permissions.DEVsetPermissionsForCollection(self, system, collection, permissionsLevel, roleName)

10 changes: 10 additions & 0 deletions clearblade/Devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@


def getDevices(system, authenticatedUser, query=None):
"""Return Devices as Authenticated User"""
if query:
params = {}
params["FILTERS"] = query.filters
Expand All @@ -18,6 +19,7 @@ def getDevices(system, authenticatedUser, query=None):


def getDevice(system, authenticatedUser, name):
"""Return Device as Authenticated User"""
url = system.url + "/api/v/2/devices/" + system.systemKey + "/" + name
resp = restcall.get(url, headers=authenticatedUser.headers, sslVerify=system.sslVerify)
return resp
Expand Down Expand Up @@ -49,6 +51,7 @@ def __init__(self, system, name, key="", authToken="", x509keyPair=None):
cbErrors.handle(-1)

def authorize(self, key):
"""Authenticate as Device"""
cbLogs.info("Authenticating", self.name, "as a device...")
credentials = {
"deviceName": self.name,
Expand All @@ -60,6 +63,7 @@ def authorize(self, key):
cbLogs.info("Successfully authenticated!")

def authorize_x509(self, x509keyPair):
"""Authenticate as Device using x509 Key Pair"""
cbLogs.info("Authenticating", self.name, "as a device using x509 key pair...")
credentials = {
"system_key": self.systemKey,
Expand All @@ -71,6 +75,7 @@ def authorize_x509(self, x509keyPair):
cbLogs.info("Successfully authenticated!")

def update(self, info):
"""Update Device"""
payload = info
try:
json.loads(payload)
Expand All @@ -85,6 +90,7 @@ def update(self, info):
###########################

def DEVnewDevice(developer, system, name, enabled=True, type="", state="", active_key="", allow_certificate_auth=False, allow_key_auth=True, certificate="", description="", keys=""):
"""Create Device as Developer"""
url = system.url + "/admin/devices/" + system.systemKey + "/" + name
data = {
"active_key": active_key,
Expand All @@ -104,6 +110,7 @@ def DEVnewDevice(developer, system, name, enabled=True, type="", state="", activ


def DEVgetDevices(developer, system, query=None):
"""Return Devices as Developer"""
if query:
params = {}
params["FILTERS"] = query.filters
Expand All @@ -117,19 +124,22 @@ def DEVgetDevices(developer, system, query=None):


def DEVgetDevice(developer, system, name):
"""Return Device as Developer"""
url = system.url + "/api/v/2/devices/" + system.systemKey + "/" + name
resp = restcall.get(url, headers=developer.headers, sslVerify=system.sslVerify)
return resp


def DEVupdateDevice(developer, system, name, updates):
"""Update Device as Developer"""
url = system.url + "/api/v/2/devices/" + system.systemKey + "/" + name
resp = restcall.put(url, headers=developer.headers, data=updates, sslVerify=system.sslVerify)
cbLogs.info("Successfully updated device:", name + ".")
return resp


def DEVdeleteDevice(developer, system, name):
"""Delete Device as Developer"""
url = system.url + "/api/v/2/devices/" + system.systemKey + "/" + name
resp = restcall.delete(url, headers=developer.headers, sslVerify=system.sslVerify)
cbLogs.info("Successfully deleted device:", name + ".")
Expand Down
Loading