Example #1
0
def awsiot_client(access_key = None,secret_key = None):
    if access_key == None:
        access_key = os.environ["AWS_ACCESS_KEY_ID"]
        
    if secret_key == None:    
        secret_key = os.environ["AWS_SECRET_ACCESS_KEY"]
    port = 8883

    region = "eu-west-1"

    # This is specific to your AWS account
    host = "abc123def456.iot.{0:s}.amazonaws.com".format(region)

    extra_headers = functools.partial(
        get_amazon_auth_headers,
        access_key,
        secret_key,
        region,
        host,
        port,
    )

    client = Client(transport="websockets")

    client.ws_set_options(headers=extra_headers)
    
    return client
Example #2
0
def init_client():
    #variabili di sistema settate 
    access_key = os.environ["AWS_ACCESS_KEY_ID"]
    secret_key = os.environ["AWS_SECRET_ACCESS_KEY"]
    port = 443

    region = "us-east-2"

    # This is specific to your AWS account
    host = "a3pwbt0axh6wnd-ats.iot.us-east-2.amazonaws.com".format(region)

    extra_headers = functools.partial(
        get_amazon_auth_headers,
        access_key,
        secret_key,
        region,
        host,
        port,
    )

    client = Client(transport="websockets")
  
    client.ws_set_options(headers=extra_headers)
    
    # Use client as normal from here
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_publish = on_publish

    client.tls_set()
    client.connect(host, 443,60)
    
    return client
Example #3
0
    def simple_publish(self, payload, routing_key='', **kwargs):
        sp_client_id = 'spc-' + str(uuid.uuid4())
        sp_client = Client(client_id=sp_client_id, transport="websockets")
        sp_client.ws_set_options(self.endpoint)
        sp_client.username_pw_set(self.credentials[0], self.credentials[1])
        if self.tls_context:
            sp_client.tls_set_context(self.tls_context)
        sp_client.connect(self.host,
                          self.port,
                          keepalive=self.heartbeat_interval)

        sp_client.loop_start()

        res = sp_client.publish(routing_key, payload=payload)
        res.wait_for_publish()

        sp_client.loop_stop()
        self.log.debug("rc={!r}".format(res.rc))
        return res.rc == 0
Example #4
0
def example_use():
    access_key = os.environ["AWS_ACCESS_KEY_ID"]
    secret_key = os.environ["AWS_SECRET_ACCESS_KEY"]
    port = 8883

    region = "eu-west-1"

    # This is specific to your AWS account
    host = "abc123def456.iot.{0:s}.amazonaws.com".format(region)

    extra_headers = functools.partial(
        get_amazon_auth_headers,
        access_key,
        secret_key,
        region,
        host,
        port,
    )

    client = Client(transport="websockets")

    client.ws_set_options(headers=extra_headers)
# This is specific to custom authorizer setup
token = {"device_id": device_name}
token_str = base64.b64encode(json.dumps(token))

command = "/bin/echo -n %s | openssl dgst -sha256 -sign %s 2>/dev/null| openssl base64 2>/dev/null" % (
    token_str, private_key)

return_code, return_str = commands.getstatusoutput(command)
signature = return_str.strip().replace('\n', '')
aws_headers = {
    "IoTDemoAuthorizerToken": token_str,
    "X-Amz-CustomAuthorizer-Signature": signature,
    "X-Amz-CustomAuthorizer-Name": authorizer_name
}
client = Client(device_name, transport="websockets")
client.ws_set_options(headers=aws_headers)
client.tls_set(ca_certs=ca_certs_file)
client.on_connect = on_connect
client.on_message = on_message
client.connect(iot_endpoint, 443, 60)


def pub_msg():
    try:
        pri_loopCount = 0
        while True:
            print 'please input:',
            msg = raw_input()
            private_data = msg
            message = {}
            message['message'] = json.dumps({
Example #6
0
def execute_subscription_api(gql_client, subscription):
    """ subscription のため、以下の処理を行う

        1. Subscription APIへ投げる
        2. 1.のレスポンスに含まれる内容を使って、エンドポイントにMQTTで接続する

        参考:https://github.com/eclipse/paho.mqtt.python/issues/277
    """
    def on_connect(client, userdata, flags, respons_code):
        print('connected')
        # 接続できたのでsubscribeする
        client.subscribe(topic)

    def on_message(client, userdata, msg):
        # メッセージを表示する
        print(f'{msg.topic} {str(msg.payload)}')
        # onCreate系
        # path/to/onCreateAppSyncToDo/ b'{"data":{"onCreateAppSyncToDo":{"title":"new","content":"new content","__typename":"AppSyncToDo"}}}'
        #
        # onUpdate系
        # path/to/onUpdateAppSyncToDo/ b'{"data":{"onUpdateAppSyncToDo":{"title":"new","content":"update","__typename":"AppSyncToDo"}}}'
        #
        # onDelete系
        # path/to/onDeleteAppSyncToDo/ b'{"data":{"onDeleteAppSyncToDo":{"title":"new","content":"update","__typename":"AppSyncToDo"}}}'

        # メッセージを受信したので、今回は切断してみる
        # これがないと、再びメッセージを待ち続ける
        client.disconnect()

    # Subscription APIに投げると、MQTTの接続情報が返ってくる
    r = gql_client.execute(subscription)

    # JSON文字列なので、デシリアライズしてPythonオブジェクトにする
    response = json.loads(r)

    # 中身を見てみる
    print(response)
    """ =>
    {'extensions': 
         {'subscription':
              {
                  'mqttConnections': [
                      {'url': 'wss://<host>.iot.<region>.amazonaws.com/mqtt?<v4_credential>',
                       'topics': ['path/to/onCreateAppSyncToDo/'], 
                       'client': '<client_id>'}],
                  'newSubscriptions': {
                      'onCreateAppSyncToDo': 
                          {'topic': 'path/to/onCreateAppSyncToDo/', 
                           'expireTime': None}}}}, 
        'data': {'onCreateAppSyncToDo': None}}
    """

    # Subscribeするのに必要な情報を取得する
    client_id = response['extensions']['subscription']['mqttConnections'][0][
        'client']
    topic = response['extensions']['subscription']['mqttConnections'][0][
        'topics'][0]

    # URLはparseして、扱いやすくする
    url = response['extensions']['subscription']['mqttConnections'][0]['url']
    urlparts = urlparse(url)

    # ヘッダーとして、netloc(ネットワーク上の位置)を設定
    headers = {
        'Host': '{0:s}'.format(urlparts.netloc),
    }

    # 送信時、ClientIDを指定した上でWebSocketで送信しないと、通信できないので注意
    mqtt_client = MQTTClient(client_id=client_id, transport='websockets')

    # 接続時のコールバックメソッドを登録する
    mqtt_client.on_connect = on_connect

    # データ受信時のコールバックメソッドを登録する
    mqtt_client.on_message = on_message

    # ヘッダやパスを指定する
    mqtt_client.ws_set_options(path=f'{urlparts.path}?{urlparts.query}',
                               headers=headers)

    # TLSを有効にする
    mqtt_client.tls_set()

    # wssで接続するため、443ポートに投げる
    mqtt_client.connect(urlparts.netloc, port=443)

    # 受信するのを待つ
    mqtt_client.loop_forever()