Ameba Arduino: [RTL8195AM] Google Cloud IOT

材料准备
  • Ameba x 1

范例说明

这个范例里说明了如何在AMEBA上使用Cloud IoT Core。本范例不需要额外的Library,单纯使用WiFiSSLClient及PubSubClient来进行连线,在准备编译进Ameba之前,需要先注册及设置Google Cloud IoT Platform,其教学可参考于Standard SDK的范例:

https://www.amebaiot.com/google-cloud-iot/

我们打开范例 “File” -> “Examples” -> “AmebaMQTTClient” -> “google_cloud”, 如果Google Cloud IoT Platform已设置完成,我们将能得到project_id, registry_id, device_id 及private.pem.key。如下图所示,在此范例中project_id测试用的参数填入amebago-193913, registry_id填入amebago-registry及device_id填入amebago-rs256-device,请记得privateKeyBuff也要填入生成的private.pem.key ,以上参数更新完毕后即可编译并烧录至Ameba。

1

1

接着我们打开终端机软体,如下图在顺利连接上网路后开始进行Google Cloud的连接,并在连接成功之际发布讯息” This is Ameba’s x message!!”,其中x为每次回圈递增的数值。

1

验证:
在Google Cloud SDK Shell底下键入:

$ gcloud beta pubsub subscriptions pull --auto-ack \
projects/amebago-193913/subscriptions/amebago-subscription

下图即显示最近来自Ameba发布的讯息

1

程式码说明

在setup()里我们预先进行Certificate的设置,即设置RootCA和Private Key
 wifiClient.setRootCA((unsigned char*)rootCABuff);
  wifiClient.setClientCertificate(NULL, (unsigned char*)privateKeyBuff);

在loop()里,每次的loop都会检查网路状况,如果网路环境有问题就会重新进行连线

if (WiFi.status() != WL_CONNECTED) {
    while (WiFi.begin(ssid, pass) != WL_CONNECTED) 
    {
      delay(1000);
    }
    Serial.println("Connected to wifi");
  }

在开始准备发布之际需要产生mqtt_id,clientPass及pub_topic:
产生mqtt_id:

mqtt_id = (char *)malloc(strlen("projects/") + strlen(project_id) + strlen("/locations/us-central1/registries/") + strlen(registry_id) + strlen("/devices/") + strlen(device_id) + 1);
sprintf(mqtt_id, "projects/%s/locations/us-central1/registries/%s/devices/%s", project_id, registry_id, device_id);

产生clientPass(经由JWT Format产生):

clientPass = jwt_generator((unsigned char*)privateKeyBuff, project_id, 3600*1);

产生pub_topic:

pub_topic = (char *)malloc(strlen("/devices/") + strlen(device_id) + strlen("/events") + 1);
sprintf(pub_topic, "/devices/%s/events", device_id);

MQTT Server参数设定:

 client.setServer(GOOGLE_MQTT_SERVER, GOOGLE_MQTT_PORT);
 client.setPublishQos(MQTTQOS1);
 client.waitForAck(true);

接着开始进行google cloud的连线

if (client.connect(mqtt_id, clientUser, clientPass) )
 {
	..........
	for(int i = 0; i < count; i++){
     ..........
     sprintf(payload, "This is Ameba's %d message!!", i);
     ret = client.publish(pub_topic, payload);   
     ..........
 }
	..........
   client.disconnect();
 }
 free(mqtt_id);
 free(pub_topic);

如果成功,就会将payload以client.publish method发布出去,最后别忘了作正确的断线及free掉mqtt_id及pub_topic的buffer。

请先确认已安装QQ通讯软体