def connect(self): self.log.info('init(): connecting to AWS Shadow') self.client = AWSIoTMQTTShadowClient("iota") self.client.configureEndpoint(self.thingEndpoint, 8883) self.client.configureCredentials(*self.credentialFiles) self.client.configureConnectDisconnectTimeout(10) # 10 sec self.client.configureMQTTOperationTimeout(5) # 5 sec self.client.connect() self.log.info('init(): connected to AWS Shadow')
def test_awsiotmqtt_shadow_client_connect(mock_connect, mock_disconnect): client = AWSIoTMQTTShadowClient("myClientID", useWebsocket=False, hostName="YOUR.ENDPOINT", portNumber=8883) with client: client.createShadowHandlerWithName("Bot", True) mock_connect.assert_called_once_with(600) mock_disconnect.assert_called_once_with()
def createIoTShadowClient(endpoint, thingname, keyPath, certPath, rootCaPath): # For certificate based connection myShadowClient = AWSIoTMQTTShadowClient(thingname) # Configurations # For TLS mutual authentication myShadowClient.configureEndpoint(endpoint, config.aws_iot_port()) myShadowClient.configureCredentials(rootCaPath, keyPath, certPath) myShadowClient.configureConnectDisconnectTimeout(10) myShadowClient.configureMQTTOperationTimeout(5) return myShadowClient
def __init__(self, host, rootCAPath, certificatePath, privateKeyPath, thingName, clientId, useWebsocket=False): self.host = host self.rootCAPath = rootCAPath self.certificatePath = certificatePath self.privateKeyPath = privateKeyPath self.useWebsocket = useWebsocket self.thingName = thingName self.clientId = clientId if useWebsocket and certificatePath and privateKeyPath: print("X.509 cert authentication and WebSocket are mutual exclusive. Please pick one.") exit(2) if not useWebsocket and (not certificatePath or not privateKeyPath): print("Missing credentials for authentication.") exit(2) # 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 AWSIoTMQTTShadowClient self.myAWSIoTMQTTShadowClient = None if useWebsocket: self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True) self.myAWSIoTMQTTShadowClient.configureEndpoint(host, 443) self.myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath) else: self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId) self.myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883) self.myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTShadowClient configuration self.myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT self.myAWSIoTMQTTShadowClient.connect() # Create a deviceShadow with persistent subscription self.deviceShadowHandler = self.myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True) self.shadowCallbackContainer_Bot = ShadowCallbackContainer(self.deviceShadowHandler) # Listen on deltas self.deviceShadowHandler.shadowRegisterDeltaCallback(self.shadowCallbackContainer_Bot.customShadowCallbackDelta) # Create the initial State self._desired_state = {} self._reported_state = {} self._devices = []
def __init__(self, main): self.main = main self.iot_details = {} self.thing_name = 'BarBot' self.disabled = False #TODO: load this from the settings file schedule.every(30).seconds.do(self.ping) alive_thread = threading.Thread(target=self.keep_alive, daemon=True) alive_thread.start() if not path.exists('./certs/iotDetails.json'): self.disabled = True print('IoT files don\'t exist') return #Load AWS IoT Core details from json file with open('./certs/iotDetails.json', 'r') as file: self.iot_details = json.load(file) self.mqtt_client = AWSIoTMQTTClient('barbot') self.mqtt_client.configureEndpoint(self.iot_details['endpoint'], 8883) self.mqtt_client.configureCredentials( './certs/root-CA.crt', './certs/BarBot-private.pem.key', './certs/BarBot-certificate.pem.crt') self.mqtt_client.configureOfflinePublishQueueing(-1) self.mqtt_client.configureDrainingFrequency(2) self.mqtt_client.configureConnectDisconnectTimeout(15) self.mqtt_client.configureMQTTOperationTimeout(5) try: self.mqtt_client.connect() self.mqtt_client.subscribe('barbot-main', 0, self.parse_message) print('Connected to AWS IoT Core!') #Setup Shadow handler self.shadow_client = AWSIoTMQTTShadowClient('barbot-shadow') self.shadow_client.configureEndpoint(self.iot_details['endpoint'], 8883) self.shadow_client.configureCredentials( './certs/root-CA.crt', './certs/BarBot-private.pem.key', './certs/BarBot-certificate.pem.crt') self.shadow_client.configureAutoReconnectBackoffTime(1, 32, 20) self.shadow_client.configureConnectDisconnectTimeout(10) self.shadow_client.configureMQTTOperationTimeout(5) self.shadow_client.connect() print("Connected to BarBot's IoT Shadow") self.shadow_handler = self.shadow_client.createShadowHandlerWithName( self.thing_name, True) except Exception as e: print(e) self.disabled = True
def __init__(self, certDir, logLevel=logging.WARNING, clientID=None): if clientID == None: clientID = platform.node() + '.' + str(os.getpid()) self.clientID = clientID self.client = AWSIoTMQTTShadowClient(clientID) self.configureLogging(logLevel) self.configureConnection(certDir)
def local_shadow_connect(device_name, config_file, root_ca, certificate, private_key, group_ca_dir): cfg = GroupConfigFile(config_file) ggd_name = cfg['devices'][device_name]['thing_name'] iot_endpoint = cfg['misc']['iot_endpoint'] dip = DiscoveryInfoProvider() dip.configureEndpoint(iot_endpoint) dip.configureCredentials( caPath=root_ca, certPath=certificate, keyPath=private_key ) dip.configureTimeout(10) # 10 sec logging.info( "[shadow_connect] Discovery using CA:{0} cert:{1} prv_key:{2}".format( root_ca, certificate, private_key )) gg_core, discovery_info = discover_configured_core( config_file=config_file, dip=dip, device_name=ggd_name, ) if not gg_core: raise EnvironmentError("[core_connect] Couldn't find the Core") ca_list = discovery_info.getAllCas() core_list = discovery_info.getAllCores() group_id, ca = ca_list[0] core_info = core_list[0] logging.info("Discovered Greengrass Core:{0} from Group:{1}".format( core_info.coreThingArn, group_id) ) group_ca_file = save_group_ca(ca, group_ca_dir, group_id) # local Greengrass Core discovered # get a shadow client to receive commands mqttsc = AWSIoTMQTTShadowClient(ggd_name) # now connect to Core from this Device logging.info("[core_connect] gca_file:{0} cert:{1}".format( group_ca_file, certificate)) mqttsc.configureCredentials(group_ca_file, private_key, certificate) mqttc = mqttsc.getMQTTConnection() mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST) if not mqtt_connect(mqttsc, gg_core): raise EnvironmentError("connection to Master Shadow failed.") # create and register the shadow handler on delta topics for commands # with a persistent connection to the Master shadow master_shadow = mqttsc.createShadowHandlerWithName( cfg['misc']['master_shadow_name'], True) return mqttc, mqttsc, master_shadow, ggd_name
def configure_shadow_client(self): self.mqtt_shadow_client = AWSIoTMQTTShadowClient(self.device_name) self.mqtt_shadow_client.configureEndpoint(self.ggc_host_addr, 8883) # noqa: E501 self.mqtt_shadow_client.configureCredentials(self.root_ca_path, self.private_key_path, self.cert_path) # AWSIoTMQTTShadowClient configuration self.mqtt_shadow_client.configureAutoReconnectBackoffTime( 1, 32, 20) # noqa: E501 self.mqtt_shadow_client.configureConnectDisconnectTimeout(10) self.mqtt_shadow_client.configureMQTTOperationTimeout(5) self.mqtt_shadow_client.connect()
def __init__(self, thingName, iotEndpoint, rootCA=rootCA, privateKey=privateKey, certFile=certFile): self.rootCA = rootCA self.privateKey = privateKey self.certFile = certFile self.iotEndpoint = iotEndpoint self.thingName = thingName self.shadowClient = AWSIoTMQTTShadowClient(self.thingName) self.deviceShadow = None self.mqttClient = None self.connect()
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 = AWSIoTMQTTShadowClient(client_id) self.client.configureEndpoint(end_point, 8883) self.client.configureCredentials(root_ca, private_key, certificate) self.client.configureAutoReconnectBackoffTime(2, 32, 20) self.client.configureConnectDisconnectTimeout(10) # 10 sec self.client.configureMQTTOperationTimeout(5) # 5 sec
def connectMQTT(self): self.myShadowClient = AWSIoTMQTTShadowClient("thermo") #self.myAWSIoTMQTTClient = AWSIoTMQTTClient("thermo") self.myShadowClient.configureEndpoint(self.host, 8883) self.myShadowClient.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath) # myShadowClient connection configuration self.myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myShadowClient.connect() self.myAWSIoTMQTTClient = self.myShadowClient.getMQTTConnection() self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT #self.myAWSIoTMQTTClient.connect() # myAWSIoTMQTTClient.subscribe("thermo", 1, customCallback) # self.myAWSIoTMQTTClient.publish("thermo", "[[\'"+(strftime(DATE_FORMAT,localtime())+"\','TT','START','1']]", 1) # Create a device shadow instance using persistent subscription self.myDeviceShadow = self.myShadowClient.createShadowHandlerWithName("mythermo", True) return
def setup_aws(self): try: self.shadowClient = AWSIoTMQTTShadowClient("TemperatureServer") self.shadowClient.configureEndpoint( "a2yizg9mkkd9ph-ats.iot.us-west-2.amazonaws.com", 8883) self.shadowClient.configureCredentials(PATH_TO_ROOT, PATH_TO_KEY, PATH_TO_CERT) self.shadowClient.configureConnectDisconnectTimeout(10) # 10 sec self.shadowClient.configureMQTTOperationTimeout(5) # 5 sec self.shadowClient.connect() self.device_shadow = self.shadowClient.createShadowHandlerWithName( "TemperatureServer", True) except: print("Error setting up AWS retrying...") time.sleep(1) self.setup_aws()
def __init__(self, device): self.mqttc = AWSIoTMQTTShadowClient(thingName) self.mqttc.configureEndpoint( 'a2soq6ydozn6i0-ats.iot.us-west-2.amazonaws.com', 8883) self.mqttc.configureCredentials( './certificates/AmazonRootCA1.pem', './certificates/' + thingName + '.private.key', './certificates/' + thingName + '.cert.pem') self.mqttc.configureConnectDisconnectTimeout(10) self.mqttc.configureMQTTOperationTimeout(5) self.device_shadow = self.mqttc.createShadowHandlerWithName( thingName, True) self.device_shadow = self.mqttc.createShadowHandlerWithName( thingName, True) self.device_shadow.on_message = self.on_message self.device_shadow.json_encode = self.json_encode self.device = device
def __init__(self, thingname: str, host: str, root_ca_path: str, private_key_path: str, certificate_path: str): """Initiate AWS IoT connection :param thingname: AWSIoT thing name :param host: AWSIoT endpoint FQDN :param root_ca_path: local file path to Amazon root certificate :param private_key_path: local file path to device private key :param certificate_path: local file path to device certificate """ # Init Shadow Client MQTT connection self.shadow_client = AWSIoTMQTTShadowClient(thingname) self.shadow_client.configureEndpoint(host, 8883) self.shadow_client.configureCredentials(root_ca_path, private_key_path, certificate_path) # AWSIoTMQTTShadowClient configuration self.shadow_client.configureAutoReconnectBackoffTime(1, 32, 20) self.shadow_client.configureConnectDisconnectTimeout(20) # 20 sec self.shadow_client.configureMQTTOperationTimeout(20) # 20 sec # force shadow client to use offline publish queueing # overriding the default behaviour for shadow clients in the SDK mqtt_client = self.shadow_client.getMQTTConnection() mqtt_client.configureOfflinePublishQueueing(-1) # Connect to AWS IoT with a 300 second keepalive self.shadow_client.connect(300) # Create a deviceShadow with persistent subscription and register delta handler self.shadow_handler = self.shadow_client.createShadowHandlerWithName( thingname, True) self.shadow_handler.shadowRegisterDeltaCallback( self.custom_shadow_callback_delta) # initial status post self.status_post('STARTING') # dictionary to hold callback responses self._callbackresponses = {} # callbacks in this class post events on to this queue self.event_queue = queue.SimpleQueue() self.settings = {}
def connectIoTAttempt(ep, port, rootca, key, cert, timeoutSec, retryLimit): global awsIoTMQTTClient, awsShadowClient, weatherDeviceShadow awsShadowClient = AWSIoTMQTTShadowClient(cfgThingName) awsShadowClient.configureEndpoint(ep, port) awsShadowClient.configureCredentials(rootca, key, cert) awsIoTMQTTClient = awsShadowClient.getMQTTConnection() # AWSIoTMQTTClient connection configuration awsIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) awsIoTMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing awsIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz awsIoTMQTTClient.configureConnectDisconnectTimeout(timeoutSec) awsIoTMQTTClient.configureMQTTOperationTimeout(timeoutSec) #Attempt to connect for attempt in range(0, retryLimit): try: if awsIoTMQTTClient.connect(): print("AWS IoT connected") ledOn("green") except Exception, e: print str(e) continue break
def __init__(self): # Init data members # Connection related self._endpoint = "" self._rootCAFilePathList = "" self._certificateFilePathList = "" self._privateKeyFilePathList = "" self._useWebsocket = False self._AWSIoTMQTTShadowClient = None self._thermostatSimulatorShadowHandler = None # GUI related self._tkRootHandler = tkinter.Tk() self._reportedDataVariable = None self._reportedDataDisplayBox = None self._desiredDataVariable = None self._desiredDataDisplayBox = None self._setTemperatureInputBox = None self._setTemperatureButton = None # Check command line inputs if not self._checkInputs(): raise ValueError("Malformed/Missing command line inputs.") # Create and configure AWSIoTMQTTShadowClient self._AWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient( "ThermostatSimulatorApp", useWebsocket=self._useWebsocket) if self._useWebsocket: self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 443) self._AWSIoTMQTTShadowClient.configureCredentials( self._rootCAFilePathList[0]) else: self._AWSIoTMQTTShadowClient.configureEndpoint( self._endpoint, 8883) self._AWSIoTMQTTShadowClient.configureCredentials( self._rootCAFilePathList[0], self._privateKeyFilePathList[0], self._certificateFilePathList[0]) self._AWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime( 1, 128, 20) self._AWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) self._AWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # Set keepAlive interval to be 1 second and connect # Raise exception if there is an error in connecting to AWS IoT self._AWSIoTMQTTShadowClient.connect(5) self._thermostatSimulatorShadowHandler = self._AWSIoTMQTTShadowClient.createShadowHandlerWithName( "room", True) # Generate GUI self._packModule()
def build_shadow_client(): certificate_authority = glob.glob( os.path.join(BASE_DIRECTORY, 'config', '*Authority*.pem')) private_key = glob.glob( os.path.join(BASE_DIRECTORY, 'config', '*private.pem.key')) certificate = glob.glob( os.path.join(BASE_DIRECTORY, 'config', '*certificate.pem.crt')) if not certificate_authority or not private_key or not certificate: logging.warning( 'Need CA, private key, and certificate file located in config/') return None shadow_client = AWSIoTMQTTShadowClient(IOT_CLIENT_ID) shadow_client.configureEndpoint(IOT_ENDPOINT, 8883) shadow_client.configureCredentials(certificate_authority[0], private_key[0], certificate[0]) shadow_client.configureConnectDisconnectTimeout(10) shadow_client.configureMQTTOperationTimeout(5) return shadow_client
def connect_to_shadow_service(self, groupCAPath, coreInfo): shadowClient = AWSIoTMQTTShadowClient(self.CLIENT_ID) shadowClient.configureCredentials(groupCAPath, self.PRIVATE_KEY_PATH, self.CERTIFICATE_PATH) connectivityInfo = coreInfo.connectivityInfoList[0] ggcHost = connectivityInfo.host ggcPort = connectivityInfo.port shadowClient.configureEndpoint(ggcHost, ggcPort) shadowClient.connect() return shadowClient
def __init__(self, client_id, display_topic, endpoint, ca, key, cert, stage_controller): self.client_id = client_id self.display_topic = display_topic self.stage_controller = stage_controller self.refresh_timer = None self.show_text_cb = None self.state = {} client = AWSIoTMQTTClient(client_id) client.configureEndpoint(endpoint, 8883) client.configureCredentials(ca, key, cert) client.configureAutoReconnectBackoffTime(1, 32, 20) client.configureOfflinePublishQueueing(0) client.configureDrainingFrequency(2) # Draining: 2 Hz client.configureConnectDisconnectTimeout(10) # 10 sec client.configureMQTTOperationTimeout(5) # 5 sec self.client = client self.shadow_client = AWSIoTMQTTShadowClient( self.client_id, awsIoTMQTTClient=client)
def __init__(self): # Cofigure logging self.logger = logging.getLogger("AWSIoTPythonSDK.core") self.logger.setLevel(logging.DEBUG) self.streamHandler = logging.StreamHandler() self.formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.streamHandler.setFormatter(self.formatter) self.logger.addHandler(self.streamHandler) self.awsiotHost = "a130ba174k0fld-ats.iot.us-west-2.amazonaws.com" self.awsiotPort = 443 self.rootCAPath = "/home/pi/Mirror/cerf/VeriSign-Class3-Public-Primary-Certification-Authority-G5.pem" self.privateKeyPath = "/home/pi/Mirror/cerf/78755df119-private.pem.key" self.certificatePath = "/home/pi/Mirror/cerf/78755df119-certificate.pem.crt" self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("RPI_RULE") self.myAWSIoTMQTTShadowClient.configureEndpoint( self.awsiotHost, self.awsiotPort) self.myAWSIoTMQTTShadowClient.configureCredentials( self.rootCAPath, self.privateKeyPath, self.certificatePath) self.myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime( 1, 32, 10) self.myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout( 10) # 10sec self.myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) #5sec self.myAWSIoTMQTTShadowClient._AWSIoTMQTTClient.configureOfflinePublishQueueing( 5, AWSIoTPythonSDK.core.util.enums.DropBehaviorTypes.DROP_OLDEST ) # Infinite offline Publish queueing #connect to AWS IoT self.myAWSIoTMQTTShadowClient.connect() #create a devcie Shadow with persistent subscription self.thingName = "my_rpi" self.deviceShadowHandler = self.myAWSIoTMQTTShadowClient.createShadowHandlerWithName( self.thingName, True) self.temperature = "" self.humidity = "" self.window = "True" self.human_presence = "True"
def _initialize(self): mosaic_path = os.path.expanduser('~') + "/.mosaicdata/" root_ca_path = mosaic_path + "root-ca.crt" private_key_path = mosaic_path + "private.pem.key" certificate_path = mosaic_path + "certificate.pem.crt" # Initialization self._myShadowClient = AWSIoTMQTTShadowClient(self._hub_id) self._myShadowClient.configureEndpoint(constants.SHADOW_CLIENT_HOST, 8883) self._myShadowClient.configureCredentials(root_ca_path, private_key_path, certificate_path) # Configuration self._myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) self._myShadowClient.configureConnectDisconnectTimeout(15) # 15 sec self._myShadowClient.configureMQTTOperationTimeout(5) # 5 sec self._myShadowClient.onOnline = self._onOnline self._myShadowClient.onOffline = self._onOffline self._logger.info("Shadow client initialized")
def assign_shadow_certificates(): # assign the certificates for the connection to the device shadow on the IoT core. shadowclient = AWSIoTMQTTShadowClient("client id") shadowclient.configureEndpoint("your endpoint", 8883) shadowclient.configureCredentials("rootCA.pem", "private key", "certificate") return shadowclient
def __init__(self, deviceName): self.clientId = deviceName self.rootCAPath = "devices/config/root-CA.crt" self.privateKeyPath = "devices/config/" + deviceName + ".private.key" self.certificatePath = "devices/config/" + deviceName + ".cert.pem" self.host = "a3w259c8e2kscd-ats.iot.us-east-1.amazonaws.com" self.port = 8883 self.shadowClient = AWSIoTMQTTShadowClient(self.clientId) self.shadowClient.configureEndpoint(self.host, self.port) self.shadowClient.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath) self.shadowClient.configureAutoReconnectBackoffTime(1, 32, 20) self.shadowClient.configureConnectDisconnectTimeout(10) self.shadowClient.configureMQTTOperationTimeout(5) self.shadowClient.connect() self.handler = self.shadowClient.createShadowHandlerWithName( self.clientId, True)
def connect(self): """ Instantiate mqtt clients and delete them when exiting. We use AWSIoTMQTTShadowClient to create our MQTT connection. This manager will close the connection on exit """ self.shadow_client = AWSIoTMQTTShadowClient(self._cloud.app_id + str(os.urandom(6)), useWebsocket=True) self.shadow_client.configureEndpoint(self._cloud.mqtt_endpoint, 443) setuppath = '/usr/local/etc/aws-root-ca1.cer' pippath = site.USER_SITE if path.exists( "%s/usr/local/etc/aws-root-ca1.cer" % site.USER_SITE) else get_python_lib() cerpath = setuppath if path.exists( setuppath) else "%s/usr/local/etc/aws-root-ca1.cer" % pippath self.shadow_client.configureCredentials(cerpath) self.shadow_client.configureIAMCredentials(self._cloud.access_key_id, self._cloud.secret_key, self._cloud.session_token) self.shadow_client.configureAutoReconnectBackoffTime(1, 128, 20) self.shadow_client.configureConnectDisconnectTimeout(10) self.shadow_client.configureMQTTOperationTimeout(5) # Set keepAlive interval to be 1 second and connect # Raise exception if there is an error in connecting to AWS IoT try: if not self.shadow_client.connect(5): raise Exception('AWSIoTMQTTShadowClientCouldNotConnect') except ValueError as e: logger.error( "shadow_client.connect returned '%s'" ', credentials are not authorized.', str(e)) return -1 self.device = self.shadow_client.createShadowHandlerWithName( self._id, True) self.connection = self.shadow_client.getMQTTConnection() logger.info('[+] mqtt connected')
def cert_assignment(): MQTTclient = AWSIoTMQTTClient("rasp_pi_sub") Shadowclient = AWSIoTMQTTShadowClient("rasp_pi_sub_shadow") MQTTclient.configureEndpoint("endpoint", 8883) Shadowclient.configureEndpoint("endpoint", 8883) MQTTclient.configureCredentials("rootCA.pem", "private key", "certificate") Shadowclient.configureCredentials("rootCA.pem", "private key", "certificate") return MQTTclient, Shadowclient
def SetupAWS(self): try: self.client = AWSIoTMQTTShadowClient("PIRCamera") self.client.configureEndpoint( "a2yizg9mkkd9ph-ats.iot.us-west-2.amazonaws.com", 8883) self.client.configureCredentials(PATH_TO_ROOT, PATH_TO_KEY, PATH_TO_CERT) self.client.configureConnectDisconnectTimeout(10) # 10 sec self.client.configureMQTTOperationTimeout(5) # 5 sec self.client.connect() self.shadow_connect = self.client.createShadowHandlerWithName( "SecurityCamera", True) # Setup the MQTT endpoint # Spin up resources event_loop_group = io.EventLoopGroup(1) host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) self.mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=ENDPOINT, cert_filepath=PATH_TO_CERT, pri_key_filepath=PATH_TO_KEY, client_bootstrap=client_bootstrap, ca_filepath=PATH_TO_ROOT, client_id=CLIENT_ID, clean_session=False, keep_alive_secs=6) connect_future = self.mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() self.mqtt_connection.subscribe(topic=TOPIC, qos=mqtt.QoS.AT_LEAST_ONCE, callback=self.subcallback) except: print("AWS failed to setup, retrying...") time.sleep(1) self.SetupAWS()
def __init_shadow(self): self.__shadow = AWSIoTMQTTShadowClient( self.__config["aws"]["client_id"] + "_shadow") try: self.__shadow.configureEndpoint(self.__config["aws"]["endpoint"], self.__config["aws"]["port"]) logger.info("Trying to connect to {}:{}".format( self.__config["aws"]["endpoint"], self.__config["aws"]["port"])) self.__shadow.configureCredentials(self.__config["aws"]["root"], self.__config["aws"]["private"], self.__config["aws"]["cert"]) # Infinite offline Publish queueing self.__shadow.configureAutoReconnectBackoffTime(1, 32, 20) self.__shadow.configureConnectDisconnectTimeout(10) # 10 sec self.__shadow.configureMQTTOperationTimeout(5) # 5 sec self.__shadow.connect() self.__shadowHandle = self.__shadow.createShadowHandlerWithName( self.__config["aws"]["thing_id"], True) except AWSIoTExceptions.connectTimeoutException as error: logger.error("Problem with MQTT configuration: {}".format(error)) logger.debug("Initialised AWS Standard Client...")
def __init__(self, display, workout): self.display = display self.workout = workout self.shadowClient = AWSIoTMQTTShadowClient(clientId) self.shadowClient.configureEndpoint(host, port) self.shadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) self.shadowClient.configureAutoReconnectBackoffTime(1, 32, 20) self.shadowClient.configureConnectDisconnectTimeout(10) self.shadowClient.configureMQTTOperationTimeout(1) self.display.updateStatus("Connecting to AWS IoT...") self.display.update() self.shadowClient.connect() self.shadowHandler = self.shadowClient.createShadowHandlerWithName( thingName, True) self.shadowHandler.shadowRegisterDeltaCallback(self.delta_callback) self.gotoIdle() self.display.updateStatus("") self.display.update()
def connect_shadow_client(self, clientId_suffix='_shadow'): # Init AWSIoTMQTTShadowClient clientId = self.clientId + clientId_suffix self.myAWSIoTMQTTShadowClient = None if self.useWebsocket: self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient( clientId, useWebsocket=True) self.myAWSIoTMQTTShadowClient.configureEndpoint(self.host, 443) self.myAWSIoTMQTTShadowClient.configureCredentials(self.rootCAPath) else: self.myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId) self.myAWSIoTMQTTShadowClient.configureEndpoint(self.host, 8883) self.myAWSIoTMQTTShadowClient.configureCredentials( self.rootCAPath, self.privateKeyPath, self.certificatePath) # AWSIoTMQTTShadowClient configuration self.myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime( 1, 32, 20) self.myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout( 10) # 10 sec self.myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT self.myAWSIoTMQTTShadowClient.connect()
def start_listening(): myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId) myAWSIoTMQTTShadowClient.configureEndpoint(AWSEndpoint, AWSPort) myAWSIoTMQTTShadowClient.configureCredentials(get_path("AmazonCA.pem"), get_path("Rasp-private.key"), get_path("Rasp-cert.crt")) myAWSIoTMQTTShadowClient.connect() deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName( IOTName, True) shadowCallbackContainer_Bot = ShadowCallbackContainer(deviceShadowHandler) # Listen on deltas deviceShadowHandler.shadowRegisterDeltaCallback( shadowCallbackContainer_Bot.customShadowCallback_Delta) # Loop forever while True: time.sleep(0.2)
def local_shadow_connect(device_name, config_file, root_ca, certificate, private_key, group_ca_dir): cfg = GroupConfigFile(config_file) ggd_name = cfg['devices'][device_name]['thing_name'] iot_endpoint = cfg['misc']['iot_endpoint'] dip = DiscoveryInfoProvider() dip.configureEndpoint(iot_endpoint) dip.configureCredentials(caPath=root_ca, certPath=certificate, keyPath=private_key) dip.configureTimeout(10) # 10 sec logging.info( "[shadow_connect] Discovery using CA:{0} cert:{1} prv_key:{2}".format( root_ca, certificate, private_key)) gg_core, discovery_info = discover_configured_core( config_file=config_file, dip=dip, device_name=ggd_name, ) if not gg_core: raise EnvironmentError("[core_connect] Couldn't find the Core") ca_list = discovery_info.getAllCas() core_list = discovery_info.getAllCores() group_id, ca = ca_list[0] core_info = core_list[0] logging.info("Discovered Greengrass Core:{0} from Group:{1}".format( core_info.coreThingArn, group_id)) group_ca_file = save_group_ca(ca, group_ca_dir, group_id) # local Greengrass Core discovered # get a shadow client to receive commands mqttsc = AWSIoTMQTTShadowClient(ggd_name) # now connect to Core from this Device logging.info("[core_connect] gca_file:{0} cert:{1}".format( group_ca_file, certificate)) mqttsc.configureCredentials(group_ca_file, private_key, certificate) mqttc = mqttsc.getMQTTConnection() mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST) if not mqtt_connect(mqttsc, gg_core): raise EnvironmentError("connection to Master Shadow failed.") # create and register the shadow handler on delta topics for commands # with a persistent connection to the Master shadow master_shadow = mqttsc.createShadowHandlerWithName( cfg['misc']['master_shadow_name'], True) return mqttc, mqttsc, master_shadow, ggd_name
def __init__(self): # Init data members # Connection related self._endpoint = "" self._rootCAFilePathList = "" self._certificateFilePathList = "" self._privateKeyFilePathList = "" self._useWebsocket = False self._AWSIoTMQTTShadowClient = None self._thermostatSimulatorShadowHandler = None # GUI related self._tkRootHandler = tkinter.Tk() self._reportedDataVariable = None self._reportedDataDisplayBox = None self._desiredDataVariable = None self._desiredDataDisplayBox = None self._setTemperatureInputBox = None self._setTemperatureButton = None # Check command line inputs if not self._checkInputs(): raise ValueError("Malformed/Missing command line inputs.") # Create and configure AWSIoTMQTTShadowClient self._AWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("ThermostatSimulatorApp", useWebsocket=self._useWebsocket) if self._useWebsocket: self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 443) self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0]) else: self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 8883) self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0], self._privateKeyFilePathList[0], self._certificateFilePathList[0]) self._AWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 128, 20) self._AWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) self._AWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # Set keepAlive interval to be 1 second and connect # Raise exception if there is an error in connecting to AWS IoT self._AWSIoTMQTTShadowClient.connect(5) self._thermostatSimulatorShadowHandler = self._AWSIoTMQTTShadowClient.createShadowHandlerWithName("room", True) # Generate GUI self._packModule()
def initialize(): global mqttc mqttc = AWSIoTMQTTClient(ggd_name) mqttc.configureEndpoint(ggd_config.sort_arm_ip, ggd_config.sort_arm_port) mqttc.configureCredentials(CAFilePath=dir_path + "/" + ggd_ca_file_path, KeyPath=dir_path + "/certs/GGD_arm.private.key", CertificatePath=dir_path + "/certs/GGD_arm.certificate.pem.crt") global mstr_shadow_client # get a shadow client to receive commands mstr_shadow_client = AWSIoTMQTTShadowClient(ggd_name) mstr_shadow_client.configureEndpoint(ggd_config.master_core_ip, ggd_config.master_core_port) mstr_shadow_client.configureCredentials( CAFilePath=dir_path + "/certs/master-server.crt", KeyPath=dir_path + "/certs/GGD_arm.private.key", CertificatePath=dir_path + "/certs/GGD_arm.certificate.pem.crt") if not mqtt_connect(mqttc): raise EnvironmentError("connection to GG Core MQTT failed.") if not mqtt_connect(mstr_shadow_client): raise EnvironmentError("connection to Master Shadow failed.") global master_shadow # create and register the shadow handler on delta topics for commands # with a persistent connection to the Master shadow master_shadow = mstr_shadow_client.createShadowHandlerWithName( ggd_config.master_shadow_name, True) token = master_shadow.shadowGet(shadow_mgr, 5) log.info("[initialize] shadowGet() tk:{0}".format(token)) with ServoProtocol() as sproto: # TODO ensure Baud rate is maxed for servo_id in ggd_config.arm_servo_ids: sproto.ping(servo=servo_id)
def initialize(device_name, config_file, root_ca, certificate, private_key, group_ca_path): global ggd_name cfg = GroupConfigFile(config_file) local = dict() remote = dict() # determine heartbeat device's thing name and endpoint for MQTT clients ggd_name = cfg['devices'][device_name]['thing_name'] iot_endpoint = cfg['misc']['iot_endpoint'] # Discover Greengrass Core dip = DiscoveryInfoProvider() dip.configureEndpoint(iot_endpoint) dip.configureCredentials( caPath=root_ca, certPath=certificate, keyPath=private_key ) dip.configureTimeout(10) # 10 sec log.info("Discovery using CA: {0} certificate: {1} prv_key: {2}".format( root_ca, certificate, private_key )) # Now discover the groups in which this device is a member. # The arm should only be in two groups. The local and master groups. discovered, discovery_info = utils.ggc_discovery( ggd_name, dip, retry_count=10, max_groups=2 ) # Each group returned has a groupId which can compare to the configured # groupId in the config file. If the IDs match, the 'local' Group has been # found and therefore local core. # If the groupId's do not match, the 'remote' or 'master' group has been # found. group_list = discovery_info.getAllGroups() for g in group_list: logging.info("[initialize] group_id:{0}".format(g.groupId)) if g.groupId == cfg['group']['id']: local_cores = g.coreConnectivityInfoList local['core'] = local_cores[0] # just grab first core as local local['ca'] = g.caList else: remote_cores = g.coreConnectivityInfoList remote['core'] = remote_cores[0] # just grab first core as remote remote['ca'] = g.caList if len(local) > 1 and len(remote) > 1: logging.info("[initialize] local_core:{0} remote_core:{1}".format( local, remote )) else: raise EnvironmentError("Couldn't find the arm's Cores.") # just save one of the group's CAs to use as a CA file later local_core_ca_file = utils.save_group_ca( local['ca'][0], group_ca_path, local['core'].groupId ) remote_core_ca_file = utils.save_group_ca( remote['ca'][0], group_ca_path, remote['core'].groupId ) # Greengrass Cores discovered, now connect to Cores from this Device # get a client to send telemetry local_mqttc = AWSIoTMQTTClient(ggd_name) log.info("[initialize] local gca_file:{0} cert:{1}".format( local_core_ca_file, certificate)) local_mqttc.configureCredentials( local_core_ca_file, private_key, certificate ) local_mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST) if not utils.mqtt_connect(mqtt_client=local_mqttc, core_info=local['core']): raise EnvironmentError("Connection to GG Core MQTT failed.") # get a shadow client to receive commands master_shadow_client = AWSIoTMQTTShadowClient(ggd_name) log.info("[initialize] remote ca_file:{0} cert:{1}".format( local_core_ca_file, certificate)) remote_mqttc = master_shadow_client.getMQTTConnection() remote_mqttc.configureCredentials( remote_core_ca_file, private_key, certificate ) if not utils.mqtt_connect(mqtt_client=master_shadow_client, core_info=remote['core']): raise EnvironmentError("Connection to Master Shadow failed.") # create and register the shadow handler on delta topics for commands # with a persistent connection to the Master shadow master_shadow = master_shadow_client.createShadowHandlerWithName( cfg['misc']['master_shadow_name'], True) log.info("[initialize] created handler for shadow name: {0}".format( cfg['misc']['master_shadow_name'] )) token = master_shadow.shadowGet(shadow_mgr, 5) log.info("[initialize] shadowGet() tk:{0}".format(token)) return local_mqttc, remote_mqttc, master_shadow
#Import SDK packages import json from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient #for cert based connection myShadowClient = AWSIoTMQTTShadowClient("raspberry-pi") myShadowClient.configureEndpoint("a1xugslbalqdxo.iot.us-east-1.amazonaws.com", 8883) myShadowClient.configureCredentials("/home/pi/python_mqtt/aws-iot-certs/rootCA.pem.crt", "/home/pi/python_mqtt/aws-iot-certs/c6417d9f55-private.pem.key", "/home/pi/python_mqtt/aws-iot-certs/c6417d9f55-certificate.pem.crt") #myShadowClient.configureConnectionDisconnectTimeout(10) myShadowClient.configureMQTTOperationTimeout(5) myShadowClient.connect() myDeviceShadow = myShadowClient.createShadowHandlerWithName("Bot", True) payload = json.dumps({ "state":{ "reported": { "this_thing_is_alive": "I am Raspberry" } } }) #myDeviceShadow.shadowGet(customCallback, 5) #myDeviceShadow.shadowUpdate(payload, shadowUpdate, 5)
class ThermoApp(App): DEVICE = '/dev/ttyAMA0' BAUD = 9600 TIMEOUT = 5 ipaddr='' lastGPUTempRead=0.0 lastWeatherRead=0.0 lastTempPressHumidRead=0.0 lastShadowUpdate=0.0 lastSetAlerts=0.0 ui = ObjectProperty(None) zones = ObjectProperty(None) zonemap=['','17','27','22'] zoneData={ '1':ThermoZone(1,17), '2':ThermoZone(2,27), '3':ThermoZone(3,22) } furnace=Furnace() currentZone=1 dataFeed = deque() deviceData={ 'AA':ThermoDevice('AA',2,'master'), 'AB':ThermoDevice('AB',2,'tess'), 'AC':ThermoDevice('AC',2,'kate'), 'AD':ThermoDevice('AD',3,'girls'), 'AE':ThermoDevice('AE',1,'snug'), 'AF':ThermoDevice('AF',1,'living'), 'AG':ThermoDevice('AG',0,'porch'), 'AH':ThermoDevice('AH',1,'ground'), 'BM':ThermoDevice('BM',0,'thermo'), 'AW':ThermoDevice('AW',0,'weather'), 'PI':ThermoDevice('PI',0,'GPU')} ser = serial.Serial(DEVICE, BAUD) voltage = 0.0 tempvale = 0.0 pressure = 0.0 weather = [] sensor = BME280(mode=BME280_OSAMPLE_8) host='a2pveb84akyryv.iot.us-east-1.amazonaws.com' rootCAPath='rootca.key' privateKeyPath='bdca28f300.private.key' certificatePath='bdca28f300.cert.pem' # -e a2pveb84akyryv.iot.us-east-1.amazonaws.com -r rootca.key -c bdca28f300.cert.pem -k bdca28f300.private.key def show_config(self): App.open_settings(self) Window.request_keyboard(self.keyboard_close, self) def keyboard_close(self): #print "close" return def build_config(self, config): config.setdefaults('startup', { 'weatherText': 'foobar', 'picSource': 'weather/1.jpg' }) self.config=config def build_settings(self, settings): jsondata = """[ { "type": "title", "title": "Thermo application" }, { "type": "options", "title": "Initial Weather", "desc": "Weather Pic", "section": "startup", "key": "picSource", "options": ["weather/1.jpg", "weather/images.jpg", "weather/part_coudy.jpg"] }, { "type": "string", "title": "Weather Title", "desc": "Weather Text", "section": "startup", "key": "weatherText" }]""" settings.add_json_panel('Thermo application', self.config, data=jsondata) def build(self): self.ui=ThermoWidget() self.ui.weatherText='ThermoWidget' self.ui.picSource='weather/1.jpg' self.ui.tempDataText="temps" self.ui.setPointText="0.0" self.ui.ipAddressText="192.168.0.0" self.ui.averageTempText="0.0" self.ui.zoneAlertsText="Loading..." btn=self.ui.ids['increase'] btn.bind(on_release=self.increaseSetPoint) btn=self.ui.ids['decrease'] btn.bind(on_release=self.decreaseSetPoint) self.zones=self.ui.ids['zones'] for z in range(0,4): btnstate='down' if self.currentZone==z else 'normal' btn = ToggleButton( allow_no_selection=False, text=str(z), group='zonegroup', size_hint=(None, None), halign='center', state=btnstate, background_normal='normal.png', background_down='down.png') btn.bind(on_release=self.switch_zone) self.zones.add_widget(btn) self.ui.weatherText=self.config.get('startup', 'weatherText') temp = subprocess.check_output(["ifconfig","wlan0"],universal_newlines=True) pos1=temp.find("inet addr:") pos2=temp.find(" Bcast:") self.ui.ipAddressText=temp[pos1+10:pos2] self.connectMQTT() Clock.schedule_interval(self.mainLoop, 10.0) return self.ui def switch_zone(self,toggle): self.currentZone=int(toggle.text) self.updateDisplay() pass def increaseSetPoint(self,instance): self.zoneData[str(self.currentZone)].setPoint+=5.0/9.0 self.takeAction() self.updateDisplay() pass def decreaseSetPoint(self,instance): self.zoneData[str(self.currentZone)].setPoint-=5.0/9.0 self.takeAction() self.updateDisplay() pass def loadConfig(self): # read config file into memory vars return def avgZone(self,zonenum): tot=0.0 cnt=0 for i in self.deviceData: device=self.deviceData[i] if(device.zone==zonenum): tot+=float(device.temp) if(device.temp>0.0): cnt+=1 if cnt==0: cnt=1 return tot/cnt def connectMQTT(self): self.myShadowClient = AWSIoTMQTTShadowClient("thermo") #self.myAWSIoTMQTTClient = AWSIoTMQTTClient("thermo") self.myShadowClient.configureEndpoint(self.host, 8883) self.myShadowClient.configureCredentials(self.rootCAPath, self.privateKeyPath, self.certificatePath) # myShadowClient connection configuration self.myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) self.myShadowClient.connect() self.myAWSIoTMQTTClient = self.myShadowClient.getMQTTConnection() self.myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing self.myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz self.myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec self.myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec # Connect and subscribe to AWS IoT #self.myAWSIoTMQTTClient.connect() # myAWSIoTMQTTClient.subscribe("thermo", 1, customCallback) # self.myAWSIoTMQTTClient.publish("thermo", "[[\'"+(strftime(DATE_FORMAT,localtime())+"\','TT','START','1']]", 1) # Create a device shadow instance using persistent subscription self.myDeviceShadow = self.myShadowClient.createShadowHandlerWithName("mythermo", True) return def updateDeviceShadow(self): if(time()-self.lastShadowUpdate > 300): thingState={ "state" : { "reported" : { "sensors" : { }, "zones" : { }, "furnace" : { } } } } for i in self.deviceData: device=self.deviceData[i] thingState["state"]["reported"]["sensors"][device.id]={"temp":tformat(device.temp),"location":device.location,"batt":device.batt,"alert":device.alert,"lastupdate":device.lastupdate,"press":device.press,"humid":device.humid} for i in self.zoneData: zone=self.zoneData[i] thingState["state"]["reported"]["zones"][zone.id]={"status":zone.status, "average":tformat(zone.average), "setPoint":tformat(zone.setPoint), "triggertemp":tformat(zone.triggertemp), "alert":zone.alert} thingState["state"]["reported"]["furnace"]={"onSeconds":self.furnace.onSeconds,"offSeconds":self.furnace.offSeconds,"maxBurnSeconds":self.furnace.maxBurnSeconds,"maxRestSeconds":self.furnace.maxRestSeconds,"status":self.furnace.status,"lastupdate":self.furnace.lastupdate} self.myDeviceShadow.shadowUpdate(json.dumps(thingState), None, 5) self.lastShadowUpdate=time() return def updateDisplay(self): # draw everything # if click then show subpanel or change config self.ui.setPointText="{:2.0f}".format(self.zoneData[str(self.currentZone)].setPoint*9/5+32.0) self.ui.averageTempText=tformat(self.avgZone(self.currentZone)) self.ui.tempDataText='' zonealerts='Alerts:' for i in self.deviceData: device=self.deviceData[i] thisDeviceText=tformat(device.temp) thisDeviceText+=" "+device.location+" "+device.alert self.ui.tempDataText+=thisDeviceText+'\n' for i in self.zoneData: zone=self.zoneData[i] if(len(zone.alert)>0): zonealerts+=" Zone"+str(zone.id)+" "+zone.alert self.ui.zoneAlertsText=zonealerts return def readSensors(self): # get data from serial RF sensors # get data from remote PI # all data in memory only in this function # get temperature # messages are 12chars aIDTYPEVALUE aIDAWAKE---- or aIDSLEEPING- # returns -100 on error, or the temperature as a float fim = time()+ self.TIMEOUT voltage = 0 tempvalue = -100 deviceid = '' while (time()<fim) and (tempvalue == -100): n = self.ser.inWaiting() if n != 0: data = self.ser.read(n) nb_msg = len(data) / 12 for i in range (0, nb_msg): msg = data[i*12:(i+1)*12] deviceid = msg[1:3] if self.deviceData.has_key(deviceid): device=self.deviceData[deviceid] device.lastupdate=strftime(DATE_FORMAT,localtime()) if msg[3:7] == "TEMP": tempvalue = msg[7:] device.temp=tempvalue self.dataFeed.append((strftime(DATE_FORMAT,localtime()), deviceid, "TEMP", tempvalue)) if msg[3:7] == "BATT": voltage = msg[7:11] if voltage == "LOW": voltage = 0.1 device.batt=voltage self.dataFeed.append((strftime(DATE_FORMAT,localtime()), deviceid+'B', "BATT", voltage)) else: sleep(5) return def getPiSensorData(self): if(time()-self.lastGPUTempRead > 60): temp = "" temp = subprocess.check_output(["/opt/vc/bin/vcgencmd","measure_temp"],universal_newlines=True) temp = temp[5 : -3] device=self.deviceData['PI'] device.lastupdate=strftime(DATE_FORMAT,localtime()) device.temp=temp self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "PI", "TEMP", temp)) self.lastGPUTempRead = time() return def getConnectedSensorData(self): if(time()-self.lastTempPressHumidRead > 60): # get BME280 data temp=self.sensor.read_temperature()-1.0 press=self.sensor.read_pressure() humid=self.sensor.read_humidity() self.pressure=press device=self.deviceData['BM'] device.lastupdate=strftime(DATE_FORMAT,localtime()) device.temp=temp device.press=press device.humid=humid self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "BM", "TEMP", temp)) self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "BP", "PRESS", press)) self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "BH", "HUMID", humid)) self.lastTempPressHumidRead = time() def getWeather(self): if(time()-self.lastWeatherRead > 1800): # get and parse AccuWeather data cur = re.compile('Currently: (.*)<') link = "http://rss.accuweather.com/rss/liveweather_rss.asp?metric=0&locCode=US|44022" f = urllib.urlopen(link) myfile = f.read() tempvalue = cur.search(myfile).group(1) temp=tempvalue[-4:-1] pos=tempvalue.find(":") description=tempvalue[0:-5] if pos<0 else tempvalue[0:pos] description=description.replace(" ","_").lower() # print("description = [" + description +"]") device=self.deviceData['AW'] device.lastupdate=strftime(DATE_FORMAT,localtime()) device.temp=(float(temp)-32)*5/9 if device.desc<>description : self.ui.picSource='weather/'+description+'.jpg' if 6 < localtime()[3] < 18 else 'weather/'+description+'_dark.jpg' device.desc=description self.ui.weatherText = tempvalue self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "AW", "NEWS", tempvalue)) self.lastWeatherRead = time() return def setAlerts(self): # Reasons for alerts: # sensor battery level below 2.3 # sensor not reporting ( sensor data age > 5x reporting ) # temperature not under control = falling when attempting to raise # alert if temp not correct direction for 10 minutes # need control switch date time if(time()-self.lastSetAlerts > 1800): for i in self.deviceData: device=self.deviceData[i] device.alert="" if (not device.batt is None) & (device.batt<2.5): device.alert="LOW" self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "ALERT", "LOW Battery in "+device.location, device.batt)) self.lastSetAlerts = time() if (len(device.lastupdate)>0) & (device.id!='AW'): age = datetime.datetime.strptime(strftime(DATE_FORMAT,localtime()),DATE_FORMAT) - datetime.datetime.strptime(device.lastupdate,DATE_FORMAT) #print "{} {}".format(device.location,age.seconds) if ( age.seconds > 600 ): device.alert="OLD" self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "ALERT", "NO Response in "+device.location, age.seconds)) self.lastSetAlerts = time() for i in self.zoneData: zone=self.zoneData[i] zone.alert="" if (zone.status): age = datetime.datetime.strptime(strftime(DATE_FORMAT,localtime()),DATE_FORMAT) - datetime.datetime.strptime(zone.lastupdate,DATE_FORMAT) if (age.seconds>600): zone.alert="OOC" self.dataFeed.append((strftime(DATE_FORMAT,localtime()), "ALERT", "OOC in zone "+str(zone.id), tformat(zone.average))) self.lastSetAlerts = time() return def uploadData(self): # put the data in the cloud or cache in a file until sucess # add it to the memory deque # if the deque > 10 try to upload it and any pending updates # else throw a flag for pending updates and write to a file if len(self.dataFeed)>10: try: # write to a file #print " write to file" with open("Output.txt", "a") as text_file: for record in self.dataFeed: text_file.write("{},{},{},{}\r\n".format(record[0],record[1],record[2],record[3])) # write to cloud #print " write to cloud" self.myAWSIoTMQTTClient.publish("thermo", json.dumps(list(self.dataFeed)), 1) # clear the deque self.dataFeed.clear() except: print("Unexpected error in uploadData:", sys.exc_info()[0]) return def downloadRequests(self): # get cloud data or web requests return def controlZone(self,zone,on,avg): zoneentry=self.zoneData[str(zone)] subprocess.call(["gpio", "-g", "write", str(zoneentry.port), "1" if on else "0"]) furnaceWasOn=False for i in self.zoneData: furnaceWasOn|=self.zoneData[i].status if(zoneentry.status != on): zoneentry.status=on furnaceIsOn=False for i in self.zoneData: furnaceIsOn|=self.zoneData[i].status if(furnaceIsOn!=furnaceWasOn): self.furnace.status=furnaceIsOn if (len(self.furnace.lastupdate)>0): age = datetime.datetime.strptime(strftime(DATE_FORMAT,localtime()),DATE_FORMAT) - datetime.datetime.strptime(self.furnace.lastupdate,DATE_FORMAT) # if it is now on - age is how long it was off if(furnaceIsOn): self.furnace.offSeconds+=age.seconds if(age.seconds>self.furnace.maxRestSeconds): self.furnace.maxRestSeconds=age.seconds # if it is now off - age is how long it was on else: self.furnace.onSeconds+=age.seconds if(age.seconds>self.furnace.maxBurnSeconds): self.furnace.maxBurnSeconds=age.seconds self.furnace.lastupdate=strftime(DATE_FORMAT,localtime()) zoneentry.lastupdate=strftime(DATE_FORMAT,localtime()) zoneentry.triggertemp=avg return def takeAction(self): # contains all rules to make decisions based on data for i in self.zoneData: zone=self.zoneData[i] zone.average=self.avgZone(zone.id) if(zone.average<10.0): self.controlZone(zone.id,False,zone.average) return #print "average in zone {} is {}".format(zone.id,zone.average) if(zone.average<zone.setPoint-0.5): self.controlZone(zone.id,True,zone.average) #turn it on if(zone.average>zone.setPoint): self.controlZone(zone.id,False,zone.average) #turn it off return def mainLoop(self,args): try: #print 'config' self.loadConfig() #print 'getWeather' self.getWeather() #print 'getPI' self.getPiSensorData() #print 'getBME' self.getConnectedSensorData() #print 'read' self.readSensors() #print 'alerts' self.setAlerts() #print 'update' self.updateDisplay() #print 'update shadow' self.updateDeviceShadow() #print 'upload' self.uploadData() #print 'download' self.downloadRequests() #print 'action' self.takeAction() except: type_, value_, traceback_ = sys.exc_info() print "EXCEPTION {}\r\n{}\r\n{}".format(type_, value_, traceback.format_tb(traceback_)) self.dataFeed.append(value_) return
if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath): parser.error("Missing credentials for authentication.") exit(2) # 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 AWSIoTMQTTShadowClient myAWSIoTMQTTShadowClient = None if useWebsocket: myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True) myAWSIoTMQTTShadowClient.configureEndpoint(host, 443) myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath) else: myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId) myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883) myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTShadowClient configuration myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20) myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) # 10 sec myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # 5 sec # Connect to AWS IoT myAWSIoTMQTTShadowClient.connect()
class ThermoSimAppGUI: _usage = """Usage: Make sure that you put all your credentials under: ./certs/ with the following naming conventions: Root CA file: *CA.crt Certificate file (not required if using MQTT over WebSocket): *.pem.crt Private key file (not required if using MQTT over WebSocket): *.pem.key Use X.509 certificate based mutual authentication: python ThermostatSimulatorApp -e <endpoint> Use MQTT over WebSocket: python ThermostatSimulatorApp -e <endpoint> -w Type "python ThermostatSimulatorApp -h" for detailed command line options. """ _helpInfo = """Available command line options: -e, --endpoint: Your custom AWS IoT custom endpoint -w, --websocket: Use MQTT over websocket -h, --help: Help infomation """ def __init__(self): # Init data members # Connection related self._endpoint = "" self._rootCAFilePathList = "" self._certificateFilePathList = "" self._privateKeyFilePathList = "" self._useWebsocket = False self._AWSIoTMQTTShadowClient = None self._thermostatSimulatorShadowHandler = None # GUI related self._tkRootHandler = tkinter.Tk() self._reportedDataVariable = None self._reportedDataDisplayBox = None self._desiredDataVariable = None self._desiredDataDisplayBox = None self._setTemperatureInputBox = None self._setTemperatureButton = None # Check command line inputs if not self._checkInputs(): raise ValueError("Malformed/Missing command line inputs.") # Create and configure AWSIoTMQTTShadowClient self._AWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("ThermostatSimulatorApp", useWebsocket=self._useWebsocket) if self._useWebsocket: self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 443) self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0]) else: self._AWSIoTMQTTShadowClient.configureEndpoint(self._endpoint, 8883) self._AWSIoTMQTTShadowClient.configureCredentials(self._rootCAFilePathList[0], self._privateKeyFilePathList[0], self._certificateFilePathList[0]) self._AWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 128, 20) self._AWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) self._AWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # Set keepAlive interval to be 1 second and connect # Raise exception if there is an error in connecting to AWS IoT self._AWSIoTMQTTShadowClient.connect(5) self._thermostatSimulatorShadowHandler = self._AWSIoTMQTTShadowClient.createShadowHandlerWithName("room", True) # Generate GUI self._packModule() # Validate command line inputs # Return False there is any malformed inputs # Return True if all the necessary inputs have been discovered def _checkInputs(self): gotEoughInputs = True # Check command line inputs try: opts, args = getopt.getopt(sys.argv[1:], "hwe:", ["endpoint=", "websocket", "help"]) if len(opts) == 0: raise getopt.GetoptError("No input parameters") for opt, arg in opts: if opt in ("-e", "--endpoint"): self._endpoint = arg if opt in ("-w", "--websocket"): self._useWebsocket = True if opt in ("-h", "--help"): print(self._helpInfo) gotEoughInputs = False except getopt.GetoptError: print(self._usage) gotEoughInputs = False # Check credential files if gotEoughInputs: self._rootCAFilePathList = glob.glob("./certs/*CA.crt") if self._useWebsocket: gotEoughInputs = gotEoughInputs and len(self._rootCAFilePathList) != 0 if not gotEoughInputs: print("Missing rootCA in ./certs/") else: self._certificateFilePathList = glob.glob("./certs/*.pem.crt") self._privateKeyFilePathList = glob.glob("./certs/*.pem.key") gotEoughInputs = gotEoughInputs and len(self._rootCAFilePathList) != 0 and len(self._certificateFilePathList) != 0 and len(self._privateKeyFilePathList) != 0 if not gotEoughInputs: print("Missing rootCA, certificate or private key in ./certs/") return gotEoughInputs def _packModule(self): self._tkRootHandler.title("ThermostatSimulatorApp") self._tkRootHandler.geometry("500x250") self._tkRootHandler.resizable(width=False, height=False) # Pack all frames baseFrame = tkinter.Frame(self._tkRootHandler) temperatureFrame = tkinter.Frame(baseFrame) temperatureFrame.pack(side="top") controlPanelFrame = tkinter.Frame(baseFrame) controlPanelFrame.pack(side="bottom") baseFrame.pack() # Pack all modules for temperature frame self._reportedDataVariable = tkinter.StringVar() self._reportedDataVariable.set("XX.X F") reportedDataTag = tkinter.Label(temperatureFrame, text="Reported Temperature:", justify="left") self._reportedDataDisplayBox = tkinter.Label(temperatureFrame, textvariable=self._reportedDataVariable, font=("Arial", 55), justify="left") # self._desiredDataVariable = tkinter.StringVar() self._desiredDataVariable.set("XX.X F") desiredDataTag = tkinter.Label(temperatureFrame, text="Desired Temperature:", justify="left") self._desiredDataDisplayBox = tkinter.Label(temperatureFrame, textvariable=self._desiredDataVariable, font=("Arial", 55), justify="left") # reportedDataTag.pack() self._reportedDataDisplayBox.pack() desiredDataTag.pack() self._desiredDataDisplayBox.pack() # Create a callback pool self._callbackPoolHandler = ThermoSimAppCallbackPool(self._tkRootHandler, self._reportedDataDisplayBox, self._thermostatSimulatorShadowHandler, self._reportedDataVariable, self._desiredDataVariable) # Pack all modules for control panel frame self._setTemperatureInputBox = tkinter.Entry(controlPanelFrame) self._setTemperatureInputBox.pack(sid="left") self._setTemperatureButton = tkinter.Button(controlPanelFrame, text="SET", command=lambda: self._callbackPoolHandler.buttonCallback(self._setTemperatureInputBox, self._desiredDataVariable)) self._setTemperatureButton.pack() def runApp(self): # Start and run the app self._tkRootHandler.after(500, self._callbackPoolHandler.sendShadowGetForReportedTemperature) # per 500ms self._tkRootHandler.after(500, self._callbackPoolHandler.updateReportedTemperatureDataVariable) # per 500ms self._tkRootHandler.mainloop()
def setup_aws_shadow_client(host, rootCAPath, privateKeyPath, certificatePath, device_name): # 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 AWSIoTMQTTShadowClient shadow = AWSIoTMQTTShadowClient(device_name + "-client") shadow.configureEndpoint(host, 8883) shadow.configureCredentials(rootCAPath, privateKeyPath, certificatePath) # AWSIoTMQTTShadowClient configuration shadow.configureAutoReconnectBackoffTime(1, 32, 20) shadow.configureConnectDisconnectTimeout(10) # 10 sec shadow.configureMQTTOperationTimeout(5) # 5 sec #Last Will shadow.configureLastWill('my/things/' + device_name + '/update', '{"state":{"reported":{"connected":"false"}}}', 1) # Connect to AWS IoT shadow.connect() # Create a deviceShadow with persistent subscription client = shadow.createShadowHandlerWithName(device_name, True) return shadow, client
os.system(' tvservice -o') os.system(' mkdir detections') os.system(' mkdir live') mac = get_mac() print (mac) s3 = boto3.client('s3', aws_access_key_id= open('keys.txt').readline().split(None, 1)[0], aws_secret_access_key= open('keys.txt').readlines()[1].split(None, 1)[0]) s3.download_file('littercam','device-'+str(mac)+'/devicename.txt', 'devicename.txt') devicename = open('devicename.txt').readline().split(None, 1)[0] print(devicename) ShadowClient = AWSIoTMQTTShadowClient("") ShadowClient.configureEndpoint("a1oa9tg9lcso0.iot.eu-west-1.amazonaws.com", 8883) 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)