class Subscriber(threading.Thread): """A threaded Subscriber object""" def __init__(self, endpoint, root_ca, key, cert, client_id=''): threading.Thread.__init__(self) self.endpoint = endpoint self.client_id = client_id self.root_ca = root_ca self.key = key self.cert = cert self._client = None self.finish = False self.daemon = True self.connected = False def connect(self): self._client = AWSIoTMQTTClient(self.client_id) self._client.configureEndpoint(self.endpoint, 8883) self._client.configureCredentials(self.root_ca, self.key, self.cert) self._client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self._client.configureConnectDisconnectTimeout(10) # 10 sec self._client.configureMQTTOperationTimeout(5) # 5 sec self.connected = self._client.connect() def subscribe(self, topic, callback, qos=1): if not self.connected: self.connect() self._client.subscribe(topic, qos, callback) def run(self): while not self.finish: time.sleep(0.001)
def heartbeat(config_file, topic, frequency=3): # read the config file cfg = GroupConfigFile(config_file) # determine heartbeat device's thing name and orient MQTT client to GG Core heartbeat_name = cfg['devices']['GGD_heartbeat']['thing_name'] mqttc = AWSIoTMQTTClient(heartbeat_name) mqttc.configureEndpoint(ggd_config.inv_arm_ip, ggd_config.inv_arm_port) mqttc.configureCredentials( CAFilePath=dir_path + "/" + ggd_ca_file_path, KeyPath=dir_path + "/certs/GGD_heartbeat.private.key", CertificatePath=dir_path + "/certs/GGD_heartbeat.certificate.pem.crt" ) mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST) if mqtt_connect(mqttc): # MQTT client has connected to GG Core, start heartbeat messages try: start = datetime.datetime.now() while True: hostname = socket.gethostname() now = datetime.datetime.now() msg = { "version": "2017-07-05", # YYYY-MM-DD "ggd_id": heartbeat_name, "hostname": hostname, "data": [ { "sensor_id": "heartbeat", "ts": now.isoformat(), "duration": str(now - start) } ] } print("[hb] publishing heartbeat msg: {0}".format(msg)) mqttc.publish(topic, json.dumps(msg), 0) time.sleep(random.random() * 10) except KeyboardInterrupt: log.info( "[__main__] KeyboardInterrupt ... exiting heartbeat") mqttc.disconnect() time.sleep(2) else: print("[hb] could not connect successfully via mqtt.")
class Client(): def __init__(self, iot_client=None, iot_data_client=None, credentials=None, ca_path=None, privkey_path=None, cert_path=None): assert ca_path, "Certificate is required" if not iot_client: iot_client = boto3.client('iot') if not iot_data_client: iot_data_client = boto3.client('iot-data') self.iot_client = iot_client self.iot_data_client = iot_data_client self.cert_path = cert_path self.privkey_path = privkey_path self.ca_path = ca_path self.credentials = credentials self.init_mqtt_client() def init_mqtt_client(self): endpoint = self.iot_client.describe_endpoint() use_websocket = True if self.credentials else False endpoint_port = 443 if use_websocket else 8883 self.mqtt_client = AWSIoTMQTTClient("testo", useWebsocket=use_websocket) self.mqtt_client.configureEndpoint(endpoint['endpointAddress'], endpoint_port) self.mqtt_client.configureOfflinePublishQueueing(-1) self.mqtt_client.configureConnectDisconnectTimeout(10) self.mqtt_client.configureMQTTOperationTimeout(10) self.configure_credentials() log.debug("OpenSSL version {}".format(ssl.OPENSSL_VERSION)) log.debug("Connecting MQTT client to {} on port {}...".format(endpoint['endpointAddress'], endpoint_port)) try: self.mqtt_client.connect() log.debug("MQTT client connected") except connectTimeoutException: log.error("Failed to connect MQTT client - timeout (check policy)") self.mqtt_client = None def configure_credentials(self): if self.credentials: self.mqtt_client.configureIAMCredentials(*(self.credentials.values())) self.mqtt_client.configureCredentials(self.ca_path) elif self.privkey_path and self.cert_path: log.debug("Using %s %s %s", str(self.ca_path), str(self.privkey_path), str(self.cert_path)) self.mqtt_client.configureCredentials(self.ca_path, self.privkey_path, self.cert_path) else: raise Exception("No credentials found")
class IOTCore: def __init__(self): config = {} # read the config file try: config_file = open('./config/aws-iot.json') # parse the content into dictionary config = json.loads(config_file.read()) except FileNotFoundError: print("file not found") raise # connect to iot try: self.client = AWSIoTMQTTClient(config["client"]) self.client.configureEndpoint(config["host"], config["port"]) self.client.configureCredentials(config["root-ca"], config["private-key"], config["certificate"]) self.client.connect() except KeyError: print("Key not found") raise except (exception.operationTimeoutException, exception.operationError) as err: print(err) raise except: print("unknown error") def publish(self, key, data): # publish data to iot try: self.client.publish(key, data, 0) except (exception.operationTimeoutException, exception.operationError) as err: print(err) raise except: print("unknown error") def disconnect(self): # disconnect from iot self.client.disconnect()
msg.payload, hostname='iot.eclipse.org') def paho_run(paho_client): paho_client.on_connect = paho_on_connect paho_client.on_message = paho_on_message paho_client.connect('iot.eclipse.org', 1883, 60) paho_client.loop_forever() #while True: # time.sleep(1.0) AWS_Client = AWSIoTMQTTClient("HP-Ireland-app2") endpoint = "a2mxpvymzj1qjd.iot.eu-west-1.amazonaws.com" AWS_Client.configureEndpoint(endpoint, 8883) root_ca = './keys/root-CA.crt' prvt_key = './keys/HP-Ireland.private.key' cert_pem = './keys/HP-Ireland.cert.pem' AWS_Client.configureCredentials(root_ca, prvt_key, cert_pem) AWS_Client.connect() #myMQTTClient.subscribe("AWS/Aarhus/traffic/alert", 0, customCallback) #myMQTTClient.subscribe("AWS/Aarhus/debug", 0, customCallback) #myMQTTClient.subscribe("AWS/Aarhus/info", 0, customCallback) AWS_Client.subscribe("AWS/Aarhus/#", 0, AWS_Callback) #myMQTTClient.subscribe("PI/DHT11", 0, customCallback) #AWS_Client.subscribe("$aws/things/PI_Ireland/shadow/#", 0, AWS_Callback) paho_client = paho.mqtt.client.Client() paho_thread = Thread(target=paho_run, args=(paho_client, ))
# Ratchet_Button Test Client import sys import ssl from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import json import time import random mqttc = AWSIoTMQTTClient("smartparking_EdgeGatewayDevice") mqttc.configureEndpoint("greengrass-ats.iot.us-west-2.amazonaws.com", 8883) mqttc.configureCredentials("./root.ca.pem", "./private.key", "./cert.pem") #Function to encode a payload into JSON def json_encode(string): return json.dumps(string) mqttc.json_encode = json_encode counter = 0 while True: message = { "timestamp": time.time(), "metrics": [{ "name": "sp-area1-sensor1/scan", "value": 1
class Client: client = None def __init__(self, client_id, end_point, root_ca, private_key, certificate): """ :param client_id: :param end_point: :param root_ca: :param private_key: :param certificate: """ self.client = AWSIoTMQTTClient(client_id) self.client.configureEndpoint(end_point, 8883) self.client.configureCredentials(root_ca, private_key, certificate) self.client.configureAutoReconnectBackoffTime(2, 32, 20) self.client.configureOfflinePublishQueueing(-1) self.client.configureDrainingFrequency(2) self.client.configureConnectDisconnectTimeout(10) self.client.configureMQTTOperationTimeout(5) def connect(self): """ 接続処理 :return: 結果(True:成功、False:失敗) """ return self.client.connect() def publish(self, topic, payload): """ Publish処理 :param topic: トピック名 :param payload: 送信データ :return: 結果(True:成功、False:失敗) """ return self.client.publish(topic, payload, 1) def subscribe(self, topic, cb): """ Subscribe処理 :param topic: トピック名 :param cb: コールバック関数 :return: 結果(True:成功、False:失敗) """ return self.client.subscribe(topic, 1, cb) def unsubscribe(self, topic): """ Unsubscribe処理 :param topic: トピック名 :return: 結果(True:成功、False:失敗) """ return self.client.unsubscribe(topic) def disconnect(self): """ 切断処理 :return: 結果(True:成功、False:失敗) """ return self.client.disconnect()
print(message.topic) print("--------------\n\n") host = "a3c16s480tb79n-ats.iot.us-east-1.amazonaws.com" rootCAPath = "rootca.pem" certificatePath = "certificate.pem.crt" privateKeyPath = "private.pem.key" my_rpi = AWSIoTMQTTClient("P1650688") my_rpi.configureEndpoint(host, 8883) my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath) my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz my_rpi.configureConnectDisconnectTimeout(10) # 10 sec my_rpi.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT my_rpi.connect() my_rpi.subscribe("sensors/light", 1, customCallback) sleep(2) # Publish to the same topic in a loop forever loopCount = 0 while True:
rideCymbal = Drum(173, 179, WHITE,[51,52,55,59],'rideCymbal') highHat = Drum(179, 184, GREEN,[42,46,44],'highHat') #crashCymbal = Drum(184, 191, GREEN) crash = Drum(184, 191, GREEN,[49,57],'crash') # Alternatively specify a hardware SPI connection on /dev/spidev0.0: SPI_PORT = 0 SPI_DEVICE = 0 pixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE), gpio=GPIO) # For certificate based connection myMQTTClient = AWSIoTMQTTClient("recordDrum") # For Websocket connection # myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True) # Configurations # For TLS mutual authentication myMQTTClient.configureEndpoint("a3lka4ud7kfmrw-ats.iot.us-east-1.amazonaws.com", 8883) # For Websocket # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443) # For TLS mutual authentication with TLS ALPN extension # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443) myMQTTClient.configureCredentials("/greengrass/certs/AmazonRootCA1.pem", "/greengrass/certs/6acf979319.private.key", "/greengrass/certs/6acf979319.cert.pem") # For Websocket, we only need to configure the root CA # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH") myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 s myMQTTClient.connect() topicValue = "/song/userHit" def blink_drums(pixels, drumList, sessionId = "none", voltageDict = {}, stageName = "Guest"):
class ProvisioningHandler: def __init__(self, file_path): """Initializes the provisioning handler Arguments: file_path {string} -- path to your configuration file """ # Logging logging.basicConfig(level=logging.ERROR) self.logger = logging.getLogger(__name__) # Load configuration settings from config.ini config = Config(file_path) self.config_parameters = config.get_section('SETTINGS') self.secure_cert_path = self.config_parameters['SECURE_CERT_PATH'] self.iot_endpoint = self.config_parameters['IOT_ENDPOINT'] self.template_name = self.config_parameters[ 'PROVISIONING_TEMPLATE_NAME'] self.claim_cert = self.certFullPath( self.config_parameters['CLAIM_CERT']) self.secure_key = self.certFullPath( self.config_parameters['SECURE_KEY']) self.root_cert = self.certFullPath(self.config_parameters['ROOT_CERT']) self.machine_config = self.config_parameters['MACHINE_CONFIG_PATH'] self.error = '' with open(self.machine_config) as json_file: data = json.load(json_file) self.serial_num = data['serial_num'] self.model_type = data['model_type'] # ------------------------------------------------------------------------------ # -- PROVISIONING HOOKS EXAMPLE -- # Provisioning Hooks are a powerful feature for fleet provisioning. Most of the # heavy lifting is performed within the cloud lambda. However, you can send # device attributes to be validated by the lambda. An example is show in the line # below (.hasValidAccount could be checked in the cloud against a database). # Alternatively, a serial number, geo-location, or any attribute could be sent. # # -- Note: This attribute is passed up as part of the register_thing method and # will be validated in your lambda's event data. # ------------------------------------------------------------------------------ if not os.path.exists(self.claim_cert): self.error = '### Bootstrap cert non-existent. Official cert may already be in place.' else: self.hasValidAccount = True self.primary_MQTTClient = AWSIoTMQTTClient( "fleet_provisioning_demo") self.primary_MQTTClient.onMessage = self.on_message_callback self.callback_returned = False self.message_payload = {} def certFullPath(self, cert): return "{}/{}".format(self.secure_cert_path, cert) def core_connect(self): """ Method used to connect to connect to AWS IoTCore Service. Endpoint collected from config. """ self.primary_MQTTClient.configureEndpoint(self.iot_endpoint, 8883) self.primary_MQTTClient.configureCredentials(self.root_cert, self.secure_key, self.claim_cert) self.primary_MQTTClient.configureOfflinePublishQueueing(-1) self.primary_MQTTClient.configureDrainingFrequency(2) self.primary_MQTTClient.configureConnectDisconnectTimeout(10) self.primary_MQTTClient.configureMQTTOperationTimeout(3) self.logger.info('##### CONNECTING WITH PROVISIONING CLAIM CERT #####') print('##### CONNECTING WITH PROVISIONING CLAIM CERT #####') self.primary_MQTTClient.connect() def enable_error_monitor(self): """ Subscribe to pertinent IoTCore topics that would emit errors """ self.primary_MQTTClient.subscribe( "$aws/provisioning-templates/{}/provision/json/rejected".format( self.template_name), 1, callback=self.basic_callback) self.primary_MQTTClient.subscribe( "$aws/certificates/create/json/rejected", 1, callback=self.basic_callback) def get_official_certs(self, callback): """ Initiates an async loop/call to kick off the provisioning flow. Triggers: on_message_callback() providing the certificate payload """ return asyncio.run(self.orchestrate_provisioning_flow(callback)) async def orchestrate_provisioning_flow(self, callback): # Connect to core with provision claim creds self.core_connect() # Monitor topics for errors self.enable_error_monitor() # Make a publish call to topic to get official certs self.primary_MQTTClient.publish("$aws/certificates/create/json", "{}", 0) # Wait the function return until all callbacks have returned # Returned denoted when callback flag is set in this class. while not self.callback_returned: await asyncio.sleep(0) return callback(self.message_payload) def on_message_callback(self, message): """ Callback Message handler responsible for workflow routing of msg responses from provisioning services. Arguments: message {string} -- The response message payload. """ json_data = json.loads(message.payload) # A response has been recieved from the service that contains certificate data. if 'certificateId' in json_data: self.logger.info('##### SUCCESS. SAVING KEYS TO DEVICE! #####') print('##### SUCCESS. SAVING KEYS TO DEVICE! #####') self.assemble_certificates(json_data) # A response contains acknowledgement that the provisioning template has been acted upon. elif 'deviceConfiguration' in json_data: self.logger.info( '##### CERT ACTIVATED AND THING {} CREATED #####'.format( json_data['thingName'])) print('##### CERT ACTIVATED AND THING {} CREATED #####'.format( json_data['thingName'])) self.rotate_certs() else: self.logger.info(json_data) def assemble_certificates(self, payload): """ Method takes the payload and constructs/saves the certificate and private key. Method uses existing AWS IoT Core naming convention. Arguments: payload {string} -- Certifiable certificate/key data. Returns: ownership_token {string} -- proof of ownership from certificate issuance activity. """ # Cert ID cert_id = payload['certificateId'] self.new_key_root = cert_id[0:10] self.new_cert_name = '{}-certificate.pem.crt'.format(self.new_key_root) # Create certificate f = open('{}/{}'.format(self.secure_cert_path, self.new_cert_name), 'w+') f.write(payload['certificatePem']) f.close() # Create private key self.new_key_name = '{}-private.pem.key'.format(self.new_key_root) f = open('{}/{}'.format(self.secure_cert_path, self.new_key_name), 'w+') f.write(payload['privateKey']) f.close() # Extract/return Ownership token self.ownership_token = payload['certificateOwnershipToken'] # register newly aquired cert self.register_thing(self.serial_num, self.ownership_token) def register_thing(self, serial, token): """Calls the fleet provisioning service responsible for acting upon instructions within device templates. Arguments: serial {string} -- unique identifer for the thing. Specified as a property in provisioning template. token {string} -- The token response from certificate creation to prove ownership/immediate possession of the certs. Triggers: on_message_callback() - providing acknowledgement that the provisioning template was processed. """ self.logger.info('##### CREATING THING ACTIVATING CERT #####') print('##### CREATING THING ACTIVATING CERT #####') register_template = { "certificateOwnershipToken": token, "parameters": { "SerialNumber": self.serial_num, "ModelType": self.model_type, "hasValidAccount": self.hasValidAccount } } # Register thing / activate certificate self.primary_MQTTClient.publish( "$aws/provisioning-templates/{}/provision/json".format( self.template_name), json.dumps(register_template), 0) def rotate_certs(self): """Responsible for (re)connecting to IoTCore with the newly provisioned/activated certificate - (first class citizen cert) """ self.logger.info('##### CONNECTING WITH OFFICIAL CERT #####') print('##### CONNECTING WITH OFFICIAL CERT #####') self.cert_validation_test() self.new_cert_pub_sub() print("##### ACTIVATED AND TESTED CREDENTIALS ({}, {}). #####".format( self.new_key_name, self.new_cert_name)) print("##### FILES SAVED TO {} #####".format(self.secure_cert_path)) self.remove_bootstrap_certs() print("##### REMOVED BOOTSTRAP CREDENTIALS #####".format( self.secure_cert_path)) def cert_validation_test(self): self.test_MQTTClient = AWSIoTMQTTClient(self.serial_num) self.test_MQTTClient.configureEndpoint(self.iot_endpoint, 8883) self.test_MQTTClient.configureCredentials( self.root_cert, self.certFullPath(self.new_key_name), self.certFullPath(self.new_cert_name)) # Infinite offline Publish queueing self.test_MQTTClient.configureOfflinePublishQueueing(-1) self.test_MQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.test_MQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.test_MQTTClient.configureMQTTOperationTimeout(3) # 5 sec self.test_MQTTClient.connect() def basic_callback(self, client, userdata, msg): """Method responding to the openworld publish attempt. Demonstrating a successful pub/sub with new certificate. """ self.logger.info(msg.payload.decode()) self.message_payload = msg.payload.decode() self.callback_returned = True def new_cert_pub_sub(self): """Method testing a call to the 'openworld' topic (which was specified in the policy for the new certificate) """ self.test_MQTTClient.subscribe("dt/{}/test".format(self.serial_num), 1, self.basic_callback) self.test_MQTTClient.publish( "dt/{}/test".format(self.serial_num), str({ "service_response": "##### YOUR INDIVIDUALIZED PRODUCTION CERTS HAVE BEEN SUCCESSFULLY ACTIVATED AND ADDED TO THE /certs FOLDER #####" }), 0) def remove_bootstrap_certs(self): try: os.remove("{}/bootstrap-private.pem.key".format( self.secure_cert_path)) os.remove("{}/bootstrap-certificate.pem.crt".format( self.secure_cert_path)) except OSError: pass
# Import SDK packages from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient # For certificate based connection myMQTTClient = AWSIoTMQTTClient("iotconsole-1566721259865-4") # For Websocket connection # myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True) # Configurations # For TLS mutual authentication myMQTTClient.configureEndpoint("**5asn11fe**-ats.iot.ap-south-1.amazonaws.com", 8883) # For Websocket # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443) # For TLS mutual authentication with TLS ALPN extension # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443) myMQTTClient.configureCredentials("CA.pem", "9ee8dcee7c-private.pem.key", "9ee8dcee7c-certificate.pem.crt") # For Websocket, we only need to configure the root CA # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH") myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myMQTTClient.connect() myMQTTClient.publish("myTopic", "myPayload", 0) myMQTTClient.subscribe("myTopic", 1, customCallback) #myMQTTClient.unsubscribe("myTopic") myMQTTClient.disconnect()
# Take reference to the following example: # https://docs.aws.amazon.com/iot/latest/developerguide/iot-moisture-raspi-setup.html # # Documentation for AWSIoTPythonSDK: # https://github.com/aws/aws-iot-device-sdk-python from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from .settings import * # Init AWSIoTMQTTClient aws_client = None aws_client = AWSIoTMQTTClient(CLIENT_ID) aws_client.configureEndpoint(HOST, PORT) aws_client.configureCredentials(ROOT_CA, KEY, CERT) # AWSIoTMQTTClient connection configuration aws_client.configureAutoReconnectBackoffTime(1, 32, 20) aws_client.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing aws_client.configureDrainingFrequency(2) # Draining: 2 Hz aws_client.configureConnectDisconnectTimeout(10) # 10 sec aws_client.configureMQTTOperationTimeout(5) # 5 sec
bz = Buzzer(5) # LCD display grants access lcd = LCD() displayDefaultMsg() host = str(configurationFile["dynamoDB_configuration"]["host"]) rootCAPath = str(configurationFile["dynamoDB_configuration"]["rootCAPath"]) certificatePath = str( configurationFile["dynamoDB_configuration"]["certificatePath"]) privateKeyPath = str( configurationFile["dynamoDB_configuration"]["privateKeyPath"]) try: my_rpi = AWSIoTMQTTClient( str(configurationFile["dynamoDB_configuration"]["Pub-Sub"])) my_rpi.configureEndpoint( host, int(configurationFile["dynamoDB_configuration"]["port"])) my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath) my_rpi.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz my_rpi.configureConnectDisconnectTimeout(10) # 10 sec my_rpi.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT my_rpi.connect() my_rpi.subscribe("ACNA2/MQTT_subscription", 1, customCallback) except Exception as e: print(e) print("Unable to connect AWS! Exiting code!") exit()
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import configparser import logging import random import time logging.basicConfig(format="%(asctime)s %(levelname)s [%(name)s] %(message)s", level=logging.INFO) #Load configuration from config.ini config = configparser.ConfigParser() config.read('config.ini') #Setup MQTT client and security certificates mqttc = AWSIoTMQTTClient("TemperatureSensor1_monitor") mqttc.configureEndpoint(config['Endpoints']['BJS_IOT_ENDPOINT'], int(config['Endpoints']['BJS_IOT_ENDPOINT_PORT'])) mqttc.configureCredentials(config['Certs']['ROOT_CA'], config['Certs']['TEMPERATURE_SENSOR_1_PRIVATE_KEY'], config['Certs']['TEMPERATURE_SENSOR_1_CERT']) #Connect to IoT Core mqttc.connect() logging.info('MQTT Client Connected to IoT Core') #Callback: MQTT Subscribe def mqtt_subscribe_callback(client, userdata, message): logging.info(f'Received message on topic {message.topic} :') logging.info(message.payload)
from DocClientUtils import prettifyBatch, readJson from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from RGB import RGB from Button import Button import time import socket import numpy as np import sys HOST = "192.168.43.186" TEMP_PORT = 8090 PRESS_PORT = 8091 duration = 30 myMQTTClient = AWSIoTMQTTClient("pi01") myMQTTClient.configureEndpoint( "a1x06kutqzbjah-ats.iot.us-east-1.amazonaws.com", 8883) myMQTTClient.configureCredentials( "Certificates/AmazonRootCA1.pem", "Certificates/900b9cf919-private.pem.key", "Certificates/900b9cf919-certificate.pem.crt") myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) with open("Information/Bioreactor.json", 'r') as fp: Bioreactor = json.load(fp) print(Bioreactor) TOPIC = "/%s/%s/%s" % (Bioreactor['Facility'].split("|")[0],
import RPi.GPIO as GPIO from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from time import sleep from datetime import date, datetime # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() # AWS IoT certificate based connection myMQTTClient = AWSIoTMQTTClient("123afhlss456") myMQTTClient.configureEndpoint("auf9cn18w1qbv.iot.us-east-2.amazonaws.com", 8883) myMQTTClient.configureCredentials("/home/pi/certs/root-CA.pem", "/home/pi/certs/4b4aef80d1-private.pem.key", "/home/pi/certs/4b4aef80d1-certificate.pem.crt") myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec #connect and publish myMQTTClient.connect() myMQTTClient.publish("homesec/cam", "connected", 0) #loop and publish sensor reading while 1: now = datetime.utcnow() now_str = now.strftime('%Y-%m-%dT%H:%M:%SZ') #e.g. 2016-04-18T06:12:25.877Z #instance = dht11.DHT11(pin = 4) #BCM GPIO04 #result = instance.read() #if result.is_valid(): payload = '{ "Date_and_time:": "' + now_str + '","Intruder": ' + "name to be replaced" + ' }'
#import motor_runner #import net_check from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient #https://cloudncode.blog/2017/11/07/make-your-first-iot-device-via-aws-iot-service-and-raspberry-pi/ def run_motor(self, params, packet): motor_runner.pulse(2) myMQTTClient.publish('$aws/things/RpiTest1/shadow/get', packet.payload, 0) myMQTTClient = AWSIoTMQTTClient( "raspberryPiHome" ) #random key, if another connection using the same key is opened the previous one is auto closed by AWS IOT myMQTTClient.configureEndpoint( "a3h6jjcgxk2mdj-ats.iot.ap-southeast-1.amazonaws.com", 8883) certRootPath = 'C:\\ProgApps\\Mosquitto\\Test\\aws-iot-device-sdk-python\\' myMQTTClient.configureCredentials( "{}rootCA.pem".format(certRootPath), "{}087ec6e9eb-private.pem.key".format(certRootPath), "{}087ec6e9eb-certificate.pem.crt".format(certRootPath)) myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myMQTTClient.connect() myMQTTClient.subscribe("$aws/things/RpiTest1/shadow/update", 1, run_motor)
CLIENT_NAME = "store-sensor-seattle1" TOPIC = "SeattleStoreTemp/1" # Broker path is under AWS IoT > Settings (at the bottom left) BROKER_PATH = "a2j1bxgczfkiaf-ats.iot.us-east-1.amazonaws.com" # RSA 2048 bit key: Amazon Root CA 1 found here: # https://docs.aws.amazon.com/iot/latest/developerguide/managing-device-certs.html # change with certificates downloaded ROOT_CA_PATH = './AmazonRootCA1.pem' PRIVATE_KEY_PATH = './326bd30940-private.pem.key' CERTIFICATE_PATH = './326bd30940-certificate.pem.crt' IoTclient = AWSIoTMQTTClient(CLIENT_NAME) IoTclient.configureEndpoint(BROKER_PATH, 8883) IoTclient.configureCredentials( ROOT_CA_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH ) # Allow the device to queue infinite messages IoTclient.configureOfflinePublishQueueing(-1) # Number of messages to send after a connection returns IoTclient.configureDrainingFrequency(1) # 1 requests/second # How long to wait for a [dis]connection to complete (in seconds) IoTclient.configureConnectDisconnectTimeout(10)
ESP32_MQTT_PASSWORD = '******' ESP32_MQTT_TOPIC = 'esp32/topic' #--------------------------------------------------------------------------------------------# AWS_MQTT_TOPIC_data = 'AWS_IoT/topic/data' AWS_MQTT_TOPIC_info = 'AWS_IoT/topic/info' #--------------------------------------------------------------------------------------------# #--------------------------------------------------------------------------------------------# # AWS IoT certificate based connection AWS_MQTTClient = AWSIoTMQTTClient("myClientID") # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 8883) AWS_MQTTClient.configureCredentials( "/home/pi/cert/Amazon_Root_CA_1.pem", "/home/pi/cert/61000fee35-private.pem.key", "/home/pi/cert/61000fee35-certificate.pem.crt") AWS_MQTTClient.configureEndpoint( "a2gztmlqjheqhq-ats.iot.us-east-1.amazonaws.com", 8883) AWS_MQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing AWS_MQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz AWS_MQTTClient.configureConnectDisconnectTimeout(10) # 10 sec AWS_MQTTClient.configureMQTTOperationTimeout(5) # 5 sec #--------------------------------------------------------------------------------------------# # The callback for when the client receives a CONNACK response from the server. def esp32_on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() - if we lose the connection and # reconnect then subscriptions will be renewed.
def get_iot_client(device_id, endpoint): client = AWSIoTMQTTClient(device_id, useWebsocket=True) client.configureEndpoint(endpoint, 443) client.configureCredentials('AmazonRootCA1.pem') return client
def aws_mqtt_node(): # init node rospy.init_node('aws_mqtt_node', anonymous=True) #, log_level=rospy.DEBUG) # load parameters params = rospy.get_param("~", {}) print(params) mqtt_params = params.pop("mqtt", {}) bridge_params = params.pop("bridge", {}) host = mqtt_params.pop("host", "") rootCAPath = mqtt_params.pop("rootCAPath", "") certificatePath = mqtt_params.pop("certificatePath", "") privateKeyPath = mqtt_params.pop("privateKeyPath", "") clientId = mqtt_params.pop("clientId", "") # Init AWSIoTMQTTClient myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, 8883) try: myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) except: raise IOError("Cannot load certificates...") else: # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing( 0) # -1:Infinite offline Publish queueing. 0:no queue myAWSIoTMQTTClient.configureDrainingFrequency(50) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # dependency injection config = create_config(myAWSIoTMQTTClient) inject.configure(config) # Connect to AWS IoT try: myAWSIoTMQTTClient.connect() except: raise IOError("Cannot connect to AWS IoT...") else: # configure bridges bridges = [] # setup publishing bridge bridges.append(create_publish_bridge()) # setup subscribing bridges for bridge_args in bridge_params: try: bridges.append(create_subscribe_bridge(**bridge_args)) except Exception, e: rospy.logerr(str(e)) rospy.logerr("Cannot subscribe to the topic %s" % (bridge_args.pop("topic_from", ""))) rospy.loginfo(rospy.get_caller_id() + " All settings are ready!") # spin() simply keeps python from exiting until this node is stopped for bridge in bridges: rospy.on_shutdown(bridge.on_shutdown) rospy.on_shutdown(myAWSIoTMQTTClient.disconnect) rospy.spin()
print("--------------\n\n") if message.topic == 'rebootCommandguyi': # execute the reboot function info = json.loads(message.payload) location = info['Location'] ip = info['ID'] ssh_reboot.sshAndReboot(ip, location).judgements() def offline(): print('aws iot is offline.') # Init AWSIoTMQTTClient device = AWSIoTMQTTClient(clientId) device.configureEndpoint(host, 80) device.configureCredentials(caPath, keyPath, certPath) # AWSIoTMQTTClient connection configuration device.configureAutoReconnectBackoffTime(1, 32, 20) device.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing device.configureDrainingFrequency(2) # Draining: 2 Hz device.configureConnectDisconnectTimeout(10) # 10 sec device.configureMQTTOperationTimeout(5) # 5 sec device.onOffline = offline # Connect and subscribe to AWS IoT try: print('AWS IoT connecting...') device.connect(1200) print('AWS IoT connected')
camera.hflip = True ###################### # #### Init S3 ####### ###################### s3Resource = boto3.resource('s3') s3Client = boto3.client('s3') # Init Rekognition rekClient = boto3.client('rekognition') # Init AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, 443) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, 8883) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient SETTINGS = { "client_name": "PeopleCounter_cogni", "https_endpoint": "some-endpoint.iot.us-east-1.amazonaws.com", "port": 8883, "root_cert": "certs.awsiot/VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem", "private_key": "certs.awsiot/some-id-private.pem.key", "thing_cert": "certs.awsiot/some-id-certificate.pem.crt" } client = AWSIoTMQTTClient(SETTINGS["client_name"]) client.configureEndpoint(SETTINGS["https_endpoint"], SETTINGS["port"]) client.configureCredentials(SETTINGS["root_cert"], SETTINGS["private_key"], SETTINGS["thing_cert"]) client.configureOfflinePublishQueueing(-1) client.configureDrainingFrequency(2) client.configureConnectDisconnectTimeout(10) client.configureMQTTOperationTimeout(5) client.connect() print("Yay!")
import time GREENGRASS_IP = "<your DeepLens's IP address>" logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.DEBUG) # Queue to receive the pictures from the DeepLens thumbnail_queue = queue.Queue() # For certificate based connection mqttClient = AWSIoTMQTTClient("trigger") # Configurations # For TLS mutual authentication mqttClient.configureEndpoint(GREENGRASS_IP, 8883) # Make sure your certificates and key names are the same as below mqttClient.configureCredentials("./certs/rootca.pem", "./certs/private.pem.key", "./certs/certificate.pem.crt") mqttClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing mqttClient.configureDrainingFrequency(2) # Draining: 2 Hz mqttClient.configureConnectDisconnectTimeout(5) # 5 sec mqttClient.configureMQTTOperationTimeout(5) # 5 sec def main(): try: connected = False logger.debug("Connecting")
class MQTTClient(PluginInterface): options = [ 'sensorid', 'topicid', 'topic_pfx', 'endpoint', 'rootca', 'prikey', 'devcert', 'batch', 'interval', 'fields', 'datafmt' ] topic_pfx = 'gravity' endpoint = None rootca = 'root-CA.crt' prikey = 'iot.private.key' devcert = 'iot.cert.pem' interval = 1 fields = ['gravity', 'long', 'cross', 'latitude', 'longitude', 'datetime'] datafmt = 'marine' # Ordered list of marine fields _marine_fieldmap = [ 'header', 'gravity', 'long', 'cross', 'beam', 'temp', 'pressure', 'etemp', 'vcc', 've', 'al', 'ax', 'status', 'checksum', 'latitude', 'longitude', 'speed', 'course', 'datetime' ] _airborne_fieldmap = [] # Defaults to integer cast if not specified here _field_casts = { 'header': str, 'gravity': float, 'latitude': float, 'longitude': float, 'speed': float, 'course': float, 'datetime': convert_time } def __init__(self): super().__init__() # Set AWSIoTPythonSDK logger level from default logging.getLogger('AWSIoTPythonSDK').setLevel(logging.WARNING) self.client = None self.tick = 0 self.sensorid = None self._errcount = 0 @classmethod def extract_fields(cls, data: str, fieldmap=_marine_fieldmap): extracted = {} data = data.split(',') for i, field in enumerate(fieldmap): if field.lower() in cls.fields: try: extracted[field] = cls._field_casts.get( field.lower(), int)(data[i]) except ValueError: extracted[field] = data[i] return extracted @staticmethod def consumer_type() -> set: return {str} # def _batch_process(self): # # TODO: Implement batch publish feature, perhaps collect items in a queue until a limit is reached # # then publish as a list of json maps # sendqueue = [] # limit = 10 def configure_client(self): if self.endpoint is None: raise ValueError("No endpoint provided for MQTT Plugin.") try: self.sensorid = getattr(self, 'sensorid', str(uuid4())[0:8]) topicid = getattr(self, 'topicid', self.sensorid) self.client = AWSIoTMQTTClient(self.sensorid, useWebsocket=False) self.client.configureEndpoint(self.endpoint, 8883) self.client.configureOfflinePublishQueueing(10000) self.client.configureConnectDisconnectTimeout(10) self.client.configureCredentials(join_cfg(self.rootca), join_cfg(self.prikey), join_cfg(self.devcert)) self.client.configureDrainingFrequency(2) self.client.configureMQTTOperationTimeout(5) self.client.connect() topic = '/'.join([self.topic_pfx, topicid]) except AttributeError: LOG.exception( "Missing attributes from configuration for MQTT plugin.") raise return topic def run(self): topic = self.configure_client() while not self.exiting: item = self.get(block=True, timeout=None) self.tick += 1 if item is None or item == "" or self.tick % self.interval: self.task_done() continue else: try: self.tick = 0 # reset tick count fields = item.split(',') timestamp = convert_time(fields[-1]) if not len(fields): continue data_dict = self.extract_fields(item) item_json = json.dumps({ 'd': self.sensorid, 't': timestamp, 'v': data_dict }) self.client.publish(topic, item_json, 0) self.task_done() except: LOG.exception( "Exception occured in mqtt-run loop. Item value: %s", item) self._errcount += 1 if self._errcount > 10: # Terminate MQTT if errors accumulate raise self.client.disconnect()
adc = Adafruit_ADS1x15.ADS1115() #ADC identification lastConnectionTime = time.time() lastUpdateTime = time.time() intialtime = time.time() recordingInterval = time.time() payload = [] messageBuffer = {} timesave = 0 lastupdate = 0 ident = 0 count = 0 myMQTTClient = AWSIoTMQTTClient("aws_thing1") myMQTTClient.configureEndpoint( "ase8a56yxgsqk.iot.us-east-2.amazonaws.com", 8883) #link to the amazon webservice client to recieve the information myMQTTClient.configureCredentials( "/home/pi/Downloads/connect_device_package/root-CA.crt", "/home/pi/Downloads/connect_device_package/aws_thing1.private.key", "/home/pi/Downloads/connect_device_package/aws_thing1.cert.pem" ) #location for certificate files and identification of raspberry pi myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) while 1: check = uf.internet_check()
#MQTT Istemci olusturma ve guvenlik sertifikalarini tanimlama #Sertifa isimleri ile AWS IoT Thing indirdiginiz sertifika isimlerinin ayni olmasina dikkat edin. currentPath = os.getcwd() roboName = os.path.basename(currentPath) latitude = 0 longtitude = 0 battery = 100 isBusy = 'false' ID = 10000 print("RoboName--> " + roboName) mqttClient = AWSIoTMQTTClient(roboName) #Ayarlar sayfasindaki IoTEndpoint buraya ekleyin mqttClient.configureEndpoint("ENDPOINT BURAYA KOPYALANACAK", 8883) mqttClient.configureCredentials("../root-CA.crt", "PrivateKey.pem", "certificate.pem.crt") #JSON formatina encode eden fonksiyon def toJSON(string): return json.dumps(string) mqttClient.toJSON = toJSON #Degiskenleri ve MQTT mesaji tanimlari message = { 'roboName': roboName, 'latitude': random.uniform(-90.0, +90.0),
import random import sys import ssl import uuid from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import urllib.request import time import datetime thingName = "ratchet-azer" mqttc = AWSIoTMQTTClient(thingName) #Make sure you use the correct region! mqttc.configureEndpoint("data.iot.us-east-1.amazonaws.com", 8883) mqttc.configureCredentials( "./rootCA.pem", "./ratchet-azer-privateKey.pem", "./ratchet-azer-certificate.pem") #Function to encode a payload into JSON def json_encode(string): return json.dumps(string) mqttc.json_encode = json_encode #Connect to the gateway mqttc.connect() print("Connected") # Function to get the randomvin def random_vin():
print("Received PUBACK packet id: ") print(mid) print("++++++++++++++\n\n") # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId2) myAWSIoTMQTTClient.configureEndpoint(endpoint, 8883) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 600, 300) myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(600) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myAWSIoTMQTTClient.onMessage = customOnMessage # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() # Note that we are not putting a message callback here. We are using the general message notification callback.
root_cert = '../aws-auth/AmazonRootCA1.pem' private_key = '../aws-auth/951ad5141e-private.pem.key' cert = '../aws-auth/951ad5141e-certificate.pem.crt' def sub_cb(self): camera.start_preview() sleep(1) camera.capture('/home/pi/Desktop/gx_folder/image.jpg') camera.stop_preview() aws_client.publish(self.pub_topic, "message_received", 0) ip_addr = 'a2ot5vs3yt7xtc-ats.iot.us-west-2.amazonaws.com' port = 8883 aws_client = AWSIoTMQTTClient("motion") aws_client.configureEndpoint(ip_addr, port) aws_client.configureCredentials(root_cert, private_key, cert) aws_client.configureAutoReconnectBackoffTime(1, 32, 20) aws_client.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing aws_client.configureDrainingFrequency(2) # Draining: 2 Hz aws_client.configureConnectDisconnectTimeout(10) # 10 sec aws_client.configureMQTTOperationTimeout(5) # 5 sec aws_client.connect() sub_topic = "pet-feeder/motion" pub_topic = "pet-feeder/test" aws_client.subscribe(sub_topic, 1, sub_cb)
# -*- coding:utf8 -*- from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient import os import time def customCallback(client, userdata, message): print('message: ') print(message.payload) print('topic: ') print(message.topic) print('--------------\n\n') myMQTTClient = AWSIoTMQTTClient('python') myMQTTClient.configureEndpoint(os.environ['AWSIOT_HOST'], 8883) myMQTTClient.configureCredentials('keys/G5.pem', 'keys/private.pem.key', 'keys/certificate.pem.crt') myMQTTClient.configureOfflinePublishQueueing(-1) myMQTTClient.configureDrainingFrequency(2) myMQTTClient.configureConnectDisconnectTimeout(10) myMQTTClient.configureMQTTOperationTimeout(5) myMQTTClient.connect() while True: myMQTTClient.subscribe("test", 1, customCallback) time.sleep(1)
ShadowClient.configureCredentials(get_rootca(), get_private(),get_cert()) ShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) ShadowClient.configureConnectDisconnectTimeout(30) # 10 sec ShadowClient.configureMQTTOperationTimeout(10) # 5 sec ShadowClient.connect() deviceShadowHandler = ShadowClient.createShadowHandlerWithName(devicename, True) #shadowCallbackContainer_Bot = shadowCallbackContainer(deviceShadowHandler) #deviceShadowHandler.shadowRegisterDeltaCallback(shadowCallbackContainer_Bot.customShadowCallback_Delta) # MQTT Connection establishement myMQTTClient = AWSIoTMQTTClient(devicename) myMQTTClient.configureEndpoint("a1oa9tg9lcso0.iot.eu-west-1.amazonaws.com", 8883) myMQTTClient.configureCredentials(get_rootca(), get_private(),get_cert()) myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec #connect and publish myMQTTClient.connect() con = psycopg2.connect("host='litterbugdb.c1ekrfqx70oj.eu-west-1.rds.amazonaws.com' dbname='littering' user='******' password='******'") cur = con.cursor() cur.execute("SELECT id FROM devices where mac_addr='%s'",[mac])
privateKeyPath = "./certs/DaizawaWattMeter.private.key" clientId = "basicPubSub" topic = "daizawattmeter" # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.INFO) streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Init AWSIoTMQTTClient myAWSIoTMQTTClient = None myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, 8883) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect() N = 60 i = 0 current_total = 0
print("Discovery failed after %d retries. Exiting...\n" % (MAX_DISCOVERY_RETRIES)) sys.exit(-1) # Iterate through all connection options for the core and use the first successful one myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath, certificatePath) myAWSIoTMQTTClient.onMessage = customOnMessage connected = False for connectivityInfo in coreInfo.connectivityInfoList: currentHost = connectivityInfo.host currentPort = connectivityInfo.port print("Trying to connect to core at %s:%d" % (currentHost, currentPort)) myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort) try: myAWSIoTMQTTClient.connect() connected = True break except BaseException as e: print("Error in connect!") print("Type: %s" % str(type(e))) if not connected: print("Cannot connect to core %s. Exiting..." % coreInfo.coreThingArn) sys.exit(-2) loopCount = 0 while True: message = {}
class ElfThread(threading.Thread): """ The abstract thread that sets up interaction with AWS IoT Things """ def __init__(self, thing_name, cli, thing, cfg, args=(), kwargs={}): super(ElfThread, self).__init__( name=thing_name, args=args, kwargs=kwargs ) self.thing_name = thing_name self.thing = thing self.root_cert = cli.root_cert self.topic = '{0}/{1}'.format(cli.topic, self.thing_name) self.region = cli.region self.cfg = cfg self.duration = cli.duration self.aws_iot = _get_iot_session(self.region, cli.profile_name) self.message_qos = cli.qos if policy_name_key not in thing.keys(): policy_name, policy_arn = _create_and_attach_policy( self.region, self.topic, self.thing_name, self.thing['certificateArn'], cli ) self.policy_name = policy_name self.policy_arn = policy_arn log.debug("[elf_thread] attached policy on cert:{0}".format( thing['certificateArn'])) else: log.debug("[elf_thread] policy_name:{0} exists.".format( policy_name_key)) self.policy_name = thing[policy_name_key] self.policy_arn = thing[policy_arn_key] # setup MQTT client elf_id = uuid.UUID(cfg[elf_id_key]) # use ELF ID and a random string since we must use unique Client ID per # client. cid = elf_id.urn.split(":")[2] + "_" + make_string(3) self.mqttc = AWSIoTMQTTClient(clientID=cid) t_name = cfg_dir + thing_name_template.format(0) endpoint = self.aws_iot.describe_endpoint() log.info("ELF connecting asynchronously to IoT endpoint:'{0}'".format( endpoint['endpointAddress'])) self.mqttc.configureEndpoint( hostName=endpoint['endpointAddress'], portNumber=AWS_IOT_MQTT_PORT ) self.mqttc.configureCredentials( CAFilePath=self.root_cert, KeyPath=t_name + ".prv", CertificatePath=t_name + ".pem" ) self.mqttc.configureAutoReconnectBackoffTime(1, 128, 20) self.mqttc.configureOfflinePublishQueueing(90, DROP_OLDEST) self.mqttc.configureDrainingFrequency(3) self.mqttc.configureConnectDisconnectTimeout(20) self.mqttc.configureMQTTOperationTimeout(5) self.mqttc.connect() # keepalive default at 30 seconds
if not discovered: print("Discovery failed after %d retries. Exiting...\n" % (MAX_DISCOVERY_RETRIES)) sys.exit(-1) # Iterate through all connection options for the core and use the first successful one myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath, certificatePath) myAWSIoTMQTTClient.onMessage = customOnMessage connected = False for connectivityInfo in coreInfo.connectivityInfoList: currentHost = connectivityInfo.host currentPort = connectivityInfo.port print("Trying to connect to core at %s:%d" % (currentHost, currentPort)) myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort) try: myAWSIoTMQTTClient.connect() connected = True break except BaseException as e: print("Error in connect!") print("Type: %s" % str(type(e))) print("Error message: %s" % e.message) if not connected: print("Cannot connect to core %s. Exiting..." % coreInfo.coreThingArn) sys.exit(-2) # Successfully connected to the core if args.mode == 'both' or args.mode == 'subscribe':
port = 8883 # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Init AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
if not args.useWebsocket and not args.port: # When no port override for non-WebSocket, default to 8883 port = 8883 # Configure logging logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) # Init AWSIoTMQTTClient myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTClient connection configuration myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT myAWSIoTMQTTClient.connect()
from xbgw.command.rci import RCICommandProcessor from xbgw.settings import SettingsRegistry, SettingsMixin, Setting from xbgw.debug.echo import EchoCommand from ConfigParser import SafeConfigParser try: from build import version except ImportError: version = "None" SETTINGS_FILE = "xbgw_settings.json" PID_FILE = "xbgw.pid" awsClient = AWSIoTMQTTClient("connectport") awsClient.configureEndpoint("a2uxgca99ev3iu-ats.iot.us-west-2.amazonaws.com", 8883) awsClient.configureCredentials( "/userfs/WEB/python/certs/AmazonRootCA1.pem", "/userfs/WEB/python/certs/965e2a8102-private.pem.key", "/userfs/WEB/python/certs/965e2a8102-certificate.pem.crt") awsClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing awsClient.configureDrainingFrequency(2) # Draining: 2 Hz awsClient.configureConnectDisconnectTimeout(10) # 10 sec awsClient.configureMQTTOperationTimeout(5) # 5 sec awsClient.connect() #ROUTER_ID_ARRAY = [("[0005]!"), ("[00:13:a2:00:41:93:b7:a8]!"), ("[00:13:a2:00:41:93:b8:88]!"), ("[00:13:a2:00:41:93:b8:81]!"), ("[00:13:a2:00:41:93:b8:96]!"), ("[00:13:a2:00:41:93:b8:c4]!"), ("[00:13:a2:00:41:93:b7:b7]!"), ("[00:13:a2:00:41:93:b7:a5]!"), ("[00:13:a2:00:41:93:b7:c0]!"), ("[00:13:a2:00:41:93:b8:db]!"), ("[00:13:a2:00:41:93:b9:23]!"), ("[00:13:a2:00:41:93:b7:a2]!"), ("[00:13:a2:00:41:93:b8:ed]!"), ("[00:13:a2:00:41:93:b7:84]!"), ("[00:13:a2:00:41:93:b8:74]!"), ("[00:13:a2:00:41:93:b7:9f]!")]; #ROOM_ID_ARRAY = [("Main"),("AWSTest10"),("AWSTest11"),("AWSTest12"),("AWSTest13"),("AWSTest14"),("AWSTest15"),("AWSTest16"),("AWSTest17"),("AWSTest18"),("AWSTest19"),("AWSTest20"), ("AWSTest21"), ("AWSTest22"), ("AWSTest23"), ("AWSTest24")]; #NumNodes = 16;