def main(): gateway = TBGatewayMqttClient("127.0.0.1", "TEST_GATEWAY_TOKEN") gateway.connect() gateway.gw_connect_device("Example Name") # device disconnecting will not delete device, gateway just stops receiving messages gateway.gw_disconnect_device("Example Name") gateway.disconnect()
def __init__(self, token, host='mindcloud.mindlabs.cl', certificate_path = "certificado.pem", port = 8883): self.host = host self.port = port self.certificate_path = certificate_path self.gateway = TBGatewayMqttClient(host, token) self.gateway.connect(tls=True, ca_certs = certificate_path, port = port)
def stand(self): from tb_gateway_mqtt import TBGatewayMqttClient self.agent.on("sensor-data", self.on_sensor_data) self.host = self.get_config("host") self.token = self.get_config("token") self.info("Initializing ThingsBoardPublisher to [{}]".format( self.host)) self.client = TBGatewayMqttClient(self.host, self.token) super().stand()
def main(): client = TBGatewayMqttClient(THINGSBOARD_HOST, GATEWAY_ACCESS_TOKEN) client.connect() """ You are able to provide every parameter or pass claiming request like: request_example = { "DEVICE A": { "secretKey": "DEVICE_A_SECRET_KEY", "durationMs": "30000" }, "DEVICE B": { "secretKey": "DEVICE_B_SECRET_KEY", "durationMs": "60000" } info = client.gw_claim(claiming_request=request_example).wait_for_publish() """ client.gw_connect_device(DEVICE_NAME) info = client.gw_claim(device_name=DEVICE_NAME, secret_key=SECRET_KEY, duration=DURATION) info.wait_for_publish() if info.rc == 0: print("Claiming request was sent.") client.stop()
def main(): gateway = TBGatewayMqttClient("127.0.0.1", "TEST_GATEWAY_TOKEN") gateway.connect() # now rpc_request_response will process rpc requests from servers gateway.gw_set_server_side_rpc_request_handler(rpc_request_response) # without device connection it is impossible to get any messages gateway.gw_connect_device("Test Device A2", "default") while not gateway.stopped: time.sleep(1)
def main(): gateway = TBGatewayMqttClient("127.0.0.1", "TEST_GATEWAY_TOKEN") gateway.connect() gateway.gw_request_shared_attributes("Example Name", ["temperature"], callback) while not gateway.stopped: time.sleep(1)
class GatewayUploader(): def __init__(self, token, host='mindcloud.mindlabs.cl', certificate_path = "certificado.pem", port = 8883): self.host = host self.port = port self.certificate_path = certificate_path self.gateway = TBGatewayMqttClient(host, token) self.gateway.connect(tls=True, ca_certs = certificate_path, port = port) def send_message(self, device_name, data): self.gateway.gw_connect_device(device_name) result = self.gateway.gw_send_telemetry(device_name, data) print(result) success = result.get() == TBPublishInfo.TB_ERR_SUCCESS print(success) self.gateway.gw_disconnect_device(device_name) print("desconectando") def close_connection(self): self.gateway.disconnect()
class ThingsBoardPublisher(Module): # dependencies = ["tb-mqtt-client"] logger = logging.getLogger("raula.thingsboard") client = None def stand(self): from tb_gateway_mqtt import TBGatewayMqttClient self.agent.on("sensor-data", self.on_sensor_data) self.host = self.get_config("host") self.token = self.get_config("token") self.info("Initializing ThingsBoardPublisher to [{}]".format( self.host)) self.client = TBGatewayMqttClient(self.host, self.token) super().stand() def skid(self): self.client.disconnect() super().skid() def on_sensor_data(self, event, sensor): import time from tb_device_mqtt import TBDeviceMqttClient, TBPublishInfo from tb_gateway_mqtt import TBGatewayMqttClient self.debug("Publishing telemetry to thingsboard") try: device_id = sensor.guid self.client.connect() self.client.gw_connect_device(device_id) self.debug("Connected to thingsboard [{}] as [{}]".format( self.host, device_id)) telemetry = {"ts": int(round(time.time() * 1000)), "values": event} success = self.client != None if (success): result = self.client.gw_send_telemetry(device_id, telemetry) # get is a blocking call that awaits delivery status success = result.get() == TBPublishInfo.TB_ERR_SUCCESS self.logger.debug( "Publish to ThingsBoard [successs ? {}]".format(success)) except: self.error("Failed to connect to thingsboard [{}]".format( self.host), exc_info=True)
def run_ble_adapter(): parser = argparse.ArgumentParser() parser.add_argument("-s", "--server", default="localhost", help="server address, default \"localhost\"") parser.add_argument("-p", "--port", type=int, default=1883, help="mqtt port, default 1883") required = parser.add_argument_group("required arguments") required.add_argument("-t", "--token", required=True, help="access token") args = parser.parse_args() # Load extensions for interacting with devices for extension in extensions.registered_extensions: print("Loading '", extension.ble_name(), "' extension...") known_devices[extension.ble_name()] = { "desription": extension.description(), "extension": extension, "scanned": {} } rescan_required = True def on_server_side_rpc_request(request_id, request_body): print("Received TB RPC call", request_body) if request_body["method"] == "doRescan": print("Scheduling rescan") global rescan_required rescan_required = True gateway = TBGatewayMqttClient(args.server, args.token) gateway.set_server_side_rpc_request_handler(on_server_side_rpc_request) gateway.connect(port=args.port) while True: if rescan_required: ble_rescan(gateway) rescan_required = False for type, type_data in known_devices.items(): for dev_addr, dev_data in type_data["scanned"].items(): try: instance = dev_data["inst"] ble_periph = dev_data["periph"] tb_dev_name = dev_data["tb_name"] telemetry = {} print("Connecting to device:", tb_dev_name) ble_periph.connect(dev_addr, "public") if instance.notify_supported(): if instance.notify_started() == False: instance.start_notify(ble_periph) class NotiDelegate(DefaultDelegate): def __init__(self): DefaultDelegate.__init__(self) self.dev_instance = instance self.telemetry = {} def handleNotification(self, handle, data): print("Received notifications for handle:", handle) self.telemetry = self.dev_instance.handle_notify(handle, data) print("Getting notification from:", tb_dev_name) deleagate = NotiDelegate() ble_periph.withDelegate(deleagate) if ble_periph.waitForNotifications(1): print("Data received:", deleagate.telemetry) telemetry.update(deleagate.telemetry) print("Polling data from:", tb_dev_name) poll_telemetry = instance.poll(ble_periph) print("Data received:", poll_telemetry) telemetry.update(poll_telemetry) if not telemetry: print("No data to send for current device") continue gateway_pkt = { "ts": int(round(time.time() * 1000)), "values" : telemetry } print("Sending data to TB:", gateway_pkt) gateway.gw_connect_device(tb_dev_name) gateway.gw_send_telemetry(tb_dev_name, gateway_pkt) gateway.gw_disconnect_device(tb_dev_name) except KeyboardInterrupt: print("Exiting the application") sys.exit() except Exception as e: print("Exception caught:", e) finally: print("Disconnecting from device") ble_periph.disconnect() time.sleep(1)
import logging from tb_gateway_mqtt import TBGatewayMqttClient logging.basicConfig(level=logging.DEBUG) gateway = TBGatewayMqttClient("127.0.0.1", "TEST_GATEWAY_TOKEN") gateway.connect() gateway.gw_connect_device("Example Name") # device disconnecting will not delete device, gateway just stops receiving messages gateway.gw_disconnect_device("Example Name") gateway.disconnect()
import psutil logging.basicConfig(level=logging.DEBUG) def rpc_request_response(request_body): # request body contains id, method and other parameters print(request_body) method = request_body["data"]["method"] device = request_body["device"] req_id = request_body["data"]["id"] # dependently of request method we send different data back if method == 'getCPULoad': gateway.gw_send_rpc_reply(device, req_id, {"CPU load": psutil.cpu_percent()}) elif method == 'getMemoryLoad': gateway.gw_send_rpc_reply(device, req_id, {"Memory": psutil.virtual_memory().percent}) else: print('Unknown method: ' + method) gateway = TBGatewayMqttClient("127.0.0.1", "TEST_GATEWAY_TOKEN") gateway.connect() # now rpc_request_response will process rpc requests from servers gateway.gw_set_server_side_rpc_request_handler(rpc_request_response) # without device connection it is impossible to get any messages gateway.gw_connect_device("Test Device A2") while True: time.sleep(1)
"extension": extension_class, "scanned": {} } rescan_required = True def on_server_side_rpc_request(request_id, request_body): print("Received TB RPC call", request_body) if request_body["method"] == "doRescan": print("Scheduling rescan") global rescan_required rescan_required = True gateway = TBGatewayMqttClient(args.server, args.token) gateway.set_server_side_rpc_request_handler(on_server_side_rpc_request) gateway.connect(port=args.port) while True: if rescan_required: ble_rescan(gateway) rescan_required = False for type, type_data in known_devices.items(): for dev_addr, dev_data in type_data["scanned"].items(): try: instance = dev_data["inst"] ble_periph = dev_data["periph"] tb_dev_name = dev_data["tb_name"]
logging.basicConfig(level=logging.DEBUG) def callback(result): print("Callback for attributes, {0}".format(result)) def callback_for_everything(result): print("Everything goes here, {0}".format(result)) def callback_for_specific_attr(result): print("Specific attribute callback, {0}".format(result)) gateway = TBGatewayMqttClient("127.0.0.1", "SGxDCjGxUUnm5ZJOnYHh") gateway.connect() # without device connection it is impossible to get any messages gateway.gw_connect_device("Test Device A2") gateway.gw_subscribe_to_all_attributes(callback_for_everything) gateway.gw_subscribe_to_attribute("Test Device A2", "temperature", callback_for_specific_attr) sub_id = gateway.gw_subscribe_to_all_device_attributes("Test Device A2", callback) gateway.gw_unsubscribe(sub_id) while True: time.sleep(1)
import logging from tb_gateway_mqtt import TBGatewayMqttClient import socket logging.basicConfig(level=logging.DEBUG) # connecting to localhost gateway = TBGatewayMqttClient(socket.gethostname()) gateway.connect(tls=True, ca_certs="mqttserver.pub.pem", cert_file="mqttclient.nopass.pem") gateway.disconnect()
def main(): gateway = TBGatewayMqttClient("127.0.0.1", "TEST_GATEWAY_TOKEN") # without device connection it is impossible to get any messages gateway.connect() gateway.gw_connect_device("Test Device A2") gateway.gw_send_telemetry("Test Device A2", telemetry_simple) gateway.gw_send_telemetry("Test Device A2", telemetry_array) gateway.gw_send_attributes("Test Device A2", attributes) gateway.stop()
import logging import time from tb_gateway_mqtt import TBGatewayMqttClient logging.basicConfig(level=logging.DEBUG) def callback(result, exception): if exception is not None: print("Exception: " + str(exception)) else: print(result) gateway = TBGatewayMqttClient("127.0.0.1", "SGxDCjGxUUnm5ZJOnYHh") gateway.connect() gateway.gw_request_shared_attributes("Example Name", ["temperature"], callback) while True: time.sleep(1)
def main(): gateway = TBGatewayMqttClient("127.0.0.1", "TEST_GATEWAY_TOKEN") gateway.connect() # without device connection it is impossible to get any messages gateway.gw_connect_device("Test Device A2") gateway.gw_subscribe_to_all_attributes(callback_for_everything) gateway.gw_subscribe_to_attribute("Test Device A2", "temperature", callback_for_specific_attr) sub_id = gateway.gw_subscribe_to_all_device_attributes( "Test Device A2", callback) gateway.gw_unsubscribe(sub_id) while True: time.sleep(1)