def __init__(self, credentials): self.systemKey = credentials['systemKey'] self.systemSecret = credentials['systemSecret'] self.platformURL = credentials['platformURL'] self.gatewayAddress = self.GetMacAddress() #Connect to MQTT cbSystem=System(self.systemKey, self.systemSecret, self.platformURL) #authenticate this adapter with the edge sleep_time = 1 cbAuth=cbSystem.User(credentials['username'], credentials['password']) while not cbAuth.checkAuth(): print("trying to authenticate again by sleeping for %d", sleep_time) time.sleep(sleep_time) sleep_time = sleep_time << 1 cbAuth = cbSystem.User(credentials['username'], credentials['password']) if sleep_time > 60: break self.gatewayName = "thunderboard" self.client = cbSystem.Messaging(cbAuth) self.client.connect() # the on_connect is not working self.client.on_message = self.CommandCallback
def __init__(self, credentials): self.systemKey = credentials['systemKey'] self.systemSecret = credentials['systemSecret'] self.username = credentials['username'] self.password = credentials['password'] self.platformURL = credentials['platformURL'] self.gatewayAddress = self.GetMacAddress() #Connect to MQTT cbSystem = System(self.systemKey, self.systemSecret, self.platformURL) # Device Auth if 'active_key' in credentials: self.gatewayName = credentials["name"] self.active_key = credentials['active_key'] cbAuth = cbSystem.Device(self.gatewayName, credentials['active_key']) else: self.gatewayName = self.gatewayAddress cbAuth = cbSystem.User(credentials['username'], credentials['password']) # right now override the GatewayName so that portal demos work easier self.gatewayName = "thunderboard" self.client = cbSystem.Messaging(cbAuth) self.client.connect() # the on_connect is not working self.client.on_message = self.CommandCallback
def main(): logging.basicConfig(filename='clearblade_challenge.log', encoding='utf-8', level=logging.DEBUG) #send message to ClearBlade platform SystemKey = 'c4dfbc880ce891a09fe8eb92eb9d01' SystemSecret = 'C4DFBC880CC0D8A8B5FCE5B4DB44' admin_email = '*****@*****.**' admin_pw = 'H1r3m3pls' mySystem = System(SystemKey, SystemSecret) admin = mySystem.User(admin_email, admin_pw) mqtt = mySystem.Messaging(admin) sys_overview, bles = create_msgs() mqtt.connect() for ble in bles: print(json.dumps(ble)) # debug print statement mqtt.publish('ble/_platform', json.dumps(ble)) sleep(1) mqtt.publish('sysinfo', json.dumps(sys_overview)) mqtt.disconnect()
from clearblade.ClearBladeCore import System import json import time import properties, metrics # credentials SystemKey = properties.systemKey SystemSecret = properties.systemSecret email = properties.email password = properties.password mySystem = System(SystemKey, SystemSecret) user = mySystem.User(email, password) mqtt = mySystem.Messaging(user) mqtt.connect() while True: usage = metrics.getUsage() mqtt.publish("usageQ", json.dumps(usage)) time.sleep(10) mqtt.disconnect()
datefmt='%m-%d-%Y %H:%M:%S %p') handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(formatter) logger = logging.getLogger(name) logging.basicConfig(level=os.environ.get("LOGLEVEL", LOGLEVEL)) logger.addHandler(handler) return logger #Main Loop if __name__ == '__main__': logger = setup_custom_logger('BLE Adapter') scanner = ScanDelegate() exitapp = False cbSystem = System(SystemKey, SystemSecret, SystemURL) cbAuth = cbSystem.User(cbUser, cbPass) mqtt = cbSystem.Messaging(cbAuth) #mqtt.on_connect = on_connect #mqtt.on_message = on_message mqtt.connect() #Connect to the msg broker while not exitapp: logging.info("Scan Period: %s seconds", scanTimePeriod) devices = scanner.scanProcess() try: processDeviceList(devices) #logging.info('Sleeping for %s', waitTimeBetweenScans) #time.sleep(waitTimeBetweenScans) except KeyboardInterrupt: exitapp = True mqtt.disconnect() os._exit(0)
# Email: [email protected] from clearblade.ClearBladeCore import System import random import time import psutil import os # System credentials SystemKey = os.environ.get("SYSTEM_KEY") SystemSecret = os.environ.get("SYSTEM_SECRET") mySystem = System(SystemKey, SystemSecret) # Log in as Sahil sahil = mySystem.User("*****@*****.**", "sahilmehta") # Use Sahil to access a messaging client mqtt = mySystem.Messaging(sahil) # Set up callback function def on_connect(client, userdata, flags, rc): # When we connect to the broker, start publishing our data to the Test Topic channel payload = "CPU Utilization : " + str( psutil.cpu_percent()) + ", Available Virtual Memory: " + str( psutil.virtual_memory()[2]) # Connect callback to client mqtt.on_connect = on_connect
systemSecret = os.environ.get("SystemSecret", None) if systemSecret == None: print("Please add System Secret") sys.exit(1) mySystem = System(systemKey, systemSecret) ## Change: geeting the password from environment password = os.environ.get("clearblabe_password", None) if password == None: print("Please add PASSWORD") sys.exit(1) print(password) # Log in as Preet preet = mySystem.User("*****@*****.**", password) # Accessing the messaging client mqtt = mySystem.Messaging(preet) # Connecting... mqtt.connect() # coverting the data to string format ## change: no need to convert data to string str_data = str(data) # sending the data mqtt.publish("preetlaptop", str_data) ## Change: logging out the user
"battery_percent": batt[0], "secsleft": batt[1], "power_plugged": power } js = json.dumps(dic) return js SystemKey = "dce7d4cb0b80c1eec1bbbaa9a262" SystemSecret = "DCE7D4CB0BC2A092D3E1FFC3D831" mySystem = System(SystemKey, SystemSecret) email = "*****@*****.**" password = "******" jiang = mySystem.User(email, password) mqtt = mySystem.Messaging(jiang) def on_connect(client, userdata, flags, rc): # When we connect to the broker, start publishing our data to the keelhauled channel for i in range(10): payload = get_resource() print payload client.publish("jiang/info", payload) time.sleep(3) #Connect callback to client mqtt.on_connect = on_connect
import psutil, json, time from datetime import datetime from clearblade.ClearBladeCore import System def get_pc_state(): results = {} results["time"] = datetime.utcnow().isoformat() results["cpu_usage"] = psutil.cpu_percent(10) return json.dumps(results) # System credentials SYSTEM_KEY = "<your_system_key>" SYSTEM_SECRET = "<your_system_secrete>" pc_state_system = System(SYSTEM_KEY, SYSTEM_SECRET) adam = pc_state_system.User("<your_email>", "<your_password>") mqtt = pc_state_system.Messaging(adam) while True: pc_state = get_pc_state() mqtt.connect() mqtt.publish("pc_state", pc_state) mqtt.disconnect() time.sleep(900)
''' author @yash clearBlade MQTT Message Communicator March 9th, 2020 ''' # IMPORTS import psutil from clearblade.ClearBladeCore import System, Query, Developer import time # Setup system I created on the web console using credentials SystemKey = "8eedb6e60b8892f4e0e5d6fe8111" SystemSecret = "8EEDB6E60BFCD5B4E8A6F5E7E264" mySystem = System(SystemKey, SystemSecret) # Setup User yash = mySystem.User("*****@*****.**", "D00pamine!!") # Start messaging system mqtt = mySystem.Messaging(yash) # Connect mqtt.connect() # Test message for i in range(20): mqtt.publish("/test", psutil.cpu_percent()) mqtt.disconnect()
################################ ## Adapter time ## ################################ # Set up ZMQ publisher connection pub_context = zmq.Context() zmq_pub_sock = pub_context.socket(zmq.PUB) zmq_pub_sock.bind(zmq_bind_address) # Set up ZMQ subscriber connection sub_context = zmq.Context() zmq_sub_sock = sub_context.socket(zmq.SUB) # Set up MQTT connection zmq_system = System(system_key, system_secret, cb_url) zmq_user = zmq_system.User(email, password) mqtt = zmq_system.Messaging(zmq_user, client_id="zmq_tester") mqtt_connected = False # When we connect, subscribe to all topics in our subscriptions array def on_connect(client, userdata, flags, rc): global mqtt_connected mqtt_connected = True for topic in mqtt_incoming_subscriptions: client.subscribe(topic) # When we receive a message, forward it via ZMQ def on_message(client, userdata, message): zmq_message = "{}{}{}".format(message.topic, zmq_topic_delimiter,
import time import json import threading import psutil with open('../config/config.json', 'r') as f: config = json.load(f) print(config) #Configure SystemKey = config["SystemKey"] SystemSecret = config["SystemSecret"] mySystem = System(SystemKey, SystemSecret) email = config["email"] password = config["password"] akshat = mySystem.User(email, password) #Establish MQTT mqtt = mySystem.Messaging(akshat) mqtt.connect() #Send data every 3 second while (True): try: payload = { "ctx_switches": psutil.cpu_stats().ctx_switches, "processor_count": psutil.cpu_count(), # count keeps changing on linux and windows. "process_queue": psutil.getloadavg()[0], } # length of process queue.
cbLogs.DEBUG = False cbLogs.MQTT_DEBUG = False # my system credentials SystemKey = "e0b3f8e40ba4879dc5c7e2e7ce1b" SystemSecret = "E0B3F8E40BA4ADDCAAE4AFA7FB67" # instance of my system mySystem = System(SystemKey, SystemSecret) # Log in as Sulochan user = "******" userPass = "******" # user object of current session thisUserObject = mySystem.User(user, userPass) # MQTT object mqtt = mySystem.Messaging(thisUserObject) #what to do after connection def on_connect(client, userdata, flags, rc): #listen/subscribe to analytics topic client.subscribe("analytics") #what to do after receiving message def on_message(client, userdata, message): #display analytics received from the clearblade IoT code service print "Message received from SERVER: \n"; print "*****************************\n"; print message.payload
import json import ast import sys published = 0 rc = 1 print(sys.argv) url = "https://staging.clearblade.com" SystemKey = "a6c2e6d10bc2f183fca3c7d3d0fe01" SystemSecret = "A6C2E6D10BCADB819FABF8FCD94E" mySystem = System(SystemKey, SystemSecret, url, safe=False, sslVerify=True) user = mySystem.User("*****@*****.**", "password") print("Welcome User!") mqtt = mySystem.Messaging(user) def on_connect(client, userdata, flags, rc): client.subscribe("config") client.subscribe("send") client.subscribe("send/results") def on_message(client, userdata, message): if (message.topic == "config"): print("Config Message Received!")
import PIL import scipy import _pickle as cpickle import time from struct import * url = "http://*****:*****@clearblade.com", "ashokverma") print("\n HI\n") # Use Sanket to access a messaging client mqtt = mySystem.Messaging(sanket) imgcv = cv2.imread("./sample_img/sample_dog.jpg") print(imgcv.shape) final = imgcv.tostring() # Set up callback functions def on_connect(client, userdata, flags, rc): # When we connect to the broker, subscribe to the southernplayalisticadillacmuzik channel client.subscribe("config") client.subscribe("predict") client.subscribe("predict/results")
from clearblade.ClearBladeCore import System import time #System credentials SystemKey = "b4bab3e70baaaa8cae8397bff6be01" SystemSecret = "9CBFB3E70BC8D0D1F0C4EE8DA79501" mySystem = System(SystemKey,SystemSecret) #User credentials email = "*****@*****.**" password = "******" #Authenticating as username username = mySystem.User(email,password) #use username to message mqtt = mySystem.Messaging(username) def on_connect(client, userdata, flags, rc): # When we connect to the broker, subscribe to the analytics topic client.subscribe("analytics") def on_message(client, userdata, message): # When we receive a message, print it out print("Received message '" + message.payload.decode("utf-8") + "' on topic '" + message.topic + "'") # Connect callbacks to client mqtt.on_connect = on_connect mqtt.on_message = on_message mqtt.connect() while(True): time.sleep(1) # wait for messages
with open("train_params.json", 'r') as fp: train_params = json.load(fp) key = train_params["systemKey"] secret = train_params["systemSecret"] url = train_params["url"] collection = train_params["featureCol"] user = train_params["email"] pswd = train_params["password"] SystemKey = key SystemSecret = secret mySystem = System(SystemKey, SystemSecret, url=url) user = mySystem.User(user, pswd) myCol = mySystem.Collection(user, collectionName=collection) rows = myCol.getItems() featureDataset = collection + ".json" with open(featureDataset, 'w') as fp: json.dump(rows, fp, indent=2) myCol1 = mySystem.Collection(user, collectionName="TrainingFiles") rows = myCol1.getItems() os.system("mkdir myCode") files = rows[-1]
enterEmail = input("enter your email\n") enterPass = input("enter your password\n") break elif (answer == "n"): anon = mySystem.AnonUser() enterEmail = input("enter your email\n") enterPass = input("enter your password\n") newUser = mySystem.registerUser(anon, enterEmail, enterPass) break else: answer = input("wrong answer, input Y/n again.\n") email = enterEmail password = enterPass newUser = mySystem.User(email, password) #access the platform and generate a token mqtt = mySystem.Messaging( newUser) #use the token to access messaging on your account mqtt.connect() #connect to messaging client counter = 0 time.sleep(1) print("\nPlease press 'S' to start scanning your CPU average.") while True: try: if keyboard.is_pressed('s'): print("Scanning is about to start!") time.sleep(1) break except: break
from clearblade.ClearBladeCore import System import time import random # System credentials SystemKey = "9abbd2970baabf8aa6d2a9abcc47" SystemSecret = "9ABBD2970BA6AABFE6E8AEB8B14F" mySystem = System(SystemKey, SystemSecret) # Log in as Riswan Riswan = mySystem.User("*****@*****.**", "Ghana2020") # Use Riswan to access a messaging client mqtt = mySystem.Messaging(Riswan) # Set up callback functions def on_connect(client, userdata, flags, rc): # When we connect to the broker, subscribe to the CPU Usage topic client.subscribe("ComputerCPU-USAGE") def on_message(client, userdata, message): # When we receive a message, print it out and store it in a collection of dictionary print("Received message '" + message.payload + "' on topic '" + message.topic + "'") # Connect callbacks to client mqtt.on_connect = on_connect mqtt.on_message = on_message
# mySystem = System(SystemKey, SystemSecret, url, safe=False) SystemKey = "d4a68fb60becb78bcdb4ecdffd2c" SystemSecret = "D4A68FB60BD2DF8998A5EBC0E5EA01" mySystem = System(SystemKey, SystemSecret, safe=False) # Auth as anon # anon = mySystem.AnonUser() # Use the anon user to register Martin # martin = mySystem.registerUser("*****@*****.**", "ashokverma") # mySystem. sanket = mySystem.User("*****@*****.**", "password") print("\n HI\n") # Use Sanket to access a messaging client mqtt = mySystem.Messaging(sanket) # result # options = {"model": "cfg/yolo.cfg", "load": "bin/yolov2-tiny.weights", "threshold": 0.1} # tfnet = TFNet(options) imgcv = cv2.imread("./sample_img/sample_dog.jpg") # result = tfnet.return_predict(imgcv) # Set up callback functions def on_connect(client, userdata, flags, rc): # When we connect to the broker, subscribe to the southernplayalisticadillacmuzik channel client.subscribe("config")
logging.debug(json.dumps(CB_CONFIG)) if not CB_CONFIG['logCB']: logging.debug("Setting cbLogs.DEBUG to False") cbLogs.DEBUG = False if not CB_CONFIG['logMQTT']: logging.debug("Setting cbLogs.MQTT_DEBUG to False") cbLogs.MQTT_DEBUG = False EXITAPP = False CB_SYSTEM = System(CB_CONFIG['systemKey'], CB_CONFIG['systemSecret'], CB_CONFIG['platformURL'] + ":" + CB_CONFIG['httpPort']) logging.info("Authenticating") CBAUTH = CB_SYSTEM.User(CB_CONFIG['mqttUserID'], CB_CONFIG['mqttPassword']) logging.info("Auth Complete") #Connect to the message broker logging.info("Initializing the ClearBlade message broker") CB_MQTT = CB_SYSTEM.Messaging(CBAUTH) CB_MQTT.on_connect = on_connect CB_MQTT.on_message = on_adapterRequest CB_MQTT.on_disconnect = on_disconnect logging.info("Connecting to the ClearBlade message broker") CB_MQTT.connect() while not SCOPE_VARS['EXIT_APP']: try: pass except KeyboardInterrupt: SCOPE_VARS['EXIT_APP'] = True
""" factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor # System credentials SystemKey = "ce8dd0e50b8acd82fc969396be3f" SystemSecret = "CE8DD0E50BE0B183A7EDC89EA39001" mySystem = System(SystemKey, SystemSecret) # Log in as Sanket boren = mySystem.User("*****@*****.**", "19990219Zbr#") # Use Boren to access a messaging client mqtt = mySystem.Messaging(boren) #Connect mqtt.connect() #When i connect to the broker, start publishing sytem information to the update topic in a static 1s interval while (True): #Grab memory Information svmem = psutil.virtual_memory() swap = psutil.swap_memory() mem_total = f"{get_size(svmem.total)}" mem_available = f"{get_size(svmem.available)}"