Filter results by

ARTIK 05X to ARTIK Cloud via MQTT

Having connected your ARTIK 05X module to an MQTT broker, you're just a step away from making that broker ARTIK Cloud. Doing so, you'll be accomplishing much the same thing as you did in Connect to the World, but this time you'll do it over a frugal MQTT link and you will have complete control of all you send and receive.

Prerequisites

Before you begin:

  • Complete the previous ARTIK 05X MQTT subscriber and publisher articles.

  • Determine the GPIO pins you plan to use. Look at the mappings page, as well as the noted Tizen RT source code files. The XGPIO pins are referenced as gpio30-32, 37-55, and 57-59. Our code uses only gpio37-55.

Creating Device on ARTIK Cloud

Samsung ARTIK Cloud makes it easy to interact with your IoT devices. Once you have acquired data, it's a simple matter to send it off to ARTIK Cloud for viewing and archiving. ARTIK Cloud can also analyze the data and send back appropriate actions according to the rules you decide.

Open your ARTIK Cloud home page

Open and log into the My ARTIK Cloud page in your browser to get ready to use ARTIK Cloud. If you haven't signed up for a free account, you will be given the chance to do so.

Site Looks Like This Used for
My ARTIK Cloud Connecting a device; obtaining access tokens; viewing data sent by the device

This first page is what the User sees. However, as a Developer creating a device, you will also use the separate Developer Dashboard page, which we talk about below.

Create a new device and upload Manifest

We will stream GPIO and ADC data from your ARTIK 053 board to ARTIK Cloud. In order to do this, we need to create a matching device in ARTIK Cloud that knows what kind of data tags to expect.

ARTIK Cloud refers to the file containing the data template information as the Manifest. It's just a .JSON-format file. Setting it up here is easy, since we've already built it for you!

Step Looks Like This
1. Go to the ARTIK Cloud Developer Dashboard and log in.
2. Click + New Device Type  
3. Name your device. The Unique Name
requires camel case: start each portion with a lower-case letter.
For ours we chose
DEVICE DISPLAY NAME: "A053 all-in-one"
UNIQUE NAME: "mqtt-A053"
4. Click CREATE DEVICE TYPE.



5. Click ADD DEVICE TYPE INFO.
6. Download the pre-built manifest.

             .json manifest



7. Click UPLOAD A MANIFEST.
and browse to your downloaded
manifest.
8. Click ACTIVATE MANIFEST at the
bottom of the manifest as shown below.
 

You've created an ARTIK device using the manifest code we supplied. You can see now why we called it "all-in-one" – there's probably a lot more GPIO control than you'll need! You can strip it down later to just cover the I/O functions of interest to you.

Take a moment to appreciate how easy it was to set up a new project to store its data on ARTIK Cloud. That's all there was to it!

Connect the device

As a Developer, you just created a device. Now it's time for you to act as a User so that you can select and use that device. Go back to your My ARTIK Cloud page.

You can now click CONNECT A DEVICE and choose your new device to get started. Be careful to not select some other device with a similar name, or a public device.

Under Give Your Device a Name you can pick something like "MyA053AIO". Your device general name is still "A053 all-in-one" but this instance of it is now MyA053AIO.

Get the Device Token

Every call you make to ARTIK Cloud requires an access token. The Device Token is one of three types of access tokens, and is the one we'll use in this tutorial.

Still on your My ARTIK Cloud page, click on your newly connected device.

It's easy for any valid user to obtain the Device ID and Device Token needed to exchange information with ARTIK Cloud. In this case, the device of interest will be our newly created “My Temp Sensor”, but you'll follow this procedure any time you need to insert Device information into your code.

  1. Go to My ARTIK Cloud and log in (if you have not already).

  2. Click on the device of interest.

  3. When you see the Device Info pop-up, click GENERATE DEVICE TOKEN… to get a Device Token. You'll only see that link the first time; after that, the token will already be visible as shown below.

  4. Leave the Device Info page open.

Setting Up Subscriber/Publisher Edge Device

You will use an ARTIK 05X module as your edge device and create a project in the ARTIK IDE as you did here.

  1. Start with complete MQTT subscriber and publisher code. Copy it in place of the "Hello World" main.c code like you did previously.

    main.c code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    /****************************************************************************
     *
     * Copyright 2016 Samsung Electronics All Rights Reserved.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing,
     * software distributed under the License is distributed on an
     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
     * either express or implied. See the License for the specific
     * language governing permissions and limitations under the License.
     */
    
    #include <tinyara/config.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <ctype.h>
    #include "wifi.h"
    #include "keys.h"
    #include <tinyara/gpio.h>
    #include <tinyara/pwm.h>
    #include <tinyara/analog/adc.h>
    #include <tinyara/analog/ioctl.h>
    #include <apps/netutils/dhcpc.h>
    #include <apps/netutils/mqtt_api.h>
    #include <apps/netutils/ntpclient.h>
    
    
    // NTP
    #define NTP_REFRESH_PERIOD  (60 * 60) /* seconds */
    #define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
    
    #define RED_ON_BOARD_LED 45
    #define ADC_MAX_SAMPLES 4
    #define NET_DEVNAME "wl1"
    #define DEFAULT_CLIENT_ID "123456789"
    #define SERVER_ADDR "api.artik.cloud"//"52.200.124.224"
    #define DEVICE_ID "_your_DEVICE_ID_goes_here_" //FIX
    #define DEVICE_TOKEN "_your_DEVICE_TOKEN_goes_here_" // FIX
    #define ACTION_TOPIC "/v1.1/actions/_your_DEVICE_ID_goes_here_" // FIX
    #define MESSAGE_TOPIC "/v1.1/messages/_your_DEVICE_ID_goes_here_" //FIX
    
    // NTP
    static struct ntpc_server_conn_s ntp_server_conn[] = {{ NULL, 123 },};
    
    static void ntp_link_error(void)
    {
      printf("NTP error: stopping client\n");
      ntpc_stop();
    }
    
    // mqtt tls config handle
    static mqtt_tls_param_t g_tls;
    
    // mqtt client handle
    mqtt_client_t* pClientHandle = NULL;
    
    // mqtt client parameters
    mqtt_client_config_t clientConfig;
    
    // Read the value of the given gpio port
    int gpio_read(int port)
    {
      char buf[4];
      char devpath[16];
      snprintf(devpath, 16, "/dev/gpio%d", port);
      int fd = open(devpath, O_RDWR);
      if (fd < 0)
      {
        printf("fd open fail\n");
        return -1;
      }
    
      if (read(fd, buf, sizeof(buf)) < 0)
      {
        printf("read error\n");
        return -1;
      }
      close(fd);
    
      return buf[0] == '1';
    }
    
    // Write (toggle) the value of given gpio port.
    void gpio_write(int port)
    {
      int value = 0;
      char str[4];
      static char devpath[16];
      int curValue = gpio_read(port);
      printf("Current value of the gpio port%d is %d\n",port,curValue);
      if (curValue <= 0)
        value = 1;
      else if (curValue == 1)
        value = 0;
    
      snprintf(devpath, 16, "/dev/gpio%d", port);
      int fd = open(devpath, O_RDWR);
    
      ioctl(fd, GPIOIOC_SET_DIRECTION, GPIO_DIRECTION_OUT);
    
      write(fd, str, snprintf(str, 4, "%d", value != 0) + 1);
    
      close(fd);
    }
    
    // mqtt client on connect callback
    void onConnect(void* client, int result)
    {
      printf("mqtt client connected to the server\n");
    }
    
    // mqtt client on disconnect callback
    void onDisconnect(void* client, int result)
    {
      printf("mqtt client disconnected from the server\n");
    }
    
    // mqtt client on message callback
    void onMessage(void* client, mqtt_msg_t *msg)
    {
      printf("mqtt client on message received\n");
      mqtt_client_t *mqtt_client = (mqtt_client_t *)client;
    
      if (mqtt_client == NULL || mqtt_client->config == NULL)
      {
        printf("message callback: is NULL.\n");
        return;
      }
    
      if (msg->payload_len)
      {
        printf("Topic - %s , payload -  %s\n", msg->topic, msg->payload);
      } else
      {
        printf(">>> message callback: payload_len is 0\n");
      }
      char buf[msg->payload_len];
      strcpy(buf,msg->payload);
    
      // Check if the action is related to GPIO
      if (strstr(buf,"Gpio") != NULL)
      {
        // Extract the gpio port number
        int ref = 0;
        char tempBuf[3];
        char* p = strstr(buf,"Gpio");
        while (*p)
        {
          if (isdigit(*p))
            tempBuf[ref++] = *p;
          p++;
        }
        tempBuf[ref] = '\0';
        int port = atoi(tempBuf);
        printf("port is %d\n",port);
        gpio_write(port);
      }
      else if(strstr(buf,"pwm") != NULL)// Action is related to PWM
      {
        //Extract pwm port
        int ref = 0;
        char tempBuf[2];
        char* p = strstr(buf,"pwm");
        while(*p)
        {
          if (isdigit(*p))
          {
            tempBuf[ref++] = *p;
            break;
          }
          p++;
        }
        tempBuf[ref] ='\0';
        int port = atoi(tempBuf);
        printf("PWM port %d\n",port);
    
        // Extract frequency and duty
    
        // Extract Frequency
        p = strstr(buf,"Freq");
        bool fFlag = false;
        ref = 0;
        char freqBuf[10];
        while(*p)
        {
          if (isdigit(*p))
          {
            fFlag = true;
            freqBuf[ref++] = *p;
          }
          else if (fFlag)
          {
            break;
          }
          p++;
        }
        freqBuf[ref] = '\0';
        int freqValue = atoi(freqBuf);
        printf("Frequency values is %d\n",freqValue);
    
    
        // Extract Duty
    
        p = strstr(buf,"Duty");
        ref = 0;
        char dutyBuf[10];
        while(*p)
        {
          if (isdigit(*p))
            dutyBuf[ref++] = *p;
          p++;
        }
        dutyBuf[ref] = '\0';
        int dutyValue = atoi(dutyBuf);
        printf("Duty value is %d\n",dutyValue);
    
        // Set the values to the corresponding pwm port
        struct pwm_info_s pwm_info;
        pwm_info.frequency = freqValue;
        char devpath[16];
        snprintf(devpath, 16, "/dev/pwm%d", port);
        int fd = open(devpath, O_RDWR);
        if (fd < 0) {
          printf("fd open fail\n");
          return;
        }
    
        pwm_info.duty = dutyValue * 65536 / 100;
        ioctl(fd, PWMIOC_SETCHARACTERISTICS, (unsigned long)((uintptr_t)&pwm_info));
        ioctl(fd, PWMIOC_START);
      }
    }
    
    // Utility function to configure mqtt client
    void initializeConfigUtil(void)
    {
      uint8_t macId[IFHWADDRLEN];
      int result = netlib_getmacaddr("wl1", macId);
      if (result < 0)
      {
        printf("Get MAC Address failed. Assigning \
            Client ID as 123456789");
        clientConfig.client_id =
            DEFAULT_CLIENT_ID; // MAC id Artik 053
      }
      else
      {
        printf("MAC: %02x:%02x:%02x:%02x:%02x:%02x\n",
            ((uint8_t *) macId)[0],
            ((uint8_t *) macId)[1], ((uint8_t *) macId)[2],
            ((uint8_t *) macId)[3], ((uint8_t *) macId)[4],
            ((uint8_t *) macId)[5]);
        char buf[12];
        sprintf(buf, "%02x%02x%02x%02x%02x%02x",
            ((uint8_t *) macId)[0],
            ((uint8_t *) macId)[1], ((uint8_t *) macId)[2],
            ((uint8_t *) macId)[3], ((uint8_t *) macId)[4],
            ((uint8_t *) macId)[5]);
        clientConfig.client_id = buf; // MAC id Artik 053
        clientConfig.user_name = DEVICE_ID;
        clientConfig.password = DEVICE_TOKEN;
        clientConfig.clean_session = true; // check
    
        clientConfig.protocol_version = MQTT_PROTOCOL_VERSION_31;
        g_tls.ca_cert = mqtt_get_ca_certificate();  //the pointer of ca_cert buffer
        g_tls.ca_cert_len = mqtt_get_ca_certificate_size(); // the length of ca_cert buffer
    
    
        g_tls.cert = NULL;
        g_tls.cert_len = 0;
    
    
        g_tls.key = NULL;
        g_tls.key_len = 0;
    
        printf("Registering mqtt client with id = %s\n", buf);
      }
      clientConfig.on_connect = (void*) onConnect;
      clientConfig.on_disconnect = (void*) onDisconnect;
      clientConfig.on_message = (void*) onMessage;
      clientConfig.tls = &g_tls;
      //printf("Size of CA is %d\n",g_tls.ca_cert_len);
    }
    
    int main(int argc, char *argv[])
    {
      bool wifiConnected = false;
      gpio_write(RED_ON_BOARD_LED); // Turn on on board Red LED to indicate no WiFi connection is established
    
      #ifdef CONFIG_CTRL_IFACE_FIFO
      int ret;
    
      while(!wifiConnected)
      {
        ret = mkfifo(CONFIG_WPA_CTRL_FIFO_DEV_REQ,
            CONFIG_WPA_CTRL_FIFO_MK_MODE);
        if (ret != 0 && ret != -EEXIST)
        {
          printf("mkfifo error for %s: %s",
              CONFIG_WPA_CTRL_FIFO_DEV_REQ,
              strerror(errno));
        }
        ret = mkfifo(CONFIG_WPA_CTRL_FIFO_DEV_CFM,
            CONFIG_WPA_CTRL_FIFO_MK_MODE);
        if (ret != 0 && ret != -EEXIST)
        {
          printf("mkfifo error for %s: %s",
              CONFIG_WPA_CTRL_FIFO_DEV_CFM,
              strerror(errno));
        }
    
        ret = mkfifo(CONFIG_WPA_MONITOR_FIFO_DEV,
            CONFIG_WPA_CTRL_FIFO_MK_MODE);
        if (ret != 0 && ret != -EEXIST)
        {
          printf("mkfifo error for %s: %s",
              CONFIG_WPA_MONITOR_FIFO_DEV,
              strerror(errno));
        }
      #endif
    
        if (start_wifi_interface() == SLSI_STATUS_ERROR)
        {
          printf("Connect Wi-Fi failed. Try Again.\n");
        }
        else
        {
          wifiConnected = true;
          gpio_write(RED_ON_BOARD_LED); // Turn off Red LED to indicate WiFi connection is established
        }
      }
    
      printf("Connect to Wi-Fi success\n");
    
      bool mqttConnected = false;
      bool ipObtained = false;
      printf("Get IP address\n");
    
      struct dhcpc_state state;
      void *dhcp_handle;
    
      while(!ipObtained)
      {
        dhcp_handle = dhcpc_open(NET_DEVNAME);
        ret = dhcpc_request(dhcp_handle, &state);
        dhcpc_close(dhcp_handle);
    
        if (ret != OK)
        {
          printf("Failed to get IP address\n");
          printf("Try again\n");
          sleep(1);
        }
        else
        {
          ipObtained = true;
        }
      }
      netlib_set_ipv4addr(NET_DEVNAME, &state.ipaddr);
      netlib_set_ipv4netmask(NET_DEVNAME, &state.netmask);
      netlib_set_dripv4addr(NET_DEVNAME, &state.default_router);
    
      printf("IP address  %s\n", inet_ntoa(state.ipaddr));
    
      // NTP
      sleep(1);
      ntp_server_conn[0].hostname = "0.pool.ntp.org";
      if (ntpc_start(ntp_server_conn, ARRAY_SIZE(ntp_server_conn), NTP_REFRESH_PERIOD, ntp_link_error) < 0)
      {
        printf("Failed to start NTP client.\n"
            "The date may be incorrect and lead to undefined behavior\n");
      }
      else
      {
        int num_retries = 10;
    
        /* Wait for the date to be set */
        while ((ntpc_get_link_status() != NTP_LINK_UP) && --num_retries)
        {
          sleep(2);
        }
    
        if (!num_retries)
        {
          printf("Failed to reach NTP server.\n"
              "The date may be incorrect and lead to undefined behavior\n");
        }
      }
    
    
      initializeConfigUtil();
    
      pClientHandle = mqtt_init_client(&clientConfig);
      if (pClientHandle == NULL)
      {
        printf("mqtt client handle initialization fail\n");
        return 0;
      }
    
      while (mqttConnected == false )
      {
        sleep(2);
        // Connect mqtt client to server
        int result = mqtt_connect(pClientHandle,
            SERVER_ADDR, 8883, 60);
        if (result < 0)
        {
          printf("mqtt client connect to server fail - %d\n ",result);
          continue;
        }
        mqttConnected = true;
      }
    
      bool mqttSubscribe = false;
    
      // Subscribe to topic of interest
      while (mqttSubscribe == false )
      {
        sleep(2);
        int result = mqtt_subscribe(pClientHandle,
            ACTION_TOPIC, 0);
        if (result < 0)
        {
          printf("mqtt client subscribe to topic \
              failed\n");
          continue;
        }
        mqttSubscribe = true;
        printf("mqtt client Subscribed to the topic \
            successfully\n");
    
        sleep(2);
        bool tempFlag = false;
    
        while (1)
        {
          sleep(10); // Publish message to ARTIK cloud every 10s
          // Publish ADC port readings
          char str[600];
          bool adcFlag = false;
          strcpy(str,"{\"ADC\":{");
          int fd;
          struct adc_msg_s samples[ADC_MAX_SAMPLES];
          ssize_t nbytes;
    
          fd = open("/dev/adc0", O_RDONLY);
          if (fd < 0)
          {
            printf("fd open failed: %d\n", errno);
          }
    
          ret = ioctl(fd, ANIOC_TRIGGER, 0);
          if (ret < 0)
          {
            printf("ioctl failed: %d\n",errno);
            close(fd);
          }
    
          sleep(1); //wait after trigger before reading samples
    
          nbytes = read(fd, samples, sizeof(samples));
          if (nbytes < 0)
          {
            if (errno != EINTR)
            {
              printf("fd read failed: %d\n", errno);
              close(fd);
            }
          }
          else if (nbytes == 0)
          {
            printf("No data read, Ignoring\n");
          }
          else
          {
            int nsamples = nbytes / sizeof(struct adc_msg_s);
            if (nsamples * sizeof(struct adc_msg_s) != nbytes)
            {
              printf("read size=%ld is not a multiple of sample size=%d, Ignoring\n",(long)nbytes, sizeof(struct adc_msg_s));
            }
            else
            {
              printf("ADC Sample:\n");
              int i;
              for (i = 0; i < nsamples; i++)
              {
                printf("%d: channel: %d, value: %d\n", i + 1, samples[i].am_channel, samples[i].am_data);
                if (adcFlag)
                  strcat(str,",");
                char tempBuf[20];
                sprintf(tempBuf,"\"Channel%d\":%d",samples[i].am_channel, samples[i].am_data);
                strcat(str,tempBuf);
                adcFlag = true;
              }
            }
          close(fd);
          }
          strcat(str,"},");
    
          // Publish GPIO port readings
    
          strcat(str,"\"GPIO\":{");
          int j;
          for ( j = 37; j <= 55; j++)
          {
            strcat(str,"\"gpio");
            char buf[10];
            sprintf(buf,"%d\":%d",j,gpio_read(j));
            strcat(str,buf);
            if (j != 55)
            strcat(str,",");
          }
          strcat(str,"}}");
          if (mqtt_publish(pClientHandle, MESSAGE_TOPIC, str, sizeof(str), 0, 0) != 0)
          {
            printf("Error: mqtt_publish() failed.\n");
          }
          else
          {
            printf("Published %s\n",str);
          }
        }
      }
      return 0;
    }
    
  2. You'll also need to create the wifi.h header file like you did before, as well as a new header file that you'll call keys.h for the ARTIK Cloud security keys.

          

    wifi.c code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    #include <net/if.h>
    #include <apps/netutils/wifi/slsi_wifi_api.h>
    
    // WIFi
    #define STATE_DISCONNECTED      0
    #define STATE_CONNECTED       1
    
    #define SLSI_WIFI_SECURITY_OPEN   "open"
    #define SLSI_WIFI_SECURITY_WPA2_AES "wpa2_aes"
    
    #define SSID "hotspot" //FIX
    #define PSK  "12345672" //FIX
    
    slsi_security_config_t *getSecurityConfig(char *sec_type,
        char *psk, WiFi_InterFace_ID_t mode);
    
    static int g_connection_state = STATE_DISCONNECTED;
    static uint8_t g_join_result  = 0;
    
    static sem_t g_sem_join;
    
    /**
     * Handler for network link up connection event
     *
     *   Sets the global connection state variable and the
     *   result of the network join request.
     */
    void networkLinkUpHandler(slsi_reason_t* reason) {
      g_connection_state = STATE_CONNECTED;
    
      g_join_result = reason->reason_code;
      sem_post(&g_sem_join);
    }
    
    /**
     * Handler for network link down connection event
     *
     *   Sets the global connection variable when the access
     *   point is disconnected from the network.
     */
    void networkLinkDownHandler(slsi_reason_t* reason) {
      g_connection_state = STATE_DISCONNECTED;
    
      if (reason) {
        printf("Disconnected from network %s "
             "reason_code: %d %s\n", reason->bssid,
            reason->reason_code,
            reason->locally_generated ?
                "(locally_generated)": "");
      } else {
        printf("Disconnected from network\n");
      }
    }
    
    /**
     * Starts the Wi-Fi interface and request connection to the
     * specified network
     *
     *   Return: Completed successfully or failed
     *
     *   Starts the Wi-Fi interface in Station mode and requests
     *   to join the specified network.
     */
    int8_t start_wifi_interface(void) {
    
      if ( WiFiRegisterLinkCallback(&networkLinkUpHandler,
          &networkLinkDownHandler) ) {
        return SLSI_STATUS_ERROR;
      }
    
      if ( WiFiStart(SLSI_WIFI_STATION_IF, NULL) ==
          SLSI_STATUS_ERROR ) {
        return SLSI_STATUS_ERROR;
      }
    
      sem_init(&g_sem_join, 0, 0);
    
      slsi_security_config_t *security_config =
          getSecurityConfig(SLSI_WIFI_SECURITY_WPA2_AES,
            PSK, SLSI_WIFI_STATION_IF);
    
      if ( WiFiNetworkJoin((uint8_t*)SSID, strlen(SSID),
          NULL, security_config) == SLSI_STATUS_ERROR ) {
        return SLSI_STATUS_ERROR;
      }
    
      sem_wait(&g_sem_join);
    
      if( g_join_result ) {
         return SLSI_STATUS_ERROR;
      }
    
      free(security_config);
      sem_destroy(&g_sem_join);
    
      return SLSI_STATUS_SUCCESS;
    }

    keys.h code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    static const char mqtt_ca_crt_rsa[] =
            "-----BEGIN CERTIFICATE-----\r\n"
            "MIIGazCCBVOgAwIBAgIQUQ7MqdQi65jhxr9oCRZ2jDANBgkqhkiG9w0BAQsFADB+\r\n"
            "MQswCQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAd\r\n"
            "BgNVBAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxLzAtBgNVBAMTJlN5bWFudGVj\r\n"
            "IENsYXNzIDMgU2VjdXJlIFNlcnZlciBDQSAtIEc0MB4XDTE2MDMxNjAwMDAwMFoX\r\n"
            "DTE4MDMxNTIzNTk1OVowczELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3Ju\r\n"
            "aWExETAPBgNVBAcMCFNhbiBKb3NlMSQwIgYDVQQKDBtTYW1zdW5nIFNlbWljb25k\r\n"
            "dWN0b3IsIEluYy4xFjAUBgNVBAMMDSouYXJ0aWsuY2xvdWQwggEiMA0GCSqGSIb3\r\n"
            "DQEBAQUAA4IBDwAwggEKAoIBAQDYITWk11g32FfyVoAZ1+IZoXApT0jtKJ8eQdrq\r\n"
            "5WM6b03NzAWkPtPGAaQCr06mbz6qyVCDOOUPdTN9NSOXtpM9AzKts0GThgdAfN1f\r\n"
            "zjuL8BE6uDwowD4TIpxeHTeh3iQrqqNQi4fHr4X5BYib6RH0Fk8XY8zydGXY/9lP\r\n"
            "BPB7e81eaVog7bno7SAxweR+nwseMXkMvxPuZeFekdwZ0SqWbCbZYU4dERalocOQ\r\n"
            "yf1lqRj//9VU2Uh8lvUgAbD3foz9WIA62kQ+G+JWQVOnPJwuak93YXYmKBusVIE2\r\n"
            "95H4FIYZThaXt7AbUd9jkvEbhaxXkAxmmt6+qX0stOiqYf3hAgMBAAGjggLuMIIC\r\n"
            "6jAlBgNVHREEHjAcgg0qLmFydGlrLmNsb3VkggthcnRpay5jbG91ZDAJBgNVHRME\r\n"
            "AjAAMA4GA1UdDwEB/wQEAwIFoDArBgNVHR8EJDAiMCCgHqAchhpodHRwOi8vc3Mu\r\n"
            "c3ltY2IuY29tL3NzLmNybDBhBgNVHSAEWjBYMFYGBmeBDAECAjBMMCMGCCsGAQUF\r\n"
            "BwIBFhdodHRwczovL2Quc3ltY2IuY29tL2NwczAlBggrBgEFBQcCAjAZDBdodHRw\r\n"
            "czovL2Quc3ltY2IuY29tL3JwYTAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUH\r\n"
            "AwIwHwYDVR0jBBgwFoAUX2DPYZBV34RDFIpgKrL1evRDGO8wVwYIKwYBBQUHAQEE\r\n"
            "SzBJMB8GCCsGAQUFBzABhhNodHRwOi8vc3Muc3ltY2QuY29tMCYGCCsGAQUFBzAC\r\n"
            "hhpodHRwOi8vc3Muc3ltY2IuY29tL3NzLmNydDCCAXsGCisGAQQB1nkCBAIEggFr\r\n"
            "BIIBZwFlAHUA3esdK3oNT6Ygi4GtgWhwfi6OnQHVXIiNPRHEzbbsvswAAAFTfSa4\r\n"
            "SAAABAMARjBEAiBWbuO1LGslxrERGTsZRmf0RCP5hzFWJi2q+9UsCZtOPgIgC/fN\r\n"
            "rL3gLCD5WQw+/wRAIp2QsziMd83xyJ/jRiWSoaAAdQCkuQmQtBhYFIe7E6LMZ3AK\r\n"
            "PDWYBPkb37jjd80OyA3cEAAAAVN9JrhoAAAEAwBGMEQCICcUbZYNecAWGf9XCWmO\r\n"
            "FziyFts+Z2V6FfJ+/bgJntslAiA67Az9obN6maIfa11IirC5ZpSII+X8aYXXrkdh\r\n"
            "v2r3DQB1AGj2mPgfZIK+OozuuSgdTPxxUV1nk9RE0QpnrLtPT/vEAAABU30muGgA\r\n"
            "AAQDAEYwRAIgbEwTAAl72dv0e+GLxC1jv34DIk/K+0iFSLywt1D/GSQCIEt39UVk\r\n"
            "TSoz4FkyS61yGRE9qmSkPMpUKre3WTa+ZcORMA0GCSqGSIb3DQEBCwUAA4IBAQBA\r\n"
            "icvCtJDGWtpLonENFIZwl7JnDACA2jxdIKZYoGHgyDwxwln9Lg78bcRvOp0vZ168\r\n"
            "kwvvu0DXzZmtnYLU92bxQfcfQpJOpii88AMX2iyk7uFx4YI9HYbUXZph9uwt77b4\r\n"
            "PyyJONz1V+wR0YNQ5Ukcg1S4nZy1XgrI5tq2LVd0pPgAbA0O6/3RRjPcF1vkIKuy\r\n"
            "ppmVqcaoiNij18ALeNEKkblBzGq0zr8csdvzKQ/FZXEhT3gJY/Gv5H6pA+8ZEsMQ\r\n"
            "+0BGiYKkbI2IHY47dWXH394iSsWAZq73AIwo+Xi76FI1cG3NPECHD92w1iTBS8ej\r\n"
            "uW7KrUwGg+cPXREDasEb\r\n"
            "-----END CERTIFICATE-----\r\n"
            "-----BEGIN CERTIFICATE-----\r\n"
            "MIIFODCCBCCgAwIBAgIQUT+5dDhwtzRAQY0wkwaZ/zANBgkqhkiG9w0BAQsFADCB\r\n"
            "yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL\r\n"
            "ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp\r\n"
            "U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW\r\n"
            "ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0\r\n"
            "aG9yaXR5IC0gRzUwHhcNMTMxMDMxMDAwMDAwWhcNMjMxMDMwMjM1OTU5WjB+MQsw\r\n"
            "CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV\r\n"
            "BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxLzAtBgNVBAMTJlN5bWFudGVjIENs\r\n"
            "YXNzIDMgU2VjdXJlIFNlcnZlciBDQSAtIEc0MIIBIjANBgkqhkiG9w0BAQEFAAOC\r\n"
            "AQ8AMIIBCgKCAQEAstgFyhx0LbUXVjnFSlIJluhL2AzxaJ+aQihiw6UwU35VEYJb\r\n"
            "A3oNL+F5BMm0lncZgQGUWfm893qZJ4Itt4PdWid/sgN6nFMl6UgfRk/InSn4vnlW\r\n"
            "9vf92Tpo2otLgjNBEsPIPMzWlnqEIRoiBAMnF4scaGGTDw5RgDMdtLXO637QYqzu\r\n"
            "s3sBdO9pNevK1T2p7peYyo2qRA4lmUoVlqTObQJUHypqJuIGOmNIrLRM0XWTUP8T\r\n"
            "L9ba4cYY9Z/JJV3zADreJk20KQnNDz0jbxZKgRb78oMQw7jW2FUyPfG9D72MUpVK\r\n"
            "Fpd6UiFjdS8W+cRmvvW1Cdj/JwDNRHxvSz+w9wIDAQABo4IBYzCCAV8wEgYDVR0T\r\n"
            "AQH/BAgwBgEB/wIBADAwBgNVHR8EKTAnMCWgI6Ahhh9odHRwOi8vczEuc3ltY2Iu\r\n"
            "Y29tL3BjYTMtZzUuY3JsMA4GA1UdDwEB/wQEAwIBBjAvBggrBgEFBQcBAQQjMCEw\r\n"
            "HwYIKwYBBQUHMAGGE2h0dHA6Ly9zMi5zeW1jYi5jb20wawYDVR0gBGQwYjBgBgpg\r\n"
            "hkgBhvhFAQc2MFIwJgYIKwYBBQUHAgEWGmh0dHA6Ly93d3cuc3ltYXV0aC5jb20v\r\n"
            "Y3BzMCgGCCsGAQUFBwICMBwaGmh0dHA6Ly93d3cuc3ltYXV0aC5jb20vcnBhMCkG\r\n"
            "A1UdEQQiMCCkHjAcMRowGAYDVQQDExFTeW1hbnRlY1BLSS0xLTUzNDAdBgNVHQ4E\r\n"
            "FgQUX2DPYZBV34RDFIpgKrL1evRDGO8wHwYDVR0jBBgwFoAUf9Nlp8Ld7LvwMAnz\r\n"
            "Qzn6Aq8zMTMwDQYJKoZIhvcNAQELBQADggEBAF6UVkndji1l9cE2UbYD49qecxny\r\n"
            "H1mrWH5sJgUs+oHXXCMXIiw3k/eG7IXmsKP9H+IyqEVv4dn7ua/ScKAyQmW/hP4W\r\n"
            "Ko8/xabWo5N9Q+l0IZE1KPRj6S7t9/Vcf0uatSDpCr3gRRAMFJSaXaXjS5HoJJtG\r\n"
            "QGX0InLNmfiIEfXzf+YzguaoxX7+0AjiJVgIcWjmzaLmFN5OUiQt/eV5E1PnXi8t\r\n"
            "TRttQBVSK/eHiXgSgW7ZTaoteNTCLD0IX4eRnh8OsN4wUmSGiaqdZpwOdgyA8nTY\r\n"
            "Kvi4Os7X1g8RvmurFPW9QaAiY4nxug9vKWNmLT+sjHLF+8fk1A/yO0+MKcc=\r\n"
            "-----END CERTIFICATE-----\r\n"
            "-----BEGIN CERTIFICATE-----\r\n"
            "MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\r\n"
            "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\r\n"
            "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\r\n"
            "QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\r\n"
            "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\r\n"
            "b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\r\n"
            "9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\r\n"
            "CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\r\n"
            "nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\r\n"
            "43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\r\n"
            "T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\r\n"
            "gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\r\n"
            "BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\r\n"
            "TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\r\n"
            "DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\r\n"
            "hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\r\n"
            "06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\r\n"
            "PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\r\n"
            "YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\r\n"
            "CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\r\n"
            "-----END CERTIFICATE-----\r\n";
    
    
    static const char mqtt_cli_crt_rsa[] =
        "-----BEGIN CERTIFICATE-----\r\n"
        "MIIDNzCCAh+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n"
        "MA8GA1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n"
        "MTEwMjEyMTQ0NDA2WhcNMjEwMjEyMTQ0NDA2WjA0MQswCQYDVQQGEwJOTDERMA8G\r\n"
        "A1UEChMIUG9sYXJTU0wxEjAQBgNVBAMTCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\r\n"
        "AQEBBQADggEPADCCAQoCggEBAMFNo93nzR3RBNdJcriZrA545Do8Ss86ExbQWuTN\r\n"
        "owCIp+4ea5anUrSQ7y1yej4kmvy2NKwk9XfgJmSMnLAofaHa6ozmyRyWvP7BBFKz\r\n"
        "NtSj+uGxdtiQwWG0ZlI2oiZTqqt0Xgd9GYLbKtgfoNkNHC1JZvdbJXNG6AuKT2kM\r\n"
        "tQCQ4dqCEGZ9rlQri2V5kaHiYcPNQEkI7mgM8YuG0ka/0LiqEQMef1aoGh5EGA8P\r\n"
        "hYvai0Re4hjGYi/HZo36Xdh98yeJKQHFkA4/J/EwyEoO79bex8cna8cFPXrEAjya\r\n"
        "HT4P6DSYW8tzS1KW2BGiLICIaTla0w+w3lkvEcf36hIBMJcCAwEAAaNNMEswCQYD\r\n"
        "VR0TBAIwADAdBgNVHQ4EFgQUpQXoZLjc32APUBJNYKhkr02LQ5MwHwYDVR0jBBgw\r\n"
        "FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQEFBQADggEBAJxnXClY\r\n"
        "oHkbp70cqBrsGXLybA74czbO5RdLEgFs7rHVS9r+c293luS/KdliLScZqAzYVylw\r\n"
        "UfRWvKMoWhHYKp3dEIS4xTXk6/5zXxhv9Rw8SGc8qn6vITHk1S1mPevtekgasY5Y\r\n"
        "iWQuM3h4YVlRH3HHEMAD1TnAexfXHHDFQGe+Bd1iAbz1/sH9H8l4StwX6egvTK3M\r\n"
        "wXRwkKkvjKaEDA9ATbZx0mI8LGsxSuCqe9r9dyjmttd47J1p1Rulz3CLzaRcVIuS\r\n"
        "RRQfaD8neM9c1S/iJ/amTVqJxA1KOdOS5780WhPfSArA+g4qAmSjelc3p4wWpha8\r\n"
        "zhuYwjVuX6JHG0c=\r\n" "-----END CERTIFICATE-----\r\n";
    
    static const char mqtt_cli_key_rsa[] =
        "-----BEGIN RSA PRIVATE KEY-----\r\n"
        "MIIEpAIBAAKCAQEAwU2j3efNHdEE10lyuJmsDnjkOjxKzzoTFtBa5M2jAIin7h5r\r\n"
        "lqdStJDvLXJ6PiSa/LY0rCT1d+AmZIycsCh9odrqjObJHJa8/sEEUrM21KP64bF2\r\n"
        "2JDBYbRmUjaiJlOqq3ReB30Zgtsq2B+g2Q0cLUlm91slc0boC4pPaQy1AJDh2oIQ\r\n"
        "Zn2uVCuLZXmRoeJhw81ASQjuaAzxi4bSRr/QuKoRAx5/VqgaHkQYDw+Fi9qLRF7i\r\n"
        "GMZiL8dmjfpd2H3zJ4kpAcWQDj8n8TDISg7v1t7HxydrxwU9esQCPJodPg/oNJhb\r\n"
        "y3NLUpbYEaIsgIhpOVrTD7DeWS8Rx/fqEgEwlwIDAQABAoIBAQCXR0S8EIHFGORZ\r\n"
        "++AtOg6eENxD+xVs0f1IeGz57Tjo3QnXX7VBZNdj+p1ECvhCE/G7XnkgU5hLZX+G\r\n"
        "Z0jkz/tqJOI0vRSdLBbipHnWouyBQ4e/A1yIJdlBtqXxJ1KE/ituHRbNc4j4kL8Z\r\n"
        "/r6pvwnTI0PSx2Eqs048YdS92LT6qAv4flbNDxMn2uY7s4ycS4Q8w1JXnCeaAnYm\r\n"
        "WYI5wxO+bvRELR2Mcz5DmVnL8jRyml6l6582bSv5oufReFIbyPZbQWlXgYnpu6He\r\n"
        "GTc7E1zKYQGG/9+DQUl/1vQuCPqQwny0tQoX2w5tdYpdMdVm+zkLtbajzdTviJJa\r\n"
        "TWzL6lt5AoGBAN86+SVeJDcmQJcv4Eq6UhtRr4QGMiQMz0Sod6ettYxYzMgxtw28\r\n"
        "CIrgpozCc+UaZJLo7UxvC6an85r1b2nKPCLQFaggJ0H4Q0J/sZOhBIXaoBzWxveK\r\n"
        "nupceKdVxGsFi8CDy86DBfiyFivfBj+47BbaQzPBj7C4rK7UlLjab2rDAoGBAN2u\r\n"
        "AM2gchoFiu4v1HFL8D7lweEpi6ZnMJjnEu/dEgGQJFjwdpLnPbsj4c75odQ4Gz8g\r\n"
        "sw9lao9VVzbusoRE/JGI4aTdO0pATXyG7eG1Qu+5Yc1YGXcCrliA2xM9xx+d7f+s\r\n"
        "mPzN+WIEg5GJDYZDjAzHG5BNvi/FfM1C9dOtjv2dAoGAF0t5KmwbjWHBhcVqO4Ic\r\n"
        "BVvN3BIlc1ue2YRXEDlxY5b0r8N4XceMgKmW18OHApZxfl8uPDauWZLXOgl4uepv\r\n"
        "whZC3EuWrSyyICNhLY21Ah7hbIEBPF3L3ZsOwC+UErL+dXWLdB56Jgy3gZaBeW7b\r\n"
        "vDrEnocJbqCm7IukhXHOBK8CgYEAwqdHB0hqyNSzIOGY7v9abzB6pUdA3BZiQvEs\r\n"
        "3LjHVd4HPJ2x0N8CgrBIWOE0q8+0hSMmeE96WW/7jD3fPWwCR5zlXknxBQsfv0gP\r\n"
        "3BC5PR0Qdypz+d+9zfMf625kyit4T/hzwhDveZUzHnk1Cf+IG7Q+TOEnLnWAWBED\r\n"
        "ISOWmrUCgYAFEmRxgwAc/u+D6t0syCwAYh6POtscq9Y0i9GyWk89NzgC4NdwwbBH\r\n"
        "4AgahOxIxXx2gxJnq3yfkJfIjwf0s2DyP0kY2y6Ua1OeomPeY9mrIS4tCuDQ6LrE\r\n"
        "TB6l9VGoxJL4fyHnZb8L5gGvnB1bbD8cL6YPaDiOhcRseC9vBiEuVg==\r\n"
        "-----END RSA PRIVATE KEY-----\r\n";
    
    
    
    const unsigned char *mqtt_get_ca_certificate(void)
    {
        return (const unsigned char *)mqtt_ca_crt_rsa;
    }
    
    const unsigned char *mqtt_get_client_certificate(void)
    {
        return (const unsigned char *)mqtt_cli_crt_rsa;
    }
    
    const unsigned char *mqtt_get_client_key(void)
    {
        return (const unsigned char *)mqtt_cli_key_rsa;
    }
    
    int mqtt_get_ca_certificate_size(void)
    {
        return sizeof(mqtt_ca_crt_rsa);
    }
    
    int mqtt_get_client_certificate_size(void)
    {
        return sizeof(mqtt_cli_crt_rsa);
    }
    
    int mqtt_get_client_key_size(void)
    {
        return sizeof(mqtt_cli_key_rsa);
    }
    
  3. From your open ARTIK Cloud "Device Info" page, copy and paste these codes into your main.c code:
    • Device ID -- to the DEVICE_ID, ACTION_TOPIC, and MESSAGE_TOPIC fields
    • Device Token -- to the DEVICE_TOKEN field.
    Replace only the highlighted fields.
    #define DEVICE_ID "_your_DEVICE_ID_goes_here_"  
    #define DEVICE_TOKEN "_your_DEVICE_TOKEN_goes_here_"
    #define ACTION_TOPIC "/v1.1/actions/_your_DEVICE_ID_goes_here_"
    #define MESSAGE_TOPIC "/v1.1/messages/_your_DEVICE_ID_goes_here_"
  4. Change the Wi-Fi credentials in wifi.h as you did in the previous tutorials.
  5. Flash-load the code to your ARTIK 05X board as always.

You're ready to go!

Running the A053 All-in-One Project

Any time you apply power, your board will:

  • Retrieve the date using Network Time Protocol (ntp)
  • Publish to ARTIK Cloud all A053 GPIO and ADC input information
  • Receive Actions from ARTIK Cloud to the A053 to control GPIO and PWM outputs.

You will need a functioning Wi-Fi network for this to operate correctly, of course. But you won't need a terminal connection!

Data published

The 053 board sends the readings of each of the GPIO pins and the ADC values to the ARTIK Cloud every 10s, in an array and in a single payload.

Here is an example of the full JSON format payload sent to ARTIK Cloud:

1
2
3
4
5
6
7
8
{"ADC":{
   "Channel0":14,"Channel1":16,"Channel2":16,"Channel3":16
 },
 "GPIO"{
    "gpio37":0,"gpio38":0,"gpio39":0,"gpio40":0,"gpio41":0,"gpio42":1,"gpio43":1,"gpio44":1,"gpio45":0,"gpio46":0,
    "gpio47":0,"gpio48":0,"gpio49":0,"gpio50":0,"gpio51":0,"gpio52":0,"gpio53":0,"gpio54":0,"gpio55":0
 }
}

You can shorten this to send just the items you need to update on that particular transmission, send multiple payloads, send at different intervals, etc. just by modifying the code.

On the ARTIK Cloud side, click on +/- CHARTS to display only the GPIO pins and ADC channels of your choosing.

The resulting charts will provide all the information you need. You can then use ARTIK Cloud Rules to act on that data, possibly including sending back an Action to your A053 device or any other device you control through ARTIK Cloud.

Board switches. gpio42 reflects the state of SW702; gpio44 reflects the state of SW703. Push and hold a switch, then wait for the next 10s cycle on ARTIK Cloud to see the state change.

Actions

The code subscribes to Actions to toggle a GPIO pin or activate a PWM pin. You just need to specify the Action in the manifest. For example:

toggleGpio31

pwm0Freq20Duty80

GPIO output. Toggle GPIO pins using the format toggleGpioXX

Our code is set up to drive gpio31, 32, 45, and 49. You can easily change this in the code. gpio45/49 toggle the Red and Blue LEDs on the A053 board.

To test:

  1. On the My ARTIK Cloud user site, go to Rules and click + NEW RULE.
  2. For "Select a field on a device", you could choose any GPIO pin. Consider gpio42 or gpio44 since they are activated by convenient board switches.
  3. For the Action to send, pick gpio45 or gpio49.
  4. Back on the Rules page, just hover over the action and click TEST when you see it.

Did it work? Try holding down the switch you chose and see if that will also (after the 10s cycle) toggle the output GPIO pin.

PWM output. You can set up a simple LED circuit to show the output from the PWM pin, set with the frequency and duty mentioned in the Action, using the format pwmXFreqXXXXDutyXXXX

To test: Set up a Rule similarly to what you did for the GPIO pins.

Extra Credit

A primary advantage of using MQTT instead of Websockets is the savings in not only bandwidth but also in code overhead.

When you set up your project, you had to choose the "extra" configuration to get MQTT. But you didn't really need all the other baggage that went along with it.

Once your code is working, try your hand at creating a custom SDK – un-select the Websocket module, rebuild your project using the new SDK, and see how much code space you've freed up!

Last updated on: