blob: a7f6478b1af9f7b9769dcc802fc19017e51cd2f1 [file] [log] [blame]
nxptest2d0c5292022-06-24 19:04:49 +08001/*
2 *
3 * Copyright (c) 2020 Project CHIP Authors
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17//#include "FreeRTOS.h"
18//#include "task.h"
19
20#include <lib/shell/Engine.h>
21
22#include <app/server/OnboardingCodesUtil.h>
23#include <platform/CHIPDeviceLayer.h>
24#include <setup_payload/SetupPayload.h>
25
26#include <lib/core/CHIPCore.h>
27#include <lib/support/Base64.h>
28#include <lib/support/CHIPArgParser.hpp>
29#include <lib/support/CodeUtils.h>
30
31//#include <lib/support/RandUtils.h> //==> rm from TE7.5
32#include <app-common/zap-generated/attribute-id.h>
Boris Zbarskyb46af332022-12-01 00:33:16 -050033#include <app-common/zap-generated/ids/Clusters.h>
nxptest2d0c5292022-06-24 19:04:49 +080034#include <app/server/Dnssd.h>
35#include <app/server/Server.h>
36#include <app/util/af-types.h>
37#include <app/util/attribute-storage.h>
38#include <app/util/attribute-table.h>
39#include <lib/support/CHIPMem.h>
40#include <lib/support/logging/CHIPLogging.h>
41#include <platform/CHIPDeviceLayer.h>
42#include <setup_payload/QRCodeSetupPayloadGenerator.h>
43
44#include <app/InteractionModelEngine.h>
45
46#include <ChipShellCollection.h>
47
48// cr++
crlonxpa6ecd622022-09-30 01:51:50 +080049#if (defined(CONFIG_CHIP_MW320_REAL_FACTORY_DATA) && (CONFIG_CHIP_MW320_REAL_FACTORY_DATA == 1))
50#include "FactoryDataProvider.h"
51#else
nxptest2d0c5292022-06-24 19:04:49 +080052#include <credentials/DeviceAttestationCredsProvider.h>
53#include <credentials/examples/DeviceAttestationCredsExample.h>
crlonxpa6ecd622022-09-30 01:51:50 +080054#endif // if CONFIG_CHIP_MW320_REAL_FACTORY_DATA
nxptest2d0c5292022-06-24 19:04:49 +080055// cr--
56// ota++
57#include "app/clusters/ota-requestor/BDXDownloader.h"
58#include "app/clusters/ota-requestor/DefaultOTARequestor.h"
59#include "app/clusters/ota-requestor/DefaultOTARequestorDriver.h"
60#include "app/clusters/ota-requestor/DefaultOTARequestorStorage.h"
61//#include <app/clusters/ota-requestor/DefaultOTARequestorUserConsent.h>
62#include "platform/nxp/mw320/OTAImageProcessorImpl.h"
63//#include "app/clusters/ota-requestor/OTARequestorDriver.h"
64
65// for ota module test
66#include "mw320_ota.h"
67
68// ota--
69#include "app/clusters/bindings/BindingManager.h"
70#include "binding-handler.h"
71
72/* platform specific */
73#include "board.h"
74#include "clock_config.h"
75#include "fsl_debug_console.h"
76#include "fsl_gpio.h"
77#include "pin_mux.h"
78
79#include <wm_os.h>
80extern "C" {
81#include "boot_flags.h"
82#include "cli.h"
83#include "dhcp-server.h"
84#include "iperf.h"
85#include "mflash_drv.h"
86#include "network_flash_storage.h"
87#include "partition.h"
88#include "ping.h"
89#include "wlan.h"
90#include "wm_net.h"
91}
92#include "fsl_aes.h"
93#include "lpm.h"
94
95/*******************************************************************************
96 * Definitions
97 ******************************************************************************/
98#define APP_AES AES
99#define CONNECTION_INFO_FILENAME "connection_info.dat"
crlonxpa6ecd622022-09-30 01:51:50 +0800100#define SSID_FNAME "ssid_fname"
101#define PSK_FNAME "psk_fname"
102
103#define VERSION_STR "mw320-2.9.10-005"
nxptest2d0c5292022-06-24 19:04:49 +0800104enum
105{
106 MCUXPRESSO_WIFI_CLI,
107 MATTER_SHELL,
108 MAX_SELECTION,
109};
110static int Matter_Selection = MAX_SELECTION;
111#define RUN_RST_LT_DELAY 10
crlonxpa6ecd622022-09-30 01:51:50 +0800112static const char * TAG = "mw320";
113
nxptest2d0c5292022-06-24 19:04:49 +0800114/*******************************************************************************
115 * Variables
116 ******************************************************************************/
117static SemaphoreHandle_t aesLock;
118static struct wlan_network sta_network;
119static struct wlan_network uap_network;
120
121const int TASK_MAIN_PRIO = OS_PRIO_3;
122const int TASK_MAIN_STACK_SIZE = 800;
123portSTACK_TYPE * task_main_stack = NULL;
124TaskHandle_t task_main_task_handler;
125
crlonxpa6ecd622022-09-30 01:51:50 +0800126uint8_t * __FACTORY_DATA_START;
127uint32_t __FACTORY_DATA_SIZE;
128
nxptest2d0c5292022-06-24 19:04:49 +0800129#if CHIP_ENABLE_OPENTHREAD
130extern "C" {
131#include <openthread/platform/platform-softdevice.h>
132}
133#endif // CHIP_ENABLE_OPENTHREAD
134
135using namespace chip;
136using namespace chip::Credentials;
137using namespace ::chip::app;
138using namespace chip::Shell;
139using namespace chip::DeviceLayer;
140
141// ota ++
142using chip::BDXDownloader;
143using chip::DefaultOTARequestor;
144using chip::OTADownloader;
145using chip::OTAImageProcessorImpl;
146using chip::OTAImageProgress;
147
148DefaultOTARequestor gRequestorCore;
149DefaultOTARequestorStorage gRequestorStorage;
150chip::DeviceLayer::DefaultOTARequestorDriver gRequestorUser;
151BDXDownloader gDownloader;
152OTAImageProcessorImpl gImageProcessor;
153// chip::ota::DefaultOTARequestorUserConsent gUserConsentProvider;
154// static chip::ota::UserConsentState gUserConsentState = chip::ota::UserConsentState::kGranted;
155
156void InitOTARequestor(void)
157{
158 // Initialize and interconnect the Requestor and Image Processor objects -- START
159 SetRequestorInstance(&gRequestorCore);
160
161 gRequestorStorage.Init(chip::Server::GetInstance().GetPersistentStorage());
162
163 // Set server instance used for session establishment
164 gRequestorCore.Init(chip::Server::GetInstance(), gRequestorStorage, gRequestorUser, gDownloader);
165
166 // WARNING: this is probably not realistic to know such details of the image or to even have an OTADownloader instantiated at
167 // the beginning of program execution. We're using hardcoded values here for now since this is a reference application.
168 // TODO: instatiate and initialize these values when QueryImageResponse tells us an image is available
169 // TODO: add API for OTARequestor to pass QueryImageResponse info to the application to use for OTADownloader init
170 // OTAImageProcessor ipParams;
171 // ipParams.imageFile = CharSpan("dnld_img.txt");
172 // gImageProcessor.SetOTAImageProcessorParams(ipParams);
173 gImageProcessor.SetOTADownloader(&gDownloader);
174
175 // Connect the Downloader and Image Processor objects
176 gDownloader.SetImageProcessorDelegate(&gImageProcessor);
177 gRequestorUser.Init(&gRequestorCore, &gImageProcessor);
178 /*
179 if (gUserConsentState != chip::ota::UserConsentState::kUnknown)
180 {
181 gUserConsentProvider.SetUserConsentState(gUserConsentState);
182 gRequestorUser.SetUserConsentDelegate(&gUserConsentProvider);
183 }
184 */
185 // Initialize and interconnect the Requestor and Image Processor objects -- END
186}
187
crlonxpa6ecd622022-09-30 01:51:50 +0800188const char * mw320_get_verstr(void)
189{
190 return VERSION_STR;
191}
192
193void save_network(char * ssid, char * pwd);
194void save_network(char * ssid, char * pwd)
195{
196 int ret;
197
198 ret = save_wifi_network((char *) SSID_FNAME, (uint8_t *) ssid, strlen(ssid) + 1);
199 if (ret != WM_SUCCESS)
200 {
201 PRINTF("Error: write ssid to flash failed\r\n");
202 }
203
204 ret = save_wifi_network((char *) PSK_FNAME, (uint8_t *) pwd, strlen(pwd) + 1);
205 if (ret != WM_SUCCESS)
206 {
207 PRINTF("Error: write psk to flash failed\r\n");
208 }
209
210 return;
211}
212
nxptest2d0c5292022-06-24 19:04:49 +0800213// ota --
214
215namespace {
216static void rst_args_lt(System::Layer * aSystemLayer, void * aAppState);
217}
218
219#if defined(__cplusplus)
220extern "C" {
221#endif /* __cplusplus */
222
223volatile int g_ButtonPress = 0;
224bool need2sync_sw_attr = false;
225
226void sw2_handle(bool frm_clk)
227{
228 static uint8_t click_cnt = 0;
229 static uint8_t run_times = 0;
230
231 if (frm_clk == true)
232 {
233 // Called while user clicks the button
234 click_cnt++;
235 PRINTF(" (%d times) \r\n", click_cnt);
236 return;
237 }
238 // Called regularlly from a thread every 500ms
239 run_times++;
240 if (click_cnt > 4)
241 {
242 // More than 4 clicks within the last second => erase the saved parameters
243 PRINTF("--> enough clicks (%d times) => resetting the saved parameters \r\n", click_cnt);
244 ::erase_all_params();
245 DeviceLayer::SystemLayer().StartTimer(System::Clock::Milliseconds32(RUN_RST_LT_DELAY), rst_args_lt, nullptr);
246 click_cnt = 0;
247 }
248 if (run_times >= 2)
249 {
250 // Called twice with gap==500ms
251 click_cnt = 0;
252 run_times = 0;
253 }
254
255 return;
256}
257
258void GPIO_IRQHandler(void)
259{
260 uint32_t intrval = GPIO_PortGetInterruptFlags(GPIO, GPIO_PORT(BOARD_SW1_GPIO_PIN));
261
262 // Clear the interrupt
263 GPIO_PortClearInterruptFlags(GPIO, GPIO_PORT(BOARD_SW1_GPIO_PIN), intrval);
264 // Check which sw tiggers the interrupt
265 if (intrval & 1UL << GPIO_PORT_PIN(BOARD_SW1_GPIO_PIN))
266 {
267 PRINTF("SW_1 click => do switch handler\r\n");
268 /* Change state of button. */
269 g_ButtonPress++;
270 need2sync_sw_attr = true;
271 }
272 else if (intrval & 1UL << GPIO_PORT_PIN(BOARD_SW2_GPIO_PIN))
273 {
274 PRINTF("SW_2 click \r\n");
275 sw2_handle(true);
276 }
277 SDK_ISR_EXIT_BARRIER;
278}
279
280#if defined(__cplusplus)
281}
282#endif /* __cplusplus */
283
284/*
285EmberAfStatus emberAfExternalAttributeReadCallback(EndpointId endpoint, ClusterId clusterId,
286 EmberAfAttributeMetadata * attributeMetadata, uint16_t manufacturerCode,
287 uint8_t * buffer, uint16_t maxReadLength, int32_t index)
288{
289 PRINTF("====> emberAfExternalAttributeReadCallback\r\n");
290
Boris Zbarskyb46af332022-12-01 00:33:16 -0500291 if(clusterId == Clusters::Switch::Id) {
nxptest2d0c5292022-06-24 19:04:49 +0800292 *buffer = g_ButtonPress;
293 }
294 return EMBER_ZCL_STATUS_SUCCESS;
295}
296*/
297
298namespace {
299typedef enum
300{
301 chip_srv_all,
302 dns_srv,
303 srv_type_max
304} srv_type_t;
305
306typedef enum
307{
308 led_yellow,
309 led_amber,
310 led_max
311} led_id_t;
312
313static void run_chip_srv(System::Layer * aSystemLayer, void * aAppState);
314static void run_dnssrv(System::Layer * aSystemLayer, void * aAppState);
315static void run_update_chipsrv(srv_type_t srv_type);
316static void led_on_off(led_id_t lt_id, bool is_on);
317bool is_connected = false;
318/*******************************************************************************
319 * Prototypes
320 ******************************************************************************/
crlonxpa6ecd622022-09-30 01:51:50 +0800321static void load_network(char * ssid, char * pwd);
322
nxptest2d0c5292022-06-24 19:04:49 +0800323/*
324static void saveProfile(int argc, char **argv);
325static void loadProfile(int argc, char **argv);
326static void resetProfile(int argc, char **argv);
327
328static void wlanIeeePowerSave(int argc, char **argv);
329static void wlanDeepSleep(int argc, char **argv);
330static void mcuPowerMode(int argc, char **argv);
331
332
333static struct cli_command saveload[] = {
334 {"save-profile", "<profile_name>", saveProfile},
335 {"load-profile", NULL, loadProfile},
336 {"reset-profile", NULL, resetProfile},
337};
338
339static struct cli_command wlanPower[] = {
340 {"wlan-ieee-power-save", "<on/off> <wakeup condition>", wlanIeeePowerSave},
341 {"wlan-deepsleep", "<on/off>", wlanDeepSleep},
342};
343
344static struct cli_command mcuPower[] = {
345 {"mcu-power-mode", "<pm0/pm1/pm2/pm4> [<pm2_io_exclude_mask>]", mcuPowerMode},
346};
347*/
348
349TaskHandle_t sShellTaskHandle;
350
351/*******************************************************************************
352 * Code
353 ******************************************************************************/
354static status_t APP_AES_Lock(void)
355{
356 if (pdTRUE == xSemaphoreTakeRecursive(aesLock, portMAX_DELAY))
357 {
358 return kStatus_Success;
359 }
360 else
361 {
362 return kStatus_Fail;
363 }
364}
365
366static void APP_AES_Unlock(void)
367{
368 xSemaphoreGiveRecursive(aesLock);
369}
370
crlonxpa6ecd622022-09-30 01:51:50 +0800371static void load_network(char * ssid, char * pwd)
372{
373 int ret;
374 unsigned char ssid_buf[IEEEtypes_SSID_SIZE + 1];
375 unsigned char psk_buf[WLAN_PSK_MAX_LENGTH];
376 uint32_t len;
377
378 len = IEEEtypes_SSID_SIZE + 1;
379 ret = get_saved_wifi_network((char *) SSID_FNAME, ssid_buf, &len);
380 if (ret != WM_SUCCESS)
381 {
382 PRINTF("Error: Read saved SSID\r\n");
383 strcpy(ssid, "");
384 }
385 else
386 {
387 PRINTF("saved_ssid: [%s]\r\n", ssid_buf);
388 strcpy(ssid, (const char *) ssid_buf);
389 }
390
391 len = WLAN_PSK_MAX_LENGTH;
392 ret = get_saved_wifi_network((char *) PSK_FNAME, psk_buf, &len);
393 if (ret != WM_SUCCESS)
394 {
395 PRINTF("Error: Read saved PSK\r\n");
396 strcpy(pwd, "");
397 }
398 else
399 {
400 PRINTF("saved_psk: [%s]\r\n", psk_buf);
401 strcpy(pwd, (const char *) psk_buf);
402 }
403}
404
nxptest2d0c5292022-06-24 19:04:49 +0800405/*
406static void saveProfile(int argc, char **argv)
407{
408 int ret;
409 struct wlan_network network;
410
411 if (argc < 2)
412 {
413 PRINTF("Usage: %s <profile_name>\r\n", argv[0]);
414 PRINTF("Error: specify network to save\r\n");
415 return;
416 }
417
418 ret = wlan_get_network_byname(argv[1], &network);
419 if (ret != WM_SUCCESS)
420 {
421 PRINTF("Error: network not found\r\n");
422 }
423 else
424 {
425 ret = save_wifi_network((char *)CONNECTION_INFO_FILENAME, (uint8_t *)&network, sizeof(network));
426 if (ret != WM_SUCCESS)
427 {
428 PRINTF("Error: write network to flash failed\r\n");
429 }
430 }
431}
432
433static void loadProfile(int argc, char **argv)
434{
435 int ret;
436 struct wlan_network network;
437 uint32_t len = sizeof(network);
438
439 ret = get_saved_wifi_network((char *)CONNECTION_INFO_FILENAME, (uint8_t *)&network, &len);
440 if (ret != WM_SUCCESS || len != sizeof(network))
441 {
442 PRINTF("Error: No network saved\r\n");
443 }
444 else
445 {
446 ret = wlan_add_network(&network);
447 if (ret != WM_SUCCESS)
448 {
449 PRINTF("Error: network data corrupted or network already added\r\n");
450 }
451 }
452}
453
454static void resetProfile(int argc, char **argv)
455{
456 int ret;
457
458 ret = reset_saved_wifi_network((char *)CONNECTION_INFO_FILENAME);
459 if (ret != WM_SUCCESS)
460 {
461 PRINTF("Error: Reset profile failed\r\n");
462 }
463}
464
465static void wlanIeeePowerSave(int argc, char **argv)
466{
467 bool on = false;
468 bool off = false;
469 uint32_t cond;
470 int ret;
471
472 if (argc >= 2)
473 {
474 on = (strcmp(argv[1], "on") == 0);
475 off = (strcmp(argv[1], "off") == 0);
476 }
477 if ((argc < 2) || (!on && !off) || (on && argc < 3))
478 {
479 PRINTF("Usage: %s <on/off> [<wakeup condition>]\r\n", argv[0]);
480 PRINTF(" wakeup condictions needed by \"on\" command:\r\n");
481 PRINTF(" bit0=1: broadcast data\r\n");
482 PRINTF(" bit1=1: unicast data\r\n");
483 PRINTF(" bit2=1: mac events\r\n");
484 PRINTF(" bit3=1: multicast data\r\n");
485 PRINTF(" bit4=1: arp broadcast data\r\n");
486 PRINTF(" bit6=1: management frame\r\n");
487 return;
488 }
489
490 if (on)
491 {
492 cond = strtoul(argv[2], NULL, 0);
493 ret = wlan_ieeeps_on(cond);
494 }
495 else
496 {
497 ret = wlan_ieeeps_off();
498 }
499
500 if (ret != WM_SUCCESS)
501 {
502 PRINTF("Cannot request IEEE power save mode change!\r\n");
503 }
504 else
505 {
506 PRINTF("IEEE power save mode change requested!\r\n");
507 }
508}
509
510static void wlanDeepSleep(int argc, char **argv)
511{
512 bool on;
513 int ret;
514
515 if ((argc < 2) || ((strcmp(argv[1], "on") != 0) && (strcmp(argv[1], "off") != 0)))
516 {
517 PRINTF("Usage: %s <on/off>\r\n", argv[0]);
518 PRINTF("Error: specify deep sleep on or off.\r\n");
519 return;
520 }
521
522 on = (strcmp(argv[1], "on") == 0);
523 if (on)
524 {
525 ret = wlan_deepsleepps_on();
526 }
527 else
528 {
529 ret = wlan_deepsleepps_off();
530 }
531
532 if (ret != WM_SUCCESS)
533 {
534 PRINTF("Cannot request deep sleep mode change!\r\n");
535 }
536 else
537 {
538 PRINTF("Deep sleep mode change requested!\r\n");
539 }
540}
541
542
543static void mcuPowerMode(int argc, char **argv)
544{
545 uint32_t excludeIo = 0U;
546
547 if ((argc < 2) || (strlen(argv[1]) != 3) || (argv[1][0] != 'p') || (argv[1][1] != 'm') || (argv[1][2] < '0') ||
548 (argv[1][2] > '4') || (argv[1][2] == '3'))
549 {
550 PRINTF("Usage: %s <pm0/pm1/pm2/pm4> [<pm2_io_exclude_mask>]\r\n", argv[0]);
551 PRINTF(" pm2_io_exclude_mask: bitmask of io domains to keep on in PM2.\r\n");
552 PRINTF(" e.g. 0x5 means VDDIO0 and VDDIO2 will not be powered off in PM2\r\n");
553 PRINTF("Error: specify power mode to enter.\r\n");
554 return;
555 }
556
557 if (argv[1][2] - '0' == 2U)
558 {
559 if (argc < 3)
560 {
561 PRINTF("Error: PM2 need 3rd parameter.\r\n");
562 return;
563 }
564 else
565 {
566 excludeIo = strtoul(argv[2], NULL, 0);
567 }
568 }
569
570 LPM_SetPowerMode(argv[1][2] - '0', excludeIo);
571}
572*/
573
574static void mcuInitPower(void)
575{
576 lpm_config_t config = {
577 /* System PM2/PM3 less than 50 ms will be skipped. */
578 .threshold = 50U,
579 /* SFLL config and RC32M setup takes approx 14 ms. */
580 .latency = 15U,
581 .enableWakeupPin0 = true,
582 .enableWakeupPin1 = true,
583 .handler = NULL,
584 };
585
586 LPM_Init(&config);
587}
588
589/* Callback Function passed to WLAN Connection Manager. The callback function
590 * gets called when there are WLAN Events that need to be handled by the
591 * application.
592 */
593int wlan_event_callback(enum wlan_event_reason reason, void * data)
594{
595 int ret;
596 struct wlan_ip_config addr;
597 char ip[16];
598 static int auth_fail = 0;
599
600 // PRINTF("[%s] WLAN: received event %d\r\n", __FUNCTION__, reason);
601 switch (reason)
602 {
603 case WLAN_REASON_INITIALIZED:
crlonxpa6ecd622022-09-30 01:51:50 +0800604 // PRINTF("app_cb: WLAN initialized\r\n");
nxptest2d0c5292022-06-24 19:04:49 +0800605#ifdef MCUXPRESSO_WIFI_CLI
606 ret = wlan_basic_cli_init();
607 if (ret != WM_SUCCESS)
608 {
609 PRINTF("Failed to initialize BASIC WLAN CLIs\r\n");
610 return 0;
611 }
612
613 ret = wlan_cli_init();
614 if (ret != WM_SUCCESS)
615 {
616 PRINTF("Failed to initialize WLAN CLIs\r\n");
617 return 0;
618 }
619 PRINTF("WLAN CLIs are initialized\r\n");
620
621 ret = ping_cli_init();
622 if (ret != WM_SUCCESS)
623 {
624 PRINTF("Failed to initialize PING CLI\r\n");
625 return 0;
626 }
627
628 ret = iperf_cli_init();
629 if (ret != WM_SUCCESS)
630 {
631 PRINTF("Failed to initialize IPERF CLI\r\n");
632 return 0;
633 }
634#endif
635 ret = dhcpd_cli_init();
636 if (ret != WM_SUCCESS)
637 {
638 // PRINTF("Failed to initialize DHCP Server CLI\r\n");
639 return 0;
640 }
641#ifdef MCUXPRESSO_WIFI_CLI
642 if (cli_register_commands(saveload, sizeof(saveload) / sizeof(struct cli_command)))
643 {
644 return -WM_FAIL;
645 }
646
647 if (cli_register_commands(wlanPower, sizeof(wlanPower) / sizeof(struct cli_command)))
648 {
649 return -WM_FAIL;
650 }
651
652 if (cli_register_commands(mcuPower, sizeof(mcuPower) / sizeof(struct cli_command)))
653 {
654 return -WM_FAIL;
655 }
656
657 PRINTF("CLIs Available:\r\n");
658 if (Matter_Selection == MCUXPRESSO_WIFI_CLI)
659 help_command(0, NULL);
660#endif
661 break;
662 case WLAN_REASON_INITIALIZATION_FAILED:
crlonxpa6ecd622022-09-30 01:51:50 +0800663 // PRINTF("app_cb: WLAN: initialization failed\r\n");
nxptest2d0c5292022-06-24 19:04:49 +0800664 break;
665 case WLAN_REASON_SUCCESS:
crlonxpa6ecd622022-09-30 01:51:50 +0800666 // PRINTF("app_cb: WLAN: connected to network\r\n");
nxptest2d0c5292022-06-24 19:04:49 +0800667 ret = wlan_get_address(&addr);
668 if (ret != WM_SUCCESS)
669 {
crlonxpa6ecd622022-09-30 01:51:50 +0800670 // PRINTF("failed to get IP address\r\n");
nxptest2d0c5292022-06-24 19:04:49 +0800671 return 0;
672 }
673
674 net_inet_ntoa(addr.ipv4.address, ip);
675
676 ret = wlan_get_current_network(&sta_network);
677 if (ret != WM_SUCCESS)
678 {
crlonxpa6ecd622022-09-30 01:51:50 +0800679 // PRINTF("Failed to get External AP network\r\n");
nxptest2d0c5292022-06-24 19:04:49 +0800680 return 0;
681 }
682
683 PRINTF("Connected to following BSS:\r\n");
684 PRINTF("SSID = [%s], IP = [%s]\r\n", sta_network.ssid, ip);
crlonxpa6ecd622022-09-30 01:51:50 +0800685 save_network(sta_network.ssid, sta_network.security.psk);
nxptest2d0c5292022-06-24 19:04:49 +0800686
687#ifdef CONFIG_IPV6
688 {
689 int i;
690 (void) PRINTF("\r\n\tIPv6 Addresses\r\n");
691 for (i = 0; i < MAX_IPV6_ADDRESSES; i++)
692 {
693 if (sta_network.ip.ipv6[i].addr_state != IP6_ADDR_INVALID)
694 {
695 (void) PRINTF("\t%-13s:\t%s (%s)\r\n", ipv6_addr_type_to_desc(&(sta_network.ip.ipv6[i])),
696 inet6_ntoa(sta_network.ip.ipv6[i].address),
697 ipv6_addr_state_to_desc(sta_network.ip.ipv6[i].addr_state));
698 }
699 }
700 (void) PRINTF("\r\n");
701 }
702#endif
703 auth_fail = 0;
704 is_connected = true;
705 run_update_chipsrv(dns_srv);
706
707 if (is_uap_started())
708 {
709 wlan_get_current_uap_network(&uap_network);
710 ret = wlan_stop_network(uap_network.name);
711 /* if (ret != WM_SUCCESS)
712 PRINTF("Error: unable to stop network\r\n");
713 else
714 PRINTF("stop uAP, SSID = [%s]\r\n", uap_network.ssid);
715 */
716 }
717 break;
718 case WLAN_REASON_CONNECT_FAILED:
719 // PRINTF("app_cb: WLAN: connect failed\r\n");
720 break;
721 case WLAN_REASON_NETWORK_NOT_FOUND:
722 // PRINTF("app_cb: WLAN: network not found\r\n");
723 break;
724 case WLAN_REASON_NETWORK_AUTH_FAILED:
725 // PRINTF("app_cb: WLAN: network authentication failed\r\n");
726 auth_fail++;
727 if (auth_fail >= 3)
728 {
729 // PRINTF("Authentication Failed. Disconnecting ... \r\n");
730 wlan_disconnect();
731 auth_fail = 0;
732 }
733 break;
734 case WLAN_REASON_ADDRESS_SUCCESS:
735 // PRINTF("network mgr: DHCP new lease\r\n");
736 break;
737 case WLAN_REASON_ADDRESS_FAILED:
738 // PRINTF("app_cb: failed to obtain an IP address\r\n");
739 break;
740 case WLAN_REASON_USER_DISCONNECT:
741 // PRINTF("app_cb: disconnected\r\n");
742 auth_fail = 0;
743 break;
744 case WLAN_REASON_LINK_LOST:
745 is_connected = false;
746 run_update_chipsrv(dns_srv);
747 // PRINTF("app_cb: WLAN: link lost\r\n");
748 break;
749 case WLAN_REASON_CHAN_SWITCH:
750 // PRINTF("app_cb: WLAN: channel switch\r\n");
751 break;
752 case WLAN_REASON_UAP_SUCCESS:
753 // PRINTF("app_cb: WLAN: UAP Started\r\n");
754 ret = wlan_get_current_uap_network(&uap_network);
755
756 if (ret != WM_SUCCESS)
757 {
758 PRINTF("Failed to get Soft AP network\r\n");
759 return 0;
760 }
761
762 // PRINTF("Soft AP \"%s\" started successfully\r\n", uap_network.ssid);
763 if (dhcp_server_start(net_get_uap_handle()))
764 PRINTF("Error in starting dhcp server\r\n");
765 // PRINTF("DHCP Server started successfully\r\n");
766 break;
767 case WLAN_REASON_UAP_CLIENT_ASSOC:
768 PRINTF("app_cb: WLAN: UAP a Client Associated\r\n");
769 // PRINTF("Client => ");
770 // print_mac((const char *)data);
771 // PRINTF("Associated with Soft AP\r\n");
772 break;
773 case WLAN_REASON_UAP_CLIENT_DISSOC:
774 // PRINTF("app_cb: WLAN: UAP a Client Dissociated\r\n");
775 // PRINTF("Client => ");
776 // print_mac((const char *)data);
777 // PRINTF("Dis-Associated from Soft AP\r\n");
778 break;
779 case WLAN_REASON_UAP_STOPPED:
780 // PRINTF("app_cb: WLAN: UAP Stopped\r\n");
781 // PRINTF("Soft AP \"%s\" stopped successfully\r\n", uap_network.ssid);
782 dhcp_server_stop();
783 // PRINTF("DHCP Server stopped successfully\r\n");
784 break;
785 case WLAN_REASON_PS_ENTER:
786 // PRINTF("app_cb: WLAN: PS_ENTER\r\n");
787 break;
788 case WLAN_REASON_PS_EXIT:
789 // PRINTF("app_cb: WLAN: PS EXIT\r\n");
790 break;
791 default:
792 PRINTF("app_cb: WLAN: Unknown Event: %d\r\n", reason);
793 }
794 return 0;
795}
796
797#if 0
798char profile[8] = "mw320";
799char ssid[32] = "matter_mw320";
800char psk[64] = "12345678";
801char network_ip[15] = "192.168.2.1";
802char network_netmask[15] = "255.255.255.0";
803const uint8_t kOptionalDefaultStringTag1 = 1;
804const uint8_t kOptionalDefaultStringTag2 = 2;
805const uint8_t kOptionalDefaultStringTag3 = 3;
806
807std::string createSetupPayload()
808{
809 CHIP_ERROR err = CHIP_NO_ERROR;
810 std::string result;
811 std::string kOptionalDefaultStringValue1 = "IP:";
812 std::string kOptionalDefaultStringValue2 = "SSID:";
813 std::string kOptionalDefaultStringValue3 = "Key:";
814 uint16_t discriminator;
815
816 kOptionalDefaultStringValue1.append( network_ip, sizeof(network_ip) );
817 kOptionalDefaultStringValue2.append( ssid, sizeof(ssid) );
818 kOptionalDefaultStringValue3.append( psk, sizeof(psk) );
819 err = ConfigurationMgr().GetSetupDiscriminator(discriminator);
820 if (err != CHIP_NO_ERROR)
821 {
822 PRINTF("[%s]: Couldn't get discriminator: %s\r\n", __FUNCTION__, ErrorStr(err));
823 return result;
824 }
825
826 uint32_t setupPINCode;
827 err = ConfigurationMgr().GetSetupPinCode(setupPINCode);
828 if (err != CHIP_NO_ERROR)
829 {
830 PRINTF("[%s]: Couldn't get setupPINCode: %s\r\n", __FUNCTION__, ErrorStr(err));
831 return result;
832 }
833
834 uint16_t vendorId;
835 err = ConfigurationMgr().GetVendorId(vendorId);
836 if (err != CHIP_NO_ERROR)
837 {
838 PRINTF("[%s]: Couldn't get vendorId: %s\r\n", __FUNCTION__, ErrorStr(err));
839 return result;
840 }
841
842 uint16_t productId;
843 err = ConfigurationMgr().GetProductId(productId);
844 if (err != CHIP_NO_ERROR)
845 {
846 PRINTF("[%s]: Couldn't get productId: %s\r\n", __FUNCTION__, ErrorStr(err));
847 return result;
848 }
849 SetupPayload payload;
850 payload.version = 0;
851 payload.discriminator = discriminator;
852 payload.setUpPINCode = setupPINCode;
Boris Zbarskyecbaab52022-08-09 10:53:22 -0400853 payload.rendezvousInformation.SetValue(chip::RendezvousInformationFlag::kBLE);
nxptest2d0c5292022-06-24 19:04:49 +0800854 payload.vendorID = vendorId;
855 payload.productID = productId;
856
857 err = payload.addOptionalVendorData(kOptionalDefaultStringTag1, kOptionalDefaultStringValue1);
858 if (err != CHIP_NO_ERROR)
859 {
860 PRINTF("[%s]: Couldn't add payload Vnedor string %d \r\n", __FUNCTION__, kOptionalDefaultStringTag1);
861 }
862 err = payload.addOptionalVendorData(kOptionalDefaultStringTag2, kOptionalDefaultStringValue2);
863 if (err != CHIP_NO_ERROR)
864 {
865 PRINTF("[%s]: Couldn't add payload Vnedor string %d \r\n", __FUNCTION__, kOptionalDefaultStringTag2);
866 }
867 err = payload.addOptionalVendorData(kOptionalDefaultStringTag3, kOptionalDefaultStringValue3);
868 if (err != CHIP_NO_ERROR)
869 {
870 PRINTF("[%s]: Couldn't add payload Vnedor string %d \r\n", __FUNCTION__, kOptionalDefaultStringTag3);
871 }
872
873 QRCodeSetupPayloadGenerator generator(payload);
874 size_t tlvDataLen = sizeof(kOptionalDefaultStringValue1)+sizeof(kOptionalDefaultStringValue2)+sizeof(kOptionalDefaultStringValue3);
875 uint8_t tlvDataStart[tlvDataLen];
876 err = generator.payloadBase38Representation(result, tlvDataStart, tlvDataLen);
877
878 if (err != CHIP_NO_ERROR)
879 {
880 PRINTF("[%s]: Couldn't get payload string %d \r\n", __FUNCTION__, err);
881 }
882 return result;
883}
884#endif // 0
885
886#if 0
887void demo_init(void)
888{
889 struct wlan_network network;
890 int ret = 0;
891
892 // add uAP profile
893 memset(&network, 0, sizeof(struct wlan_network));
894 memcpy(network.name, profile, strlen(profile));
895
896 memcpy(network.ssid, ssid, strlen(ssid));
897 network.channel = 1;
898
899 network.ip.ipv4.address = net_inet_aton(network_ip);
900 network.ip.ipv4.gw = net_inet_aton(network_ip);
901 network.ip.ipv4.netmask = net_inet_aton(network_netmask);
902 network.ip.ipv4.addr_type = ADDR_TYPE_STATIC;
903
904 network.security.psk_len = strlen(psk);
905 strcpy(network.security.psk, psk);
906 network.security.type = WLAN_SECURITY_WPA2;
907
908 network.role = WLAN_BSS_ROLE_UAP;
909
910 ret = wlan_add_network(&network);
911 switch (ret)
912 {
913 case WM_SUCCESS:
914 PRINTF("Added \"%s\"\r\n", network.name);
915 break;
916 case -WM_E_INVAL:
917 PRINTF("Error: network already exists or invalid arguments\r\n");
918 break;
919 case -WM_E_NOMEM:
920 PRINTF("Error: network list is full\r\n");
921 break;
922 case WLAN_ERROR_STATE:
923 PRINTF("Error: can't add networks in this state\r\n");
924 break;
925 default:
926 PRINTF(
927 "Error: unable to add network for unknown"
928 " reason\r\n");
929 break;
930 }
931
932 // start uAP
933 ret = wlan_start_network(profile);
934 if (ret != WM_SUCCESS)
935 PRINTF("Error: unable to start network\r\n");
936 else
937 PRINTF("start uAP ssid: %s\r\n", network.ssid);
938
939}
940#endif // 0
941
942void task_main(void * param)
943{
944#if 0
945 int32_t result = 0;
946 flash_desc_t fl;
947 struct partition_entry *p, *f1, *f2;
948 short history = 0;
949 uint32_t *wififw;
950#ifdef CONFIG_USE_PSM
951 struct partition_entry *psm;
952#endif
953
954 mcuInitPower();
955
956 boot_init();
957
958 mflash_drv_init();
959
960 PRINTF("[%s]: Initialize CLI\r\n", __FUNCTION__);
961 result = cli_init();
962 if (WM_SUCCESS != result)
963 {
964 assert(false);
965 }
966
967 PRINTF("[%s]: Initialize WLAN Driver\r\n", __FUNCTION__);
968 result = part_init();
969 if (WM_SUCCESS != result)
970 {
971 assert(false);
972 }
973
974#ifdef CONFIG_USE_PSM
975 psm = part_get_layout_by_id(FC_COMP_PSM, NULL);
976 part_to_flash_desc(psm, &fl);
977#else
978 fl.fl_dev = 0U;
979 fl.fl_start = MFLASH_FILE_BASEADDR;
980 fl.fl_size = MFLASH_FILE_SIZE;
981#endif
982 init_flash_storage((char *)CONNECTION_INFO_FILENAME, &fl);
983
984 f1 = part_get_layout_by_id(FC_COMP_WLAN_FW, &history);
985 f2 = part_get_layout_by_id(FC_COMP_WLAN_FW, &history);
986
987 if (f1 && f2)
988 {
989 p = part_get_active_partition(f1, f2);
990 }
991 else if (!f1 && f2)
992 {
993 p = f2;
994 }
995 else if (!f2 && f1)
996 {
997 p = f1;
998 }
999 else
1000 {
1001 PRINTF("[%s]: Wi-Fi Firmware not detected\r\n", __FUNCTION__);
1002 p = NULL;
1003 }
1004
1005 if (p != NULL)
1006 {
1007 part_to_flash_desc(p, &fl);
1008 wififw = (uint32_t *)mflash_drv_phys2log(fl.fl_start, fl.fl_size);
1009 assert(wififw != NULL);
1010 /* First word in WIFI firmware is magic number. */
1011 assert(*wififw == (('W' << 0) | ('L' << 8) | ('F' << 16) | ('W' << 24)));
1012
1013 /* Initialize WIFI Driver */
1014 /* Second word in WIFI firmware is WIFI firmware length in bytes. */
1015 /* Real WIFI binary starts from 3rd word. */
1016 result = wlan_init((const uint8_t *)(wififw + 2U), *(wififw + 1U));
1017 if (WM_SUCCESS != result)
1018 {
1019 assert(false);
1020 }
1021 PRINTF("[%s]: wlan_init success \r\n", __FUNCTION__);
1022
1023 result = wlan_start(wlan_event_callback);
1024 if (WM_SUCCESS != result)
1025 {
1026 assert(false);
1027 }
1028 }
1029
Andrei Litvin1145bac2022-11-03 17:39:11 -04001030 while (true)
nxptest2d0c5292022-06-24 19:04:49 +08001031 {
1032 /* wait for interface up */
1033 os_thread_sleep(os_msec_to_ticks(5000));
1034 PRINTF("[%s]: looping\r\n", __FUNCTION__);
1035 }
1036#endif // 0
1037}
1038
1039static void run_chip_srv(System::Layer * aSystemLayer, void * aAppState)
1040{
1041 // Init ZCL Data Model and CHIP App Server
1042 {
1043 // Initialize device attestation config
crlonxpa6ecd622022-09-30 01:51:50 +08001044#if (defined(CONFIG_CHIP_MW320_REAL_FACTORY_DATA) && (CONFIG_CHIP_MW320_REAL_FACTORY_DATA == 1))
1045 FactoryDataProvider::GetDefaultInstance().Init();
1046#if (CHIP_DEVICE_CONFIG_ENABLE_DEVICE_INSTANCE_INFO_PROVIDER == 1)
1047 SetDeviceInstanceInfoProvider(&FactoryDataProvider::GetDefaultInstance());
1048#endif // USE_LOCAL_DEVICEINSTANCEINFOPROVIDER
1049 SetDeviceAttestationCredentialsProvider(&FactoryDataProvider::GetDefaultInstance());
1050 SetCommissionableDataProvider(&FactoryDataProvider::GetDefaultInstance());
1051#else
nxptest2d0c5292022-06-24 19:04:49 +08001052 SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider());
crlonxpa6ecd622022-09-30 01:51:50 +08001053#endif // CONFIG_CHIP_MW320_REAL_FACTORY_DATA
nxptest2d0c5292022-06-24 19:04:49 +08001054 }
1055 {
1056 // chip::Server::GetInstance().Init();
1057 // uint16_t securePort = CHIP_PORT;
1058 // uint16_t unsecurePort = CHIP_UDC_PORT;
1059
1060 // PRINTF("==> call chip::Server() \r\n");
nxptest2d0c5292022-06-24 19:04:49 +08001061 // chip::Server::GetInstance().Init(nullptr, securePort, unsecurePort);
1062
1063 static chip::CommonCaseDeviceServerInitParams initParams;
1064 (void) initParams.InitializeStaticResourcesBeforeServerInit();
1065 chip::Server::GetInstance().Init(initParams);
1066 PRINTF("Done to call chip::Server() \r\n");
1067 }
1068 // ota ++
1069 {
1070 InitOTARequestor();
1071#if (MW320_OTA_TEST == 1)
1072 // for ota module test
1073 mw320_fw_update_test();
1074#endif // MW320_OTA_TEST
1075 }
1076 // ota --
1077 // binding ++
1078 InitBindingHandlers();
1079 // binding --
1080
1081 return;
1082}
1083
1084static void run_dnssrv(System::Layer * aSystemLayer, void * aAppState)
1085{
1086 chip::app::DnssdServer::Instance().StartServer();
1087 if (is_connected == true)
1088 {
1089 led_on_off(led_amber, true);
1090 }
1091 else
1092 {
1093 led_on_off(led_amber, false);
1094 }
1095 return;
1096}
1097
1098#define RUN_CHIPSRV_DELAY 1
1099static void run_update_chipsrv(srv_type_t srv_type)
1100{
1101 switch (srv_type)
1102 {
1103 case chip_srv_all:
1104 DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds16(RUN_CHIPSRV_DELAY), run_chip_srv, nullptr);
1105 break;
1106 case dns_srv:
1107 DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds16(RUN_CHIPSRV_DELAY), run_dnssrv, nullptr);
1108 break;
1109 default:
1110 return;
1111 }
1112 return;
1113}
1114
1115//=============================================================================
1116// Light behaior while resetting the saved arguments
1117//
1118static void rst_args_lt(System::Layer * aSystemLayer, void * aAppState)
1119{
1120 // PRINTF("%s(), Turn on lights \r\n", __FUNCTION__);
1121 led_on_off(led_amber, true);
1122 led_on_off(led_yellow, true);
1123 // sleep 3 second
1124 // PRINTF("%s(), sleep 3 seconds \r\n", __FUNCTION__);
1125 os_thread_sleep(os_msec_to_ticks(3000));
1126 // PRINTF("%s(), Turn off lights \r\n", __FUNCTION__);
1127 led_on_off(led_amber, false);
1128 led_on_off(led_yellow, false);
1129 return;
1130}
1131
1132void task_test_main(void * param)
1133{
Andrei Litvin1145bac2022-11-03 17:39:11 -04001134 while (true)
nxptest2d0c5292022-06-24 19:04:49 +08001135 {
1136 /* wait for interface up */
1137 os_thread_sleep(os_msec_to_ticks(500));
1138 /*PRINTF("[%s]: looping\r\n", __FUNCTION__);*/
1139 if (need2sync_sw_attr == true)
1140 {
1141 static bool is_on = false;
1142 uint16_t value = g_ButtonPress & 0x1;
1143 is_on = !is_on;
1144 value = (uint16_t) is_on;
1145 // sync-up the switch attribute:
1146 PRINTF("--> update ZCL_CURRENT_POSITION_ATTRIBUTE_ID [%d] \r\n", value);
Boris Zbarskyb46af332022-12-01 00:33:16 -05001147 emAfWriteAttribute(1, Clusters::Switch::Id, ZCL_CURRENT_POSITION_ATTRIBUTE_ID, (uint8_t *) &value, sizeof(value), true,
nxptest2d0c5292022-06-24 19:04:49 +08001148 false);
crlonxpa6ecd622022-09-30 01:51:50 +08001149#ifdef SUPPORT_MANUAL_CTRL
1150 // sync-up the Light attribute (for test event, OO.M.ManuallyControlled)
Boris Zbarskyb46af332022-12-01 00:33:16 -05001151 PRINTF("--> update [Clusters::Switch::Id]: ZCL_ON_OFF_ATTRIBUTE_ID [%d] \r\n", value);
1152 emAfWriteAttribute(1, Clusters::Switch::Id, ZCL_ON_OFF_ATTRIBUTE_ID, (uint8_t *) &value, sizeof(value), true, false);
crlonxpa6ecd622022-09-30 01:51:50 +08001153#endif // SUPPORT_MANUAL_CTRL
1154
nxptest2d0c5292022-06-24 19:04:49 +08001155 need2sync_sw_attr = false;
1156 }
1157 // =============================
1158 // Call sw2_handle to clear click_count if needed
1159 sw2_handle(false);
1160 // =============================
1161 }
1162 return;
1163}
1164
crlonxpa6ecd622022-09-30 01:51:50 +08001165void init_mw320_sdk()
nxptest2d0c5292022-06-24 19:04:49 +08001166{
1167 flash_desc_t fl;
1168 struct partition_entry *p, *f1, *f2;
1169 short history = 0;
1170 uint32_t * wififw;
1171 struct partition_entry * psm;
crlonxpa6ecd622022-09-30 01:51:50 +08001172 struct partition_entry * manu_dat;
1173 uint8_t * pmfdat;
nxptest2d0c5292022-06-24 19:04:49 +08001174
crlonxpa6ecd622022-09-30 01:51:50 +08001175 PRINTF("=> init mw320 sdk \r\n");
nxptest2d0c5292022-06-24 19:04:49 +08001176 PRINTF("call mcuInitPower() \r\n");
1177 mcuInitPower();
1178 boot_init();
1179 mflash_drv_init();
1180 cli_init();
1181 part_init();
crlonxpa6ecd622022-09-30 01:51:50 +08001182
nxptest2d0c5292022-06-24 19:04:49 +08001183 psm = part_get_layout_by_id(FC_COMP_PSM, NULL);
1184 part_to_flash_desc(psm, &fl);
1185 init_flash_storage((char *) CONNECTION_INFO_FILENAME, &fl);
crlonxpa6ecd622022-09-30 01:51:50 +08001186 PRINTF("[PSM]: (start, len)=(0x%x, 0x%x)\r\n", fl.fl_start, fl.fl_size);
1187
1188 manu_dat = part_get_layout_by_id(FC_COMP_USER_APP, NULL);
1189 part_to_flash_desc(manu_dat, &fl);
1190 PRINTF("[Manufacture_Data]: (start, len)=(0x%x, 0x%x)\r\n", fl.fl_start, fl.fl_size);
1191 pmfdat = (uint8_t *) mflash_drv_phys2log(fl.fl_start, fl.fl_size);
1192 __FACTORY_DATA_START = pmfdat;
1193 __FACTORY_DATA_SIZE = (uint32_t) fl.fl_size;
1194
nxptest2d0c5292022-06-24 19:04:49 +08001195 f1 = part_get_layout_by_id(FC_COMP_WLAN_FW, &history);
1196 f2 = part_get_layout_by_id(FC_COMP_WLAN_FW, &history);
1197 if (f1 && f2)
1198 {
1199 p = part_get_active_partition(f1, f2);
1200 }
1201 else if (!f1 && f2)
1202 {
1203 p = f2;
1204 }
1205 else if (!f2 && f1)
1206 {
1207 p = f1;
1208 }
1209 else
1210 {
crlonxpa6ecd622022-09-30 01:51:50 +08001211 // PRINTF("[%s]: Wi-Fi Firmware not detected\r\n", __FUNCTION__);
nxptest2d0c5292022-06-24 19:04:49 +08001212 p = NULL;
1213 }
1214 if (p != NULL)
1215 {
1216 part_to_flash_desc(p, &fl);
1217 wififw = (uint32_t *) mflash_drv_phys2log(fl.fl_start, fl.fl_size);
crlonxpa6ecd622022-09-30 01:51:50 +08001218 // assert(wififw != NULL);
nxptest2d0c5292022-06-24 19:04:49 +08001219 /* First word in WIFI firmware is magic number. */
1220 assert(*wififw == (('W' << 0) | ('L' << 8) | ('F' << 16) | ('W' << 24)));
1221 wlan_init((const uint8_t *) (wififw + 2U), *(wififw + 1U));
crlonxpa6ecd622022-09-30 01:51:50 +08001222 // PRINTF("[%s]: wlan_init success \r\n", __FUNCTION__);
nxptest2d0c5292022-06-24 19:04:49 +08001223 wlan_start(wlan_event_callback);
crlonxpa6ecd622022-09-30 01:51:50 +08001224 // demo_init();
nxptest2d0c5292022-06-24 19:04:49 +08001225 os_thread_sleep(os_msec_to_ticks(5000));
1226 }
crlonxpa6ecd622022-09-30 01:51:50 +08001227 PRINTF(" mw320 init complete! \r\n");
1228
1229 return;
1230}
1231
1232void ShellCLIMain(void * pvParameter)
1233{
1234 const int rc = streamer_init(streamer_get());
1235 if (rc != 0)
1236 {
1237 ChipLogError(Shell, "Streamer initialization failed: %d", rc);
1238 return;
1239 }
1240
1241 PRINTF("version: [%s] \r\n", VERSION_STR);
1242
1243 // Initialize the SDK components
1244 init_mw320_sdk();
1245
1246 ChipLogDetail(Shell, "Initializing CHIP shell commands: %d", rc);
1247
1248 chip::Platform::MemoryInit();
1249 chip::DeviceLayer::PlatformMgr().InitChipStack();
1250 ConfigurationMgr().LogDeviceConfig();
1251 PrintOnboardingCodes(chip::RendezvousInformationFlag::kOnNetwork);
1252 chip::DeviceLayer::PlatformMgr().StartEventLoopTask();
1253#if CHIP_DEVICE_CONFIG_ENABLE_WPA
1254 chip::DeviceLayer::ConnectivityManagerImpl().StartWiFiManagement();
1255#endif
1256
1257 cmd_misc_init();
1258 // cmd_otcli_init();
1259 ChipLogDetail(Shell, "Run CHIP shell Task: %d", rc);
nxptest2d0c5292022-06-24 19:04:49 +08001260
1261 // std::string qrCodeText = createSetupPayload();
1262 // PRINTF("SetupQRCode: [%s]\r\n", qrCodeText.c_str());
crlonxpa6ecd622022-09-30 01:51:50 +08001263 {
1264 char def_ssid[IEEEtypes_SSID_SIZE + 1];
1265 char def_psk[WLAN_PSK_MAX_LENGTH];
1266 load_network(def_ssid, def_psk);
nxptest2d0c5292022-06-24 19:04:49 +08001267
crlonxpa6ecd622022-09-30 01:51:50 +08001268 if ((strlen(def_ssid) <= 0) || (strlen(def_psk) <= 0))
1269 {
1270 // No saved connected_ap_info => Using the default ssid/password
1271 strcpy(def_ssid, "nxp_matter");
1272 strcpy(def_psk, "nxp12345");
1273 }
1274 PRINTF("Connecting to [%s, %s] \r\n", def_ssid, def_psk);
Yufeng Wang42b44382022-11-03 18:04:11 -07001275
1276 // TODO: ConnectivityMgrImpl is the platform implementation of ConnectivityMgr layer.
1277 // Application should use the APIs defined src/include/platform to talk to the Matter
1278 // platfrom layer, instead of calling into the functions defined in the platform implemenation.
1279 // ConnectivityMgrImpl().ProvisionWiFiNetwork(def_ssid, def_psk);
crlonxpa6ecd622022-09-30 01:51:50 +08001280 }
nxptest2d0c5292022-06-24 19:04:49 +08001281
1282 // Run CHIP servers
1283 run_update_chipsrv(chip_srv_all);
1284
1285 Engine::Root().RunMainLoop();
1286}
1287
1288static void led_on_off(led_id_t lt_id, bool is_on)
1289{
1290 GPIO_Type * pgpio;
1291 uint32_t gpio_pin;
1292
1293 // Configure the GPIO / PIN
1294 switch (lt_id)
1295 {
1296 case led_amber:
1297 pgpio = BOARD_LED_AMBER_GPIO;
1298 gpio_pin = BOARD_LED_AMBER_GPIO_PIN;
1299 break;
1300 case led_yellow:
1301 default: // Note: led_yellow as default
1302 pgpio = BOARD_LED_YELLOW_GPIO;
1303 gpio_pin = BOARD_LED_YELLOW_GPIO_PIN;
1304 }
1305 // Do on/off the LED
1306 if (is_on == true)
1307 {
1308 // PRINTF("led on\r\n");
1309 GPIO_PortClear(pgpio, GPIO_PORT(gpio_pin), 1u << GPIO_PORT_PIN(gpio_pin));
1310 }
1311 else
1312 {
1313 // PRINTF("led off\r\n");
1314 GPIO_PortSet(pgpio, GPIO_PORT(gpio_pin), 1u << GPIO_PORT_PIN(gpio_pin));
1315 }
1316 return;
1317}
1318
1319} // namespace
1320
1321int StartShellTask(void)
1322{
1323 int ret = 0;
1324
1325 // Start Shell task.
1326 switch (Matter_Selection)
1327 {
1328 case MCUXPRESSO_WIFI_CLI:
1329#ifdef MCUXPRESSO_WIFI_CLI
1330 if (xTaskCreate(task_main, "main", TASK_MAIN_STACK_SIZE, task_main_stack, TASK_MAIN_PRIO, &task_main_task_handler) !=
1331 pdPASS)
1332 {
1333 ret = -1;
1334 }
1335 break;
1336#endif
1337 case MATTER_SHELL:
1338 default:
1339 if (xTaskCreate(ShellCLIMain, "SHELL", TASK_MAIN_STACK_SIZE, NULL, TASK_MAIN_PRIO, &sShellTaskHandle) != pdPASS)
1340 {
1341 ret = -1;
1342 }
1343 if (xTaskCreate(task_test_main, "testmain", TASK_MAIN_STACK_SIZE, task_main_stack, TASK_MAIN_PRIO,
1344 &task_main_task_handler) != pdPASS)
1345 {
1346 PRINTF("Failed to crete task_test_main() \r\n");
1347 ret = -1;
1348 }
1349 break;
1350 }
1351
1352 return ret;
1353}
1354
1355#define gpio_led_cfg(base, pin, cfg) \
1356 { \
1357 GPIO_PinInit(base, pin, cfg); \
1358 GPIO_PortSet(base, GPIO_PORT(pin), 1u << GPIO_PORT_PIN(pin)); \
1359 }
1360
1361#define gpio_sw_cfg(base, pin, cfg, irq, trig) \
1362 { \
1363 GPIO_PinInit(base, pin, cfg); \
1364 GPIO_PinSetInterruptConfig(base, pin, trig); \
1365 GPIO_PortEnableInterrupts(base, GPIO_PORT(pin), 1UL << GPIO_PORT_PIN(pin)); \
1366 EnableIRQ(irq); \
1367 }
1368
1369void gpio_init(void)
1370{
1371 gpio_pin_config_t led_config = {
1372 kGPIO_DigitalOutput,
1373 0,
1374 };
1375 gpio_pin_config_t sw_config = {
1376 kGPIO_DigitalInput,
1377 0,
1378 };
1379
1380 /* Init output amber led gpio off */
1381 gpio_led_cfg(BOARD_LED_AMBER_GPIO, BOARD_LED_AMBER_GPIO_PIN, &led_config);
1382
1383 /* Init output yellow led gpio off */
1384 gpio_led_cfg(BOARD_LED_YELLOW_GPIO, BOARD_LED_YELLOW_GPIO_PIN, &led_config);
1385
1386 /* Init/config input sw_1 GPIO. */
1387 gpio_sw_cfg(BOARD_SW1_GPIO, BOARD_SW1_GPIO_PIN, &sw_config, BOARD_SW1_IRQ, kGPIO_InterruptFallingEdge);
1388
1389 /* Init/config input sw_2 GPIO. */
1390 gpio_sw_cfg(BOARD_SW2_GPIO, BOARD_SW2_GPIO_PIN, &sw_config, BOARD_SW2_IRQ, kGPIO_InterruptFallingEdge);
1391 return;
1392}
1393
1394int main(void)
1395{
1396 // char ch;
1397 // unsigned int bp;
1398 // unsigned int mw320_sec = 9000000;
1399 // unsigned int default_ch;
1400 // unsigned int default_1= 0;
1401 // unsigned int default_2= 0;
1402
1403 /* Initialize platform */
1404 // BOARD_ConfigMPU();
1405 BOARD_InitPins();
1406 BOARD_BootClockRUN();
1407
1408 BOARD_InitDebugConsole();
1409#ifdef MCUXPRESSO_WIFI_CLI
1410 PRINTF("\nPlease Select [1/2] => 1. MCUXpress format 2. Matter format. \r\n");
1411 do
1412 {
1413 ch = GETCHAR();
1414 PUTCHAR(ch);
1415 if (ch == '1')
1416 Matter_Selection = MCUXPRESSO_WIFI_CLI;
1417 else if (ch == '2')
1418 Matter_Selection = MATTER_SHELL;
1419 } while (ch != '\r');
1420 if (Matter_Selection == MAX_SELECTION)
1421 Matter_Selection = MATTER_SHELL;
1422 PRINTF("\n\n[%s]: MW320 %s .\r\n", __FUNCTION__,
1423 (Matter_Selection == MCUXPRESSO_WIFI_CLI) ? "MCUXPresso WiFi CLI" : "Matter Shell");
1424#else
1425#ifdef CONFIGURE_UAP
1426 PRINTF("\nDo you want to use the default SSID and key for mw320 uAP? [y/n]\r\n");
1427 do
1428 {
1429 ch = GETCHAR();
1430 PUTCHAR(ch);
1431 if (ch == 'n')
1432 {
1433 PRINTF("\nPlease input your SSID: [ 1 ~ 32 characters]\r\n");
1434 bp = 0;
1435 do
1436 {
1437 ssid[bp] = GETCHAR();
1438 PUTCHAR(ssid[bp]);
1439 bp++;
1440 if (bp > sizeof(ssid))
1441 {
1442 PRINTF("\n ERROR: your SSID length=%d is larger than %d \r\n", bp, sizeof(ssid));
1443 return 0;
1444 }
1445 } while (ssid[bp - 1] != '\r');
1446 ssid[bp - 1] = '\0';
1447 PRINTF("\nPlease input your KEY: [ 8 ~ 63 characters]\r\n");
1448 bp = 0;
1449 do
1450 {
1451 psk[bp] = GETCHAR();
1452 PUTCHAR(psk[bp]);
1453 bp++;
1454 if (bp > sizeof(psk))
1455 {
1456 PRINTF("\n ERROR: your KEY length=%d is larger than %d \r\n", bp, sizeof(psk));
1457 return 0;
1458 }
1459 } while (psk[bp - 1] != '\r');
1460 psk[bp - 1] = '\0';
1461 if ((bp - 1) < 8)
1462 {
1463 PRINTF("\n ERROR: KEY length=%d is less than 8 \r\n", (bp - 1));
1464 return 0;
1465 }
1466 break;
1467 }
1468 if (ch == '\r')
1469 {
1470 break;
1471 }
1472 } while (ch != 'y');
1473#endif
1474#endif
1475 // PRINTF("\nMW320 uAP SSID=%s key=%s ip=%s \r\n", ssid, psk, network_ip);
1476
1477 CLOCK_EnableXtal32K(kCLOCK_Osc32k_External);
1478 CLOCK_AttachClk(kXTAL32K_to_RTC);
1479
1480 aesLock = xSemaphoreCreateRecursiveMutex();
1481 assert(aesLock != NULL);
1482
1483 AES_Init(APP_AES);
1484 AES_SetLockFunc(APP_AES_Lock, APP_AES_Unlock);
1485 gpio_init();
1486
1487 StartShellTask();
1488
1489 /* Start FreeRTOS */
1490 vTaskStartScheduler();
1491
1492 return 0;
1493}
1494
1495bool lowPowerClusterSleep()
1496{
1497 return true;
1498}
1499
1500static void OnOnOffPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value)
1501{
1502 VerifyOrExit(attributeId == ZCL_ON_OFF_ATTRIBUTE_ID,
1503 ChipLogError(DeviceLayer, "Unhandled Attribute ID: '0x%04lx", attributeId));
1504 VerifyOrExit(endpointId == 1 || endpointId == 2, ChipLogError(DeviceLayer, "Unexpected EndPoint ID: `0x%02x'", endpointId));
1505
1506 // At this point we can assume that value points to a bool value.
1507 led_on_off(led_yellow, (*value != 0) ? true : false);
1508
1509exit:
1510 return;
1511}
1512
1513static void OnSwitchAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value)
1514{
1515 // auto * pimEngine = chip::app::InteractionModelEngine::GetInstance();
1516 // bool do_sendrpt = false;
1517
1518 VerifyOrExit(attributeId == ZCL_CURRENT_POSITION_ATTRIBUTE_ID,
1519 ChipLogError(DeviceLayer, "Unhandled Attribute ID: '0x%04lx", attributeId));
1520 // Send the switch status report now
1521/*
1522 for (uint32_t i = 0 ; i<pimEngine->GetNumActiveReadHandlers() ; i++) {
1523 ReadHandler * phandler = pimEngine->ActiveHandlerAt(i);
1524 if (phandler->IsType(chip::app::ReadHandler::InteractionType::Subscribe) &&
1525 (phandler->IsGeneratingReports() || phandler->IsAwaitingReportResponse())) {
1526 phandler->UnblockUrgentEventDelivery();
1527 do_sendrpt = true;
1528 break;
1529 }
1530 }
1531 if (do_sendrpt == true) {
Boris Zbarskyb46af332022-12-01 00:33:16 -05001532 ConcreteEventPath event_path(endpointId, Clusters::Switch::Id, 0);
nxptest2d0c5292022-06-24 19:04:49 +08001533 pimEngine->GetReportingEngine().ScheduleEventDelivery(event_path, chip::app::EventOptions::Type::kUrgent,
1534 sizeof(uint16_t));
1535 }
1536*/
1537exit:
1538 return;
1539}
1540
crlonxpa6ecd622022-09-30 01:51:50 +08001541uint32_t identifyTimerCount;
1542constexpr uint32_t kIdentifyTimerDelayMS = 250;
1543typedef struct _Identify_Timer
1544{
1545 EndpointId ep;
1546 uint32_t identifyTimerCount;
1547} Identify_Time_t;
1548Identify_Time_t id_time[MAX_ENDPOINT_COUNT];
1549
1550void IdentifyTimerHandler(System::Layer * systemLayer, void * appState)
1551{
1552 Identify_Time_t * pidt = (Identify_Time_t *) appState;
1553 PRINTF(" -> %s(%u, %u) \r\n", __FUNCTION__, pidt->ep, pidt->identifyTimerCount);
1554 if (pidt->identifyTimerCount)
1555 {
1556 pidt->identifyTimerCount--;
Boris Zbarskyb46af332022-12-01 00:33:16 -05001557 emAfWriteAttribute(pidt->ep, Clusters::Identify::Id, ZCL_IDENTIFY_TIME_ATTRIBUTE_ID, (uint8_t *) &pidt->identifyTimerCount,
crlonxpa6ecd622022-09-30 01:51:50 +08001558 sizeof(identifyTimerCount), true, false);
1559 DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds16(1), IdentifyTimerHandler, pidt);
1560 }
1561}
1562
1563static void OnIdentifyPostAttributeChangeCallback(EndpointId endpointId, AttributeId attributeId, uint8_t * value)
1564{
1565 VerifyOrExit(attributeId == ZCL_IDENTIFY_TIME_ATTRIBUTE_ID,
1566 ChipLogError(DeviceLayer, "[%s] Unhandled Attribute ID: '0x%04lx", TAG, attributeId));
1567 VerifyOrExit((endpointId < MAX_ENDPOINT_COUNT),
1568 ChipLogError(DeviceLayer, "[%s] EndPoint > max: [%u, %u]", TAG, endpointId, MAX_ENDPOINT_COUNT));
1569 if (id_time[endpointId].identifyTimerCount != *value)
1570 {
1571 id_time[endpointId].ep = endpointId;
1572 id_time[endpointId].identifyTimerCount = *value;
1573 PRINTF("-> Identify: %u \r\n", id_time[endpointId].identifyTimerCount);
1574 DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds16(1), IdentifyTimerHandler, &id_time[endpointId]);
1575 }
1576
1577exit:
1578 return;
1579}
1580
nxptest2d0c5292022-06-24 19:04:49 +08001581/*
1582 Callback to receive the cluster modification event
1583*/
nxptest8582b3b2022-07-01 11:04:38 +08001584void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & path, uint8_t type, uint16_t size, uint8_t * value)
nxptest2d0c5292022-06-24 19:04:49 +08001585{
1586 PRINTF("==> MatterPostAttributeChangeCallback, cluster: %x, attr: %x, size: %d \r\n", path.mClusterId, path.mAttributeId, size);
1587 // path.mEndpointId, path.mClusterId, path.mAttributeId, mask, type, size, value
1588 switch (path.mClusterId)
1589 {
Boris Zbarskyb46af332022-12-01 00:33:16 -05001590 case Clusters::OnOff::Id:
nxptest2d0c5292022-06-24 19:04:49 +08001591 OnOnOffPostAttributeChangeCallback(path.mEndpointId, path.mAttributeId, value);
1592 break;
Boris Zbarskyb46af332022-12-01 00:33:16 -05001593 case Clusters::Switch::Id:
nxptest2d0c5292022-06-24 19:04:49 +08001594 OnSwitchAttributeChangeCallback(path.mEndpointId, path.mAttributeId, value);
1595 // SwitchToggleOnOff();
1596 // Trigger to send on/off/toggle command to the bound devices
1597 chip::BindingManager::GetInstance().NotifyBoundClusterChanged(1, chip::app::Clusters::OnOff::Id, nullptr);
1598 break;
Boris Zbarskyb46af332022-12-01 00:33:16 -05001599 case Clusters::Identify::Id:
crlonxpa6ecd622022-09-30 01:51:50 +08001600 OnIdentifyPostAttributeChangeCallback(path.mEndpointId, path.mAttributeId, value);
1601 break;
nxptest2d0c5292022-06-24 19:04:49 +08001602 default:
1603 break;
1604 }
1605 return;
1606}
1607
1608EmberAfStatus emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId,
1609 const EmberAfAttributeMetadata * attributeMetadata, uint8_t * buffer)
1610{
1611 PRINTF("====> %s() \r\n", __FUNCTION__);
1612 return EMBER_ZCL_STATUS_SUCCESS;
1613}
1614
1615EmberAfStatus emberAfExternalAttributeReadCallback(EndpointId endpoint, ClusterId clusterId,
1616 const EmberAfAttributeMetadata * attributeMetadata, uint8_t * buffer,
1617 uint16_t maxReadLength)
1618{
1619 // Added for the pairing of TE9 to report the commission_info
Andrei Litvindb492352022-11-19 15:00:25 +01001620 // default function (in callback-stub.cpp)
nxptest2d0c5292022-06-24 19:04:49 +08001621 //
1622 PRINTF("-> %s()\n\r", __FUNCTION__);
1623 return EMBER_ZCL_STATUS_SUCCESS;
1624}