

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 無線更新示範應用程式
<a name="ota-demo"></a>

FreeRTOS 包含示範應用程式，示範over-the-air(OTA) 程式庫的功能。OTA 示範應用程式位於 `freertos/demos/ota/ota_demo_core_mqtt/ota_demo_core_mqtt.c`或 `freertos/demos/ota/ota_demo_core_http/ota_demo_core_http.c`檔案中。

OTA 示範應用程式可執行下列作業：

1. 初始化 FreeRTOS 網路堆疊和 MQTT 緩衝集區。

1. 使用 建立任務以執行 OTA 程式庫`vRunOTAUpdateDemo()`。

1. 使用 `_establishMqttConnection()` 建立 MQTT 用戶端。

1. 使用 連線至 AWS IoT MQTT 中介裝置，`IotMqtt_Connect()`並註冊 MQTT 中斷連線回呼：`prvNetworkDisconnectCallback`。

1. 呼叫 `OTA_AgentInit()` 來建立 OTA 任務，並註冊在 OTA 任務完成時使用的回呼。

1. 重複使用 MQTT 連線與 `xOTAConnectionCtx.pvControlClient = _mqttConnection;`

1. 如果 MQTT 中斷連線，應用程式會暫停 OTA 代理程式，嘗試使用指數延遲與抖動重新連線，然後繼續 OTA 代理程式。

在使用 OTA 更新之前，請先完成 中的所有先決條件 [FreeRTOS Over-the-Air更新](freertos-ota-dev.md)

完成設定 OTA 更新後，請在支援 OTA 功能的平台上下載、建置、刷新和執行 FreeRTOS OTA 示範。裝置特定的示範指示適用於下列符合 FreeRTOS 資格的裝置：
+ [Texas Instruments CC3220SF-LAUNCHXL](download-ota-ti.md)
+ [Microchip Curiosity PIC32MZEF](download-ota-mchip.md)
+ [Espressif ESP32](download-ota-esp.md)
+ [在 Renesas RX65N 上下載、建置、刷新和執行 FreeRTOS OTA 示範](download-rx65n-ota.md)

在裝置上建置、刷新和執行 OTA 示範應用程式之後，您可以使用 AWS IoT 主控台或 AWS CLI 來建立 OTA 更新任務。在您建立 OTA 更新任務後，請連線終端機模擬器，以查看 OTA 的進度更新。請記下程序中產生的任何錯誤。

成功的 OTA 更新任務，會顯示如下所示的輸出。為簡潔起見，此範例中的某些行已從清單中移除。

```
    249 21207 [iot_thread] [ota_demo_core_mqtt.c:1850] [INFO] [MQTT]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    250 21247 [MQTT Agent Task] [core_mqtt.c:886] [INFO] [MQTT] Packet received. ReceivedBytes=601.
    251 21247 [MQTT Agent Task] [core_mqtt.c:1045] [INFO] [MQTT] De-serialized incoming PUBLISH packet: DeserializerResult=MQTTSuccess.
    252 21248 [MQTT Agent Task] [core_mqtt.c:1058] [INFO] [MQTT] State record updated. New state=MQTTPubAckSend.
    253 21249 [MQTT Agent Task] [ota_demo_core_mqtt.c:976] [INFO] [MQTT] Received job message callback, size 548.
    254 21252 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[execution.jobId: AFR_OTA-9702f1a3-b747-4c3e-a0eb-a3b0cf83ddbb]
    255 21253 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[execution.jobDocument.afr_ota.streamname: AFR_OTA-945d320b-a18b-441b-b435-4a18d4e7671f]
    256 21255 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[execution.jobDocument.afr_ota.protocols: ["MQTT"]]
    257 21256 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[filepath: aws_demos.bin]
    258 21257 [OTA Agent Task] [ota.c:1684] [INFO] [OTA] Extracted parameter: [key: value]=[filesize: 1164016]
    259 21258 [OTA Agent Task] [ota.c:1684] [INFO] [OTA] Extracted parameter: [key: value]=[fileid: 0]
    260 21259 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[certfile: ecdsa-sha256-signer.crt.pem]
    261 21260 [OTA Agent Task] [ota.c:1575] [INFO] [OTA] Extracted parameter [ sig-sha256-ecdsa: MEQCIE1SFkIHHiZAvkPpu6McJtx7SYoD... ]
    262 21261 [OTA Agent Task] [ota.c:1684] [INFO] [OTA] Extracted parameter: [key: value]=[fileType: 0]
    263 21262 [OTA Agent Task] [ota.c:2199] [INFO] [OTA] Job document was accepted. Attempting to begin the update.
    264 21263 [OTA Agent Task] [ota.c:2323] [INFO] [OTA] Job parsing success: OtaJobParseErr_t=OtaJobParseErrNone, Job name=AFR_OTA-9702f1a3-b747-4c3e-a0eb-a3b0cf83ddbb
    265 21318 [iot_thread] [ota_demo_core_mqtt.c:1850] [INFO] [MQTT]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    266 21418 [iot_thread] [ota_demo_core_mqtt.c:1850] [INFO] [MQTT]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    267 21469 [OTA Agent Task] [ota.c:938] [INFO] [OTA] Setting OTA data interface.
    268 21470 [OTA Agent Task] [ota.c:2839] [INFO] [OTA] Current State=[CreatingFile], Event=[ReceivedJobDocument], New state=[CreatingFile]
    269 21482 [MQTT Agent Task] [core_mqtt.c:886] [INFO] [MQTT] Packet received. ReceivedBytes=3.
    270 21483 [OTA Agent Task] [ota_demo_core_mqtt.c:1503] [INFO] [MQTT] SUBSCRIBED to topic $aws/things/__test_infra_thing71/streams/AFR_OTA-945d320b-a18b-441b-b435-4a18d4e7671f/data/cbor to bro
    271 21484 [OTA Agent Task] [ota.c:2839] [INFO] [OTA] Current State=[RequestingFileBlock], Event=[CreateFile], New state=[RequestingFileBlock]
    272 21518 [iot_thread] [ota_demo_core_mqtt.c:1850] [INFO] [MQTT]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    273 21532 [MQTT Agent Task] [core_mqtt_agent_command_functions.c:76] [INFO] [MQTT] Publishing message to $aws/things/__test_infra_thing71/streams/AFR_OTA-945d320b-a18b-441b-b435-4a18d4e7671f/
    274 21534 [OTA Agent Task] [ota_demo_core_mqtt.c:1553] [INFO] [MQTT] Sent PUBLISH packet to broker $aws/things/__test_infra_thing71/streams/AFR_OTA-945d320b-a18b-441b-b435-4a18d4e7671f/get/cbor
    275 21534 [OTA Agent Task] [ota_mqtt.c:1112] [INFO] [OTA] Published to MQTT topic to request the next block: topic=$aws/things/__test_infra_thing71/streams/AFR_OTA-945d320b-a18b-441b-b435-4a1
    276 21537 [OTA Agent Task] [ota.c:2839] [INFO] [OTA] Current State=[WaitingForFileBlock], Event=[RequestFileBlock], New state=[WaitingForFileBlock]
    277 21558 [MQTT Agent Task] [core_mqtt.c:886] [INFO] [MQTT] Packet received. ReceivedBytes=4217.
    278 21559 [MQTT Agent Task] [core_mqtt.c:1045] [INFO] [MQTT] De-serialized incoming PUBLISH packet: DeserializerResult=MQTTSuccess.
    279 21560 [MQTT Agent Task] [core_mqtt.c:1058] [INFO] [MQTT] State record updated. New state=MQTTPublishDone.
    280 21561 [MQTT Agent Task] [ota_demo_core_mqtt.c:1026] [INFO] [MQTT] Received data message callback, size 4120.
    281 21563 [OTA Agent Task] [ota.c:2464] [INFO] [OTA] Received valid file block: Block index=0, Size=4096
    282 21566 [OTA Agent Task] [ota.c:2683] [INFO] [OTA] Number of blocks remaining: 284
     
    ... // Output removed for brevity
     
    3672 42745 [OTA Agent Task] [ota.c:2464] [INFO] [OTA] Received valid file block: Block index=284, Size=752
    3673 42747 [OTA Agent Task] [ota.c:2633] [INFO] [OTA] Received final block of the update.
    (428298) ota_pal: No such certificate file: ecdsa-sha256-signer.crt.pem. Using certificate in ota_demo_config.h.
    3674 42818 [iot_thread] [ota_demo_core_mqtt.c:1850] [INFO] [MQTT]  Received: 285   Queued: 285   Processed: 284   Dropped: 0
    3675 42918 [iot_thread] [ota_demo_core_mqtt.c:1850] [INFO] [MQTT]  Received: 285   Queued: 285   Processed: 284   Dropped: 0
     
    ... // Output removed for brevity
     
    3678 43197 [OTA Agent Task] [ota.c:2654] [INFO] [OTA] Received entire update and validated the signature.
    3685 43215 [OTA Agent Task] [ota_demo_core_mqtt.c:862] [INFO] [MQTT] Received OtaJobEventActivate callback from OTA Agent.
     
    ... // Output removed for brevity
     
    2 39 [iot_thread] [INFO ][DEMO][390] ---------STARTING DEMO---------
     
    [0;32mI (3633) WIFI: WIFI_EVENT_STA_CONNECTED
    [0;32mI (4373) WIFI: SYSTEM_EVENT_STA_GOT_IP
     
    ... // Output removed for brevity 
     
    4 351 [sys_evt] [INFO ][DEMO][3510] Connected to WiFi access point, ip address: 255.255.255.0.
    5 351 [iot_thread] [INFO ][DEMO][3510] Successfully initialized the demo. Network type for the demo: 1
    6 351 [iot_thread] [ota_demo_core_mqtt.c:1902] [INFO] [MQTT] OTA over MQTT demo, Application version 0.9.1
    7 351 [iot_thread] [ota_demo_core_mqtt.c:1323] [INFO] [MQTT] Creating a TLS connection to <endpoint>-ats.iot.us-west-2.amazonaws.com:8883.
    9 718 [iot_thread] [core_mqtt.c:886] [INFO] [MQTT] Packet received. ReceivedBytes=2.
    10 718 [iot_thread] [core_mqtt_serializer.c:970] [INFO] [MQTT] CONNACK session present bit not set.
    11 718 [iot_thread] [core_mqtt_serializer.c:912] [INFO] [MQTT] Connection accepted.
     
    ... // Output removed for brevity
     
    17 736 [OTA Agent Task] [ota_demo_core_mqtt.c:1503] [INFO] [MQTT] SUBSCRIBED to topic $aws/things/__test_infra_thing71/jobs/notify-next to broker.
    18 737 [OTA Agent Task] [ota_mqtt.c:381] [INFO] [OTA] Subscribed to MQTT topic: $aws/things/__test_infra_thing71/jobs/notify-next
    30 818 [iot_thread] [ota_demo_core_mqtt.c:1850] [INFO] [MQTT]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    31 819 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[execution.jobId: AFR_OTA-9702f1a3-b747-4c3e-a0eb-a3b0cf83ddbb]
    32 820 [OTA Agent Task] [ota.c:1684] [INFO] [OTA] Extracted parameter: [key: value]=[execution.statusDetails.updatedBy: 589824]
    33 822 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[execution.jobDocument.afr_ota.streamname: AFR_OTA-945d320b-a18b-441b-b435-4a18d4e7671f]
    34 823 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[execution.jobDocument.afr_ota.protocols: ["MQTT"]]
    35 824 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[filepath: aws_demos.bin]
    36 825 [OTA Agent Task] [ota.c:1684] [INFO] [OTA] Extracted parameter: [key: value]=[filesize: 1164016]
    37 826 [OTA Agent Task] [ota.c:1684] [INFO] [OTA] Extracted parameter: [key: value]=[fileid: 0]
    38 827 [OTA Agent Task] [ota.c:1645] [INFO] [OTA] Extracted parameter: [key: value]=[certfile: ecdsa-sha256-signer.crt.pem]
    39 828 [OTA Agent Task] [ota.c:1575] [INFO] [OTA] Extracted parameter [ sig-sha256-ecdsa: MEQCIE1SFkIHHiZAvkPpu6McJtx7SYoD... ]
    40 829 [OTA Agent Task] [ota.c:1684] [INFO] [OTA] Extracted parameter: [key: value]=[fileType: 0]
    41 830 [OTA Agent Task] [ota.c:2102] [INFO] [OTA] In self test mode.
    42 830 [OTA Agent Task] [ota.c:1936] [INFO] [OTA] New image has a higher version number than the current image: New image version=0.9.1, Previous image version=0.9.0
    43 832 [OTA Agent Task] [ota.c:2120] [INFO] [OTA] Image version is valid: Begin testing file: File ID=0
    53 896 [OTA Agent Task] [ota.c:794] [INFO] [OTA] Beginning self-test.
    62 971 [OTA Agent Task] [ota_demo_core_mqtt.c:1553] [INFO] [MQTT] Sent PUBLISH packet to broker $aws/things/__test_infra_thing71/jobs/AFR_OTA-9702f1a3-b747-4c3e-a0eb-a3b0cf83ddbb/update to br63 971 [MQTT Agent Task] [core_mqtt.c:1045] [INFO] [MQTT] De-serialized incoming PUBLISH packet: DeserializerResult=MQTTSuccess.
    65 973 [MQTT Agent Task] [core_mqtt.c:1058] [INFO] [MQTT] State record updated. New state=MQTTPublishDone.
    64 973 [OTA Agent Task] [ota_demo_core_mqtt.c:902] [INFO] [MQTT] Successfully updated with the new image.
```

# Over-the-air示範組態
<a name="ota-demo-specific-config"></a>

OTA 示範組態是 中提供的示範特定組態選項`aws_iot_ota_update_demo.c`。這些組態與 OTA 程式庫組態檔案中提供的 OTA 程式庫組態不同。

**OTA\$1DEMO\$1KEEP\$1ALIVE\$1SECONDS**  
對於 MQTT 用戶端，此組態是完成一個控制封包傳輸到開始傳送下一個控制封包之間可能經過的最大時間間隔。如果沒有控制封包，則會傳送 PINGREQ。代理程式必須中斷用戶端的連線，該用戶端在此保持作用間隔的一倍半內不會傳送訊息或 PINGREQ 封包。此組態應根據應用程式的需求進行調整。

**OTA\$1DEMO\$1CONN\$1RETRY\$1BASE\$1INTERVAL\$1SECONDS**  
重試網路連線之前的基本間隔，以秒為單位。OTA 示範會在此基本時間間隔之後嘗試重新連線。每次嘗試失敗後，間隔會加倍。隨機延遲也會新增至間隔，最多可達此基本延遲的上限。

**OTA\$1DEMO\$1CONN\$1RETRY\$1MAX\$1INTERVAL\$1SECONDS**  
重試網路連線之前的最大間隔，以秒為單位。每次失敗的嘗試都會加倍重新連線延遲，但只能達到此最大值，加上相同間隔的抖動。

# 在 Texas Instruments CC3220SF-LAUNCHXL 下載、建置、刷新和執行 FreeRTOS OTA 示範
<a name="download-ota-ti"></a>

**重要**  <a name="deprecation-message"></a>
此參考整合託管在已棄用的 Amazon-FreeRTOS 儲存庫上。我們建議您在建立新專案時從[這裡開始](freertos-getting-started-modular.md)。如果您已經有以現在已棄用的 Amazon-FreeRTOS 儲存庫為基礎的現有 FreeRTOS 專案，請參閱 [Amazon-FreeRTOS Github 儲存庫遷移指南](github-repo-migration.md)。 FreeRTOS <a name="download-demo"></a>

**下載 FreeRTOS 和 OTA 示範程式碼**
+ 您可以在 GitHub 網站 https：//[https://github.com/FreeRTOS/FreeRTOS](https://github.com/FreeRTOS/FreeRTOS) 下載原始程式碼。<a name="build-demo"></a>

**建置示範應用程式**

1. 遵循 中的指示，將`aws_demos`專案[FreeRTOS 入門](freertos-getting-started.md)匯入 Code Composer Studio、設定您的 AWS IoT 端點、Wi-Fi SSID 和密碼，以及電路板的私有金鑰和憑證。

1.  開啟 `freertos/vendors/vendor/boards/board/aws_demos/config_files/aws_demo_config.h`、註解 `#define CONFIG_CORE_MQTT_MUTUAL_AUTH_DEMO_ENABLED`，並定義 `CONFIG_OTA_MQTT_UPDATE_DEMO_ENABLED`或 `CONFIG_OTA_HTTP_UPDATE_DEMO_ENABLED`。

1. 建置解決方案並確認過程中沒有發生任何錯誤。

1. 啟動終端機模擬器，並使用以下設定來連線到您的電路板：
   + 傳輸速率：115200
   + 資料位元：8
   + 同位：無
   + 停止位元：1

1. 在您的主機板上執行專案，確認它可以連線到 Wi-Fi 及 AWS IoT MQTT 訊息中介裝置。

執行時，終端機模擬器應會顯示與以下內容相似的文字：

```
    0 1000 [Tmr Svc] Simple Link task created
    Device came up in Station mode
    1 2534 [Tmr Svc] Write certificate...
    2 5486 [Tmr Svc] [ERROR] Failed to destroy object. PKCS11_PAL_DestroyObject failed.
    3 5486 [Tmr Svc] Write certificate...
    4 5776 [Tmr Svc] Security alert threshold = 15
    5 5776 [Tmr Svc] Current number of alerts = 1
    6 5778 [Tmr Svc] Running Demos.
    7 5779 [iot_thread] [INFO ][DEMO][5779] ---------STARTING DEMO---------
    8 5779 [iot_thread] [INFO ][INIT][5779] SDK successfully initialized.
    Device came up in Station mode
    [WLAN EVENT] STA Connected to the AP: afrlab-pepper , BSSID: 74:83:c2:b4:46:27
    [NETAPP EVENT] IP acquired by the device
    Device has connected to afrlab-pepper
    Device IP Address is 192.168.36.176 
    9 8283 [iot_thread] [INFO ][DEMO][8282] Successfully initialized the demo. Network type for the demo: 1
    10 8283 [iot_thread] [INFO] OTA over MQTT demo, Application version 0.9.0
    11 8283 [iot_thread] [INFO] Creating a TLS connection to <endpoint>-ats.iot.us-west-2.amazonaws.com:8883.
    12 8852 [iot_thread] [INFO] Creating an MQTT connection to <endpoint>-ats.iot.us-west-2.amazonaws.com.
    13 8914 [iot_thread] [INFO] Packet received. ReceivedBytes=2.
    14 8914 [iot_thread] [INFO] CONNACK session present bit not set.
    15 8914 [iot_thread] [INFO] Connection accepted.
    16 8914 [iot_thread] [INFO] Received MQTT CONNACK successfully from broker.
    17 8914 [iot_thread] [INFO] MQTT connection established with the broker.
    18 8915 [iot_thread] [INFO]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    19 8953 [OTA Agent T] [INFO] Current State=[RequestingJob], Event=[Start], New state=[RequestingJob]
    20 9008 [MQTT Agent ] [INFO] Packet received. ReceivedBytes=3.
    21 9015 [OTA Agent T] [INFO] SUBSCRIBED to topic $aws/things/__test_infra_thing73/jobs/notify-next to broker.
    22 9015 [OTA Agent T] [INFO] Subscribed to MQTT topic: $aws/things/__test_infra_thing73/jobs/notify-next
    23 9504 [MQTT Agent ] [INFO] Publishing message to $aws/things/__test_infra_thing73/jobs/$next/get.
    24 9535 [MQTT Agent ] [INFO] Packet received. ReceivedBytes=2.
    25 9535 [MQTT Agent ] [INFO] Ack packet deserialized with result: MQTTSuccess.
    26 9536 [MQTT Agent ] [INFO] State record updated. New state=MQTTPublishDone.
    27 9537 [OTA Agent T] [INFO] Sent PUBLISH packet to broker $aws/things/__test_infra_thing73/jobs/$next/get to broker.
    28 9537 [OTA Agent T] [WARN] OTA Timer handle NULL for Timerid=0, can't stop.
    29 9537 [OTA Agent T] [INFO] Current State=[WaitingForJob], Event=[RequestJobDocument], New state=[WaitingForJob]
    30 9539 [MQTT Agent ] [INFO] Packet received. ReceivedBytes=120.
    31 9539 [MQTT Agent ] [INFO] De-serialized incoming PUBLISH packet: DeserializerResult=MQTTSuccess.
    32 9540 [MQTT Agent ] [INFO] State record updated. New state=MQTTPublishDone.
    33 9540 [MQTT Agent ] [INFO] Received job message callback, size 62.
    34 9616 [OTA Agent T] [INFO] Failed job document content check: Required job document parameter was not extracted: parameter=execution
    35 9616 [OTA Agent T] [INFO] Failed job document content check: Required job document parameter was not extracted: parameter=execution.jobId
    36 9617 [OTA Agent T] [INFO] Failed job document content check: Required job document parameter was not extracted: parameter=execution.jobDocument
    37 9617 [OTA Agent T] [INFO] Failed job document content check: Required job document parameter was not extracted: parameter=execution.jobDocument.afr_ota
    38 9617 [OTA Agent T] [INFO] Failed job document content check: Required job document parameter was not extracted: parameter=execution.jobDocument.afr_ota.protocols
    39 9618 [OTA Agent T] [INFO] Failed job document content check: Required job document parameter was not extracted: parameter=execution.jobDocument.afr_ota.files
    40 9618 [OTA Agent T] [INFO] Failed job document content check: Required job document parameter was not extracted: parameter=filesize
    41 9618 [OTA Agent T] [INFO] Failed job document content check: Required job document parameter was not extracted: parameter=fileid
    42 9619 [OTA Agent T] [INFO] Failed to parse JSON document as AFR_OTA job: DocParseErr_t=7
    43 9619 [OTA Agent T] [INFO] No active job available in received job document: OtaJobParseErr_t=OtaJobParseErrNoActiveJobs
    44 9619 [OTA Agent T] [ERROR] Failed to execute state transition handler: Handler returned error: OtaErr_t=OtaErrJobParserError
    45 9620 [OTA Agent T] [INFO] Current State=[WaitingForJob], Event=[ReceivedJobDocument], New state=[CreatingFile]
    46 9915 [iot_thread] [INFO]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    47 10915 [iot_thread] [INFO]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    48 11915 [iot_thread] [INFO]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    49 12915 [iot_thread] [INFO]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    50 13915 [iot_thread] [INFO]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
    51 14915 [iot_thread] [INFO]  Received: 0   Queued: 0   Processed: 0   Dropped: 0
```

# 在 Microchip Curiosity PIC32MZEF 上下載、建置、刷新和執行 FreeRTOS OTA 示範
<a name="download-ota-mchip"></a>

**重要**  <a name="deprecation-message"></a>
此參考整合託管在已棄用的 Amazon-FreeRTOS 儲存庫上。我們建議您在建立新專案時從[這裡開始](freertos-getting-started-modular.md)。如果您已經有以現在已棄用的 Amazon-FreeRTOS 儲存庫為基礎的現有 FreeRTOS 專案，請參閱 [Amazon-FreeRTOS Github 儲存庫遷移指南](github-repo-migration.md)。 FreeRTOS 

**注意**  
為與 Microchip 達成一致，我們將從 FreeRTOS 參考整合儲存庫主分支中移除 Curiosity PIC32MZEF (DM320104)，並且不會再將其帶入新版本。Microchip 已發出[正式通知](https://www.microchip.com/DevelopmentTools/ProductDetails/PartNO/DM320104)，指出不再建議將 PIC32MZEF (DM320104) 用於新設計。PIC32MZEF 專案和原始程式碼仍然可以透過先前的版本標籤存取。Microchip 建議客戶使用 Curiosity [ PIC32MZ-EF-2.0 開發板 (DM320209)](https://devices.amazonaws.com/detail/a3G0h0000077I69EAE/Curiosity-PIC32MZ-EF-2-0-Development-Board) 進行新設計。PIC32MZv1 平台仍然可以在 FreeRTOS 參考整合儲存庫的 [v202012.00](https://github.com/aws/amazon-freertos/tree/202012.00) 中找到。不過，FreeRTOS 參考的 [v202107.00](https://github.com/aws/amazon-freertos/tree/202107.00) 不再支援平台。<a name="mch-dowload-demo"></a>

**下載 FreeRTOS OTA 示範程式碼**
+ 您可以在 GitHub 網站 https：//[https://github.com/FreeRTOS/FreeRTOS](https://github.com/FreeRTOS/FreeRTOS) 下載原始程式碼。<a name="mch-build-demo"></a>

**建置 OTA 更新示範應用程式**

1. 遵循 中的指示，將`aws_demos`專案[FreeRTOS 入門](freertos-getting-started.md)匯入 MPLAB X IDE、設定您的 AWS IoT 端點、Wi-Fi SSID 和密碼，以及電路板的私有金鑰和憑證。

1. 開啟 `vendors/vendor/boards/board/aws_demos/config_files/ota_demo_config.h` 檔案，然後輸入您的憑證。

   ```
   [] = "your-certificate-key";
   ```

1. 將程式碼簽署憑證的內容貼到這裡：

   ```
   #define otapalconfigCODE_SIGNING_CERTIFICATE [] = "your-certificate-key";
   ```

   遵循與 `aws_clientcredential_keys.h` -- 相同的格式，每一行必須以新的行字元 ('\$1n') 結尾，並以引號括住。

   例如，您的憑證應看起來與下列類似：

   ```
   "-----BEGIN CERTIFICATE-----\n"
   "MIIBXTCCAQOgAwIBAgIJAM4DeybZcTwKMAoGCCqGSM49BAMCMCExHzAdBgNVBAMM\n"
   "FnRlc3Rf62lnbmVyQGFtYXpvbi5jb20wHhcNMTcxMTAzMTkxODM1WhcNMTgxMTAz\n"
   "MTkxODM2WjAhMR8wHQYDVQBBZZZ0ZXN0X3NpZ25lckBhbWF6b24uY29tMFkwEwYH\n"
   "KoZIzj0CAQYIKoZIzj0DAQcDQgAERavZfvwL1X+E4dIF7dbkVMUn4IrJ1CAsFkc8\n"
   "gZxPzn683H40XMKltDZPEwr9ng78w9+QYQg7ygnr2stz8yhh06MkMCIwCwYDVR0P\n"
   "BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMAoGCCqGSM49BAMCA0gAMEUCIF0R\n"
   "r5cb7rEUNtWOvGd05MacrgOABfSoVYvBOK9fP63WAqt5h3BaS123coKSGg84twlq\n"
   "TkO/pV/xEmyZmZdV+HxV/OM=\n"
   "-----END CERTIFICATE-----\n";
   ```

1. 安裝 [Python 3](https://www.python.org/downloads/) 或更新版本。

1. 透過執行 `pip install pyopenssl` 來安裝 `pyOpenSSL`。

1. 複製 `demos/ota/bootloader/utility/codesigner_cert_utility/` 路徑中格式為 .pem 的程式碼簽署憑證。將該憑證檔案重新命名為 `aws_ota_codesigner_certificate.pem`。

1.  開啟 `freertos/vendors/vendor/boards/board/aws_demos/config_files/aws_demo_config.h`、註解 `#define CONFIG_CORE_MQTT_MUTUAL_AUTH_DEMO_ENABLED`，並定義 `CONFIG_OTA_MQTT_UPDATE_DEMO_ENABLED`或 `CONFIG_OTA_HTTP_UPDATE_DEMO_ENABLED`。

1. 建置解決方案並確認過程中沒有發生任何錯誤。

1. 啟動終端機模擬器，並使用以下設定來連線到您的電路板：
   + 傳輸速率：115200
   + 資料位元：8
   + 同位：無
   + 停止位元：1

1. 從電路板拔除除錯器，並在電路板上執行專案，以確認它可以連線至 Wi-Fi 和 AWS IoT MQTT 訊息代理程式。

當您執行專案時，MPLAB X IDE 應會開啟輸出視窗。確認已選取 **ICD4** 索引標籤。您應該會看到下列輸出。

```
Bootloader version 00.09.00
[prvBOOT_Init] Watchdog timer initialized.
[prvBOOT_Init] Crypto initialized.

[prvValidateImage] Validating image at Bank : 0
[prvValidateImage] No application image or magic code present at: 0xbd000000
[prvBOOT_ValidateImages] Validation failed for image at 0xbd000000

[prvValidateImage] Validating image at Bank : 1
[prvValidateImage] No application image or magic code present at: 0xbd100000
[prvBOOT_ValidateImages] Validation failed for image at 0xbd100000

[prvBOOT_ValidateImages] Booting default image.


>0 36246 [IP-task] vDHCPProcess: offer ac140a0eip
                                                 1 36297 [IP-task] vDHCPProcess: offer ac140a0eip
                 2 36297 [IP-task]

IP Address: 172.20.10.14
3 36297 [IP-task] Subnet Mask: 255.255.255.240
4 36297 [IP-task] Gateway Address: 172.20.10.1
5 36297 [IP-task] DNS Server Address: 172.20.10.1


6 36299 [OTA] OTA demo version 0.9.2
7 36299 [OTA] Creating MQTT Client...
8 36299 [OTA] Connecting to broker...
9 38673 [OTA] Connected to broker.
10 38793 [OTA Task] [prvSubscribeToJobNotificationTopics] OK: $aws/things/devthingota/jobs/$next/get/accepted
11 38863 [OTA Task] [prvSubscribeToJobNotificationTopics] OK: $aws/things/devthingota/jobs/notify-next
12 38863 [OTA Task] [OTA_CheckForUpdate] Request #0
13 38964 [OTA] [OTA_AgentInit] Ready.
14 38973 [OTA Task] [prvParseJSONbyModel] Extracted parameter [ clientToken: 0:devthingota ]
15 38973 [OTA Task] [prvParseJSONbyModel] parameter not present: execution
16 38973 [OTA Task] [prvParseJSONbyModel] parameter not present: jobId
17 38973 [OTA Task] [prvParseJSONbyModel] parameter not present: jobDocument
18 38973 [OTA Task] [prvParseJSONbyModel] parameter not present: streamname
19 38973 [OTA Task] [prvParseJSONbyModel] parameter not present: files
20 38975 [OTA Task] [prvParseJSONbyModel] parameter not present: filepath
21 38975 [OTA Task] [prvParseJSONbyModel] parameter not present: filesize
22 38975 [OTA Task] [prvParseJSONbyModel] parameter not present: fileid
23 38975 [OTA Task] [prvParseJSONbyModel] parameter not present: certfile
24 38975 [OTA Task] [prvParseJSONbyModel] parameter not present: sig-sha256-ecdsa
25 38975 [OTA Task] [prvParseJobDoc] Ignoring job without ID.
26 38975 [OTA Task] [prvOTA_Close] Context->0x8003b620
27 38975 [OTA Task] [prvPAL_Abort] Abort - OK
28 39964 [OTA] State: Ready  Received: 1   Queued: 1   Processed: 1   Dropped: 0
29 40964 [OTA] State: Ready  Received: 1   Queued: 1   Processed: 1   Dropped: 0
30 41964 [OTA] State: Ready  Received: 1   Queued: 1   Processed: 1   Dropped: 0
31 42964 [OTA] State: Ready  Received: 1   Queued: 1   Processed: 1   Dropped: 0
32 43964 [OTA] State: Ready  Received: 1   Queued: 1   Processed: 1   Dropped: 0
33 44964 [OTA] State: Ready  Received: 1   Queued: 1   Processed: 1   Dropped: 0
34 45964 [OTA] State: Ready  Received: 1   Queued: 1   Processed: 1   Dropped: 0
35 46964 [OTA] State: Ready  Received: 1   Queued: 1   Processed: 1   Dropped: 0
36 47964 [OTA] State: Ready  Received: 1   Queued: 1   Processed: 1   Dropped: 0
```

終端機模擬器應會顯示與以下內容相似的文字：

```
AWS Validate: no valid signature in descr: 0xbd000000
AWS Validate: no valid signature in descr: 0xbd100000


>AWS Launch:  No Map performed. Running directly from address: 0x9d000020?
AWS Launch:  wait for app at: 0x9d000020
WILC1000: Initializing...
0 0 

>[None] Seed for randomizer: 1172751941
1 0 [None] Random numbers: 00004272 00003B34 00000602 00002DE3
Chip ID 1503a0

[spi_cmd_rsp][356][nmi spi]: Failed cmd response read, bus error...

[spi_read_reg][1086][nmi spi]: Failed cmd response, read reg (0000108c)...

[spi_read_reg][1116]Reset and retry 10 108c

Firmware ver. : 4.2.1

Min driver ver : 4.2.1

Curr driver ver: 4.2.1

WILC1000: Initialization successful!

Start Wi-Fi Connection...
Wi-Fi Connected
2 7219 [IP-task] vDHCPProcess: offer c0a804beip
3 7230 [IP-task] vDHCPProcess: offer c0a804beip
4 7230 [IP-task] 

IP Address: 192.168.4.190
5 7230 [IP-task] Subnet Mask: 255.255.240.0
6 7230 [IP-task] Gateway Address: 192.168.0.1
7 7230 [IP-task] DNS Server Address: 208.67.222.222


8 7232 [OTA] OTA demo version 0.9.0
9 7232 [OTA] Creating MQTT Client...
10 7232 [OTA] Connecting to broker...
11 7232 [OTA] Sending command to MQTT task.
12 7232 [MQTT] Received message 10000 from queue.
13 8501 [IP-task] Socket sending wakeup to MQTT task.
14 10207 [MQTT] Received message 0 from queue.
15 10256 [IP-task] Socket sending wakeup to MQTT task.
16 10256 [MQTT] Received message 0 from queue.
17 10256 [MQTT] MQTT Connect was accepted. Connection established.
18 10256 [MQTT] Notifying task.
19 10257 [OTA] Command sent to MQTT task passed.
20 10257 [OTA] Connected to broker.
21 10258 [OTA Task] Sending command to MQTT task.
22 10258 [MQTT] Received message 20000 from queue.
23 10306 [IP-task] Socket sending wakeup to MQTT task.
24 10306 [MQTT] Received message 0 from queue.
25 10306 [MQTT] MQTT Subscribe was accepted. Subscribed.
26 10306 [MQTT] Notifying task.
27 10307 [OTA Task] Command sent to MQTT task passed.
28 10307 [OTA Task] [OTA] Subscribed to topic: $aws/things/Microchip/jobs/$next/get/accepted

29 10307 [OTA Task] Sending command to MQTT task.
30 10307 [MQTT] Received message 30000 from queue.
31 10336 [IP-task] Socket sending wakeup to MQTT task.
32 10336 [MQTT] Received message 0 from queue.
33 10336 [MQTT] MQTT Subscribe was accepted. Subscribed.
34 10336 [MQTT] Notifying task.
35 10336 [OTA Task] Command sent to MQTT task passed.
36 10336 [OTA Task] [OTA] Subscribed to topic: $aws/things/Microchip/jobs/notify-next

37 10336 [OTA Task] [OTA] Check For Update #0
38 10336 [OTA Task] Sending command to MQTT task.
39 10336 [MQTT] Received message 40000 from queue.
40 10366 [IP-task] Socket sending wakeup to MQTT task.
41 10366 [MQTT] Received message 0 from queue.
42 10366 [MQTT] MQTT Publish was successful.
43 10366 [MQTT] Notifying task.
44 10366 [OTA Task] Command sent to MQTT task passed.
45 10376 [IP-task] Socket sending wakeup to MQTT task.
46 10376 [MQTT] Received message 0 from queue.
47 10376 [OTA Task] [OTA] Set job doc parameter [ clientToken: 0:Microchip ]
48 10376 [OTA Task] [OTA] Missing job parameter: execution
49 10376 [OTA Task] [OTA] Missing job parameter: jobId
50 10376 [OTA Task] [OTA] Missing job parameter: jobDocument
51 10378 [OTA Task] [OTA] Missing job parameter: ts_ota
52 10378 [OTA Task] [OTA] Missing job parameter: files
53 10378 [OTA Task] [OTA] Missing job parameter: streamname
54 10378 [OTA Task] [OTA] Missing job parameter: certfile
55 10378 [OTA Task] [OTA] Missing job parameter: filepath
56 10378 [OTA Task] [OTA] Missing job parameter: filesize
57 10378 [OTA Task] [OTA] Missing job parameter: sig-sha256-ecdsa
58 10378 [OTA Task] [OTA] Missing job parameter: fileid
59 10378 [OTA Task] [OTA] Missing job parameter: attr
60 10378 [OTA Task] [OTA] Returned buffer to MQTT Client.
61 11367 [OTA] [OTA] Queued: 1   Processed: 1   Dropped: 0
62 12367 [OTA] [OTA] Queued: 1   Processed: 1   Dropped: 0
63 13367 [OTA] [OTA] Queued: 1   Processed: 1   Dropped: 0
64 14367 [OTA] [OTA] Queued: 1   Processed: 1   Dropped: 0
65 15367 [OTA] [OTA] Queued: 1   Processed: 1   Dropped: 0
66 16367 [OTA] [OTA] Queued: 1   Processed: 1   Dropped: 0
```

此輸出顯示 Microchip Curiosity PIC32MZEF 可以連線至 AWS IoT 並訂閱 OTA 更新所需的 MQTT 主題。`Missing job parameter` 訊息是在預期中的內容，因為沒有任何擱置中的 OTA 更新任務。

# 在 Espressif ESP32 上下載、建置、刷新和執行 FreeRTOS OTA 示範
<a name="download-ota-esp"></a>

**重要**  <a name="deprecation-message"></a>
此參考整合託管在已棄用的 Amazon-FreeRTOS 儲存庫上。我們建議您在建立新專案時從[這裡開始](freertos-getting-started-modular.md)。如果您已經有以現在已棄用的 Amazon-FreeRTOS 儲存庫為基礎的現有 FreeRTOS 專案，請參閱 [Amazon-FreeRTOS Github 儲存庫遷移指南](github-repo-migration.md)。 FreeRTOS 

1. 從 [GitHub](https://github.com/aws/amazon-freertos) 下載 FreeRTOS 來源。如需說明，請參閱 [ README.md](https://github.com/aws/amazon-freertos/blob/main/README.md) 檔案。在您的 IDE 中建立專案，並包含所有必要的來源及程式庫。

1. 遵循 [Espressif 入門](https://docs.aws.amazon.com/freertos/latest/userguide/getting_started_espressif.html)中的說明，設定必要的 GCC 型工具鏈。

1. 開啟 `freertos/vendors/vendor/boards/board/aws_demos/config_files/aws_demo_config.h`、註解 `#define CONFIG_CORE_MQTT_MUTUAL_AUTH_DEMO_ENABLED`，並定義 `CONFIG_OTA_MQTT_UPDATE_DEMO_ENABLED`或 `CONFIG_OTA_HTTP_UPDATE_DEMO_ENABLED`。

1. 在 `vendors/espressif/boards/esp32/aws_demos` 目錄中執行 `make`，以便建置示範專案。您可以透過執行 `make flash monitor` 刷新示範程式並驗證其輸出，如 [Espressif 入門](https://docs.aws.amazon.com/freertos/latest/userguide/getting_started_espressif.html)中所述。

1. 執行 OTA 更新示範前，請留意下列事項：
   + 開啟 `freertos/vendors/vendor/boards/board/aws_demos/config_files/aws_demo_config.h`、註解 `#define CONFIG_CORE_MQTT_MUTUAL_AUTH_DEMO_ENABLED`，並定義 `CONFIG_OTA_MQTT_UPDATE_DEMO_ENABLED`或 `CONFIG_OTA_HTTP_UPDATE_DEMO_ENABLED`。
   + 開啟 `vendors/vendor/boards/board/aws_demos/config_files/ota_demo_config.h`，並將 SHA-256/ECDSA 程式碼簽署憑證複製到：

     ```
     #define otapalconfigCODE_SIGNING_CERTIFICATE [] = "your-certificate-key";
     ```

# 在 Renesas RX65N 上下載、建置、刷新和執行 FreeRTOS OTA 示範
<a name="download-rx65n-ota"></a>

**重要**  <a name="deprecation-message"></a>
此參考整合託管在已棄用的 Amazon-FreeRTOS 儲存庫上。我們建議您在建立新專案時從[這裡開始](freertos-getting-started-modular.md)。如果您已經有以現在已棄用的 Amazon-FreeRTOS 儲存庫為基礎的現有 FreeRTOS 專案，請參閱 [Amazon-FreeRTOS Github 儲存庫遷移指南](github-repo-migration.md)。 FreeRTOS 

本章說明如何下載、建置、刷新和執行 Renesas RX65N 上的 FreeRTOS OTA 示範應用程式。

**Topics**
+ [設定您的操作環境](#download-rx65n-ota-environment)
+ [設定您的 AWS 資源](#download-rx65n-ota-setup)
+ [匯入、設定標頭檔案並建置 aws\$1demos 和 boot\$1loader](#download-rx65n-ota-import-configure)

## 設定您的操作環境
<a name="download-rx65n-ota-environment"></a>

本節中的程序使用以下環境：
+ **IDE**：e2 Studio 7.8.0、e2 Studio 2020-07
+ **工具鏈**：CCRX Compiler v3.0.1
+ **目標裝置**：RSKRX65N-2MB
+ **偵錯工具**：E2、E2 Lite 模擬器
+ **軟體**：Renesas Flash Programmer、Renesas Secure Flash Programmer.exe、Tera Term

**設定您的硬體**

1. 將 E2 Lite 模擬器和 USB 序列埠連接到 RX65N 主機板和 PC。

1. 將電源連接至 RX65N。

## 設定您的 AWS 資源
<a name="download-rx65n-ota-setup"></a>

1. 若要執行 FreeRTOS 示範，您必須擁有具有存取 AWS IoT 服務許可之 IAM 使用者的 AWS 帳戶。如果您尚未完成，請遵循中的步驟[設定AWS您的帳戶和許可](freertos-prereqs.md#freertos-account-and-permissions)。

1. 若要設定 OTA 更新，請遵循中的步驟[OTA 更新先決條件](ota-prereqs.md)。特別是，請遵循中的步驟[使用 MQTT 進行 OTA 更新的先決條件](ota-mqtt-freertos.md)。

1. 開啟 [AWS IoT 主控台](https://console.aws.amazon.com/iot/home)。

1. 在左側導覽窗格中，選擇**管理**，然後選擇**要**建立物件的物件。

   物件是其中裝置或邏輯實體的表示法 AWS IoT。它可以是實體裝置或感應器 (例如燈泡或牆上的開關)。它也可以是邏輯實體，例如未連線的應用程式執行個體或實體實體 AWS IoT，但與這樣做的裝置 （例如具有引擎感應器或控制面板的汽車） 相關。 AWS IoT 提供可協助您管理物件的物件登錄檔。

   1. 選擇**建立**，然後選擇**建立單一物件**。

   1. 輸入物件**的名稱**，然後選擇**下一步**。

   1. 選擇 **Create certificate (建立憑證)**。

   1. 下載建立的三個檔案，然後選擇**啟用**。

   1. 選擇 **Attach a policy (連接政策)**。  
![\[主控台畫面顯示要下載的檔案\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/download-these-files-rx65n.png)

   1. 選取您在 中建立的政策[裝置政策](ota-mqtt-freertos.md#ota-mqtt-freertos-device-policy)。

      使用 MQTT 接收 OTA 更新的每個裝置都必須在 中註冊為物件， AWS IoT 而且該物件必須具有類似列出的附加政策。如需 `"Action"` 和 `"Resource"` 物件中的項目的詳細資訊，請參閱 [AWS IoT 核心政策動作](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policy-actions.html)和 [AWS IoT 核心動作資源](https://docs.aws.amazon.com/iot/latest/developerguide/iot-action-resources.html)。

**備註**
      + `iot:Connect` 許可允許您的裝置 AWS IoT 透過 MQTT 連線至 。
      +  AWS IoT 工作 (`.../jobs/*`) 主題的 `iot:Subscribe` 和 `iot:Publish` 許可允許連接的裝置接收工作通知和工作文件，並發佈工作執行的完成狀態。
      + OTA 串流 (`.../streams/*`) AWS IoT 主題的 `iot:Subscribe`和 `iot:Publish`許可允許連線的裝置從中擷取 OTA 更新資料 AWS IoT。需要這些許可才能透過 MQTT 執行韌體更新。
      + `iot:Receive` 許可允許 AWS IoT Core 在這些主題上發佈訊息到連線的裝置。每次交付 MQTT 訊息時，都會檢查此許可。您可以使用此許可來撤銷目前訂閱主題之用戶端的存取權。

1. 建立程式碼簽署設定檔並註冊程式碼簽署憑證 AWS。

   1. 若要建立金鑰和認證，請參閱 [ Renesas MCU 韌體更新設計政策](https://www.renesas.com/us/en/document/apn/renesas-mcu-firmware-update-design-policy)中的第 7.3 節「使用 OpenSSL 產生 ECDSA-SHA256 金鑰對」。

   1. 開啟 [AWS IoT 主控台](https://console.aws.amazon.com/iot/home)。在左側導覽窗格中，選取**管理**，然後選取**任務**。選取**建立任務**，然後選取**建立 OTA 更新任務**。

   1. 在**選取要更新的裝置**下，選擇**選取**，然後選擇您先前建立的物件。選取**下一步**。

   1. 在**建立 FreeRTOS OTA 更新任務**頁面上，執行下列動作：

      1. 針對**選取韌體映像傳輸的通訊協定**，選擇 **MQTT**。

      1. 針對**選取並簽署您的韌體映像**，選擇**為我簽署新的韌體映像**。

      1. 針對**程式碼簽署設定檔**，選擇**建立**。

      1. 在**建立程式碼簽署設定檔**視窗中，輸入**設定檔名稱**。針對**裝置硬體平台**，選取 **Windows Simulator**。針對**程式碼簽署憑證**，選擇**匯入**。

      1. 瀏覽以選取憑證 (`secp256r1.crt`)、憑證私有金鑰 (`secp256r1.key`) 和憑證鏈 (`ca.crt`)。

      1. 在**裝置上輸入程式碼簽署憑證的路徑名稱**。然後選擇 **Create (建立)**。

1. 若要授予 程式碼簽署的存取權 AWS IoT，請遵循中的步驟[授予 程式碼簽署的存取權 AWS IoT](code-sign-policy.md)。

如果您的 PC 上未安裝 Tera Term，您可以從 [https://ttssh2.osdn.jp/index.html.en](https://ttssh2.osdn.jp/index.html.en)：// 下載並設定它，如下所示。請確定您將 USB 序列連接埠從裝置插入 PC。

![\[Tera Term 序列連接埠設定視窗\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/tera-team-rx65n.png)


## 匯入、設定標頭檔案並建置 aws\$1demos 和 boot\$1loader
<a name="download-rx65n-ota-import-configure"></a>

若要開始，請選取最新版本的 FreeRTOS 套件，這會從 GitHub 下載並自動匯入專案。如此一來，您就可以專注於設定 FreeRTOS 和撰寫應用程式程式碼。

1. 啟動 e2 Studio。

1. 選擇**檔案**，然後選擇**匯入**。

1. 選取 **Renesas GitHub FreeRTOS （使用 IoT 程式庫） 專案**。  
![\[e-squared Studio 匯入時段\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/import-renesas-project-rx65n.png)

1. 選擇**檢查更多版本...**以顯示下載對話方塊。  
![\[e-squared Studio 下載對話方塊視窗\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/check-more-version-rx65n.png)

1. 選取最新的套件。  
![\[e-squared Studio 模組下載對話方塊視窗\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/choose-latest-version-rx65n.png)

1. 選擇**同意**以接受最終使用者授權合約。  
![\[e-squared Studio EULA 對話方塊\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/eula-rx65n.png)

1. 等待下載完成。  
![\[下載進度列\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/downloading-rx65n.png)

1. 選取 **aws\$1demos** 和 **boot\$1loader** 專案，然後選擇**完成**以匯入專案。  
![\[匯入專案視窗\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/import-projects-rx65n.png)

1. 對於這兩個專案，開啟專案屬性。在導覽窗格中，選擇**工具鏈編輯器**。

   1. 選擇**目前的工具鏈**。

   1. 選擇**目前的建置器**。  
![\[e-squared Studio 屬性視窗\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/project-properties-rx65n.png)

1. 在導覽窗格中，選擇**設定**。選擇**工具鏈**索引標籤，然後選擇工具鏈**版本**。  
![\[Renesas CCRX 版本 v3.01.00 的工具鏈整合設定，可選擇變更工具鏈。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/project-properties-toolchain-rx65n.png)

   選擇**工具設定**索引標籤，展開**轉換器**，然後選擇**輸出**。在主視窗中，確定已選取**輸出十六進位檔案**，然後選擇**輸出檔案類型**。  
![\[C/C++ 組建組態設定視窗顯示編譯器和連結器選項，例如輸出十六進位檔案、輸出檔案類型、輸出目錄和檔案分割選項。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/project-properties-settings-rx65n.png)  
![\[具有堆疊分析、工具鏈編輯器、C/C++ 一般、MCU、專案參考等選項的界面設定樹。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/project-properties-settings-2-rx65n.png)

1. 在開機載入器專案中，開啟`projects\renesas\rx65n-rsk\e2studio\boot_loader\src\key\code_signer_public_key.h`並輸入公有金鑰。如需如何建立公有金鑰的資訊，請參閱 [Renesas MCU 韌體更新設計政策](https://www.renesas.com/us/en/document/apn/renesas-mcu-firmware-update-design-policy)中的[如何在 RX65N 上使用 Amazon Web Services 實作 FreeRTOS OTA](https://www.renesas.com/us/en/document/apn/rx-family-how-implement-freertos-ota-using-amazon-web-services-rx65n)，以及第 7.3 節「使用 OpenSSL 產生 ECDSA-SHA256 金鑰對」。  
![\[程式碼編輯器顯示具有 CODE_SIGNER_PUBLIC_KEY 定義的 C 標頭檔案，以及 PEM 編碼程式碼簽署者公有金鑰變數。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/open-bootloader-project-rx65n.png)

   然後建置專案以建立 `boot_loader.mot`。

1. 開啟`aws_demos`專案。

   1. 開啟 [AWS IoT 主控台](https://console.aws.amazon.com/iot/home)。

   1. 在左側的導覽窗格中，選擇**設定**。在**裝置資料端點文字方塊中記下您的自訂端點**。

   1. 選擇**管理**，然後選擇**物件**。記下電路板的 AWS IoT 物件名稱。

   1. 在`aws_demos`專案中，開啟 `demos/include/aws_clientcredential.h` 並指定下列值。

      ```
      #define clientcredentialMQTT_BROKER_ENDPOINT[] = "Your AWS IoT endpoint";
      #define clientcredentialIOT_THING_NAME "The AWS IoT thing name of your board"
      ```  
![\[顯示 AWS IoT 物件名稱和代理程式端點組態設定的程式碼片段。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/client-credential-rx65n.png)

   1. 開啟 `tools/certificate_configuration/CertificateConfigurator.html` 檔案。

   1. 匯入您先前下載的憑證 PEM 檔案和私有金鑰 PEM 檔案。

   1. 選擇**產生並儲存 aws\$1clientcredential\$1keys.h**，並在 `demos/include/`目錄中取代此檔案。  
![\[Certificate Configuration Tool 具有 欄位，可提供來自 AWS IoT 主控台的用戶端憑證和私有金鑰 PEM 檔案，以及用於產生和儲存 aws_clientcredential_keys.h 檔案的按鈕。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/certificate-config-tool-rx65n.png)

   1. 開啟 `vendors/renesas/boards/rx65n-rsk/aws_demos/config_files/ota_demo_config.h` 檔案，並指定這些值。

      ```
      #define otapalconfigCODE_SIGNING_CERTIFICATE [] = "your-certificate-key";
      ```

      其中 *your-certificate-key* 是 檔案 的值`secp256r1.crt`。請記得在認證中的每一行後面新增 "\$1"。如需建立 `secp256r1.crt` 檔案的詳細資訊，請參閱 [Renesas MCU 韌體更新設計政策](https://www.renesas.com/us/en/document/apn/renesas-mcu-firmware-update-design-policy)中的[如何在 RX65N 上使用 Amazon Web Services 實作 FreeRTOS OTA](https://www.renesas.com/us/en/document/apn/rx-family-how-implement-freertos-ota-using-amazon-web-services-rx65n)，以及第 7.3 節「使用 OpenSSL 產生 ECDSA-SHA256 金鑰對」。  
![\[原始程式碼檔案，顯示定義 PEM 編碼程式碼簽署者憑證常數字串的 C 程式碼，其中包含修改過的憑證資料。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/codesigner-cert-rx65n.png)

1. **任務 A：安裝韌體的初始版本**

   1. 開啟 `vendors/renesas/boards/board/aws_demos/config_files/aws_demo_config.h` 檔案、註解 `#define CONFIG_CORE_MQTT_MUTUAL_AUTH_DEMO_ENABLED`，並定義 `CONFIG_OTA_MQTT_UPDATE_DEMO_ENABLED`或 `CONFIG_OTA_HTTP_UPDATE_DEMO_ENABLED`。

   1. 開啟 `demos/include/ aws_application_version.h` 檔案，並將韌體的初始版本設定為 `0.9.2`。  
![\[顯示應用程式版本定義的程式碼片段，包括主要、次要和建置版本編號的巨集。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/firmware-version-rx65n.png)

   1. 在**區段檢視器**中變更下列設定。  
![\[區段檢視器視窗顯示記憶體地址、區段名稱，例如 SU、SI、註冊和界面元件，例如網路緩衝區、例外狀況和動作按鈕。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/section-viewer-rx65n.png)

   1. 選擇**建置**以建立`aws_demos.mot`檔案。

1. `userprog.mot` 使用 Renesas Secure Flash Programmer 建立 檔案。 `userprog.mot`是 `aws_demos.mot`和 的組合`boot_loader.mot`。您可以將此檔案刷入 RX65N-RSK 以安裝初始韌體。

   1. 下載 [ https://github.com/renesas/Amazon-FreeRTOS-Tools](https://github.com/renesas/Amazon-FreeRTOS-Tools) 並開啟 `Renesas Secure Flash Programmer.exe`。

   1. 選擇**初始公司**索引標籤，然後設定下列參數：
      + **私有金鑰路徑** – 的位置`secp256r1.privatekey`。
      + **Boot Loader 檔案路徑** – `boot_loader.mot`() 的位置`projects\renesas\rx65n-rsk\e2studio\boot_loader\HardwareDebug`。
      + **檔案路徑** – `aws_demos.mot`() 的位置`projects\renesas\rx65n-rsk\e2studio\aws_demos\HardwareDebug`。  
![\[Renesas Secure Flash Programmer 視窗與 MCU、韌體驗證、序號、AES 金鑰路徑和檔案路徑欄位。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/secure-flash-rx65n.png)

   1. 建立名為 的目錄`init_firmware`、產生 `userprog.mot`，並將其儲存至 `init_firmware`目錄。確認產生成功。

1. 刷新 RX65N-RSK 上的初始韌體。

   1. 從 [https://www.renesas.com/tw/en/products/software-tools/tools/programmer/renesas-flash-programmer-programming-gui.html](https://www.renesas.com/tw/en/products/software-tools/tools/programmer/renesas-flash-programmer-programming-gui.html)：// 下載最新版本的 Renesas Flash Programmer （程式設計 GUI)。

   1. 開啟 `vendors\renesas\rx_mcu_boards\boards\rx65n-rsk\aws_demos\flash_project\erase_from_bank\ erase.rpj` 檔案以清除銀行上的資料。

   1. 選擇**開始**以清除銀行。  
![\[Renesas Flash Programmer 視窗顯示 RX Group 微型控制器專案詳細資訊、檔案路徑和快閃記憶體操作選項，例如「清除」、「程式設計」和「使用啟動和確定」驗證」按鈕。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/flash-programmer-erasing-rx65n.png)

   1. 若要刷新 `userprog.mot`，請選擇**瀏覽...**，然後導覽至 `init_firmware` 目錄，選取 `userprog.mot` 檔案，然後選擇**開始**。  
![\[Renesas Flash Programmer 視窗顯示清除操作設定，包括微控制器 RX 群組、瀏覽程式檔案的選項、清除和啟動按鈕，以及要清除之所選區塊的狀態詳細資訊。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/flash-programmer-complete-rx65n.png)

1. 0.9.2 版 （初始版本） 的韌體已安裝到您的 RX65N-RSK。RX65N-RSK 主機板現在正在接聽 OTA 更新。如果您已在 PC 上開啟 Tera Term，則在初始韌體執行時，您會看到類似以下內容的內容。

   ```
   -------------------------------------------------
   RX65N secure boot program
   -------------------------------------------------
   Checking flash ROM status.
   bank 0 status = 0xff [LIFECYCLE_STATE_BLANK]
   bank 1 status = 0xfc [LIFECYCLE_STATE_INSTALLING]
   bank info = 1. (start bank = 0)
   start installing user program.
   copy secure boot (part1) from bank0 to bank1...OK
   copy secure boot (part2) from bank0 to bank1...OK
   update LIFECYCLE_STATE from [LIFECYCLE_STATE_INSTALLING] to [LIFECYCLE_STATE_VALID]
   bank1(temporary area) block0 erase (to update LIFECYCLE_STATE)...OK
   bank1(temporary area) block0 write (to update LIFECYCLE_STATE)...OK
   swap bank...
   -------------------------------------------------
   RX65N secure boot program
   -------------------------------------------------
   Checking flash ROM status.
   bank 0 status = 0xf8 [LIFECYCLE_STATE_VALID]
   bank 1 status = 0xff [LIFECYCLE_STATE_BLANK]
   bank info = 0. (start bank = 1)
   integrity check scheme = sig-sha256-ecdsa
   bank0(execute area) on code flash integrity check...OK
   jump to user program
   0 1 [ETHER_RECEI] Deferred Interrupt Handler Task started
   1 1 [ETHER_RECEI] Network buffers: 3 lowest 3
   2 1 [ETHER_RECEI] Heap: current 234192 lowest 234192
   3 1 [ETHER_RECEI] Queue space: lowest 8
   4 1 [IP-task] InitializeNetwork returns OK
   5 1 [IP-task] xNetworkInterfaceInitialise returns 0
   6 101 [ETHER_RECEI] Heap: current 234592 lowest 233392
   7 2102 [ETHER_RECEI] prvEMACHandlerTask: PHY LS now 1
   8 3001 [IP-task] xNetworkInterfaceInitialise returns 1
   9 3092 [ETHER_RECEI] Network buffers: 2 lowest 2
   10 3092 [ETHER_RECEI] Queue space: lowest 7
   11 3092 [ETHER_RECEI] Heap: current 233320 lowest 233320
   12 3193 [ETHER_RECEI] Heap: current 233816 lowest 233120
   13 3593 [IP-task] vDHCPProcess: offer c0a80a09ip
   14 3597 [ETHER_RECEI] Heap: current 233200 lowest 233000
   15 3597 [IP-task] vDHCPProcess: offer c0a80a09ip
   16 3597 [IP-task] IP Address: 192.168.10.9
   17 3597 [IP-task] Subnet Mask: 255.255.255.0
   18 3597 [IP-task] Gateway Address: 192.168.10.1
   19 3597 [IP-task] DNS Server Address: 192.168.10.1
   20 3600 [Tmr Svc] The network is up and running
   21 3622 [Tmr Svc] Write certificate...
   22 3697 [ETHER_RECEI] Heap: current 232320 lowest 230904
   23 4497 [ETHER_RECEI] Heap: current 226344 lowest 225944
   24 5317 [iot_thread] [INFO ][DEMO][5317] ---------STARTING DEMO---------
   
   25 5317 [iot_thread] [INFO ][INIT][5317] SDK successfully initialized.
   26 5317 [iot_thread] [INFO ][DEMO][5317] Successfully initialized the demo. Network type for the demo: 4
   27 5317 [iot_thread] [INFO ][MQTT][5317] MQTT library successfully initialized.
   28 5317 [iot_thread] [INFO ][DEMO][5317] OTA demo version 0.9.2
   
   29 5317 [iot_thread] [INFO ][DEMO][5317] Connecting to broker...
   
   30 5317 [iot_thread] [INFO ][DEMO][5317] MQTT demo client identifier is rx65n-gr-rose (length 13).
   31 5325 [ETHER_RECEI] Heap: current 206944 lowest 206504
   32 5325 [ETHER_RECEI] Heap: current 206440 lowest 206440
   33 5325 [ETHER_RECEI] Heap: current 206240 lowest 206240
   38 5334 [ETHER_RECEI] Heap: current 190288 lowest 190288
   39 5334 [ETHER_RECEI] Heap: current 190088 lowest 190088
   40 5361 [ETHER_RECEI] Heap: current 158512 lowest 158168
   41 5363 [ETHER_RECEI] Heap: current 158032 lowest 158032
   42 5364 [ETHER_RECEI] Network buffers: 1 lowest 1
   43 5364 [ETHER_RECEI] Heap: current 156856 lowest 156856
   44 5364 [ETHER_RECEI] Heap: current 156656 lowest 156656
   46 5374 [ETHER_RECEI] Heap: current 153016 lowest 152040
   47 5492 [ETHER_RECEI] Heap: current 141464 lowest 139016
   48 5751 [ETHER_RECEI] Heap: current 140160 lowest 138680
   49 5917 [ETHER_RECEI] Heap: current 138280 lowest 138168
   59 7361 [iot_thread] [INFO ][MQTT][7361] Establishing new MQTT connection.
   62 7428 [iot_thread] [INFO ][MQTT][7428] (MQTT connection 81cfc8, CONNECT operation 81d0e8) Wait complete with result SUCCESS.
   63 7428 [iot_thread] [INFO ][MQTT][7428] New MQTT connection 4e8c established.
   64 7430 [iot_thread] [OTA_AgentInit_internal] OTA Task is Ready.
   65 7430 [OTA Agent T] [prvOTAAgentTask] Called handler. Current State [Ready] Event [Start] New state [RequestingJob]
   66 7431 [OTA Agent T] [INFO ][MQTT][7431] (MQTT connection 81cfc8) SUBSCRIBE operation scheduled.
   67 7431 [OTA Agent T] [INFO ][MQTT][7431] (MQTT connection 81cfc8, SUBSCRIBE operation 818c48) Waiting for operation completion.
   68 7436 [ETHER_RECEI] Heap: current 128248 lowest 127992
   69 7480 [OTA Agent T] [INFO ][MQTT][7480] (MQTT connection 81cfc8, SUBSCRIBE operation 818c48) Wait complete with result SUCCESS.
   70 7480 [OTA Agent T] [prvSubscribeToJobNotificationTopics] OK: $aws/things/rx65n-gr-rose/jobs/$next/get/accepted
   71 7481 [OTA Agent T] [INFO ][MQTT][7481] (MQTT connection 81cfc8) SUBSCRIBE operation scheduled.
   72 7481 [OTA Agent T] [INFO ][MQTT][7481] (MQTT connection 81cfc8, SUBSCRIBE operation 818c48) Waiting for operation completion.
   73 7530 [OTA Agent T] [INFO ][MQTT][7530] (MQTT connection 81cfc8, SUBSCRIBE operation 818c48) Wait complete with result SUCCESS.
   74 7530 [OTA Agent T] [prvSubscribeToJobNotificationTopics] OK: $aws/things/rx65n-gr-rose/jobs/notify-next
   75 7530 [OTA Agent T] [prvRequestJob_Mqtt] Request #0
   76 7532 [OTA Agent T] [INFO ][MQTT][7532] (MQTT connection 81cfc8) MQTT PUBLISH operation queued.
   77 7532 [OTA Agent T] [INFO ][MQTT][7532] (MQTT connection 81cfc8, PUBLISH operation 818b80) Waiting for operation completion.
   78 7552 [OTA Agent T] [INFO ][MQTT][7552] (MQTT connection 81cfc8, PUBLISH operation 818b80) Wait complete with result SUCCESS.
   79 7552 [OTA Agent T] [prvOTAAgentTask] Called handler. Current State [RequestingJob] Event [RequestJobDocument] New state [WaitingForJob]
   80 7552 [OTA Agent T] [prvParseJSONbyModel] Extracted parameter [ clientToken: 0:rx65n-gr-rose ]
   81 7552 [OTA Agent T] [prvParseJSONbyModel] parameter not present: execution
   82 7552 [OTA Agent T] [prvParseJSONbyModel] parameter not present: jobId
   83 7552 [OTA Agent T] [prvParseJSONbyModel] parameter not present: jobDocument
   84 7552 [OTA Agent T] [prvParseJSONbyModel] parameter not present: afr_ota
   85 7552 [OTA Agent T] [prvParseJSONbyModel] parameter not present: protocols
   86 7552 [OTA Agent T] [prvParseJSONbyModel] parameter not present: files
   87 7552 [OTA Agent T] [prvParseJSONbyModel] parameter not present: filepath
   99 7651 [ETHER_RECEI] Heap: current 129720 lowest 127304
   100 8430 [iot_thread] [INFO ][DEMO][8430] State: Ready  Received: 1   Queued: 0   Processed: 0   Dropped: 0
   101 9430 [iot_thread] [INFO ][DEMO][9430] State: WaitingForJob  Received: 1   Queued: 0   Processed: 0   Dropped: 0
   102 10430 [iot_thread] [INFO ][DEMO][10430] State: WaitingForJob  Received: 1   Queued: 0   Processed: 0   Dropped: 0
   103 11430 [iot_thread] [INFO ][DEMO][11430] State: WaitingForJob  Received: 1   Queued: 0   Processed: 0   Dropped: 0
   104 12430 [iot_thread] [INFO ][DEMO][12430] State: WaitingForJob  Received: 1   Queued: 0   Processed: 0   Dropped: 0
   105 13430 [iot_thread] [INFO ][DEMO][13430] State: WaitingForJob  Received: 1   Queued: 0   Processed: 0   Dropped: 0
   106 14430 [iot_thread] [INFO ][DEMO][14430] State: WaitingForJob  Received: 1   Queued: 0   Processed: 0   Dropped: 0
   107 15430 [iot_thread] [INFO ][DEMO][15430] State: WaitingForJob  Received: 1   Queued: 0   Processed: 0   Dropped: 0
   ```

1. **任務 B：更新韌體版本**

   1. 開啟 `demos/include/aws_application_version.h`檔案，並將`APP_VERSION_BUILD`字符值增加到 `0.9.3`。

   1. 重新建置專案。

1. 使用 Renesas Secure Flash Programmer 建立 `userprog.rsu` 檔案，以更新韌體版本。

   1. 開啟 `Amazon-FreeRTOS-Tools\Renesas Secure Flash Programmer.exe` 檔案。

   1. 選擇**更新公司**索引標籤，並設定下列參數：
      + **檔案路徑** – `aws_demos.mot` 檔案的位置 (`projects\renesas\rx65n-rsk\e2studio\aws_demos\HardwareDebug`)。

   1. 建立名為 `update _firmware` 的目錄。產生並`userprog.rsu`儲存到 `update_firmware` 目錄。確認產生成功。  
![\[Renesas Secure Flash Programmer 視窗，其中包含 MCU 選擇、韌體驗證類型、序號、AES MAC 金鑰欄位，以及用於產生安全韌體的檔案路徑輸入。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/update-firmware-rx65n.png)

1. 將韌體更新 上傳至 Amazon S3 儲存貯體`userproj.rsu`，如中所述[建立 Amazon S3 儲存貯體以存放您的更新](dg-ota-bucket.md)。  
![\[具有資料夾、上傳、版本和許可選項的 Amazon S3 儲存貯體管理介面\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/upload-firmware-rx65n.png)

1. 建立任務以更新 RX65N-RSK 上的韌體。

   AWS IoT Jobs 是一項服務，可通知一或多個連線裝置待定[任務](https://docs.aws.amazon.com/iot/latest/developerguide/iot-jobs.html)。任務可用來管理裝置機群、更新裝置上的韌體和安全憑證，或執行重新啟動裝置和執行診斷等管理任務。

   1. 登入 [AWS IoT 主控台](https://console.aws.amazon.com/iotv2/)。在導覽窗格中，選擇**管理**，然後選擇**任務**。

   1. 選擇**建立任務**，然後選擇**建立 OTA 更新任務**。選取物件，然後選擇**下一步**。

   1. 建立 FreeRTOS OTA 更新任務，如下所示：
      + 選擇 **MQTT**。
      + 選取您在上一節中建立的程式碼簽署設定檔。
      + 選取您上傳至 Amazon S3 儲存貯體的韌體映像。
      + 針對**裝置上的韌體映像路徑**，輸入 **test**。
      + 選擇您在上一節中建立的 IAM 角色。

   1. 選擇**下一步**。  
![\[韌體映像簽署和 OTA 更新設定，其中包含簽署新韌體、選取先前簽署的韌體、使用自訂簽署的韌體、指定程式碼簽署設定檔、韌體映像檔案、裝置上的路徑，以及 OTA 更新任務的 IAM 角色。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/create-job-next-rx65n.png)

   1. 輸入 ID，然後選擇**建立**。

1. 重新開啟 Tera Term 以確認韌體已成功更新至 OTA 示範 0.9.3 版。  
![\[命令列輸出，顯示執行緒與代理程式的初始化和連線。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/update-successful-rx65n.png)

1. 在 AWS IoT 主控台上，驗證任務狀態是否**成功**。  
![\[AFR OTA 示範測試任務概觀，顯示 1 個資源成功。\]](http://docs.aws.amazon.com/zh_tw/freertos/latest/userguide/images/completed-succeeded-rx65n.png)

# 教學課程：使用 FreeRTOS 低功耗藍牙在 Espressif ESP32 上執行 OTA 更新
<a name="ota-updates-esp32-ble"></a>

**重要**  <a name="deprecation-message"></a>
此參考整合託管在已棄用的 Amazon-FreeRTOS 儲存庫上。我們建議您在建立新專案時從[這裡開始](freertos-getting-started-modular.md)。如果您已經有以現在已棄用的 Amazon-FreeRTOS 儲存庫為基礎的現有 FreeRTOS 專案，請參閱 [Amazon-FreeRTOS Github 儲存庫遷移指南](github-repo-migration.md)。 FreeRTOS 

本教學課程說明如何更新連接到 Android 裝置上 MQTT 低功耗藍牙代理的 Espressif ESP32 微控制器。它使用 AWS IoT Over-the-air(OTA) 更新任務來更新裝置。裝置 AWS IoT 會使用 Android 示範應用程式中輸入的 Amazon Cognito 登入資料連線至 。授權的運算子會從雲端啟動 OTA 更新。當裝置透過 Android 示範應用程式連線時，會啟動 OTA 更新，並在裝置上更新韌體。

FreeRTOS 版本 2019.06.00 主要和更新版本包含低功耗藍牙 MQTT 代理支援，可用於 Wi-Fi 佈建和 AWS IoT 服務的安全連線。透過使用低功耗藍牙功能，您可以建置低功耗裝置，這些裝置可以與行動裝置配對以進行連線，而不需要 Wi-Fi。裝置可以透過使用一般存取描述檔 (GAP) 和一般屬性 (GATT) 描述檔的 Android 或 iOS SDKs 連線，使用 MQTT 進行通訊。

以下是我們將遵循的步驟，以允許透過低功耗藍牙進行 OTA 更新：

1. **設定儲存：**建立 Amazon S3 儲存貯體和政策，並設定可執行更新的使用者。

1. **建立程式碼簽署憑證：**建立簽署憑證並允許使用者簽署韌體更新。

1. **設定 Amazon Cognito 身分驗證：**建立登入資料提供者、使用者集區和使用者集區的應用程式存取權。

1. **設定 FreeRTOS：**設定低功耗藍牙、用戶端憑證和程式碼簽署公有憑證。

1. **設定 Android 應用程式：**設定登入資料提供者、使用者集區，並將應用程式部署到 Android 裝置。

1. **執行 OTA 更新指令碼：**若要啟動 OTA 更新，請使用 OTA 更新指令碼。

如需更新運作方式的詳細資訊，請參閱 [FreeRTOS Over-the-Air更新](freertos-ota-dev.md)。如需如何設定低功耗藍牙 MQTT 代理功能的詳細資訊，請參閱 文章，[文章使用低功耗藍牙搭配 Espressif ESP32 上的 FreeRTOS](https://aws.amazon.com/blogs/iot/using-bluetooth-low-energy-with-amazon-freertos-on-espressif-esp32/)，作者為 Richard Kang。

## 先決條件
<a name="ota-updates-esp32-ble-prereq"></a>

若要執行本教學課程中的步驟，您需要下列資源：
+ ESP32 開發板。
+ MicroUSB 轉 USB A 纜線。
+  AWS 帳戶 （免費方案已足夠）。
+ 搭載 Android v 6.0 或更新版本和藍牙 4.2 或更新版本的 Android 手機。

在您的開發電腦上，您需要：
+ Xtensa 工具鏈和 FreeRTOS 原始程式碼和範例有足夠的磁碟空間 (\$1500 Mb)。
+ 已安裝 Android Studio。
+ [AWS CLI](https://aws.amazon.com/cli/) 已安裝 。
+ Python3 已安裝。
+ 適用於 [Python 的 boto3 AWS Software 開發人員套件 (SDK)](https://github.com/boto/boto3)。

本教學課程中的步驟假設 Xtensa 工具鏈、ESP-IDF 和 FreeRTOS 程式碼安裝在主`/esp`目錄中的 目錄中。您必須將 `~/esp/xtensa-esp32-elf/bin` 新增至`$PATH`變數。

## 步驟 1：設定儲存體
<a name="ota-updates-esp32-ble-step1"></a>

1. [建立 Amazon S3 儲存貯體以存放您的更新](dg-ota-bucket.md) 啟用版本控制以保留韌體映像。

1. [建立 OTA 更新服務角色](create-service-role.md) 並將下列 受管政策新增至角色：
   + AWSIotLogging
   + AWSIotRuleActions
   + AWSIotThingsRegistration
   + AWSFreeRTOSOTAUpdate

1. [建立可執行 OTA 更新的使用者](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html)。此使用者可以在帳戶中簽署和部署韌體更新至 IoT 裝置，並有權在所有裝置上執行 OTA 更新。存取權應僅限於信任的實體。

1. 請遵循 的步驟，[建立 OTA 使用者政策](create-ota-user-policy.md)並將其連接到您的使用者。

## 步驟 2：建立程式碼簽署憑證
<a name="ota-updates-esp32-ble-step2"></a>

1. 建立已啟用版本控制以保留韌體映像的 Amazon S3 儲存貯體。

1. 建立可用於簽署韌體的程式碼簽署憑證。匯入憑證時，請注意憑證 Amazon Resource Name (ARN)。

   ```
   aws acm import-certificate --profile=ota-update-user --certificate file://ecdsasigner.crt --private-key file://ecdsasigner.key
   ```

   輸出範例：

   ```
   {
   "CertificateArn": "arn:aws:acm:us-east-1:<account>:certificate/<certid>"
   }
   ```

   稍後您將使用 ARN 來建立簽署設定檔。如有需要，您現在可以使用下列命令建立設定檔：

   ```
   aws signer put-signing-profile --profile=ota-update-user --profile-name esp32Profile --signing-material certificateArn=arn:aws:acm:us-east-1:account:certificate/certid --platform AmazonFreeRTOS-Default --signing-parameters certname=/cert.pem
   ```

   輸出範例：

   ```
   {
   "arn": "arn:aws:signer::<account>:/signing-profiles/esp32Profile"
   }
   ```

## 步驟 3：Amazon Cognito 身分驗證組態
<a name="ota-updates-esp32-ble-step3"></a>

**建立 AWS IoT 政策**

1. 登入 [AWS IoT 主控台](https://console.aws.amazon.com/iot/)。

1. 在主控台的右上角，選擇**我的帳戶**。在**帳戶設定**下，記下您的 12 位數帳戶 ID。

1. 在左側的導覽窗格中，選擇**設定**。在**裝置資料端點**中，記下端點值。端點應該類似 `xxxxxxxxxxxxxx.iot.us-west-2.amazonaws.com`。在此範例中， AWS 區域為「us-west-2」。

1. 在左側導覽窗格中，選擇**安全**，選擇**政策**，然後選擇**建立**。如果您的帳戶中沒有任何政策，您會看到「您還沒有任何政策」訊息，您可以選擇**建立政策**。

1. 輸入政策的名稱，例如 "esp32\$1mqtt\$1proxy\$1iot\$1policy"。

1. 在 **Add statements (新增陳述式)** 區段中，選擇 **Advanced mode (進階模式)**。將下列 JSON 複製並貼入政策編輯器視窗。`aws-account-id` 將 取代為您的帳戶 ID，並將 `aws-region`取代為您的區域 （例如 "us-west-2")。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iot:Connect",
               "Resource": "arn:aws:iot:us-east-1:123456789012:*"
           },
           {
               "Effect": "Allow",
               "Action": "iot:Publish",
               "Resource": "arn:aws:iot:us-east-1:123456789012:*"
           },
           {
               "Effect": "Allow",
               "Action": "iot:Subscribe",
               "Resource": "arn:aws:iot:us-east-1:123456789012:*"
           },
           {
               "Effect": "Allow",
               "Action": "iot:Receive",
               "Resource": "arn:aws:iot:us-east-1:123456789012:*"
           }
       ]
   }
   ```

------

1. 選擇**建立**。

**建立 AWS IoT 物件**

1. 登入 [AWS IoT 主控台](https://console.aws.amazon.com/iot/)。

1. 在左側導覽窗格中，選擇 **Manage (管理)**，然後選擇 **Things (實物)**。

1. 在右上角，選擇**建立**。如果您的帳戶中沒有註冊任何物件，則會顯示「您還沒有任何物件」訊息，您可以選擇**註冊物件**。

1. 在**建立 AWS IoT 物件**頁面上，選擇**建立單一物件**。

1. 在**將裝置新增至物件登錄**檔頁面上，輸入物件的名稱 （例如，"esp32-ble")。僅允許英數字元、連字號 (-) 和底線 (\$1) 字元。選擇**下一步**。

1. 在**新增實物的憑證**頁面上，**在略過憑證並建立實物**下，選擇**建立不含憑證的實物**。由於我們使用使用 Amazon Cognito 憑證進行身分驗證和授權的 BLE 代理行動應用程式，因此不需要裝置憑證。

**建立 Amazon Cognito 應用程式用戶端**

1. 登入 [Amazon Cognito 主控台](https://console.aws.amazon.com/cognito/users/)。

1. 在右上角導覽橫幅中，選擇**建立使用者集區**。

1. 輸入集區名稱 （例如，"esp32\$1mqtt\$1proxy\$1user\$1pool")。

1. 選擇 **Review defaults** (檢閱預設值)。

1. 在**應用程式用戶端**中，選擇**新增應用程式用戶端**，然後選擇**新增應用程式用戶端**。

1. 輸入應用程式用戶端名稱 （例如 "mqtt\$1app\$1client")。

1. 確定已選取**產生用戶端秘密**。

1. 選擇 **Create app client (建立應用程式用戶端)**。

1. 選擇 **Return to pool details (回到集區的詳細資訊)**。

1. 在使用者集區的**檢閱**頁面上，選擇**建立集區**。您應該會看到一則訊息，指出「您的使用者集區已成功建立。」 請記下集區 ID。

1. 在導覽窗格中，選擇**應用程式用戶端**。

1. 選擇**顯示詳細資訊**。記下應用程式用戶端 ID 和應用程式用戶端秘密。

**建立 Amazon Cognito 身分集區**

1. 登入 [Amazon Cognito 主控台](https://console.aws.amazon.com/cognito/federated)。

1. 選擇 **Create new identity pool** (建立新的身分池)。

1. 輸入身分集區的名稱 （例如 "mqtt\$1proxy\$1identity\$1pool")。

1. 展開**身分驗證提供者**。

1. 選擇 **Cognito** 標籤。

1. 輸入您在先前步驟中記下的使用者集區 ID 和應用程式用戶端 ID。

1. 選擇 **Create Pool** (建立集區)。

1. 在下一頁中，若要為已驗證和未驗證的身分建立新的角色，請選擇**允許**。

1. 請記下身分集區 ID，其格式為 `us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`。

**將 IAM 政策連接至已驗證的身分**

1. 開啟 Amazon Cognito [主控台](https://console.aws.amazon.com/cognito/federated)。

1. 選取您剛建立的身分集區 （例如 "mqtt\$1proxy\$1identity\$1pool")。

1. 選擇 **Edit identity pool (編輯身分集區)**。

1. 請記下指派給已驗證角色的 IAM 角色 （例如，「Cognito\$1mqtt\$1proxy\$1identity\$1poolAuth\$1Role」)。

1. 開啟 [ IAM 主控台](https://console.aws.amazon.com/iam/home)。

1. 在導覽窗格中，選擇 **Roles** (角色)。

1. 搜尋指派的角色 （例如，「Cognito\$1mqtt\$1proxy\$1identity\$1poolAuth\$1Role」)，然後選取該角色。

1. 選擇**新增內嵌政策**，然後選擇 **JSON**。

1. 輸入下列政策：

------
#### [ JSON ]

****  

   ```
   {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
          {
             "Effect": "Allow",
             "Action": [
                "iot:AttachPolicy",
                "iot:AttachPrincipalPolicy",
                "iot:Connect",
                "iot:Publish",
                "iot:Subscribe"
             ],
             "Resource": "*"
          }]
       }
   ```

------

1. 選擇**檢閱政策**。

1. 輸入政策名稱 （例如 "mqttProxyCognitoPolicy")。

1. 選擇**建立政策**。

## 步驟 4：設定 Amazon FreeRTOS
<a name="ota-updates-esp32-ble-step4"></a>

1. 從 Amazon FreeRTOS [FreeRTOS GitHub ](https://github.com/aws/amazon-freertos)程式碼。

1. 若要啟用 OTA 更新示範，請遵循中的步驟[Espressif ESP32-DevKitC 和 ESP-WROVER-KIT 入門](getting_started_espressif.md)。

1. 在下列檔案中進行這些額外的修改：

   1. 開啟`vendors/espressif/boards/esp32/aws_demos/config_files/aws_demo_config.h`並定義 `CONFIG_OTA_UPDATE_DEMO_ENABLED`。

   1. 開啟 `vendors/espressif/boards/esp32/aws_demos/common/config_files/aws_demo_config.h`並`democonfigNETWORK_TYPES`變更為 `AWSIOT_NETWORK_TYPE_BLE`。

   1. 開啟 `demos/include/aws_clientcredential.h`並輸入 的端點 URL`clientcredentialMQTT_BROKER_ENDPOINT`。

      輸入 的物件名稱 `clientcredentialIOT_THING_NAME`（例如，"esp32-ble")。當您使用 Amazon Cognito 憑證時，不需要新增憑證。

   1. 開啟 `vendors/espressif/boards/esp32/aws_demos/config_files/aws_iot_network_config.h`並變更 `configENABLED_NETWORKS` `configSUPPORTED_NETWORKS`，並只包含 `AWSIOT_NETWORK_TYPE_BLE`。

   1. 開啟 `vendors/vendor/boards/board/aws_demos/config_files/ota_demo_config.h` 檔案，然後輸入您的憑證。

      ```
      #define otapalconfigCODE_SIGNING_CERTIFICATE [] = "your-certificate-key";
      ```

   應用程式應啟動並列印示範版本：

   ```
   11 13498 [iot_thread] [INFO ][DEMO][134980] Successfully initialized the demo. Network type for the demo: 2
   12 13498 [iot_thread] [INFO ][MQTT][134980] MQTT library successfully initialized.
   13 13498 [iot_thread] OTA demo version 0.9.20
   14 13498 [iot_thread] Creating MQTT Client...
   ```

## 步驟 5：設定 Android 應用程式
<a name="ota-updates-esp32-ble-step5"></a>

1. 從 [amazon-freertos-ble-android-sdk](https://github.com/aws/amazon-freertos-ble-android-sdk) GitHub 儲存庫下載 Android 低功耗藍牙 SDK 和範例應用程式。

1. 開啟 檔案`app/src/main/res/raw/awsconfiguration.json`，並使用下列 JSON 範例中的指示填入集區 ID、區域、AppClientId 和 AppClientSecret。

   ```
   {
     "UserAgent": "MobileHub/1.0",
     "Version": "1.0",
     "CredentialsProvider": {
       "CognitoIdentity": {
         "Default": {
           "PoolId": "Cognito->Manage Identity Pools->Federated Identities->mqtt_proxy_identity_pool->Edit Identity Pool->Identity Pool ID",
           "Region": "Your region (for example us-east-1)"
         }
       }
     },
   
     "IdentityManager": {
       "Default": {}
     },
   
     "CognitoUserPool": {
       "Default": {
         "PoolId": "Cognito-> Manage User Pools -> esp32_mqtt_proxy_user_pool -> General Settings -> PoolId",
         "AppClientId": "Cognito-> Manage User Pools -> esp32_mqtt_proxy_user_pool -> General Settings -> App clients ->Show Details",
         "AppClientSecret": "Cognito-> Manage User Pools -> esp32_mqtt_proxy_user_pool -> General Settings -> App clients ->Show Details",
         "Region": "Your region (for example us-east-1)"
       }
     }
   }
   ```

1. 開啟`app/src/main/java/software/amazon/freertos/DemoConstants.java`並輸入您先前建立的政策名稱 （例如 *esp32\$1mqtt\$1proxy\$1iot\$1policy*) 以及區域 （例如 *us-east-1*)。

1. 建置並安裝 示範應用程式。

   1. 在 Android Studio 中，選擇**建置**，然後選擇**製作模組應用程式**。

   1. 選擇**執行**，然後選擇**執行應用程式**。您可以前往 Android Studio 中的 logcat 視窗窗格來監控日誌訊息。

   1. 在 Android 裝置上，從登入畫面建立 帳戶。

   1. 建立使用者。如果使用者已存在，請輸入登入資料。

   1. 允許 Amazon FreeRTOS 示範存取裝置的位置。

   1. 掃描低功耗藍牙裝置。

   1. 將找到之裝置的滑桿移至**開啟**。

   1. 在 ESP32 的序列連接埠偵錯主控台上按 **y**。

   1. 選擇**配對 & Connect**。

1. 建立連線後，**更多...**連結會變成作用中。連線完成時，Android 裝置 logcat 中的連線狀態應變更為「BLE\$1CONNECTED」：

   ```
   2019-06-06 20:11:32.160 23484-23497/software.amazon.freertos.demo I/FRD: BLE connection state changed: 0; new state: BLE_CONNECTED
   ```

1. 在傳輸訊息之前，Amazon FreeRTOS 裝置和 Android 裝置會交涉 MTU。您應該會在 logcat 中看到下列輸出：

   ```
   2019-06-06 20:11:46.720 23484-23497/software.amazon.freertos.demo I/FRD: onMTUChanged : 512 status: Success
   ```

1. 裝置會連線至應用程式，並使用 MQTT Proxy 開始傳送 MQTT 訊息。若要確認裝置可以通訊，請確定 MQTT\$1CONTROL 特性資料值變更為 01：

   ```
   2019-06-06 20:12:28.752 23484-23496/software.amazon.freertos.demo D/FRD: <-<-<- Writing to characteristic: MQTT_CONTROL with data: 01
   2019-06-06 20:12:28.839 23484-23496/software.amazon.freertos.demo D/FRD: onCharacteristicWrite for: MQTT_CONTROL; status: Success; value: 01
   ```

1. 配對裝置時，您會在 ESP32 主控台上看到提示。若要啟用 BLE，請按 **y**。除非您執行此步驟，否則示範將無法運作。

   ```
   E (135538) BT_GATT: GATT_INSUF_AUTHENTICATION: MITM Required
   W (135638) BT_L2CAP: l2cble_start_conn_update, the last connection update command still pending.
   E (135908) BT_SMP: Value for numeric comparison = 391840
   15 13588 [InputTask] Numeric comparison:391840
   16 13589 [InputTask] Press 'y' to confirm
   17 14078 [InputTask] Key accepted
   W (146348) BT_SMP: FOR LE SC LTK IS USED INSTEAD OF STK
   18 16298 [iot_thread] Connecting to broker...
   19 16298 [iot_thread] [INFO ][MQTT][162980] Establishing new MQTT connection.
   20 16298 [iot_thread] [INFO ][MQTT][162980] (MQTT connection 0x3ffd5754, CONNECT operation 0x3ffd586c) Waiting for operation completion.
   21 16446 [iot_thread] [INFO ][MQTT][164450] (MQTT connection 0x3ffd5754, CONNECT operation 0x3ffd586c) Wait complete with result SUCCESS.
   22 16446 [iot_thread] [INFO ][MQTT][164460] New MQTT connection 0x3ffc0ccc established.
   23 16446 [iot_thread] Connected to broker.
   ```

## 步驟 6：執行 OTA 更新指令碼
<a name="ota-updates-esp32-ble-step6"></a>

1. 若要安裝先決條件，請執行下列命令：

   ```
   pip3 install boto3
   ```

   ```
   pip3 install pathlib
   ```

1. 在 中增加 FreeRTOS 應用程式版本`demos/include/aws_application_version.h`。

1. 建立新的 .bin 檔案。

1. 下載 python 指令碼 [ start\$1ota.py。](https://github.com/aws-samples/amazon-freertos-ota-scripts/blob/master/scripts/start_ota.py)若要查看指令碼的說明內容，請在終端機視窗中執行下列命令：

   ```
   python3 start_ota.py -h
   ```

   您應該會看到類似下列的內容：

   ```
   usage: start_ota.py [-h] --profile PROFILE [--region REGION]
                       [--account ACCOUNT] [--devicetype DEVICETYPE] --name NAME
                       --role ROLE --s3bucket S3BUCKET --otasigningprofile
                       OTASIGNINGPROFILE --signingcertificateid
                       SIGNINGCERTIFICATEID [--codelocation CODELOCATION]
   Script to start OTA update
   optional arguments:
   -h, --help            show this help message and exit
   --profile PROFILE     Profile name created using aws configure
   --region REGION       Region
   --account ACCOUNT     Account ID
   --devicetype DEVICETYPE thing|group
   --name NAME           Name of thing/group
   --role ROLE           Role for OTA updates
   --s3bucket S3BUCKET   S3 bucket to store firmware updates
   --otasigningprofile OTASIGNINGPROFILE
                         Signing profile to be created or used
   --signingcertificateid SIGNINGCERTIFICATEID
                         certificate id (not arn) to be used
   --codelocation CODELOCATION
                         base folder location (can be relative)
   ```

1. 如果您使用提供的 CloudFormation 範本來建立資源，請執行下列命令：

   ```
   python3 start_ota_stream.py --profile otausercf --name esp32-ble --role ota_ble_iot_role-sample --s3bucket afr-ble-ota-update-bucket-sample --otasigningprofile abcd --signingcertificateid certificateid
   ```

   您應該會在 ESP32 偵錯主控台中看到更新開始：

   ```
   38 2462 [OTA Task] [prvParseJobDoc] Job was accepted. Attempting to start transfer.
   ---
   49 2867 [OTA Task] [prvIngestDataBlock] Received file block 1, size 1024
   50 2867 [OTA Task] [prvIngestDataBlock] Remaining: 1290
   51 2894 [OTA Task] [prvIngestDataBlock] Received file block 2, size 1024
   52 2894 [OTA Task] [prvIngestDataBlock] Remaining: 1289
   53 2921 [OTA Task] [prvIngestDataBlock] Received file block 3, size 1024
   54 2921 [OTA Task] [prvIngestDataBlock] Remaining: 1288
   55 2952 [OTA Task] [prvIngestDataBlock] Received file block 4, size 1024
   56 2953 [OTA Task] [prvIngestDataBlock] Remaining: 1287
   57 2959 [iot_thread] State: Active  Received: 5   Queued: 5   Processed: 5   Dropped: 0
   ```

1. 當 OTA 更新完成時，裝置會視需要重新啟動 OTA 更新程序。然後，它會嘗試使用更新的韌體進行連線。如果升級成功，更新的韌體會標記為作用中，您應該會在主控台中看到更新的版本：

   ```
   13 13498 [iot_thread] OTA demo version 0.9.21
   ```