代码之家  ›  专栏  ›  技术社区  ›  tyczj

连接到IoT核心MQTT

  •  0
  • tyczj  · 技术社区  · 7 年前

    我正在尝试连接到Google的MQTT服务器,但出现了错误 我创建了所有证书并注册了我的设备(Adafruit huzzah32)

    文档上说你连接到 mqtt.googleapis.com:8883

    我也是

    WiFiClientSecure wifi;
    MQTTClient client;
    client.begin("mqtt.googleapis.com", 8883, wifi);
    

    当我尝试连接时,我使用设备路径

    const char* jwt = "{json web token}";
    const char* device = "projects/{project-id}/locations/{cloud-region}/registries/{registry-id}/devices/{device-id}";
    
    Serial.print("Connecting to mqtt");
    while (!client.connect(device,"unused",jwt)) {
        Serial.print(".");
        delay(1000);
    }
    
    Serial.println();
    Serial.println("Connected to mqtt");
    

    但它永远不会连接

    我通过调用 openssl s_client -showcerts -connect mqtt.googleapis.com:8883 我把我的RSA私钥和证书密钥

    wifi.setCACert(googleCertificate2);
    wifi.setCertificate(myCertificate);
    wifi.setPrivateKey(privateCert);
    

    我做错了什么?

    这是连接文档 https://cloud.google.com/iot/docs/how-tos/mqtt-bridge

    使现代化

    我做了一个快速的java示例,看看我是否可以连接他们的连接示例,然后我得到一个 MqttException Bad user name or password (4)

    这是代码

    private void doStuff(){
            String clientId = String.format("ssl://%s:%s", "mqtt.googleapis.com", 8883);
            String mqttClientId = String.format("projects/%s/locations/%s/registries/%s/devices/%s","{project_id}", "us-central1", "{register}", "{device}");
            MqttConnectOptions connectOptions = new MqttConnectOptions();
            connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    
            Properties sslProps = new Properties();
            sslProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
            connectOptions.setSSLProperties(sslProps);
    
            connectOptions.setUserName("unused");
    
    
            try{
                String jwt = createJwtRsa("{project-id}");
                connectOptions.setPassword(jwt.toCharArray());
                MqttClient client = new MqttClient(clientId, mqttClientId, new MemoryPersistence());
    
                while(!client.isConnected()){
                    try{
                        client.connect(connectOptions);
                    }catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
                Log.d("","");
            }catch (Exception e){
                e.printStackTrace();
            }
    
        }
    
        private String createJwtRsa(String projectId) throws Exception {
            DateTime now = new DateTime();
            JwtBuilder jwtBuilder =
                    Jwts.builder().setIssuedAt(now.toDate()).setExpiration(now.plusDays(1000000).toDate()).setAudience(projectId);
    
            byte[] keyBytes = readBytes(getAssets().open("rsa_private_pkcs8"));
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
    
            PrivateKey k = kf.generatePrivate(spec);
    
            return jwtBuilder.signWith(SignatureAlgorithm.RS256, k).compact();
        }
    

    如您所见,我已将物联网服务帐户添加到IAM中 enter image description here

    这是否意味着我用openssl生成的密钥不正确?

    2 回复  |  直到 7 年前
        1
  •  1
  •   tyczj    7 年前

    我的问题是,我试图在我的Json Web令牌上设置一个非常大的过期日期(出于故意,所以我不必一直生成新的,因为我在arduino中没有找到这样做的方法),而且谷歌的mqtt服务器似乎一天内不接受任何内容,所以密钥必须每天更新。

    此外,为了连接到MQTT服务器,我必须更改arduino上MQTT客户机的缓冲区大小,使其缓冲区大小为1024字节。

    MQTTClient client(1024);
    

    否则,我会得到一个错误,说缓冲区不够大。

        2
  •  0
  •   Community CDub    3 年前

    这里是 IAM 正在解释角色。。。段落 here 听起来很像你所描述的:

    在Google云平台控制台的IAM页面上,验证云物联网核心服务代理角色是否出现在相关项目服务帐户的成员列表中。(查找以@gcp sa cloudiot.iam.gserviceaccount.com结尾的项目服务帐户。)

    如果云物联网核心服务代理角色未出现在成员列表中,请使用gcloud添加云物联网。相关项目服务帐户的serviceAgent角色。此角色包括发布到发布/订阅主题的权限。

    如果尚未安装,则 Cloud SDK 所有这些都需要 gcloud CLI命令,可用于列出;编辑配置(所有配置也可以通过控制台完成)。。。这可能更简单,因为那里的所有示例都使用它。

    使现代化 ...

    关于JWT刷新令牌,请参见 article 或者吃点 Q & A 或规范: JSON Web Token (JWT) , JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants . 下面是另一篇相关文章: https://medium.com/google-cloud/refreshing-json-web-tokens-jwts-for-google-cloud-iot-core-897318df3836