Anas Dalintakam
Published © GPL3+

MQTT tutorial for Azure sphere MT3620

A tutorial for Azure sphere MT3620 MQTT implementation

IntermediateProtip3 hours1,502
MQTT tutorial for Azure sphere MT3620

Things used in this project

Story

Read more

Code

main.c

C/C++
main code used to send data to mqtt and blink user led
/* Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. */
// This sample C application for Azure Sphere demonstrates how to use a UART (serial port).
// The sample opens a UART with a baud rate of 115200. Pressing a button causes characters
// to be sent from the device over the UART; data received by the device from the UART is echoed to
// the Visual Studio Output Window.
//
// It uses the API for the following Azure Sphere application libraries:
// - UART (serial port)
// - GPIO (digital input for button)
// - log (messages shown in Visual Studio's Device Output window during debugging)
// - eventloop (system invokes handlers for timer events)
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
// applibs_versions.h defines the API struct versions to use for applibs APIs.
#include "applibs_versions.h"
//#include <applibs/uart.h>
#include <applibs/gpio.h>
#include <applibs/log.h>
//#include <applibs/eventloop.h>
#include "mqtt_utilities.h"
#include "common.h"
// By default, this sample targets hardware that follows the MT3620 Reference
// Development Board (RDB) specification, such as the MT3620 Dev Kit from
// Seeed Studio.
//
// To target different hardware, you'll need to update CMakeLists.txt. See
// https://github.com/Azure/azure-sphere-samples/tree/master/Hardware for more details.
//
// This #include imports the sample_hardware abstraction from that hardware definition.
#include <hw/sample_hardware.h>
//#include "eventloop_timer_utilities.h"
//MQTT Variable
#define MQTT_PUBLISH_PERIOD 500000000
//static EventLoopTimer* publishMQTTMsgTimer = NULL;
static char* mqttConf_topic = "AZURE";
static char* mqttConf_brokerIp = "192.168.43.59";
//MQTT Variable
//#define UART_SEND_PERIOD 5
//static EventLoopTimer* sendUartTimer = NULL;
//const size_t receiveBufferSize = 20;
// File descriptors - initialized to invalid value
//static int gpioButtonFd = -1;
//static int uartFd = -1;
//EventLoop *eventLoop = NULL;
//EventRegistration* uartEventReg = NULL;
//EventLoopTimer *buttonPollTimer = NULL;
// State variables
//static GPIO_Value_Type buttonState = GPIO_Value_High;
//const char* engineRPMCmd = "010C\r";
//const char* engineTempCmd = "0105\r";
//const char* engineFuelCmd = "012F\r";
//static int engineRPM;
//static int engineTemp;
//static int engineFuel;
//static char rxData[33];
//static char rxIndex = 0;
//static char Data[20];
//static void TerminationHandler(int signalNumber);
//static void SendUartMessage(int uartFd, const char *dataToSend);
//static void ButtonTimerEventHandler(EventLoopTimer *timer);
//static ExitCode InitPeripheralsAndHandlers(void);
//static void CloseFdAndPrintError(int fd, const char *fdName);
//static void ClosePeripheralsAndHandlers(void);
//mqtt test code
int test_mqtt()
{
Log_Debug("Im in\n");
int res = MQTTInit(mqttConf_brokerIp, "1883", mqttConf_topic);
Log_Debug(res);
Log_Debug("done init\n");
//MQTTPublish(mqttConf_topic, "{\"engineTemp\":\"67.0\",\"engineRpm\":\"32.0\",\"fuel\":\"51.0\"}");
MQTTPublish(mqttConf_topic, "Wiring It my way");
//  while (1)
//  {
// }
//Log_Debug("done publish\n");
}
/// <summary>
///     Main entry point for this application.
/// </summary>
int main(void)
//int main(int argc, char *argv[])
{//test_mqtt();
/*  Log_Debug("UART application starting.\n");
//  test_mqtt();
exitCode = InitPeripheralsAndHandlers();
// Use event loop to wait for events and trigger handlers, until an error or SIGTERM happens
while (exitCode == ExitCode_Success) {
EventLoop_Run_Result result = EventLoop_Run(eventLoop, -1, true);
// Continue if interrupted by signal, e.g. due to breakpoint being set.
if (result == EventLoop_Run_Failed && errno != EINTR) {
exitCode = ExitCode_Main_EventLoopFail;
}
}
ClosePeripheralsAndHandlers();
Log_Debug("Application exiting.\n");
// return exitCode;*/
int fd = GPIO_OpenAsOutput(SAMPLE_LED, GPIO_OutputMode_PushPull, GPIO_Value_High);
if (fd < 0) {
Log_Debug(
"Error opening GPIO: %s (%d). Check that app_manifest.json includes the GPIO used.\n",
strerror(errno), errno);
// return ExitCode_Main_Led;
}
const struct timespec sleepTime = {.tv_sec = 1, .tv_nsec = 0};
while (true) {
test_mqtt();
GPIO_SetValue(fd, GPIO_Value_Low);
nanosleep(&sleepTime, NULL);
GPIO_SetValue(fd, GPIO_Value_High);
nanosleep(&sleepTime, NULL);
}
}

app_manifest.json

JSON
set ip address and gpio
{
  "SchemaVersion": 1,
  "Name" : "UART_HighLevelApp",
  "ComponentId" : "4f2d9823-dbbd-4740-a7dd-198c32ba34fe",
  "EntryPoint": "/bin/app",
  "CmdArgs": [],
  "Capabilities": {
    "AllowedConnections": [ "192.168.43.59"],
    "Gpio": [ "$SAMPLE_LED" ],
   

  },
  "ApplicationType": "Default"
}

CMakeSettings.json

JSON
{
  "environments": [
    {
      "environment": "AzureSphere"
    }
  ],
  "configurations": [
    {
      "name": "ARM-Debug",
      "generator": "Ninja",
      "configurationType": "Debug",
      "inheritEnvironments": [
        "AzureSphere"
      ],
      "buildRoot": "${projectDir}\\out\\${name}",
      "installRoot": "${projectDir}\\install\\${name}",
      "cmakeToolchain": "${env.AzureSphereDefaultSDKDir}CMakeFiles\\AzureSphereToolchain.cmake",
      "buildCommandArgs": "-v",
      "ctestCommandArgs": "",
      "variables": [
        {
          "name": "AZURE_SPHERE_TARGET_API_SET",
          "value": "latest-lts"
        }
      ]
    },
    {
      "name": "ARM-Release",
      "generator": "Ninja",
      "configurationType": "Release",
      "inheritEnvironments": [
        "AzureSphere"
      ],
      "buildRoot": "${projectDir}\\out\\${name}",
      "installRoot": "${projectDir}\\install\\${name}",
      "cmakeToolchain": "${env.AzureSphereDefaultSDKDir}CMakeFiles\\AzureSphereToolchain.cmake",
      "buildCommandArgs": "-v",
      "ctestCommandArgs": "",
      "variables": [
        {
          "name": "AZURE_SPHERE_TARGET_API_SET",
          "value": "5"
        }
      ]
    }
  ]
}

referred repo

i modified codes using this project

Credits

Anas Dalintakam

Anas Dalintakam

13 projects • 34 followers
Electronics and communication engineer-IoT researcher-DIY electronics hobbyist-blogger-hackster-maker

Comments