Infineon Team
Published © MIT

Smart Window Opener

Have you ever wanted to upgrade your window from a lame one to an awesome smart one? Here is how you do it.

AdvancedFull instructions provided2,222
Smart Window Opener

Things used in this project

Story

Read more

Custom parts and enclosures

Lock/Unlock base plate

Lock/Unlock big gear

Lock/Unlock small gear

Lock/Unlock closure V2

Open/Close inside joint

Open/Close outside joint

Open/Close guide beginning

Open/Close guide end

Open/Close guide

Open/Close rack

Open/Close rack start

Open/Close magnet slide

Open/Close gear

Open/Close guide wheel

Open/Close guide wheel axle

Open/Close motor mounting

Open/Close motor mounting back wall

Open/Close board plate

Open/Close window clamp

Open/Close guide wheel mounting 2x

Open/Close XMC2Go Clip

H-Bridge Base Plate

H-Bridge Cover

DC/DC Housing

Housing unit for DC/DC Converter

Cable Cover

These are the wire covering parts that go along the window frame

Schematics

Window Opener Fritzing

Whole fritzing schematic with the BTN8982 and XMC2Go

Fritzing Parts

These are the Fritzing parts for the Boards that were used in this project

Window Opener Fritzing

This is the fritzing schematic for the whole project, if you want to have a closer look.

Code

XMC2Go unlocker

Arduino
/**
* For basic setup just create a Tlv493d() object. If you want to use the wake up mode please use Tlv493d_w2b6(). Also
* the setUpdateRate() method is slightly different for different variants
*
* OR TODO turn as long as not in specified area
* Wait to process order and home position closed -> Always asume after new command position closed
*/


#include <Tlv493d.h>


//Physical Pin != Arduino IDE Pin they are bright green ones https://github.com/Infineon/XMC-for-Arduino/issues/23
#define powerpin 9 //Connected to Vdd of sensor to activate or deactivate 0.0

#define rotpin 5 //0.15 LOW open HIGH close status LEFT HBridge
#define startpin 4 //0.14

#define bit1pin 0 //P0.6 INPUT Bit1 Bit2 (00 TILT) (01 open) (10 close) (11 wait) for new order
#define bit2pin 1 //P0.7 INPUT
#define statuspin 2 //P0.8 OUTPUT 1 Ready 0 InProgres*/

#define anglearea 2.0 //area where stopped eg 45 degree -> success when sensorval within 43 & 47

Tlv493d Tlv493dMagnetic3DSensor = Tlv493d();

void setup() {
  Serial.begin(9600);
  while (!Serial);

  pinMode(LED2, OUTPUT);
  digitalWrite(LED2, HIGH);
  delay(50);

  pinMode(rotpin, OUTPUT);
  pinMode(startpin, OUTPUT);
  digitalWrite(startpin, LOW); //Motor stopped at start
  digitalWrite(rotpin, LOW);

  pinMode(bit1pin, INPUT);
  pinMode(bit2pin, INPUT);
  pinMode(statuspin, OUTPUT);
  digitalWrite(statuspin, LOW);
  // pinMode(LED1, OUTPUT); //Startup in progress
  // pinMode(LED2, OUTPUT);

  pinMode(powerpin, OUTPUT);  //Sensor-VDD as output
  digitalWrite(powerpin, HIGH); //Power on the sensor
  delay(50); //Wait for sensor and also for HBridge to detect on change

  Tlv493dMagnetic3DSensor.begin();
  //Tlv493dMagnetic3DSensor.enableTemp();
}

//angle 270 = closed 180 = opened 90 = opened full and open decrease angle close increases angle
void loop() {
  Tlv493dMagnetic3DSensor.updateData();
  //Rad in Degree than +180 so nothing - !only 180 degrees needed make sure to not get into trouble
  double angle = (Tlv493dMagnetic3DSensor.getAzimuth()* 57296 / 1000 );
  Serial.println(angle);
  //always set bit1 first as checked first
  if(digitalRead(bit1pin) == LOW) //open or TILT
  {
    if(digitalRead(bit2pin) == LOW)// TILT
    {
      if(angle>-90.0+anglearea)
      {
        digitalWrite(rotpin, LOW);
        digitalWrite(startpin, HIGH);
        digitalWrite(statuspin, LOW);
      }else{
        digitalWrite(startpin, LOW);//Motor off and success
        digitalWrite(statuspin, HIGH);
      }

    }else{//open 01 opening Window OPEN
      if(angle < 8.0) {
        digitalWrite(rotpin, HIGH);
      }else {
        digitalWrite(rotpin, LOW); //low open high close
      }//1.0 bugfix from openedful to opened window still locked maybe magnet not perfectly centered
      if(angle<0.0-anglearea+9.0 || angle>0.0+anglearea + 7.0)
      {
        digitalWrite(startpin, HIGH);
        digitalWrite(statuspin, LOW);
      }else{
        digitalWrite(startpin, LOW);//Motor off and success
        digitalWrite(statuspin, HIGH);
      }
    }
  }else{
    if(digitalRead(bit2pin) == LOW)
    {//close 10 CLOSE
      if(angle<90.0-anglearea)
      {
        digitalWrite(rotpin, HIGH);
        digitalWrite(startpin, HIGH);
        digitalWrite(statuspin, LOW);
      }else{
        digitalWrite(startpin, LOW);//Motor off and success
        digitalWrite(statuspin, HIGH);
      }
    }else{//wait 11 WAIT
      digitalWrite(statuspin, HIGH);
      digitalWrite(startpin, LOW); //To prevent xmc2go erlier boot than bootkit of window opener
    }
  }
  // digitalWrite(LED1, digitalRead(bit1pin)); //LEFT
  // digitalWrite(LED2, digitalRead(bit2pin)); //RIGHT

  delay(50);
}

XMC1100 open/closing

Arduino
/**
* For basic setup just create a Tle493d() object. If you want to use the wake up mode please use Tle493d_w2b6(). Also
* the setUpdateRate() method is slightly different for different variants
* P0.10(28) P0.11(29) P0.13(30) used to communicate with unlocker
*/
#define DEBUG false

#define UNLOCKERBIT1_PIN    28
#define UNLOCKERBIT2_PIN    29 // Bit1 Bit2 (00 tilt) (01 open) (10 close) (11 wait)
#define UNLOCKERFEEDBACK    30 // 1 Ready 0 InProgres

#define UNLOCKERREADY       HIGH
#define UNLOCKERINPROGRESS  LOW

#define UNLOCKERBIT1TILT    LOW
#define UNLOCKERBIT1OPEN    LOW
#define UNLOCKERBIT1CLOSE   HIGH
#define UNLOCKERBIT1WAIT    HIGH

#define UNLOCKERBIT2TILT    LOW
#define UNLOCKERBIT2OPEN    HIGH
#define UNLOCKERBIT2CLOSE   LOW
#define UNLOCKERBIT2WAIT    HIGH

#define MAIN_LOOP_DELAY     5

//Val between 1 and 255
#define MOTOR_SPEED         100

#define UART_TX_DELAY                   5000
#define UART_RECEIVED_TO_BUFFER_DELAY   2
#define MQTT_UART_VALUE_DELIMITER       ":"
#define MQTT_UART_END_DELIMITER         0x00
#define MQTT_MSG_NOTHING_RECEIVED       "nomsg"

#define LOG_DELAY 7000

//MQTT Msg to Send
#define MQTT_MSG_LOG_OK                         "ok"
#define MQTT_MSG_LOG_MAG_SENS_ERROR             "MagSensErr"
#define MQTT_MSG_LOG_Mot_CONT_SHIELD_ERROR      "MotCoShlErr"
#define MQTT_MSG_LOG_STUCK_ERROR                "StuckErr"
#define MQTT_MSG_OPEN_POSITION_REACHED          "OpenPosReach"
#define MQTT_MSG_OPEN_TILTED_POSITION_REACHED   "OpenTilPosReach"
#define MQTT_MSG_CLOSE_POSITION_REACHED         "ClosePosReach"

//MQTT Msg recieved
#define MQTT_MSG_OPEN             "open"
#define MQTT_MSG_TILT             "opentil"
#define MQTT_MSG_CLOSE            "close"
#define MQTT_MSG_EMERGENCY_STOP   "emstop"

//0-1023
#define CRITICALCURRENTSENSE 230

//also before changeing -> make sure both motors do not run at the same time
//Needed as unlocker loop is delayed by 50 increased as sometimes didn't close correctly
#define UNLOCKERCOMMANDDELAY 70

// Feedback pins for the window position
#define WINDOW_POS1 8
#define WINDOW_POS2 9

// Feedback pin to reduce the speed when close to a magnet
#define SPEED_PIN 7

/* For on board LEDs */
#include <LED.h>

#include <IfxMotorControlShield.h>

typedef enum {CLOSED,
              CLOSED_AFTER_TILT,
              CLOSED_AFTER_OPEN,
              TILTED,
              OPEN,
              STOPPED,
              OPENING,
              TILTING,
              TILTING_CLOSE,
              CLOSING,
              CLOSE_TO_TILT
              } State;

typedef enum {LOCKED,
              TILT,
              UNLOCKED,
              LOCKING,
              TILTING_LOCK,
              UNLOCKING,
              STOPPED_LOCK
            } LockState;

State state = CLOSED;
LockState unlockerState = LOCKED; //Assume Window and Handler Closed at start. Emstop assume non closed Position pressed to avoid collision. So at init if Window is not closed press emstop and close.

unsigned long startTime;
unsigned long callTime;

String received = MQTT_MSG_NOTHING_RECEIVED;

LED Led;

void setup() {

  pinMode(UNLOCKERBIT1_PIN,OUTPUT);
  pinMode(UNLOCKERBIT2_PIN,OUTPUT);
  digitalWrite(UNLOCKERBIT1_PIN,UNLOCKERBIT1WAIT);
  digitalWrite(UNLOCKERBIT2_PIN,UNLOCKERBIT2WAIT);//11 corresponds to Waiting
  pinMode(UNLOCKERFEEDBACK, INPUT);

  pinMode(WINDOW_POS1, INPUT);
  pinMode(WINDOW_POS2, INPUT);

  pinMode(SPEED_PIN, INPUT);

  Serial.begin(9600);
  while (!Serial);

  ifxMcsBiDirectionalMotor.begin();

  callTime=millis();
  startTime=millis();

  Led.Add( LED1 );
  Led.On(LED1);

}

void loop() {
  static uint8_t windowState = 0;       /* States : 0 = closed, 1 = open, 2 = opening, 3 = closing */
  static uint8_t lockerState = 0;       /* States : 0 = closed, 1 = open */
  static uint8_t oldLockPinState1 = 0;
  static uint8_t oldLockPinState2 = 0;


  static bool busyFlag = false;
  static bool motorRunning = false;
  static bool stoppedFlag = false;

  //Check and receive new Uart Msgs
  received = MQTT_MSG_NOTHING_RECEIVED;
  if(Serial.available() > 0) {
    received="";
    while(Serial.available() > 0) {
      delay(UART_RECEIVED_TO_BUFFER_DELAY);
      received+=(char) Serial.read();
    }
  }

  if(lockerState == 0) {
    digitalWrite(UNLOCKERBIT1_PIN, HIGH); // 00 open, 01 open, 10 close, 11 wait
    digitalWrite(UNLOCKERBIT2_PIN, LOW);
    delay(1000);
  }

  if(digitalRead(UNLOCKERFEEDBACK) == HIGH) {
    digitalWrite(UNLOCKERBIT1_PIN, HIGH);
    digitalWrite(UNLOCKERBIT2_PIN, HIGH);
    if(lockerState == 0) {
      lockerState = 1;
    }
  }

  // if(lockerState = 1){
  //   digitalWrite(UNLOCKERBIT1_PIN, LOW);
  //   digitalWrite(UNLOCKERBIT2_PIN, LOW);
  //   lockerState = 2;
  // }

  /*------------------------------------STOP POSITIONS----------------------------*/
  if(digitalRead(WINDOW_POS1) == LOW && digitalRead(WINDOW_POS2) == HIGH) {
    if(state == TILTING) {
      ifxMcsBiDirectionalMotor.stop();
      motorRunning = false;
      state = TILTED;
      busyFlag = false;
    }
  }
  else if(digitalRead(WINDOW_POS1) == HIGH && digitalRead(WINDOW_POS2) == LOW) {
    if(state == OPENING) {
      ifxMcsBiDirectionalMotor.stop();
      motorRunning = false;
      state = OPEN;
      busyFlag = false;
    }
  }
  else if(digitalRead(WINDOW_POS1) == LOW && digitalRead(WINDOW_POS2) == LOW) {
    if(state == CLOSING) {
      ifxMcsBiDirectionalMotor.stop();
      motorRunning = false;
      delay(UNLOCKERCOMMANDDELAY);
      digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1CLOSE);
      digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2CLOSE);
      delay(UNLOCKERCOMMANDDELAY);
      state = CLOSED;
      unlockerState = LOCKING;
    }
    else if(state == TILTING_CLOSE) {
      ifxMcsBiDirectionalMotor.stop();
      motorRunning = false;
      delay(UNLOCKERCOMMANDDELAY);
      digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1CLOSE);
      digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2CLOSE);
      delay(UNLOCKERCOMMANDDELAY);
      unlockerState = LOCKING;
      state = CLOSED_AFTER_TILT;
    }
    else if(state == CLOSE_TO_TILT) {
      ifxMcsBiDirectionalMotor.stop();
      motorRunning = false;
      delay(UNLOCKERCOMMANDDELAY);
      digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1CLOSE);
      digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2CLOSE);
      delay(UNLOCKERCOMMANDDELAY);
      unlockerState = LOCKING;
      state = CLOSED_AFTER_OPEN;
    }
  }
  /*-----------------------------------------------------------------------------*/

  /*------------------------------LOCK-------------------------------------------*/
  if(digitalRead(UNLOCKERFEEDBACK) == UNLOCKERREADY)
  {
    Led.Off( LED1 );
    if(unlockerState == LOCKING)
    {
      unlockerState = LOCKED;
      digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1WAIT);
      digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2WAIT);
      busyFlag = false;
      if(state == CLOSED_AFTER_TILT) {
        delay(UNLOCKERCOMMANDDELAY);
        digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1OPEN);
        digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2OPEN);
        delay(UNLOCKERCOMMANDDELAY);
        unlockerState = UNLOCKING;
        busyFlag = true;
      }
      if(state == CLOSED_AFTER_OPEN) {
        delay(UNLOCKERCOMMANDDELAY);
        digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1TILT);
        digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2TILT);
        delay(UNLOCKERCOMMANDDELAY);
        unlockerState = TILTING_LOCK;
        busyFlag = true;
      }
    }
    else if(unlockerState == UNLOCKING) {
      unlockerState = UNLOCKED;
      state = OPENING;
      delay(UNLOCKERCOMMANDDELAY);
      digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1WAIT);
      digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2WAIT);
      delay(UNLOCKERCOMMANDDELAY);
    }
    else if(unlockerState == TILTING_LOCK) {
      unlockerState = TILT;
      digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1WAIT);
      digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2WAIT);
      state = TILTING;
    }
  }
  else {
    Led.On( LED1 );
  }
  /*-----------------------------------------------------------------------------*/

  /*----------------------------------MQTT---------------------------------------*/
  if(received.equals(MQTT_MSG_OPEN) && busyFlag == false) { // Open
    busyFlag = true;
    if(state == CLOSED) {
      delay(UNLOCKERCOMMANDDELAY);
      digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1OPEN);
      digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2OPEN);
      delay(UNLOCKERCOMMANDDELAY);
      unlockerState = UNLOCKING;
    }
    else if(state == TILTED) {
      state = TILTING_CLOSE;
    }
    else if(state == OPEN) {
      busyFlag = false;
    }
  }
  else if(received.equals(MQTT_MSG_CLOSE) && busyFlag == false) { // Close
    busyFlag = true;
    if(state == OPEN) {
      state = CLOSING;
    }
    else if(state == TILTED) {
      state = CLOSING;
    }
    else if(state == CLOSED) {
      busyFlag = false;
    }
  }
  else if(received.equals(MQTT_MSG_TILT) && busyFlag == false) {
    busyFlag = true;
    if(state == OPEN) {
      state = CLOSE_TO_TILT;
    }
    else if(state == CLOSED) {
      delay(UNLOCKERCOMMANDDELAY);
      digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1TILT);
      digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2TILT);
      delay(UNLOCKERCOMMANDDELAY);
      unlockerState = TILTING_LOCK;
    }
    else if(state == TILTED) {
      busyFlag = false;
    }
  }

  // if(received.equals(MQTT_MSG_EMERGENCY_STOP) && stoppedFlag == false)
  // {
  //   ifxMcsBiDirectionalMotor.stop();

  //   oldLockPinState1 = digitalRead(UNLOCKERBIT1_PIN);
  //   oldLockPinState2 = digitalRead(UNLOCKERBIT2_PIN);

  //   digitalWrite(UNLOCKERBIT1_PIN, UNLOCKERBIT1WAIT);
  //   digitalWrite(UNLOCKERBIT2_PIN, UNLOCKERBIT2WAIT);

  //   stoppedFlag = true;
  // }
  // else if(received.equals(MQTT_MSG_EMERGENCY_STOP) && stoppedFlag == true) {
  //   motorRunning = false;
  //   stoppedFlag = false;

  //   digitalWrite(UNLOCKERBIT1_PIN, oldLockPinState1);
  //   digitalWrite(UNLOCKERBIT2_PIN, oldLockPinState2);
  // }
  /*-----------------------------------------------------------------------------*/

  /*--------------------------------MOTOR CONTROL--------------------------------*/
  /** Control the motor depending on the desired state **/
  if(state == OPENING && motorRunning == false) {
    ifxMcsBiDirectionalMotor.setBiDirectionalSpeed(-MOTOR_SPEED);
    ifxMcsBiDirectionalMotor.start();
    motorRunning = true;
  }
  else if(state == CLOSING && motorRunning == false) {
    ifxMcsBiDirectionalMotor.setBiDirectionalSpeed(MOTOR_SPEED);
    ifxMcsBiDirectionalMotor.start();
    motorRunning = true;
  }
  else if(state == TILTING && motorRunning == false) {
    ifxMcsBiDirectionalMotor.setBiDirectionalSpeed(-MOTOR_SPEED);
    ifxMcsBiDirectionalMotor.start();
    motorRunning = true;
  }
  else if(state == CLOSE_TO_TILT && motorRunning == false) {
    ifxMcsBiDirectionalMotor.setBiDirectionalSpeed(MOTOR_SPEED);
    ifxMcsBiDirectionalMotor.start();
    motorRunning = true;
  }
  else if(state == TILTING_CLOSE && motorRunning == false) {
    ifxMcsBiDirectionalMotor.setBiDirectionalSpeed(MOTOR_SPEED);
    ifxMcsBiDirectionalMotor.start();
    motorRunning = true;
  }
  /*-----------------------------------------------------------------------------*/

  /*-----------------------------------SPEED CONTROL-----------------------------*/
  if(digitalRead(SPEED_PIN) == HIGH) {
    if(ifxMcsBiDirectionalMotor.getBiDirectionalSpeed() > 0) {
      ifxMcsBiDirectionalMotor.setBiDirectionalSpeed(MOTOR_SPEED/4);
    }
    else {
      ifxMcsBiDirectionalMotor.setBiDirectionalSpeed(-MOTOR_SPEED/4);
    }
  }
  else {
    if(ifxMcsBiDirectionalMotor.getBiDirectionalSpeed() > 0) {
      ifxMcsBiDirectionalMotor.setBiDirectionalSpeed(MOTOR_SPEED);
    }
    else {
      ifxMcsBiDirectionalMotor.setBiDirectionalSpeed(-MOTOR_SPEED);
    }
  }
  /*-----------------------------------------------------------------------------*/

  delay(MAIN_LOOP_DELAY);
}

PSOC6 - src/main.c

C/C++
/******************************************************************************
* File Name:   main.c
*
* Description: This is the source code for MQTT Client Example in ModusToolbox.
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

/* Header file includes */
#include "cyhal.h"
#include "cybsp.h"
#include "cy_retarget_io.h"
#include "mqtt_task.h"
#include "FreeRTOS.h"
#include "task.h"

#include "uart_task.h"

/* This enables RTOS aware debugging. */
volatile int uxTopUsedPriority;



/******************************************************************************
* Global Variables
******************************************************************************/
/* This enables RTOS aware debugging. */
volatile int uxTopUsedPriority;

/******************************************************************************
 * Function Name: main
 ******************************************************************************
 * Summary:
 *  System entrance point. This function initializes retarget IO, sets up 
 *  the MQTT client task, and then starts the RTOS scheduler.
 *
 * Parameters:
 *  void
 *
 * Return:
 *  int
 *
 ******************************************************************************/
int main()
{
	//restart when failedhack solves the reliability issues but when resetting not reachable -> set retain flags mqtt?
	while(true)
	{

		cy_rslt_t result;

		/* This enables RTOS aware debugging in OpenOCD. */
		uxTopUsedPriority = configMAX_PRIORITIES - 1;

		/* Initialize the board support package. */
		result = cybsp_init();
		CY_ASSERT(result == CY_RSLT_SUCCESS);

		/* To avoid compiler warnings. */
		(void) result;


		initUART();

		/* Enable global interrupts. */
		__enable_irq();

		/* Initialize retarget-io to use the debug UART port. */
		cy_retarget_io_init(CYBSP_DEBUG_UART_TX, CYBSP_DEBUG_UART_RX,
							CY_RETARGET_IO_BAUDRATE);

		/* \x1b[2J\x1b[;H - ANSI ESC sequence to clear screen. */
		printf("\x1b[2J\x1b[;H");
		printf("===============================================================\n");
		printf("Nanodrone II - MQTT + UART Tasks\n");
		printf("===============================================================\n\n");

		/* Create the MQTT Client task. */
		xTaskCreate(mqtt_client_task, "MQTT Client task", MQTT_CLIENT_TASK_STACK_SIZE,
					NULL, MQTT_CLIENT_TASK_PRIORITY, NULL);
		/* Create the UART task. */
		xTaskCreate(uart_task, "UART task", UART_TASK_STACK_SIZE,
			NULL, UART_TASK_PRIORITY, NULL);

		/* Start the FreeRTOS scheduler. */
		vTaskStartScheduler();
	}
	/* Should never get here. Should be a program halt*/
	CY_ASSERT(0);

}

/* [] END OF FILE */

PSOC6 - src/mqtt_client_config.c

C/C++
/******************************************************************************
* File Name:   mqtt_client_config.c
*
* Description: This file contains the configuration structures used by 
*              the MQTT client for MQTT connect operation.
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

#include <stdio.h>
#include "mqtt_client_config.h"

/******************************************************************************
* Global Variables
*******************************************************************************/
/* Configure the MQTT Broker/Server details. */
struct IotNetworkServerInfo networkServerInfo =
{
    .pHostName = MQTT_BROKER_ADDRESS,
    .port = MQTT_PORT
};

#if (MQTT_SECURE_CONNECTION)
/* Configure the MQTT client credentials in case of a secure connection. */
struct IotNetworkCredentials credentials =
{
    /* Configure the client certificate. */
    .pClientCert = (const char *)CLIENT_CERTIFICATE,
    .clientCertSize = sizeof(CLIENT_CERTIFICATE),
    /* Configure the client private key. */
    .pPrivateKey = (const char *)CLIENT_PRIVATE_KEY,
    .privateKeySize = sizeof(CLIENT_PRIVATE_KEY),
    /* Configure the Root CA certificate of the MQTT Broker/Server. */
    .pRootCa = (const char *)ROOT_CA_CERTIFICATE,
    .rootCaSize = sizeof(ROOT_CA_CERTIFICATE),
    /* Application Layer Protocol Negotiation (ALPN) is used to implement 
     * MQTT with TLS Client Authentication on Port 443 from client devices.
     */
    #if (MQTT_PORT == 443)
    .pAlpnProtos = MQTT_ALPN_PROTOCOL_NAME
    #else
    .pAlpnProtos = NULL
    #endif 
};

/* Structure with the network interface details. */
IotMqttNetworkInfo_t networkInfo =
{
    .createNetworkConnection = true,
    .u.setup.pNetworkCredentialInfo = &credentials,
    .u.setup.pNetworkServerInfo = &networkServerInfo
};

#else
/* Structure with the network interface details. */
IotMqttNetworkInfo_t networkInfo =
{
    .createNetworkConnection = true,
    /* Set the credentials to NULL for a non-secure connection. */
    .u.setup.pNetworkCredentialInfo = NULL,
    .u.setup.pNetworkServerInfo = &networkServerInfo
};
#endif /* #if (MQTT_SECURE_CONNECTION) */

#if ENABLE_LWT_MESSAGE
/* Last Will and Testament (LWT) message structure. The MQTT broker will
 * publish the LWT message if this client disconnects unexpectedly.
 */
IotMqttPublishInfo_t willInfo =
{
    .qos = IOT_MQTT_QOS_0,
    .pTopicName = MQTT_WILL_TOPIC_NAME,
    .topicNameLength = (uint16_t)(sizeof(MQTT_WILL_TOPIC_NAME) - 1),
    .pPayload = MQTT_WILL_MESSAGE,
    .payloadLength = (size_t)(sizeof(MQTT_WILL_MESSAGE) - 1)
};
#endif /* ENABLE_LWT_MESSAGE */

/* MQTT connection information structure. */
IotMqttConnectInfo_t connectionInfo =
{
    .cleanSession = true,
    .awsIotMqttMode = (AWS_IOT_MQTT_MODE == 1),
    .keepAliveSeconds = MQTT_KEEP_ALIVE_SECONDS,
    #if ENABLE_LWT_MESSAGE
    .pWillInfo = &willInfo,
    #else
    .pWillInfo = NULL,
    #endif /* ENABLE_LWT_MESSAGE */
    .pUserName = NULL,
    .pPassword = NULL,
    .userNameLength = 0,
    .passwordLength = 0
};

/* Check for a valid QoS setting. 
 * The MQTT library currently supports only QoS 0 and QoS 1.
 */
#if ((MQTT_MESSAGES_QOS != 0) && (MQTT_MESSAGES_QOS != 1))
    #error "Invalid QoS setting! MQTT_MESSAGES_QOS must be either 0 or 1."
#endif

/* Check if the macros are correctly configured for AWS IoT Broker. */
#if ((MQTT_SECURE_CONNECTION != 1) && (AWS_IOT_MQTT_MODE == 1))
    #error "AWS IoT does not support unsecured connections!"
#endif

/* [] END OF FILE */

PSOC6 - src/mqtt_task.c

C/C++
/******************************************************************************
* File Name:   mqtt_task.c
*
* Description: This file contains the task that handles initialization & 
*              connection of Wi-Fi and the MQTT client. The task then starts 
*              the subscriber and the publisher tasks. The task also handles
*              all the cleanup operations to gracefully terminate the Wi-Fi and
*              MQTT connections in case of any failure.
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

#include "cyhal.h"
#include "cybsp.h"

/* FreeRTOS header files */
#include "FreeRTOS.h"
#include "task.h"

/* Task header files */
#include "mqtt_task.h"
#include "subscriber_task.h"
#include "publisher_task.h"

/* Configuration file for Wi-Fi and MQTT client */
#include "wifi_config.h"
#include "mqtt_client_config.h"

/* Middleware libraries */
//#include "cy_retarget_io.h"
#include "cy_wcm.h"
#include "cy_lwip.h"
#include "cy_iot_network_secured_socket.h"
#include "iot_init.h"
#include "iot_clock.h"

/******************************************************************************
* Macros
******************************************************************************/

// if you want to subscribe to the message, then comment the next line and uncomment the one below it
//#undef MQTT_SUBSCRIBE
#define MQTT_SUBSCRIBE

/* Queue length of a message queue that is used to communicate the status of 
 * various operations.
 */
#define MQTT_STATUS_QUEUE_LENGTH         (1u)

/* Time in milliseconds to wait before creating the publisher task. */
#define TASK_CREATION_DELAY_MS           (2000u)

/* Flag Masks for tracking which cleanup functions must be called. */
#define WCM_INITIALIZED                  (1lu << 0)
#define WIFI_CONNECTED                   (1lu << 1)
#define IOT_SDK_INITIALIZED              (1lu << 2)
#define NETWORK_STACK_INITIALIZED        (1lu << 3)
#define LIBS_INITIALIZED                 (1lu << 4)
#define CONNECTION_ESTABLISHED           (1lu << 5)

/* Macro to check if the result of an operation was successful and set the 
 * corresponding bit in the init_flag based on 'init_mask' parameter. When 
 * it has failed, print the error message and return EXIT_FAILURE to the 
 * calling function.
 */
#define CHECK_RESULT(result, init_mask, error_message...)   \
                     do                                     \
                     {                                      \
                         if ((int)result == EXIT_SUCCESS)   \
                         {                                  \
                             init_flag |= init_mask;        \
                         }                                  \
                         else                               \
                         {                                  \
                             printf(error_message);         \
                             return EXIT_FAILURE;           \
                         }                                  \
                     } while(0)

/******************************************************************************
* Global Variables
*******************************************************************************/
/* MQTT connection handle. */
IotMqttConnection_t mqttConnection = IOT_MQTT_CONNECTION_INITIALIZER;

/* Queue handle used to communicate results of various operations - MQTT 
 * Publish, MQTT Subscribe, and MQTT connection between tasks and callbacks.
 */
QueueHandle_t mqtt_status_q;

/* Flag to denote initialization status of various operations. */
uint32_t init_flag;

//Used to reset device after cleanup
cy_rslt_t rslt;
cyhal_wdt_t wdt_obj;

/******************************************************************************
* Function Prototypes
*******************************************************************************/
static int wifi_connect(void);
static int mqtt_connect(void);
static void mqtt_disconnect_callback(void *pCallbackContext,
                                     IotMqttCallbackParam_t *pCallbackParam);
#if GENERATE_UNIQUE_CLIENT_ID
static int mqtt_get_unique_client_identifier(char *mqtt_client_identifier);
#endif /* GENERATE_UNIQUE_CLIENT_ID */

static void cleanup(void);

/******************************************************************************
 * Function Name: mqtt_client_task
 ******************************************************************************
 * Summary:
 *  Task for handling initialization & connection of Wi-Fi and the MQTT client.
 *  The task also creates and manages the subscriber and publisher tasks upon 
 *  successful MQTT connection.
 *
 * Parameters:
 *  void *pvParameters : Task parameter defined during task creation (unused)
 *
 * Return:
 *  void
 *
 ******************************************************************************/
void mqtt_client_task(void *pvParameters)
{
    /* Structure that stores the data received over MQTT status queue from 
     * other tasks and callbacks.
     */
    mqtt_result_t mqtt_status;

    /* To avoid compiler warnings */
    (void)pvParameters;

    /* Create a message queue to communicate MQTT operation results 
     * between various tasks and callbacks.
     */
    mqtt_status_q = xQueueCreate(MQTT_STATUS_QUEUE_LENGTH, sizeof(mqtt_result_t));

    /* Initialize the Wi-Fi STA, connect to the Wi-Fi AP, set up the MQTT 
     * client, and connect to the MQTT broker. Jump to the cleanup block if 
     * any of the operations fails.
     */
    if ( (wifi_connect() != EXIT_SUCCESS) || (mqtt_connect() != EXIT_SUCCESS) )
    {
        goto exit_cleanup;
    }


#ifdef MQTT_SUBSCRIBE
    /* Create the subscriber task and cleanup if the operation fails. */
    if (pdPASS != xTaskCreate(subscriber_task, "Subscriber task", SUBSCRIBER_TASK_STACK_SIZE,
                              NULL, SUBSCRIBER_TASK_PRIORITY, &subscriber_task_handle))
    {
        printf("Failed to create the Subscriber task!\n");
        goto exit_cleanup;
    }

    /* Wait for the subscribe operation to complete. */
    vTaskDelay(pdMS_TO_TICKS(TASK_CREATION_DELAY_MS));
#endif // MQTT_SUBSCRIBE


    /* Create the publisher task and cleanup if the operation fails. */
    if (pdPASS != xTaskCreate(publisher_task, "Publisher task", PUBLISHER_TASK_STACK_SIZE, 
                              NULL, PUBLISHER_TASK_PRIORITY, &publisher_task_handle))
    {
        printf("Failed to create Publisher task!\n");
        goto exit_cleanup;
    }

    while (true)
    {
        /* Wait for results of MQTT operations from other tasks and callbacks. */
        if (pdTRUE == xQueueReceive(mqtt_status_q, &mqtt_status, portMAX_DELAY))
        {
            switch(mqtt_status)
            {
                case MQTT_PUBLISH_FAILURE:
                {
					#ifdef MQTT_SUBSCRIBE
                    /* Unsubscribe from the topic before cleanup. */
                    mqtt_unsubscribe();
					#endif // MQTT_SUBSCRIBE
                }
                case MQTT_SUBSCRIBE_FAILURE:
                case MQTT_DISCONNECT:
                {
                    /* Delete the subscriber and publisher tasks and go to the
                     * cleanup label as MQTT subscribe/publish has failed.
                     */
                    if (subscriber_task_handle != NULL)
                    {
                        vTaskDelete(subscriber_task_handle);
                    }
                    if (publisher_task_handle != NULL)
                    {
                        publisher_cleanup();
                        vTaskDelete(publisher_task_handle);
                    }
                    goto exit_cleanup;
                }
                default:
                    break;
            }
        }
    }

    /* Cleanup section for various operations. */
    exit_cleanup:
    cleanup();
    vTaskDelete( NULL );
}

/******************************************************************************
 * Function Name: wifi_connect
 ******************************************************************************
 * Summary:
 *  Function that initializes the Wi-Fi Connection Manager and then connects 
 *  to the Wi-Fi Access Point using the specified SSID and PASSWORD.
 *
 * Parameters:
 *  void
 *
 * Return:
 *  int : EXIT_SUCCESS on successful connection with a Wi-Fi Access Point,
 *        else EXIT_FAILURE.
 *
 ******************************************************************************/
static int wifi_connect(void)
{
    cy_rslt_t result;
    cy_wcm_connect_params_t connect_param;
    cy_wcm_ip_address_t ip_address;
    uint32_t retry_count;
    /* Configure the interface as a Wi-Fi STA (i.e. Client). */
    cy_wcm_config_t config = {.interface = CY_WCM_INTERFACE_TYPE_STA};

    /* Initialize the Wi-Fi Connection Manager and return if the operation fails. */
    result = cy_wcm_init(&config);
    CHECK_RESULT(result, WCM_INITIALIZED, "\nWi-Fi Connection Manager initialization failed!\n");
    printf("\nWi-Fi Connection Manager initialized.\n");

    /* Configure the connection parameters for the Wi-Fi interface. */
    memset(&connect_param, 0, sizeof(cy_wcm_connect_params_t));
    memcpy(connect_param.ap_credentials.SSID, WIFI_SSID, sizeof(WIFI_SSID));
    memcpy(connect_param.ap_credentials.password, WIFI_PASSWORD, sizeof(WIFI_PASSWORD));
    connect_param.ap_credentials.security = WIFI_SECURITY;

    /* Connect to the Wi-Fi AP. */
    for (retry_count = 0; retry_count < MAX_WIFI_CONN_RETRIES; retry_count++)
    {
        //printf("Connecting to Wi-Fi AP '%s'\n", connect_param.ap_credentials.SSID);
    	printf("Connecting to Wi-Fi AP '%s'\n", WIFI_SSID);
    	printf("Start crit call");
        ///max 60 seconds sometimes infinite?
        result = cy_wcm_connect_ap(&connect_param, &ip_address);
        printf("End crit call");

        if (result == CY_RSLT_SUCCESS)
        {
            printf("Successfully connected to Wi-Fi network '%s'.\n",
                    connect_param.ap_credentials.SSID);

            /* Set the appropriate bit in the init_flag to denote successful
             * Wi-Fi connection, print the assigned IP address.
             */
            init_flag |= WIFI_CONNECTED;
            if (ip_address.version == CY_WCM_IP_VER_V4)
            {
                printf("IPv4 Address Assigned: %s\n\n", ip4addr_ntoa((const ip4_addr_t *) &ip_address.ip.v4));
            }
            else if (ip_address.version == CY_WCM_IP_VER_V6)
            {
                printf("IPv6 Address Assigned: %s\n\n", ip6addr_ntoa((const ip6_addr_t *) &ip_address.ip.v6));
            }
            return EXIT_SUCCESS;
        }

        printf("Connection to Wi-Fi network failed with error code 0x%0X. "
                "Retrying in %d ms...\n", (int)result, WIFI_CONN_RETRY_INTERVAL_MS);
        vTaskDelay(pdMS_TO_TICKS(WIFI_CONN_RETRY_INTERVAL_MS));
    }

    printf("Exceeded maximum Wi-Fi connection attempts\n\n");
    return EXIT_FAILURE;
}

/******************************************************************************
 * Function Name: mqtt_connect
 ******************************************************************************
 * Summary:
 *  Function that initializes the IoT SDK, network stack, and the MQTT client.
 *  Upon successful initialization the MQTT connect operation is performed.
 *
 * Parameters:
 *  void
 *
 * Return:
 *  int : EXIT_SUCCESS on successful completion of MQTT connection,
 *        else EXIT_FAILURE.
 *
 ******************************************************************************/
static int mqtt_connect(void)
{
    /* Variable to indicate status of various operations. */
    int result = EXIT_SUCCESS;

    /* MQTT client identifier string. */
    char mqtt_client_identifier[MQTT_CLIENT_IDENTIFIER_MAX_LEN] = MQTT_CLIENT_IDENTIFIER;

    if (!IotSdk_Init())
    {
        result = EXIT_FAILURE;
    }
    CHECK_RESULT(result, IOT_SDK_INITIALIZED, "IoT SDK initialization failed!\n");
    printf("IoT SDK initialized successfully.\n");

    /* Initialize the Cypress Secure Sockets library. */
    result = IotNetworkSecureSockets_Init();
    CHECK_RESULT(result, NETWORK_STACK_INITIALIZED, "Network stack initialization failed!\n");
    printf("Network stack initialized successfully.\n");

    /* Initialize the MQTT library. */
    result = IotMqtt_Init();
    CHECK_RESULT(result, LIBS_INITIALIZED, "MQTT library initialization failed!\n\n");
    printf("MQTT library initialization successful.\n\n");

    /* Configure the user credentials as a part of MQTT Connect packet */
    if (strlen(MQTT_USERNAME) > 0)
    {
        connectionInfo.pUserName = MQTT_USERNAME;
        connectionInfo.pPassword = MQTT_PASSWORD;
        connectionInfo.userNameLength = sizeof(MQTT_USERNAME) - 1;
        connectionInfo.passwordLength = sizeof(MQTT_PASSWORD) - 1;
    }

    /* Configure the network interface and callback function for disconnection. */
    networkInfo.pNetworkInterface = IOT_NETWORK_INTERFACE_CY_SECURE_SOCKETS;
    networkInfo.disconnectCallback.function = mqtt_disconnect_callback;

    /* Generate a unique client identifier with 'MQTT_CLIENT_IDENTIFIER' string 
     * as a prefix based on `GENERATE_UNIQUE_CLIENT_ID` macro setting.
     */
    #if GENERATE_UNIQUE_CLIENT_ID
    result = mqtt_get_unique_client_identifier(mqtt_client_identifier);
    CHECK_RESULT(result, 0, "Failed to generate unique client identifier for the MQTT client!\n");
    #endif /* GENERATE_UNIQUE_CLIENT_ID */

    /* Set the client identifier buffer and length. */
    connectionInfo.pClientIdentifier = mqtt_client_identifier;
    connectionInfo.clientIdentifierLength = strlen(mqtt_client_identifier);

    printf("MQTT client '%.*s' connecting to MQTT broker '%s'...\n",
           connectionInfo.clientIdentifierLength,
           connectionInfo.pClientIdentifier,
           networkInfo.u.setup.pNetworkServerInfo->pHostName);

    /* Establish the MQTT connection. */
    result = IotMqtt_Connect(&networkInfo, &connectionInfo, MQTT_TIMEOUT_MS, &mqttConnection);
    CHECK_RESULT(result, CONNECTION_ESTABLISHED, "MQTT connection failed with error '%s'!\n\n", 
                 IotMqtt_strerror((IotMqttError_t) result));
    printf("MQTT connection successful.\n\n");
    return EXIT_SUCCESS;
}

/******************************************************************************
 * Function Name: mqtt_disconnect_callback
 ******************************************************************************
 * Summary:
 *  Callback invoked when the MQTT connection is disconnected. The function 
 *  informs the MQTT client task about the MQTT client disconnection using a
 *  message queue only if the disconnection was unexpected.
 *
 * Parameters:
 *  void *pCallbackContext : Information about expected disconnect reason (unused)
 *  IotMqttCallbackParam_t * pCallbackParam : Actual disconnection information 
 *
 * Return:
 *  void
 *
 ******************************************************************************/
static void mqtt_disconnect_callback(void *pCallbackContext,
                                     IotMqttCallbackParam_t *pCallbackParam)
{
    /* Structure that stores the data that will be sent to the MQTT client task
     * using a message queue.
     */
    mqtt_result_t mqtt_connection_status = MQTT_DISCONNECT;

    /* To avoid compiler warnings */
    (void)pCallbackContext;

    /* Inform the MQTT client task about the disconnection except when the MQTT 
     * client has invoked the MQTT disconnect function.
     */
    if (pCallbackParam->u.disconnectReason != IOT_MQTT_DISCONNECT_CALLED)
    {
        printf("MQTT client disconnected unexpectedly!\n");
        
        xQueueOverwrite(mqtt_status_q, &mqtt_connection_status);
    }
}

#if GENERATE_UNIQUE_CLIENT_ID
/******************************************************************************
 * Function Name: mqtt_get_unique_client_identifier
 ******************************************************************************
 * Summary:
 *  Function that generates unique client identifier for the MQTT client by
 *  appending a timestamp to a common prefix (MQTT_CLIENT_IDENTIFIER).
 *
 * Parameters:
 *  char *mqtt_client_identifier : Pointer to the string that stores the 
 *                                 generated unique identifier
 *
 * Return:
 *  int : EXIT_SUCCESS on successful generation of the client identifier,
 *        else EXIT_FAILURE
 *
 ******************************************************************************/
static int mqtt_get_unique_client_identifier(char *mqtt_client_identifier)
{
    int status = EXIT_SUCCESS;

    /* Check for errors from snprintf. */
    if (0 > snprintf(mqtt_client_identifier,
                     MQTT_CLIENT_IDENTIFIER_MAX_LEN,
                     MQTT_CLIENT_IDENTIFIER "%lu",
                     (long unsigned int)IotClock_GetTimeMs()))
    {
        status = EXIT_FAILURE;
    }

    return status;
}
#endif /* GENERATE_UNIQUE_CLIENT_ID */

/******************************************************************************
 * Function Name: cleanup
 ******************************************************************************
 * Summary:
 *  Function that invokes various deinit and cleanup functions for the 
 *  appropriate operations based on the init_flag.
 *
 * Parameters:
 *  void
 *
 * Return:
 *  void
 *
 ******************************************************************************/
static void cleanup(void)
{
    /* Disconnect the MQTT connection if it was established. */
    if (init_flag & CONNECTION_ESTABLISHED)
    {
        printf("Disconnecting from the MQTT Server...\n");
        IotMqtt_Disconnect(mqttConnection, 0);
    }    
    /* Clean up libraries if they were initialized. */
    if (init_flag & LIBS_INITIALIZED)
    {
        IotMqtt_Cleanup();
    }
    /* Clean up the network stack if it was initialized. */
    if (init_flag & NETWORK_STACK_INITIALIZED)
    {
        IotNetworkSecureSockets_Cleanup();
    }
    /* Clean up the IoT SDK. */
    if (init_flag & IOT_SDK_INITIALIZED)
    {
        IotSdk_Cleanup();
    }
    /* Disconnect from Wi-Fi AP. */
    if (init_flag & WIFI_CONNECTED)
    {
        if (cy_wcm_disconnect_ap() == CY_RSLT_SUCCESS)
        {
            printf("Disconnected from the Wi-Fi AP!\n");
        }
        //TODO doesnt restart after this fail
    }
    /* De-initialize the Wi-Fi Connection Manager. */
    if (init_flag & WCM_INITIALIZED)
    {
        cy_wcm_deinit();
    }

    //Hack guarantees to reset the device 1ms = 1000us
    rslt = cyhal_wdt_init(&wdt_obj, 10);
    cyhal_system_delay_us(20000);
}

/* [] END OF FILE */

PSOC6 - src/mqtt_task.h

C Header File
/******************************************************************************
* File Name:   mqtt_task.h
*
* Description: This file is the public interface of mqtt_task.c
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

#ifndef MQTT_TASK_H_
#define MQTT_TASK_H_

#include "FreeRTOS.h"
#include "queue.h"
#include "iot_mqtt.h"

/*******************************************************************************
* Macros
********************************************************************************/
/* Task parameters for MQTT Client Task. */
#define MQTT_CLIENT_TASK_PRIORITY       (2)
#define MQTT_CLIENT_TASK_STACK_SIZE     (1024 * 2)

/*******************************************************************************
* Global Variables
********************************************************************************/
/* Data-type of various MQTT operation results. */
typedef enum
{
    MQTT_SUBSCRIBE_SUCCESS,
    MQTT_SUBSCRIBE_FAILURE,
    MQTT_PUBLISH_SUCCESS,
    MQTT_PUBLISH_FAILURE,
    MQTT_DISCONNECT
} mqtt_result_t;

/*******************************************************************************
 * Extern variables
 ******************************************************************************/
extern IotMqttConnection_t mqttConnection;
extern QueueHandle_t mqtt_status_q;

/*******************************************************************************
* Function Prototypes
********************************************************************************/
void mqtt_client_task(void *pvParameters);

#endif /* MQTT_TASK_H_ */

/* [] END OF FILE */

PSOC6 - src/publisher_task.c

C/C++
/******************************************************************************
* File Name:   publisher_task.c
*
* Description: This file contains the task that initializes the user button
*              GPIO, configures the ISR, and publishes MQTT messages on the 
*              topic 'MQTT_TOPIC_NANODRONE' to control a device that is actuated by the
*              subscriber task. The file also contains the ISR that notifies
*              the publisher task about the new device state to be published.
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

#include "cyhal.h"
#include "cybsp.h"
#include "FreeRTOS.h"

/* Task header files */
#include "publisher_task.h"
#include "mqtt_task.h"
#include "subscriber_task.h"

/* Configuration file for MQTT client */
#include "mqtt_client_config.h"
#include "mqtt_topic_config.h"

/* Middleware libraries */
#include "cy_retarget_io.h"
#include "iot_mqtt.h"


#include "telemetry_queue.h"
#include <string.h>





/******************************************************************************
* Macros
******************************************************************************/
/* The maximum number of times each PUBLISH in this example will be retried. */
#define PUBLISH_RETRY_LIMIT             (10)

/* A PUBLISH message is retried if no response is received within this 
 * time (in milliseconds).
 */
#define PUBLISH_RETRY_MS                (1000)

/******************************************************************************
* Global Variables
*******************************************************************************/
/* FreeRTOS task handle for this task. */
TaskHandle_t publisher_task_handle;

/* Structure to store publish message information. -1 as \0 not needed if length is specified*/
IotMqttPublishInfo_t publishInfo[MQTT_TOPIC_AMOUNT] = {
{
    .qos = (IotMqttQos_t) MQTT_MESSAGES_QOS,
    .pTopicName = MQTT_TOPIC_MAGXVAL,
    .topicNameLength = (sizeof(MQTT_TOPIC_MAGXVAL) - 1),
    .retryMs = PUBLISH_RETRY_MS,
    .retryLimit = PUBLISH_RETRY_LIMIT
},
{
    .qos = (IotMqttQos_t) MQTT_MESSAGES_QOS,
    .pTopicName = MQTT_TOPIC_MAGYVAL,
    .topicNameLength = (sizeof(MQTT_TOPIC_MAGYVAL) - 1),
    .retryMs = PUBLISH_RETRY_MS,
    .retryLimit = PUBLISH_RETRY_LIMIT
},
{
    .qos = (IotMqttQos_t) MQTT_MESSAGES_QOS,
    .pTopicName = MQTT_TOPIC_MAGZVAL,
    .topicNameLength = (sizeof(MQTT_TOPIC_MAGZVAL) - 1),
    .retryMs = PUBLISH_RETRY_MS,
    .retryLimit = PUBLISH_RETRY_LIMIT
},
{
    .qos = (IotMqttQos_t) MQTT_MESSAGES_QOS,
    .pTopicName = MQTT_TOPIC_TEMPVAL,
    .topicNameLength = (sizeof(MQTT_TOPIC_TEMPVAL) - 1),
    .retryMs = PUBLISH_RETRY_MS,
    .retryLimit = PUBLISH_RETRY_LIMIT
},
};

IotMqttPublishInfo_t publishLog =
{
    .qos = (IotMqttQos_t) MQTT_MESSAGES_QOS,
    .pTopicName = MQTT_TOPIC_LOG,
    .topicNameLength = (sizeof(MQTT_TOPIC_LOG) - 1),
    .retryMs = PUBLISH_RETRY_MS,
    .retryLimit = PUBLISH_RETRY_LIMIT
};


extern QueueHandle_t telemetry_queue;

uint8_t message[TELEMETRY_MESSAGE_SIZE];


/******************************************************************************
 * Function Name: publisher_task
 ******************************************************************************
 * Summary:
 *  Task that handles initialization of the TELEMETRY message queue,
 *  and publishing of MQTT messages to control the device that is actuated
 *  by the subscriber task.
 *
 * Parameters:
 *  void *pvParameters : Task parameter defined during task creation (unused)
 *
 * Return:
 *  void
 *
 ******************************************************************************/
void publisher_task(void *pvParameters)
{
    /* Status variable */
    int result;

    /* Status of MQTT publish operation that will be communicated to MQTT 
     * client task using a message queue in case of failure during publish.
     */
    mqtt_result_t mqtt_publish_status = MQTT_PUBLISH_FAILURE;

    /* To avoid compiler warnings */
    (void)pvParameters;

    cyhal_gpio_init(CYBSP_USER_LED, CYHAL_GPIO_DIR_OUTPUT, CYHAL_GPIO_DRIVE_PULLUP,
                    CYBSP_LED_STATE_OFF);


    initTelemetryQueue();
    printf("TELEMETRY Message Queue created\n\n");



    while (true)
    {


    	  for( ;; ) {

    	    if(xQueueReceive(telemetry_queue, message, portMAX_DELAY ))     {
    	      cyhal_gpio_toggle(CYBSP_USER_LED);
    	      printf("%s\n",message);
    	      uint8_t* msgptr=message;
    	      //If received message starts with MQTT_UART_VALUE_DELIMITER it is a log message from the device eg :ERROR opening
    	      if(msgptr[0] == (uint8_t) MQTT_UART_VALUE_DELIMITER)
    	      {
    	    	  //get rid of traiing delimiter
    	    	  msgptr++;
    	    	  publishLog.pPayload = msgptr;
    	    	  //-1 as trailing delimiter removed
    	    	  publishLog.payloadLength = TELEMETRY_MESSAGE_SIZE-1;

    	    	  printf("Publishing '%.*s' on the topic '%s'\n\n",
    	    	  							  publishLog.payloadLength,
    	    	  							  (char *)publishLog.pPayload,
    	    	  							  publishLog.pTopicName);

    	    	  /* Publish the MQTT message with the configured settings. */
				  result = IotMqtt_PublishSync(mqttConnection,
						  &publishLog,
						  0,
						  MQTT_TIMEOUT_MS);

				  if (result != IOT_MQTT_SUCCESS)
				  {
					  /* Inform the MQTT client task about the publish failure and suspend
					   * the task for it to be killed by the MQTT client task later.
					   */
					  printf("MQTT Publish failed with error '%s'.\n\n",
							  IotMqtt_strerror((IotMqttError_t) result));
					  xQueueOverwrite(mqtt_status_q, &mqtt_publish_status);
					  vTaskSuspend( NULL );
				  }

    	      }else{
				  //strtok has issues with pointer without length -> strtok not used
				  //Splitting uint8 list by delimiter and publishing to mqtt
				  int bytecount=0;
				  int topiccount=0;
				  do{
					  int stringEnd=0;
					  while(msgptr[stringEnd] != (uint8_t) MQTT_UART_VALUE_DELIMITER && msgptr[stringEnd] != (uint8_t) MQTT_UART_END_DELIMITER)
					  {
						  stringEnd++;
						  bytecount++;
					  }

					  publishInfo[topiccount].pPayload = msgptr;
					  publishInfo[topiccount].payloadLength = stringEnd;

					  printf("Publishing '%.*s' on the topic '%s'\n\n",
							  publishInfo[topiccount].payloadLength,
							  (char *)publishInfo[topiccount].pPayload,
							  publishInfo[topiccount].pTopicName);


		//    	      break; // todo: remove, this is to avoid spending messages

					  /* Publish the MQTT message with the configured settings. */
					  result = IotMqtt_PublishSync(mqttConnection,
							  &publishInfo[topiccount],
							  0,
							  MQTT_TIMEOUT_MS);

					  if (result != IOT_MQTT_SUCCESS)
					  {
						  /* Inform the MQTT client task about the publish failure and suspend
						   * the task for it to be killed by the MQTT client task later.
						   */
						  printf("MQTT Publish failed with error '%s'.\n\n",
								  IotMqtt_strerror((IotMqttError_t) result));
						  xQueueOverwrite(mqtt_status_q, &mqtt_publish_status);
						  vTaskSuspend( NULL );
					  }
					  //PointerToLastDelimiter
					  printf("Test");
					  printf("%s\n",msgptr);
					  printf("%d\n",stringEnd);

					  msgptr+=stringEnd;

					  if(*msgptr == (uint8_t) MQTT_UART_END_DELIMITER)
					  {
						  break;
					  }
					  //move pointer to start of next string
					  msgptr++;
					  bytecount++;
					  topiccount++;
				  }while(bytecount<TELEMETRY_MESSAGE_SIZE && topiccount<MQTT_TOPIC_AMOUNT);
    	      }
    	      cyhal_gpio_toggle(CYBSP_USER_LED);

    	    }

    	  } // end for


    }
}

/******************************************************************************
 * Function Name: publisher_cleanup
 ******************************************************************************
 * Summary:
 *  Cleanup function for the publisher task
 *
 * Parameters:
 *  void
 *
 * Return:
 *  void
 *
 ******************************************************************************/
void publisher_cleanup(void)
{
}

/* [] END OF FILE */

PSOC6 - src/publisher_task.h

C Header File
/******************************************************************************
* File Name:   publisher_task.h
*
* Description: This file is the public interface of publisher_task.c
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

#ifndef PUBLISHER_TASK_H_
#define PUBLISHER_TASK_H_

#include "FreeRTOS.h"
#include "task.h"

/*******************************************************************************
* Macros
********************************************************************************/
/* Task parameters for Button Task. */
#define PUBLISHER_TASK_PRIORITY               (2)
#define PUBLISHER_TASK_STACK_SIZE             (1024 * 1)

/*******************************************************************************
* Extern Variables
********************************************************************************/
extern TaskHandle_t publisher_task_handle;

/*******************************************************************************
* Function Prototypes
********************************************************************************/
void publisher_task(void *pvParameters);
void publisher_cleanup(void);

#endif /* PUBLISHER_TASK_H_ */

/* [] END OF FILE */

PSOC6 - src/subscriber_task.c

C/C++
/******************************************************************************
* File Name:   subscriber_task.c
*
* Description: Print MQTT message to UART
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

#include "cyhal.h"
#include "cybsp.h"
#include "string.h"
#include "FreeRTOS.h"

/* Task header files */
#include "subscriber_task.h"
#include "mqtt_task.h"
#include "uart_task.h"

/* Configuration file for MQTT client */
#include "mqtt_client_config.h"
#include "mqtt_topic_config.h"

/* Middleware libraries */
#include "cy_retarget_io.h"
#include "iot_mqtt.h"

#include "telemetry_queue.h"

/******************************************************************************
* Macros
******************************************************************************/
/* The number of MQTT topics to be subscribed to. */
#define SUBSCRIPTION_COUNT          (1)

/******************************************************************************
* Function Prototypes
*******************************************************************************/
static void mqtt_subscription_callback(void *pCallbackContext,
                                       IotMqttCallbackParam_t *pPublishInfo);

/******************************************************************************
* Global Variables
*******************************************************************************/
/* Task handle for this task. */
TaskHandle_t subscriber_task_handle;


/* Configure the subscription information structure. */
IotMqttSubscription_t subscribeInfo =
{
    .qos = (IotMqttQos_t) MQTT_MESSAGES_QOS,
    .pTopicFilter = MQTT_TOPIC_CONTROL,
    .topicFilterLength = (sizeof(MQTT_TOPIC_CONTROL) - 1),
    /* Configure the callback function to handle incoming MQTT messages */
    .callback.function = mqtt_subscription_callback
};


uint8_t message[TELEMETRY_MESSAGE_SIZE];
int message_size=0;

#define PAYLOAD_GOOD                    (0x00lu)
#define PAYLOAD_BAD                   (0x01lu)

/******************************************************************************
 * Function Name: subscriber_task
 ******************************************************************************
 * Summary:
 *  Task that sets up the user LED GPIO, subscribes to topic - 'MQTT_TOPIC',
 *  and controls the user LED based on the received task notification.
 *
 * Parameters:
 *  void *pvParameters : Task parameter defined during task creation (unused)
 *
 * Return:
 *  void
 *
 ******************************************************************************/
void subscriber_task(void *pvParameters)
{
    /* Status variable */
    int result = EXIT_SUCCESS;

    uint32_t received_payload_status;

    /* Status of MQTT subscribe operation that will be communicated to MQTT 
     * client task using a message queue in case of failure in subscription.
     */
    mqtt_result_t mqtt_subscribe_status = MQTT_SUBSCRIBE_FAILURE;

    /* To avoid compiler warnings */
    (void)pvParameters;


    /* Subscribe with the configured parameters. */
    result = IotMqtt_SubscribeSync(mqttConnection,
                                   &subscribeInfo,
                                   SUBSCRIPTION_COUNT,
                                   0,
                                   MQTT_TIMEOUT_MS);
    if (result != EXIT_SUCCESS)
    {
        /* Notify the MQTT client task about the subscription failure and  
         * suspend the task for it to be killed by the MQTT client task later.
         */
        printf("MQTT Subscribe failed with error '%s'.\n\n",
               IotMqtt_strerror((IotMqttError_t) result));
        xQueueOverwrite(mqtt_status_q, &mqtt_subscribe_status);
        vTaskSuspend( NULL );
    }

    printf("MQTT client subscribed to the topic '%.*s' successfully.\n\n",
           subscribeInfo.topicFilterLength, subscribeInfo.pTopicFilter);

    while (true)
    {
        /* Block till a notification is received from the subscriber callback. */
        xTaskNotifyWait(0, 0, &received_payload_status, portMAX_DELAY);

        // you can handle payloads here
        if (received_payload_status == PAYLOAD_GOOD) {
        	// todo handle payload
        	//printf("%.*s\n",message_size,message);
        }

    }
}

/******************************************************************************
 * Function Name: mqtt_subscription_callback
 ******************************************************************************
 * Summary:
 *  Callback to handle incoming MQTT messages. This callback prints the 
 *  contents of an incoming message and notifies the subscriber task with the  
 *  LED state as per the received message.
 *
 * Parameters:
 *  void *pCallbackContext : Parameter defined during MQTT Subscribe operation
 *                           using the IotMqttCallbackInfo_t.pCallbackContext
 *                           member (unused)
 *  IotMqttCallbackParam_t * pPublishInfo : Information about the incoming 
 *                                          MQTT PUBLISH message passed by
 *                                          the MQTT library.
 *
 * Return:
 *  void
 *
 ******************************************************************************/
static void mqtt_subscription_callback(void *pCallbackContext,
                                       IotMqttCallbackParam_t *pPublishInfo)
{
    /* Received MQTT message */
    const char *pPayload = pPublishInfo->u.message.info.pPayload;
    /* LED state that should be sent to LED task depending on received message. */
    uint32_t nanodrone_payload_state = PAYLOAD_GOOD;

    /* To avoid compiler warnings */
    (void) pCallbackContext;

    memcpy(message, pPayload, TELEMETRY_MESSAGE_SIZE);
    message_size = pPublishInfo->u.message.info.payloadLength;

    //It is important to use the set size as 16 characters are allowed and there is no terminating \0 so strlen doesn't work either
    /* Print information about the incoming PUBLISH message. */
    printf("Incoming MQTT message received:\n"
           "Subscription topic filter: %.*s\n"
           "Published topic name: %.*s\n"
           "Published QoS: %d\n"
           "Published payload: %.*s\n\n",
           pPublishInfo->u.message.topicFilterLength,
           pPublishInfo->u.message.pTopicFilter,
           pPublishInfo->u.message.info.topicNameLength,
           pPublishInfo->u.message.info.pTopicName,
           pPublishInfo->u.message.info.qos,
           pPublishInfo->u.message.info.payloadLength,
           pPayload);

    //printf("Subscribe %.*s\n",pPublishInfo->u.message.info.payloadLength,pPayload);
    Cy_SCB_UART_Transmit(UART_SCB,pPayload,message_size,&uartContext);


    /* Notify the subscriber task about the received LED control message. */
    xTaskNotify(subscriber_task_handle, nanodrone_payload_state, eSetValueWithoutOverwrite);
}

/******************************************************************************
 * Function Name: mqtt_unsubscribe
 ******************************************************************************
 * Summary:
 *  Function that unsubscribes from the topic specified by the macro 
 *  'MQTT_TOPIC'. This operation is called during cleanup by the MQTT client 
 *  task.
 *
 * Parameters:
 *  void 
 *
 * Return:
 *  void 
 *
 ******************************************************************************/
void mqtt_unsubscribe(void)
{
    IotMqttError_t result = IotMqtt_UnsubscribeSync(mqttConnection,
                                                    &subscribeInfo,
                                                    SUBSCRIPTION_COUNT,
                                                    0,
                                                    MQTT_TIMEOUT_MS);
    if (result != IOT_MQTT_SUCCESS)
    {
        printf("MQTT Unsubscribe operation failed with error '%s'!\n",
               IotMqtt_strerror(result));
    }
}

/* [] END OF FILE */

PSOC6 - src/subscriber_task.h

C Header File
/******************************************************************************
* File Name:   subscriber_task.h
*
* Description: This file is the public interface of subscriber_task.c
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

#ifndef SUBSCRIBER_TASK_H_
#define SUBSCRIBER_TASK_H_

#include "FreeRTOS.h"
#include "task.h"

/*******************************************************************************
* Macros
********************************************************************************/
/* Task parameters for Subscriber Task. */
#define SUBSCRIBER_TASK_PRIORITY           (2)
#define SUBSCRIBER_TASK_STACK_SIZE         (1024 * 1)


/*******************************************************************************
* Extern Variables
********************************************************************************/
extern TaskHandle_t subscriber_task_handle;
extern uint32_t current_device_state;

/*******************************************************************************
* Function Prototypes
********************************************************************************/
void subscriber_task(void *pvParameters);
void mqtt_unsubscribe(void);

#endif /* SUBSCRIBER_TASK_H_ */

/* [] END OF FILE */

PSOC6 - src/telemetry_queue.c

C/C++
/*
 * telemetry_queue.c
 *
 *  Created on: 13 mrt. 2021
 *      Author: jancu
 */

#include "telemetry_queue.h"


#include "FreeRTOS.h"
#include "queue.h"

QueueHandle_t telemetry_queue = NULL;


void initTelemetryQueue() {
  telemetry_queue =  xQueueCreate( 10, TELEMETRY_MESSAGE_SIZE );
}

PSOC6 - src/telemetry_queue.h

C Header File
/*
 * telemetry_queue.h
 *
 *  Created on: 13 mrt. 2021
 *      Author: jancu
 */

#ifndef TELEMETRY_QUEUE_H_
#define TELEMETRY_QUEUE_H_


#define TELEMETRY_MESSAGE_SIZE 32

void initTelemetryQueue();

#endif /* TELEMETRY_QUEUE_H_ */

PSOC6 - src/uart_task.c

C/C++
/*
 * uart_task.c
 *
 *  Created on: 13 mrt. 2021
 *      Author: jancu
 */

#include "cy_pdl.h"
#include "cyhal.h"

/* FreeRTOS header files */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"

/* Task header files */
#include "uart_task.h"

#include "telemetry_queue.h"

#include "cybsp.h"  // for the user led only

/* Stores the handle of the task that will be notified when the
transmission is complete. */
volatile TaskHandle_t xTaskToNotify_UART;

/* The index within the target task's array of task notifications
to use. */
const UBaseType_t xArrayIndex = 1;


uint8_t rxBuffer[UART_BUFFER_SIZE];

/*duplicate? Allocate context for UART operation */
//cy_stc_scb_uart_context_t uartContext;

void UART_receive();


extern QueueHandle_t telemetry_queue;


/******************************************************************************
 * Function Name: uart_task
 ******************************************************************************
 * Summary:
 *  Task for handling initialization & connection of UART.
 *
 * Parameters:
 *  void *pvParameters : Task parameter defined during task creation (unused)
 *
 * Return:
 *  void
 *
 ******************************************************************************/
void uart_task(void *pvParameters) {

  /* To avoid compiler warnings */
  (void)pvParameters;
  uint32_t ulNotificationValue;
  xTaskToNotify_UART = NULL;

  while (true) {

    /* Start the receiving from UART. */
    UART_receive();
    /* Wait to be notified that the receive is complete.  Note
        the first parameter is pdTRUE, which has the effect of clearing
        the task's notification value back to 0, making the notification
        value act like a binary (rather than a counting) semaphore.  */
    ulNotificationValue = ulTaskNotifyTake(pdTRUE, portMAX_DELAY  );


    if( ulNotificationValue == 1 )
    {
      /* Blocking wait until buffer is full */
      // in this example, it will never handle because the UART interrupt fires exaxtly when the buffer is full
      while (0UL != (CY_SCB_UART_RECEIVE_ACTIVE & Cy_SCB_UART_GetReceiveStatus(UART_SCB, &uartContext))) {}
      /* Handle received data */

      if(telemetry_queue) { // queue needs to be generated}
        if( xQueueSend( telemetry_queue,
                       ( void * ) rxBuffer,
                       ( TickType_t ) 10 ) != pdPASS )
        {
            /* Failed to post the message, even after 10 ticks. */
          CY_ASSERT_L3(!0);
        }
      }

    }
  }
}

void initUART() {
  // https://cypresssemiconductorco.github.io/psoc6pdl/pdl_api_reference_manual/html/group__group__scb__uart.html


  /* Populate configuration structure */
  const cy_stc_scb_uart_config_t uartConfig = {
      .uartMode                   = CY_SCB_UART_STANDARD,
      .enableMutliProcessorMode   = false,
      .smartCardRetryOnNack       = false,
      .irdaInvertRx               = false,
      .irdaEnableLowPowerReceiver = false,
      .oversample                 = UART_OVERSAMPLE,
      .enableMsbFirst             = false,
      .dataWidth                  = 8UL,
      .parity                     = CY_SCB_UART_PARITY_NONE,
      .stopBits                   = CY_SCB_UART_STOP_BITS_1,
      .enableInputFilter          = false,
      .breakWidth                 = 11UL,
      .dropOnFrameError           = false,
      .dropOnParityError          = false,
      .receiverAddress            = 0UL,
      .receiverAddressMask        = 0UL,
      .acceptAddrInFifo           = false,
      .enableCts                  = false,
      .ctsPolarity                = CY_SCB_UART_ACTIVE_LOW,
      .rtsRxFifoLevel             = 0UL,
      .rtsPolarity                = CY_SCB_UART_ACTIVE_LOW,
      .rxFifoTriggerLevel  = 0UL,
      .rxFifoIntEnableMask = 0UL,
      .txFifoTriggerLevel  = 0UL,
      .txFifoIntEnableMask = 0UL,
  };
  /* Configure UART to operate */
  (void) Cy_SCB_UART_Init(UART_SCB, &uartConfig, &uartContext);

  /* Assign pins for UART on SCBx */

  /* Connect SCB UART function to pins */
  Cy_GPIO_SetHSIOM(UART_PORT, UART_RX_NUM, UART_RX_PIN);
  Cy_GPIO_SetHSIOM(UART_PORT, UART_TX_NUM, UART_TX_PIN);
  /* Configure pins for UART operation */
  // jc: HIGHZ is correct for UART. But in the design here, the input is "patch-wired" to another controller.
  Cy_GPIO_SetDrivemode(UART_PORT, UART_RX_NUM, CY_GPIO_DM_HIGHZ);
  //Cy_GPIO_SetDrivemode(UART_PORT, UART_RX_NUM, CY_GPIO_DM_PULLUP);
  Cy_GPIO_SetDrivemode(UART_PORT, UART_TX_NUM, CY_GPIO_DM_STRONG_IN_OFF);

  /* Assign divider type and number for UART */

  /* Connect assigned divider to be a clock source for UART */
  Cy_SysClk_PeriphAssignDivider(UART_CLOCK, UART_CLK_DIV_TYPE, UART_CLK_DIV_NUMBER);


  // set baud
  Cy_SysClk_PeriphSetDivider   (UART_CLK_DIV_TYPE, UART_CLK_DIV_NUMBER, UART_DIVISION);
  Cy_SysClk_PeriphEnableDivider(UART_CLK_DIV_TYPE, UART_CLK_DIV_NUMBER);

  /* Populate configuration structure (code specific for CM4) */
  cy_stc_sysint_t uartIntrConfig =
  {
      .intrSrc      = UART_INTR_NUM,
      .intrPriority = UART_INTR_PRIORITY,
  };
  /* Hook interrupt service routine and enable interrupt */
  (void) Cy_SysInt_Init(&uartIntrConfig, &UART_Isr);
  NVIC_EnableIRQ(UART_INTR_NUM);

  /* Enable UART to operate */
  Cy_SCB_UART_Enable(UART_SCB);
}

// UART interrupt handler
void UART_Isr() {
	Cy_SCB_UART_Interrupt(UART_SCB, &uartContext);

//	if (uartContext.rxStatus != 32) { // not a complete receive
//		return;
//	}


	BaseType_t xHigherPriorityTaskWoken = pdFALSE;

	if( xTaskToNotify_UART != NULL ) {

		/* Notify the task that the receive is complete. */
		vTaskNotifyGiveFromISR( xTaskToNotify_UART, &xHigherPriorityTaskWoken );
		/* There are no receive in progress, so no tasks to notify. */
		xTaskToNotify_UART = NULL;

		/* If xHigherPriorityTaskWoken is now set to pdTRUE then a
  context switch should be performed to ensure the interrupt
  returns directly to the highest priority task.  The macro used
  for this purpose is dependent on the port in use and may be
  called portEND_SWITCHING_ISR(). */
		portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
	}
}

// UART activate a receive with interrupt. Wait for ever for UART_BUFFER_SIZE bytes
void UART_receive() {
  /* At this point xTaskToNotify should be NULL as no receive
  is in progress.  A mutex can be used to guard access to the
  peripheral if necessary. */
  configASSERT( xTaskToNotify_UART == NULL );

  /* Store the handle of the calling task. */
  xTaskToNotify_UART = xTaskGetCurrentTaskHandle();

  /* Start receive operation (do not check status) */
  (void) Cy_SCB_UART_Receive(UART_SCB, rxBuffer, sizeof(rxBuffer), &uartContext);
}

PSOC6 - src/uart_task.h

C Header File
/*
 * uart_task.h
 *
 *  Created on: 13 mrt. 2021
 *      Author: jancu
 */

#ifndef UART_TASK_H_
#define UART_TASK_H_

#include "uart_config.h"

#include "FreeRTOS.h"

/*******************************************************************************
* Macros
********************************************************************************/
/* Task parameters for UART Task. */
#define UART_TASK_PRIORITY       (2)
#define UART_TASK_STACK_SIZE     (1024 * 3)



/* dependent on the BAUD used */

// jc 20210313: 9600 baud needs a 16 bit divider
/* UART desired baud rate is 9600 bps
 * The UART baud rate = (clk_scb / Oversample).
 * For clk_peri = 100 MHz, select divider value 864 and get SCB clock = (100 MHz / 864) = 115.7 kHz.
 * Select Oversample = 12. These setting results UART data rate = 115.7 kHz / 12 = 9645 bps.
 * For clk_peri = 100 MHz, select divider value 72 and get SCB clock = (100 MHz / 72) = 1,389 MHz.
 * Select Oversample = 12. These setting results UART data rate = 1,389 MHz / 12 = 115750 bps.
 * Choosing 9600 as it is less likely to transmit wrong charcter especially if baud rate isn't exactly the same
 */

#define UART_CLK_DIV_TYPE     (CY_SYSCLK_DIV_16_BIT)
#define UART_CLK_DIV_NUMBER   (UART_DIVIDER_NUMBER)
#define UART_OVERSAMPLE 12UL
#define UART_DIVISION 863UL


/* application dependent UART settings */
#define UART_BUFFER_SIZE 32




/*******************************************************************************
* Function Prototypes
********************************************************************************/
void uart_task(void *pvParameters);

void initUART();
void UART_Isr();

/*Variables*/
/*Allocate context for UART operation */
cy_stc_scb_uart_context_t uartContext;

#endif /* UART_TASK_H_ */

PSOC6 - headers/FreeRTOSConfig.h

C Header File
/*
 * FreeRTOS Kernel V10.0.1
 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * http://www.FreeRTOS.org
 * http://aws.amazon.com/freertos
 *
 * 1 tab == 4 spaces!
*/

#ifndef FREERTOS_CONFIG_H
#define FREERTOS_CONFIG_H

/*-----------------------------------------------------------
 * Application specific definitions.
 *
 * These definitions should be adjusted for your particular hardware and
 * application requirements.
 *
 * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE
 * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE.
 *
 * See http://www.freertos.org/a00110.html.
 *----------------------------------------------------------*/

#include "cy_syslib.h"

#define configUSE_PREEMPTION                    1
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0
#define configUSE_TICKLESS_IDLE                 1
#define configCPU_CLOCK_HZ                      SystemCoreClock
#define configTICK_RATE_HZ                      1000u
#define configMAX_PRIORITIES                    7
#define configMINIMAL_STACK_SIZE                128
#define configMAX_TASK_NAME_LEN                 32
#define configUSE_16_BIT_TICKS                  0
#define configIDLE_SHOULD_YIELD                 1
#define configUSE_TASK_NOTIFICATIONS            1
#define configUSE_MUTEXES                       1
#define configUSE_RECURSIVE_MUTEXES             1
#define configUSE_COUNTING_SEMAPHORES           1
#define configQUEUE_REGISTRY_SIZE               10
#define configUSE_QUEUE_SETS                    0
#define configUSE_TIME_SLICING                  0
#define configUSE_NEWLIB_REENTRANT              0
#define configENABLE_BACKWARD_COMPATIBILITY     0
#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 5

/* Memory allocation related definitions. */
#define configSUPPORT_STATIC_ALLOCATION         1
#define configSUPPORT_DYNAMIC_ALLOCATION        1
#define configTOTAL_HEAP_SIZE                   10240
#define configAPPLICATION_ALLOCATED_HEAP        0

/* Hook function related definitions. */
#define configUSE_IDLE_HOOK                     0
#define configUSE_TICK_HOOK                     0
#define configCHECK_FOR_STACK_OVERFLOW          2
#define configUSE_MALLOC_FAILED_HOOK            0
#define configUSE_DAEMON_TASK_STARTUP_HOOK      0

/* Run time and task stats gathering related definitions. */
#define configGENERATE_RUN_TIME_STATS           0
#define configUSE_TRACE_FACILITY                0
#define configUSE_STATS_FORMATTING_FUNCTIONS    0

/* Co-routine related definitions. */
#define configUSE_CO_ROUTINES                   0
#define configMAX_CO_ROUTINE_PRIORITIES         1

/* Software timer related definitions. */
#define configUSE_TIMERS                        1
#define configTIMER_TASK_PRIORITY               configMAX_PRIORITIES /* Updated */
#define configTIMER_QUEUE_LENGTH                10
#define configTIMER_TASK_STACK_DEPTH            configMINIMAL_STACK_SIZE

/* FreeRTOS MPU specific definitions. */
#define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0

/*
Interrupt nesting behavior configuration.
This is explained here: http://www.freertos.org/a00110.html

Priorities are controlled by two macros:
- configKERNEL_INTERRUPT_PRIORITY determines the priority of the RTOS daemon task
- configMAX_API_CALL_INTERRUPT_PRIORITY dictates the priority of ISRs that make API calls

Notes:
1. Interrupts that do not call API functions should be >= configKERNEL_INTERRUPT_PRIORITY
   and will nest.
2. Interrupts that call API functions must have priority between KERNEL_INTERRUPT_PRIORITY
   and MAX_API_CALL_INTERRUPT_PRIORITY (inclusive).
3. Interrupts running above MAX_API_CALL_INTERRUPT_PRIORITY are never delayed by the OS.
*/
/*
PSoC 6 __NVIC_PRIO_BITS = 3

0 (high)
1           MAX_API_CALL_INTERRUPT_PRIORITY 001xxxxx (0x3F)
2
3
4
5
6
7 (low)     KERNEL_INTERRUPT_PRIORITY       111xxxxx (0xFF)

!!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!!
See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html

If you call a FreeRTOS API function from an interrupt with priority higher than
MAX_API_CALL_INTERRUPT_PRIORITY FreeRTOS will generate an exception. If you need
to call a FreeRTOS API function from your system's highest priority interrupt
you must reduce all interrupt priorities to MAX_API_CALL_INTERRUPT_PRIORITY or
lower.

If your system pipe (IPC) interrupt priority is less than or equal to
MAX_API_CALL_INTERRUPT_PRIORITY then care must be taken with code that writes to
flash (including the Flash/BLE/Emulated EEPROM/Bootloader drivers from Cypress
PDL). The duration of critical sections must be kept short - see the
Configuration Considerations section of the flash driver in the PDL API
Reference.

*/

/* Put KERNEL_INTERRUPT_PRIORITY in top __NVIC_PRIO_BITS bits of CM4 register */
#define configKERNEL_INTERRUPT_PRIORITY         0xFF
/*
Put MAX_SYSCALL_INTERRUPT_PRIORITY in top __NVIC_PRIO_BITS bits of CM4 register
NOTE For IAR compiler make sure that changes of this macro is reflected in
file portable\IAR\CM4F\portasm.s in PendSV_Handler: routine
*/
#define configMAX_SYSCALL_INTERRUPT_PRIORITY    0x3F
/* configMAX_API_CALL_INTERRUPT_PRIORITY is a new name for configMAX_SYSCALL_INTERRUPT_PRIORITY
 that is used by newer ports only. The two are equivalent. */
#define configMAX_API_CALL_INTERRUPT_PRIORITY   configMAX_SYSCALL_INTERRUPT_PRIORITY


/* Set the following definitions to 1 to include the API function, or zero
to exclude the API function. */
#define INCLUDE_vTaskPrioritySet                1
#define INCLUDE_uxTaskPriorityGet               1
#define INCLUDE_vTaskDelete                     1
#define INCLUDE_vTaskSuspend                    1
#define INCLUDE_xResumeFromISR                  1
#define INCLUDE_vTaskDelayUntil                 1
#define INCLUDE_vTaskDelay                      1
#define INCLUDE_xTaskGetSchedulerState          1
#define INCLUDE_xTaskGetCurrentTaskHandle       1
#define INCLUDE_uxTaskGetStackHighWaterMark     0
#define INCLUDE_xTaskGetIdleTaskHandle          0
#define INCLUDE_eTaskGetState                   0
#define INCLUDE_xEventGroupSetBitFromISR        1
#define INCLUDE_xTimerPendFunctionCall          0
#define INCLUDE_xTaskAbortDelay                 0
#define INCLUDE_xTaskGetHandle                  0
#define INCLUDE_xTaskResumeFromISR              1

/* Normal assert() semantics without relying on the provision of an assert.h
header file. */
#define configASSERT( x ) if( ( x ) == 0 ) { taskDISABLE_INTERRUPTS(); for( ;; ); }

/* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS
standard names - or at least those used in the unmodified vector table. */
#define vPortSVCHandler     SVC_Handler
#define xPortPendSVHandler  PendSV_Handler
#define xPortSysTickHandler SysTick_Handler

/* Dynamic Memory Allocation Schemes */
#define HEAP_ALLOCATION_TYPE1                       (1)     /* heap_1.c*/
#define HEAP_ALLOCATION_TYPE2                       (2)     /* heap_2.c*/
#define HEAP_ALLOCATION_TYPE3                       (3)     /* heap_3.c*/
#define HEAP_ALLOCATION_TYPE4                       (4)     /* heap_4.c*/
#define HEAP_ALLOCATION_TYPE5                       (5)     /* heap_5.c*/
#define NO_HEAP_ALLOCATION                          (0)

#define configHEAP_ALLOCATION_SCHEME                (HEAP_ALLOCATION_TYPE3) /* Updated */

#endif /* FREERTOS_CONFIG_H */

PSOC6 - headers/iot_config.h

C Header File
/*
 * Copyright 2020-2021, Cypress Semiconductor Corporation or a subsidiary of
 * Cypress Semiconductor Corporation. All Rights Reserved.
 *
 * This software, including source code, documentation and related
 * materials ("Software"), is owned by Cypress Semiconductor Corporation
 * or one of its subsidiaries ("Cypress") and is protected by and subject to
 * worldwide patent protection (United States and foreign),
 * United States copyright laws and international treaty provisions.
 * Therefore, you may use this Software only as provided in the license
 * agreement accompanying the software package from which you
 * obtained this Software ("EULA").
 * If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
 * non-transferable license to copy, modify, and compile the Software
 * source code solely for use in connection with Cypress's
 * integrated circuit products. Any reproduction, modification, translation,
 * compilation, or representation of this Software except as specified
 * above is prohibited without the express written permission of Cypress.
 *
 * Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
 * reserves the right to make changes to the Software without notice. Cypress
 * does not assume any liability arising out of the application or use of the
 * Software or any product or circuit described in the Software. Cypress does
 * not authorize its products for use in any products where a malfunction or
 * failure of the Cypress product may reasonably be expected to result in
 * significant property damage, injury or death ("High Risk Product"). By
 * including Cypress's product in a High Risk Product, the manufacturer
 * of such system or application assumes all risk of such use and in doing
 * so agrees to indemnify Cypress against all liability.
 */
/*
 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * @file iot_config.h
 * @brief This file contains configuration settings for the MQTT Library.
 */

#ifndef IOT_CONFIG_H_
#define IOT_CONFIG_H_

#include "cy_iot_platform_types.h"

#include <assert.h>
#include <stdlib.h>

/**
 * @addtogroup mqtt_cyport_config
 * @{
 */
/**
 * @brief Default thread priority for the threads created by AWS IoT Device SDK.
 */
#define IOT_THREAD_DEFAULT_PRIORITY                 ( CY_RTOS_PRIORITY_NORMAL )
/**
 * @brief Default thread stack size for the threads created by AWS IoT Device SDK.
 * The stack size may be tuned to suit the desired use case.
 */
#define IOT_THREAD_DEFAULT_STACK_SIZE               ( 2048 )

/**
 * @brief Default wait time (in milliseconds) to receive keep-alive responses from the MQTT broker. This value may be adjusted to suit the use case and network environment.
 * Refer aws-iot-device-sdk-embedded-C/doc/lib/mqtt.txt for additional info.
 */
#define IOT_MQTT_RESPONSE_WAIT_MS                   ( 5000U )

/**
 * \cond
 * @brief Macros to enable/disable asserts in the IoT Device SDK library.
 * Asserts are disabled by default; to enable asserts, modify these macros to 1.
 */
#define IOT_CONTAINERS_ENABLE_ASSERTS               ( 0 )
#define IOT_MQTT_ENABLE_ASSERTS                     ( 0 )
#define IOT_TASKPOOL_ENABLE_ASSERTS                 ( 0 )
#define AWS_IOT_SHADOW_ENABLE_ASSERTS               ( 0 )
#define AWS_IOT_DEFENDER_ENABLE_ASSERTS             ( 0 )
#define AWS_IOT_JOBS_ENABLE_ASSERTS                 ( 0 )
/**
 * \endcond
 */

/**
 * @brief Insert program diagnostics. This function should have the same signature as [assert](https://pubs.opengroup.org/onlinepubs/9699919799/functions/assert.html)
 */
#if (IOT_CONTAINERS_ENABLE_ASSERTS == 1) || (IOT_MQTT_ENABLE_ASSERTS == 1) || (IOT_TASKPOOL_ENABLE_ASSERTS == 1) || (AWS_IOT_SHADOW_ENABLE_ASSERTS == 1) || (AWS_IOT_DEFENDER_ENABLE_ASSERTS == 1) || (AWS_IOT_JOBS_ENABLE_ASSERTS == 1)
#define Iot_DefaultAssert                           assert
#else
#define Iot_DefaultAssert
#endif

/**
 * @brief Memory allocation. This function should have the same signature as [malloc](http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html)
 */
#define Iot_DefaultMalloc                           malloc

/**
 * @brief Free memory. This function should have the same signature as [free](http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html)
 */
#define Iot_DefaultFree                             free

/**
 * \cond
 * @brief Library logging configuration. Configure the below macros to enable/disable debug logs in the library
 * Refer aws-iot-device-sdk-embedded-C/libraries/standard/common/include/iot_logging.h
 * for supported log levels.
 */
#define IOT_LOG_LEVEL_GLOBAL                        IOT_LOG_ERROR
#define IOT_LOG_LEVEL_DEMO                          IOT_LOG_ERROR
#define IOT_LOG_LEVEL_PLATFORM                      IOT_LOG_ERROR
#define IOT_LOG_LEVEL_NETWORK                       IOT_LOG_ERROR
#define IOT_LOG_LEVEL_TASKPOOL                      IOT_LOG_ERROR
#define IOT_LOG_LEVEL_MQTT                          IOT_LOG_ERROR
#define AWS_IOT_LOG_LEVEL_SHADOW                    IOT_LOG_ERROR
#define AWS_IOT_LOG_LEVEL_DEFENDER                  IOT_LOG_ERROR
#define AWS_IOT_LOG_LEVEL_JOBS                      IOT_LOG_ERROR
/**
 * \endcond
 */

/**
 * @}
 */

#endif /* ifndef IOT_CONFIG_H_ */

PSOC6 - headers/mbedtls_user_config.h

C Header File
/**
 * \file mbedtls_user_config.h
 *
 * \brief Configuration options (set of defines)
 *
 *  This set of compile-time options may be used to enable
 *  or disable features selectively, and reduce the global
 *  memory footprint.
 */
/*
 *  Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  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.
 *
 *  This file is part of mbed TLS (https://tls.mbed.org)
 */

#ifndef MBEDTLS_USER_CONFIG_HEADER
#define MBEDTLS_USER_CONFIG_HEADER


/**
 * \def MBEDTLS_HAVE_TIME_DATE
 *
 * System has time.h, time(), and an implementation for
 * mbedtls_platform_gmtime_r() (see below).
 * The time needs to be correct (not necessarily very accurate, but at least
 * the date should be correct). This is used to verify the validity period of
 * X.509 certificates.
 *
 * Comment if your system does not have a correct clock.
 *
 * \note mbedtls_platform_gmtime_r() is an abstraction in platform_util.h that
 * behaves similarly to the gmtime_r() function from the C standard. Refer to
 * the documentation for mbedtls_platform_gmtime_r() for more information.
 *
 * \note It is possible to configure an implementation for
 * mbedtls_platform_gmtime_r() at compile-time by using the macro
 * MBEDTLS_PLATFORM_GMTIME_R_ALT.
 */
#undef MBEDTLS_HAVE_TIME_DATE


/**
 * \def MBEDTLS_PLATFORM_EXIT_ALT
 *
 * MBEDTLS_PLATFORM_XXX_ALT: Uncomment a macro to let mbed TLS support the
 * function in the platform abstraction layer.
 *
 * Example: In case you uncomment MBEDTLS_PLATFORM_PRINTF_ALT, mbed TLS will
 * provide a function "mbedtls_platform_set_printf()" that allows you to set an
 * alternative printf function pointer.
 *
 * All these define require MBEDTLS_PLATFORM_C to be defined!
 *
 * \note MBEDTLS_PLATFORM_SNPRINTF_ALT is required on Windows;
 * it will be enabled automatically by check_config.h
 *
 * \warning MBEDTLS_PLATFORM_XXX_ALT cannot be defined at the same time as
 * MBEDTLS_PLATFORM_XXX_MACRO!
 *
 * Requires: MBEDTLS_PLATFORM_TIME_ALT requires MBEDTLS_HAVE_TIME
 *
 * Uncomment a macro to enable alternate implementation of specific base
 * platform function
 */
//#define MBEDTLS_PLATFORM_EXIT_ALT
#define MBEDTLS_PLATFORM_TIME_ALT
//#define MBEDTLS_PLATFORM_FPRINTF_ALT
//#define MBEDTLS_PLATFORM_PRINTF_ALT
//#define MBEDTLS_PLATFORM_SNPRINTF_ALT
//#define MBEDTLS_PLATFORM_NV_SEED_ALT
//#define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT

/**
 * \def MBEDTLS_ENTROPY_HARDWARE_ALT
 *
 * Uncomment this macro to let mbed TLS use your own implementation of a
 * hardware entropy collector.
 *
 * Your function must be called \c mbedtls_hardware_poll(), have the same
 * prototype as declared in entropy_poll.h, and accept NULL as first argument.
 *
 * Uncomment to use your own hardware entropy collector.
 */
#define MBEDTLS_ENTROPY_HARDWARE_ALT
/**
 * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED
 *
 * MBEDTLS_ECP_XXXX_ENABLED: Enables specific curves within the Elliptic Curve
 * module.  By default all supported curves are enabled.
 *
 * Comment macros to disable the curve and functions for it
 */
#undef MBEDTLS_ECP_DP_SECP192R1_ENABLED
#undef MBEDTLS_ECP_DP_SECP224R1_ENABLED
//#define MBEDTLS_ECP_DP_SECP256R1_ENABLED
#undef MBEDTLS_ECP_DP_SECP384R1_ENABLED
#undef MBEDTLS_ECP_DP_SECP521R1_ENABLED
#undef MBEDTLS_ECP_DP_SECP192K1_ENABLED
#undef MBEDTLS_ECP_DP_SECP224K1_ENABLED
#undef MBEDTLS_ECP_DP_SECP256K1_ENABLED
#undef MBEDTLS_ECP_DP_BP256R1_ENABLED
#undef MBEDTLS_ECP_DP_BP384R1_ENABLED
#undef MBEDTLS_ECP_DP_BP512R1_ENABLED
//#undef MBEDTLS_ECP_DP_CURVE25519_ENABLED
#undef MBEDTLS_ECP_DP_CURVE448_ENABLED

/**
 * \def MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
 *
 * Enable the PSK based ciphersuite modes in SSL / TLS.
 *
 * This enables the following ciphersuites (if other requisites are
 * enabled as well):
 *      MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384
 *      MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384
 *      MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA
 *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384
 *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384
 *      MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256
 *      MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256
 *      MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA
 *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256
 *      MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256
 *      MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA
 *      MBEDTLS_TLS_PSK_WITH_RC4_128_SHA
 */
#undef MBEDTLS_KEY_EXCHANGE_PSK_ENABLED


/**
 * \def MBEDTLS_PK_PARSE_EC_EXTENDED
 *
 * Enhance support for reading EC keys using variants of SEC1 not allowed by
 * RFC 5915 and RFC 5480.
 *
 * Currently this means parsing the SpecifiedECDomain choice of EC
 * parameters (only known groups are supported, not arbitrary domains, to
 * avoid validation issues).
 *
 * Disable if you only need to support RFC 5915 + 5480 key formats.
 */
#undef MBEDTLS_PK_PARSE_EC_EXTENDED


#undef MBEDTLS_FS_IO


/**
 * \def MBEDTLS_NO_PLATFORM_ENTROPY
 *
 * Do not use built-in platform entropy functions.
 * This is useful if your platform does not support
 * standards like the /dev/urandom or Windows CryptoAPI.
 *
 * Uncomment this macro to disable the built-in platform entropy functions.
 */
#define MBEDTLS_NO_PLATFORM_ENTROPY

/**
 * \def MBEDTLS_ENTROPY_FORCE_SHA256
 *
 * Force the entropy accumulator to use a SHA-256 accumulator instead of the
 * default SHA-512 based one (if both are available).
 *
 * Requires: MBEDTLS_SHA256_C
 *
 * On 32-bit systems SHA-256 can be much faster than SHA-512. Use this option
 * if you have performance concerns.
 *
 * This option is only useful if both MBEDTLS_SHA256_C and
 * MBEDTLS_SHA512_C are defined. Otherwise the available hash module is used.
 */
#define MBEDTLS_ENTROPY_FORCE_SHA256

/**
 * \def MBEDTLS_SELF_TEST
 *
 * Enable the checkup functions (*_self_test).
 */
#undef MBEDTLS_SELF_TEST

/**
 * \def MBEDTLS_SSL_FALLBACK_SCSV
 *
 * Enable support for FALLBACK_SCSV (draft-ietf-tls-downgrade-scsv-00).
 *
 * For servers, it is recommended to always enable this, unless you support
 * only one version of TLS, or know for sure that none of your clients
 * implements a fallback strategy.
 *
 * For clients, you only need this if you're using a fallback strategy, which
 * is not recommended in the first place, unless you absolutely need it to
 * interoperate with buggy (version-intolerant) servers.
 *
 * Comment this macro to disable support for FALLBACK_SCSV
 */
#undef MBEDTLS_SSL_FALLBACK_SCSV

/**
 * \def MBEDTLS_SSL_CBC_RECORD_SPLITTING
 *
 * Enable 1/n-1 record splitting for CBC mode in SSLv3 and TLS 1.0.
 *
 * This is a countermeasure to the BEAST attack, which also minimizes the risk
 * of interoperability issues compared to sending 0-length records.
 *
 * Comment this macro to disable 1/n-1 record splitting.
 */
#undef MBEDTLS_SSL_CBC_RECORD_SPLITTING

/**
 * \def MBEDTLS_SSL_RENEGOTIATION
 *
 * Enable support for TLS renegotiation.
 *
 * The two main uses of renegotiation are (1) refresh keys on long-lived
 * connections and (2) client authentication after the initial handshake.
 * If you don't need renegotiation, it's probably better to disable it, since
 * it has been associated with security issues in the past and is easy to
 * misuse/misunderstand.
 *
 * Comment this to disable support for renegotiation.
 *
 * \note   Even if this option is disabled, both client and server are aware
 *         of the Renegotiation Indication Extension (RFC 5746) used to
 *         prevent the SSL renegotiation attack (see RFC 5746 Sect. 1).
 *         (See \c mbedtls_ssl_conf_legacy_renegotiation for the
 *          configuration of this extension).
 *
 */
#undef MBEDTLS_SSL_RENEGOTIATION

/**
 * \def MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO
 *
 * Enable support for receiving and parsing SSLv2 Client Hello messages for the
 * SSL Server module (MBEDTLS_SSL_SRV_C).
 *
 * Uncomment this macro to enable support for SSLv2 Client Hello messages.
 */
//#define MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO

/**
 * \def MBEDTLS_SSL_PROTO_TLS1
 *
 * Enable support for TLS 1.0.
 *
 * Requires: MBEDTLS_MD5_C
 *           MBEDTLS_SHA1_C
 *
 * Comment this macro to disable support for TLS 1.0
 */
#undef MBEDTLS_SSL_PROTO_TLS1

/**
 * \def MBEDTLS_SSL_PROTO_TLS1_1
 *
 * Enable support for TLS 1.1 (and DTLS 1.0 if DTLS is enabled).
 *
 * Requires: MBEDTLS_MD5_C
 *           MBEDTLS_SHA1_C
 *
 * Comment this macro to disable support for TLS 1.1 / DTLS 1.0
 */
#undef MBEDTLS_SSL_PROTO_TLS1_1

/**
 * \def MBEDTLS_SSL_PROTO_DTLS
 *
 * Enable support for DTLS (all available versions).
 *
 * Enable this and MBEDTLS_SSL_PROTO_TLS1_1 to enable DTLS 1.0,
 * and/or this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2.
 *
 * Requires: MBEDTLS_SSL_PROTO_TLS1_1
 *        or MBEDTLS_SSL_PROTO_TLS1_2
 *
 * Comment this macro to disable support for DTLS
 */
#undef MBEDTLS_SSL_PROTO_DTLS

/**
 * \def MBEDTLS_SSL_DTLS_ANTI_REPLAY
 *
 * Enable support for the anti-replay mechanism in DTLS.
 *
 * Requires: MBEDTLS_SSL_TLS_C
 *           MBEDTLS_SSL_PROTO_DTLS
 *
 * \warning Disabling this is often a security risk!
 * See mbedtls_ssl_conf_dtls_anti_replay() for details.
 *
 * Comment this to disable anti-replay in DTLS.
 */
#undef MBEDTLS_SSL_DTLS_ANTI_REPLAY

/**
 * \def MBEDTLS_SSL_DTLS_HELLO_VERIFY
 *
 * Enable support for HelloVerifyRequest on DTLS servers.
 *
 * This feature is highly recommended to prevent DTLS servers being used as
 * amplifiers in DoS attacks against other hosts. It should always be enabled
 * unless you know for sure amplification cannot be a problem in the
 * environment in which your server operates.
 *
 * \warning Disabling this can ba a security risk! (see above)
 *
 * Requires: MBEDTLS_SSL_PROTO_DTLS
 *
 * Comment this to disable support for HelloVerifyRequest.
 */
#undef MBEDTLS_SSL_DTLS_HELLO_VERIFY

/**
 * \def MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
 *
 * Enable server-side support for clients that reconnect from the same port.
 *
 * Some clients unexpectedly close the connection and try to reconnect using the
 * same source port. This needs special support from the server to handle the
 * new connection securely, as described in section 4.2.8 of RFC 6347. This
 * flag enables that support.
 *
 * Requires: MBEDTLS_SSL_DTLS_HELLO_VERIFY
 *
 * Comment this to disable support for clients reusing the source port.
 */
#undef MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE

/**
 * \def MBEDTLS_SSL_DTLS_BADMAC_LIMIT
 *
 * Enable support for a limit of records with bad MAC.
 *
 * See mbedtls_ssl_conf_dtls_badmac_limit().
 *
 * Requires: MBEDTLS_SSL_PROTO_DTLS
 */
#undef MBEDTLS_SSL_DTLS_BADMAC_LIMIT

/**
 * \def MBEDTLS_SSL_SESSION_TICKETS
 *
 * Enable support for RFC 5077 session tickets in SSL.
 * Client-side, provides full support for session tickets (maintenance of a
 * session store remains the responsibility of the application, though).
 * Server-side, you also need to provide callbacks for writing and parsing
 * tickets, including authenticated encryption and key management. Example
 * callbacks are provided by MBEDTLS_SSL_TICKET_C.
 *
 * Comment this macro to disable support for SSL session tickets
 */
#undef MBEDTLS_SSL_SESSION_TICKETS

/**
 * \def MBEDTLS_SSL_EXPORT_KEYS
 *
 * Enable support for exporting key block and master secret.
 * This is required for certain users of TLS, e.g. EAP-TLS.
 *
 * Comment this macro to disable support for key export
 */
#undef MBEDTLS_SSL_EXPORT_KEYS


/**
 * \def MBEDTLS_SSL_TRUNCATED_HMAC
 *
 * Enable support for RFC 6066 truncated HMAC in SSL.
 *
 * Comment this macro to disable support for truncated HMAC in SSL
 */
#undef MBEDTLS_SSL_TRUNCATED_HMAC

/**
 * \def MBEDTLS_X509_RSASSA_PSS_SUPPORT
 *
 * Enable parsing and verification of X.509 certificates, CRLs and CSRS
 * signed with RSASSA-PSS (aka PKCS#1 v2.1).
 *
 * Comment this macro to disallow using RSASSA-PSS in certificates.
 */
#undef MBEDTLS_X509_RSASSA_PSS_SUPPORT

/**
 * \def MBEDTLS_AESNI_C
 *
 * Enable AES-NI support on x86-64.
 *
 * Module:  library/aesni.c
 * Caller:  library/aes.c
 *
 * Requires: MBEDTLS_HAVE_ASM
 *
 * This modules adds support for the AES-NI instructions on x86-64
 */
#undef MBEDTLS_AESNI_C

/**
 * \def MBEDTLS_NET_C
 *
 * Enable the TCP and UDP over IPv6/IPv4 networking routines.
 *
 * \note This module only works on POSIX/Unix (including Linux, BSD and OS X)
 * and Windows. For other platforms, you'll want to disable it, and write your
 * own networking callbacks to be passed to \c mbedtls_ssl_set_bio().
 *
 * \note See also our Knowledge Base article about porting to a new
 * environment:
 * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS
 *
 * Module:  library/net_sockets.c
 *
 * This module provides networking routines.
 */
#undef MBEDTLS_NET_C

/**
 * \def MBEDTLS_SSL_COOKIE_C
 *
 * Enable basic implementation of DTLS cookies for hello verification.
 *
 * Module:  library/ssl_cookie.c
 * Caller:
 */
#undef MBEDTLS_SSL_COOKIE_C

/**
 * \def MBEDTLS_TIMING_C
 *
 * Enable the semi-portable timing interface.
 *
 * \note The provided implementation only works on POSIX/Unix (including Linux,
 * BSD and OS X) and Windows. On other platforms, you can either disable that
 * module and provide your own implementations of the callbacks needed by
 * \c mbedtls_ssl_set_timer_cb() for DTLS, or leave it enabled and provide
 * your own implementation of the whole module by setting
 * \c MBEDTLS_TIMING_ALT in the current file.
 *
 * \note See also our Knowledge Base article about porting to a new
 * environment:
 * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS
 *
 * Module:  library/timing.c
 * Caller:  library/havege.c
 *
 * This module is used by the HAVEGE random number generator.
 */
#undef MBEDTLS_TIMING_C

/**
 * \def MBEDTLS_X509_CRL_PARSE_C
 *
 * Enable X.509 CRL parsing.
 *
 * Module:  library/x509_crl.c
 * Caller:  library/x509_crt.c
 *
 * Requires: MBEDTLS_X509_USE_C
 *
 * This module is required for X.509 CRL parsing.
 */
#undef MBEDTLS_X509_CRL_PARSE_C

/**
 * \def MBEDTLS_X509_CSR_PARSE_C
 *
 * Enable X.509 Certificate Signing Request (CSR) parsing.
 *
 * Module:  library/x509_csr.c
 * Caller:  library/x509_crt_write.c
 *
 * Requires: MBEDTLS_X509_USE_C
 *
 * This module is used for reading X.509 certificate request.
 */
#undef MBEDTLS_X509_CSR_PARSE_C

/**
 * \def MBEDTLS_X509_CREATE_C
 *
 * Enable X.509 core for creating certificates.
 *
 * Module:  library/x509_create.c
 *
 * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_WRITE_C
 *
 * This module is the basis for creating X.509 certificates and CSRs.
 */
#undef MBEDTLS_X509_CREATE_C

/**
 * \def MBEDTLS_X509_CSR_WRITE_C
 *
 * Enable creating X.509 Certificate Signing Requests (CSR).
 *
 * Module:  library/x509_csr_write.c
 *
 * Requires: MBEDTLS_X509_CREATE_C
 *
 * This module is required for X.509 certificate request writing.
 */
#undef MBEDTLS_X509_CSR_WRITE_C

/**
 * \def MBEDTLS_X509_CRT_WRITE_C
 *
 * Enable creating X.509 certificates.
 *
 * Module:  library/x509_crt_write.c
 *
 * Requires: MBEDTLS_X509_CREATE_C
 *
 * This module is required for X.509 certificate creation.
 */
#undef MBEDTLS_X509_CRT_WRITE_C

/**
 * \def MBEDTLS_CERTS_C
 *
 * Enable the test certificates.
 *
 * Module:  library/certs.c
 * Caller:
 *
 * This module is used for testing (ssl_client/server).
 */
#undef MBEDTLS_CERTS_C

/**
 * \def MBEDTLS_ERROR_C
 *
 * Enable error code to error string conversion.
 *
 * Module:  library/error.c
 * Caller:
 *
 * This module enables mbedtls_strerror().
 */
#undef MBEDTLS_ERROR_C

/**
 * \def MBEDTLS_PADLOCK_C
 *
 * Enable VIA Padlock support on x86.
 *
 * Module:  library/padlock.c
 * Caller:  library/aes.c
 *
 * Requires: MBEDTLS_HAVE_ASM
 *
 * This modules adds support for the VIA PadLock on x86.
 */
#undef MBEDTLS_PADLOCK_C

/**
 * \def MBEDTLS_RIPEMD160_C
 *
 * Enable the RIPEMD-160 hash algorithm.
 *
 * Module:  library/ripemd160.c
 * Caller:  library/md.c
 *
 */
#undef MBEDTLS_RIPEMD160_C

/**
 * \def MBEDTLS_PK_RSA_ALT_SUPPORT
 *
 * Support external private RSA keys (eg from a HSM) in the PK layer.
 *
 * Comment this macro to disable support for external private RSA keys.
 */
#undef MBEDTLS_PK_RSA_ALT_SUPPORT

/**
 * \def MBEDTLS_ARC4_C
 *
 * Enable the ARCFOUR stream cipher.
 *
 * Module:  library/arc4.c
 * Caller:  library/cipher.c
 *
 * This module enables the following ciphersuites (if other requisites are
 * enabled as well):
 *      MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA
 *      MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA
 *      MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
 *      MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA
 *      MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA
 *      MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA
 *      MBEDTLS_TLS_RSA_WITH_RC4_128_SHA
 *      MBEDTLS_TLS_RSA_WITH_RC4_128_MD5
 *      MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA
 *      MBEDTLS_TLS_PSK_WITH_RC4_128_SHA
 *
 * \warning   ARC4 is considered a weak cipher and its use constitutes a
 *            security risk. If possible, we recommend avoidng dependencies on
 *            it, and considering stronger ciphers instead.
 *
 */
#undef MBEDTLS_ARC4_C

/**
 * \def MBEDTLS_XTEA_C
 *
 * Enable the XTEA block cipher.
 *
 * Module:  library/xtea.c
 * Caller:
 */
#undef MBEDTLS_XTEA_C

/**
 * \def MBEDTLS_BLOWFISH_C
 *
 * Enable the Blowfish block cipher.
 *
 * Module:  library/blowfish.c
 */
#undef MBEDTLS_BLOWFISH_C

/**
 * \def MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED
 *
 * Enable the DHE-PSK based ciphersuite modes in SSL / TLS.
 *
 * Requires: MBEDTLS_DHM_C
 *
 * This enables the following ciphersuites (if other requisites are
 * enabled as well):
 *      MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
 *      MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
 *      MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA
 *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384
 *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384
 *      MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
 *      MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
 *      MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA
 *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256
 *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
 *      MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
 *      MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA
 *
 * \warning    Using DHE constitutes a security risk as it
 *             is not possible to validate custom DH parameters.
 *             If possible, it is recommended users should consider
 *             preferring other methods of key exchange.
 *             See dhm.h for more details.
 *
 */
#undef MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED

/**
 * \def MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
 *
 * Enable the ECDHE-PSK based ciphersuite modes in SSL / TLS.
 *
 * Requires: MBEDTLS_ECDH_C
 *
 * This enables the following ciphersuites (if other requisites are
 * enabled as well):
 *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384
 *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
 *      MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384
 *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
 *      MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
 *      MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
 *      MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA
 *      MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA
 */
#undef MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED

/**
 * \def MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
 *
 * Enable the RSA-PSK based ciphersuite modes in SSL / TLS.
 *
 * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15,
 *           MBEDTLS_X509_CRT_PARSE_C
 *
 * This enables the following ciphersuites (if other requisites are
 * enabled as well):
 *      MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384
 *      MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384
 *      MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA
 *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384
 *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384
 *      MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256
 *      MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256
 *      MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA
 *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256
 *      MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256
 *      MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA
 *      MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA
 */
#undef MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED

/**
 * Allow SHA-1 in the default TLS configuration for certificate signing if 
 * enabled in the application Makefile.
 * 
 * Without this build-time option, SHA-1 support must be activated explicitly
 * through mbedtls_ssl_conf_cert_profile. Turning on this option is not
 * recommended because of it is possible to generate SHA-1 collisions, however
 * this may be safe for legacy infrastructure where additional controls apply.
 *
 * \warning   SHA-1 is considered a weak message digest and its use constitutes
 *            a security risk. If possible, we recommend avoiding dependencies
 *            on it, and considering stronger message digests instead.
 *
 */
#ifdef CY_MQTT_ENABLE_SECURE_TEST_MOSQUITTO_SUPPORT
    #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES
#endif

#endif /* MBEDTLS_USER_CONFIG_HEADER */

PSOC6 - headers/mqtt_client_config.h

C Header File
/******************************************************************************
* File Name: mqtt_client_config.h
*
* Description: This file contains all the configuration macros used by the 
*              MQTT client in this example.
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

#ifndef MQTT_CLIENT_CONFIG_H_
#define MQTT_CLIENT_CONFIG_H_

#include "iot_mqtt.h"

/*******************************************************************************
* Macros
********************************************************************************/
/* MQTT Broker/Server address and port used for the MQTT connection. On Change set username and pwd as well
 * if it is still not working baud rate is 9600*/
#define MQTT_BROKER_ADDRESS               "1.2.3.4"
#define MQTT_PORT                         1883

/* Set this macro to 1 if the MQTT Broker being used is hosted by AWS IoT 
 * Core service, else 0.
 */
#define AWS_IOT_MQTT_MODE                 ( 0 )

/* Set this macro to 1 if a secure (TLS) connection to the MQTT Broker is  
 * required to be established, else 0.
 */
#define MQTT_SECURE_CONNECTION            ( 0 )

/* The MQTT topic on which the LED control messages will be published and 
 * subscribed.
 */
#define MQTT_TOPIC                        "ledstatus"

/* Configuration for the 'Last Will and Testament (LWT)'. It is an MQTT message 
 * that will be published by the MQTT broker if the MQTT connection is 
 * unexpectedly closed. This configuration is sent to the MQTT broker during 
 * MQTT connect operation and the MQTT broker will publish the Will message on 
 * the Will topic when it recognizes an unexpected disconnection from the client.
 * 
 * If you want to use the last will message, set this macro to 1, else 0.
 */
#define ENABLE_LWT_MESSAGE                ( 0 )
#if ENABLE_LWT_MESSAGE
    #define MQTT_WILL_TOPIC_NAME          MQTT_TOPIC "/will"
    #define MQTT_WILL_MESSAGE             ("MQTT client unexpectedly disconnected!")
#endif

/* Set the QoS that is associated with the MQTT publish, and subscribe messages.
 * Valid choices are 0, and 1. The MQTT library currently does not support 
 * QoS 2, and hence should not be used in this macro.
 */
#define MQTT_MESSAGES_QOS                 ( 1 )

/* Configure the user credentials to be sent as part of MQTT CONNECT packet */
#define MQTT_USERNAME                     "mqttusername"
#define MQTT_PASSWORD                     "mqttpwd"

/* The timeout in milliseconds for MQTT operations in this example. */
#define MQTT_TIMEOUT_MS                   ( 5000 )

/* The keep-alive interval in seconds used for MQTT ping request. */
#define MQTT_KEEP_ALIVE_SECONDS           ( 60 )

/* A unique client identifier to be used for every MQTT connection. */
#define MQTT_CLIENT_IDENTIFIER            "psoc6-mqtt-client"

/* Every active MQTT connection must have a unique client identifier. If you 
 * are using the above 'MQTT_CLIENT_IDENTIFIER' as client ID for multiple MQTT 
 * connections simultaneously, set this macro to 1. The device will then
 * generate a unique client identifier by appending a timestamp to the 
 * 'MQTT_CLIENT_IDENTIFIER' string. Example: 'psoc6-mqtt-client5927'
 */
#define GENERATE_UNIQUE_CLIENT_ID         ( 1 )

/* The longest client identifier that an MQTT server must accept (as defined
 * by the MQTT 3.1.1 spec) is 23 characters. Add 1 to include the length of the
 * NULL terminator.
 */
#define MQTT_CLIENT_IDENTIFIER_MAX_LEN    ( 24 )

/* MQTT messages which are published and subscribed on the MQTT_TOPIC that
 * controls the device (user LED in this example) state.
 */
#define MQTT_DEVICE_ON_MESSAGE            "TURN ON"
#define MQTT_DEVICE_OFF_MESSAGE           "TURN OFF"

/* As per Internet Assigned Numbers Authority (IANA) the port numbers assigned 
 * for MQTT protocol are 1883 for non-secure connections and 8883 for secure
 * connections. In some cases there is a need to use other ports for MQTT like
 * port 443 (which is reserved for HTTPS). Application Layer Protocol 
 * Negotiation (ALPN) is an extension to TLS that allows many protocols to be 
 * used over a secure connection. The ALPN ProtocolNameList specifies the 
 * protocols that the client would like to use to communicate over TLS.
 * 
 * This macro specifies the ALPN Protocol Name to be used that is supported
 * by the MQTT broker in use.
 * Note: For AWS IoT, currently "x-amzn-mqtt-ca" is the only supported ALPN 
 *       ProtocolName and it is only supported on port 443.
 */
#define MQTT_ALPN_PROTOCOL_NAME           "x-amzn-mqtt-ca"

/* Configure the below credentials in case of a secure MQTT connection. */
/* PEM-encoded client certificate */
#define CLIENT_CERTIFICATE      \
"-----BEGIN CERTIFICATE-----\n" \
"........base64 data........\n" \
"-----END CERTIFICATE-----"

/* PEM-encoded client private key */
#define CLIENT_PRIVATE_KEY          \
"-----BEGIN RSA PRIVATE KEY-----\n" \
"..........base64 data..........\n" \
"-----END RSA PRIVATE KEY-----"

/* PEM-encoded Root CA certificate */
#define ROOT_CA_CERTIFICATE     \
"-----BEGIN CERTIFICATE-----\n" \
"........base64 data........\n" \
"-----END CERTIFICATE-----"

/******************************************************************************
* Global Variables
*******************************************************************************/
extern IotMqttNetworkInfo_t networkInfo;
extern IotMqttConnectInfo_t connectionInfo;

#endif /* MQTT_CLIENT_CONFIG_H_ */

PSOC6 - headers/uart_config.h

C Header File
/*
 * uart_config.h
 *
 *  Created on: 20 mrt. 2021
 *      Author: jancu
 */

#ifndef CONFIGS_UART_CONFIG_H_
#define CONFIGS_UART_CONFIG_H_

/* dependent on the SCB and pins used */
/* Assign UART interrupt number and priority */



// SCB 1 p10_0 rx p10_1 tx

#define UART_SCB SCB10
#define UART_PORT       P5_4_PORT
#define UART_RX_NUM     P5_4_NUM
#define UART_TX_NUM     P5_5_NUM
#define UART_RX_PIN     P5_4_SCB10_UART_RX
#define UART_TX_PIN     P5_5_SCB10_UART_TX
#define UART_DIVIDER_NUMBER 1U

#define UART_CLOCK PCLK_SCB10_CLOCK

#define UART_INTR_NUM        ((IRQn_Type) scb_10_interrupt_IRQn)



// Or if SCB 5 p5_0 rx p5_1 tx 

//#define UART_SCB SCB5
//#define UART_PORT       P5_0_PORT
//#define UART_RX_NUM     P5_0_NUM
//#define UART_TX_NUM     P5_1_NUM
//#define UART_RX_PIN     P5_0_SCB5_UART_RX
//#define UART_TX_PIN     P5_1_SCB5_UART_TX
//#define UART_DIVIDER_NUMBER 5U
//
//#define UART_CLOCK PCLK_SCB5_CLOCK
//
//#define UART_INTR_NUM        ((IRQn_Type) scb_5_interrupt_IRQn)



#define UART_INTR_PRIORITY   (7U)


#endif /* CONFIGS_UART_CONFIG_H_ */

PSOC6 - headers/mqtt_topic_config.h

C Header File
/*
 * mqtt_topic_config.h
 *
 *  Created on: Mar 20, 2021
 *      Author: enrico
 */

#ifndef CONFIGS_MQTT_TOPIC_CONFIG_H_
#define CONFIGS_MQTT_TOPIC_CONFIG_H_

// -------------------------------------------------------------------------------
// MQTT Topics
// -------------------------------------------------------------------------------

/**
 * The MQTT topic on which the acquired image rating is published and subscribed.
 * Every image information rating (including all the data fields) is associated
 * to the corresponding field, identifying a specific geographical area.
 * Index defines the order of Incoming data being published in the corresponding topic
 */

#define MQTT_TOPIC_MAGXVAL							"SmartWindowOpener/magxval"
#define MQTT_TOPIC_MAGYVAL							"SmartWindowOpener/magyval"
#define MQTT_TOPIC_MAGZVAL							"SmartWindowOpener/magzval"
#define MQTT_TOPIC_TEMPVAL							"SmartWindowOpener/tempval"

/*Amount of all above defined MQTT Topics*/
#define MQTT_TOPIC_AMOUNT							4

#define MQTT_TOPIC_CONTROL              "SmartWindowOpener/control"
#define MQTT_TOPIC_LOG								  "SmartWindowOpener/log"

//Charatcter Uart message is split eg set to ":" "Smile:out:Loud:Tmpval" -> [Smile,out,Loud,tmpval]published in magxval magyval etc.
#define MQTT_UART_VALUE_DELIMITER					':'
#define MQTT_UART_END_DELIMITER					'\0'

#endif /* CONFIGS_MQTT_TOPIC_CONFIG_H_ */

PSOC6 - headers/wifi_config.h

C Header File
/******************************************************************************
* File Name: wifi_config.h
*
* Description: This file contains the configuration macros required for the 
*              Wi-Fi connection.
*
* Related Document: See README.md
*
*******************************************************************************
* (c) 2020-2021, Cypress Semiconductor Corporation. All rights reserved.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software"), is owned by Cypress Semiconductor Corporation or one of its
* subsidiaries ("Cypress") and is protected by and subject to worldwide patent
* protection (United States and foreign), United States copyright laws and
* international treaty provisions. Therefore, you may use this Software only
* as provided in the license agreement accompanying the software package from
* which you obtained this Software ("EULA").
*
* If no EULA applies, Cypress hereby grants you a personal, non-exclusive,
* non-transferable license to copy, modify, and compile the Software source
* code solely for use in connection with Cypress's integrated circuit products.
* Any reproduction, modification, translation, compilation, or representation
* of this Software except as specified above is prohibited without the express
* written permission of Cypress.
*
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Cypress
* reserves the right to make changes to the Software without notice. Cypress
* does not assume any liability arising out of the application or use of the
* Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use in any products where a malfunction or
* failure of the Cypress product may reasonably be expected to result in
* significant property damage, injury or death ("High Risk Product"). By
* including Cypress's product in a High Risk Product, the manufacturer of such
* system or application assumes all risk of such use and in doing so agrees to
* indemnify Cypress against all liability.
*******************************************************************************/

#ifndef WIFI_CONFIG_H_
#define WIFI_CONFIG_H_

#include "cy_wcm.h"

/*******************************************************************************
* Macros
********************************************************************************/
/* TODO SSID of the Wi-Fi Access Point to which the MQTT client connects. */
#define WIFI_SSID                           "YourSSID"

/* TODO Passkey of the above mentioned Wi-Fi SSID. */
#define WIFI_PASSWORD                 		"YourPWD"

/* Security type of the Wi-Fi access point. See 'cy_wcm_security_t' structure
 * in "cy_wcm.h" for more details.
 */
#define WIFI_SECURITY                     CY_WCM_SECURITY_WPA2_AES_PSK

/* Maximum Wi-Fi re-connection limit. */
//#define MAX_WIFI_CONN_RETRIES             (10u)
#define MAX_WIFI_CONN_RETRIES             (10u)

/* Wi-Fi re-connection time interval in milliseconds. */
#define WIFI_CONN_RETRY_INTERVAL_MS       (2000)

#endif /* WIFI_CONFIG_H_ */

HomeAssistant configuration.yaml

YAML
# Configure a default setup of Home Assistant (frontend, api, etc)
default_config:
#to access admin uncommnt trusted users & the lin itself as well
homeassistant:
  auth_providers:
    - type: trusted_networks
      trusted_networks:
        - 1.2.3.4/24
      trusted_users:
       1.2.3.4/24: userid
      allow_bypass_login: true

# Text to speech
tts:
  - platform: google_translate

switch:
  - platform: mqtt
    command_topic: "SmartWindowOpener/control"
    payload_on: "open"
    payload_off: "open"
    name: "Open"

  - platform: mqtt
    command_topic: "SmartWindowOpener/control"
    payload_on: "close"
    payload_off: "close"
    name: "Close"

  - platform: mqtt
    command_topic: "SmartWindowOpener/control"
    payload_on: "opentil"
    payload_off: "opentil"
    name: "OpenTilt"

  - platform: mqtt
    command_topic: "SmartWindowOpener/control"
    payload_on: "emstop"
    payload_off: "emstop"
    name: "Emergency Stop"

sensor:
  - platform: mqtt
    name: "Magnet Sensor x-Value (mT)"
    state_topic: "SmartWindowOpener/magxval"

  - platform: mqtt
    name: "Magnet Sensor y-Value (mT)"
    state_topic: "SmartWindowOpener/magyval"

  - platform: mqtt
    name: "Magnet Sensor z-Value (mT)"
    state_topic: "SmartWindowOpener/magzval"

  - platform: mqtt
    name: "Temperature (Celsius)"
    state_topic: "SmartWindowOpener/tempval"

#type: button
#  tap_action:
#    action: call-service
#    service: mqtt.publish
#    topic: SmartWindowOpener/control
#    payload:  "open"
#  name: tester
#  show_state: false

group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

HBridge2GoUnlocker

C/C++
Dave
/*
 * main.c
 *
 *  Created on: 2015 Nov 05 09:11:24
 *  Author: schwarzg
 */


/***************************************************************************
 *  H-Bridge Kit 2Go - Simple DC Motor Control Demo
 *
 *  Drives a DC motor with 1kHz PWM
 *
 *  The PWM duty cycle is gradually increased in steps of 1% up to 100%
 *  and then decreased again back to 0% .
 *
 *  After each cycle of increasing and decreasing the rotating direction
 *  of the motor is changed (DIR pin of IFX9201 is toggled)
 *
 ***************************************************************************
 *
 * forward
 *
 *    ^ motor speed
 *    |
 *    |   /\            /\
 *    |  /  \          /  \
 *    | /    \        /    \
 * 0 -|/------\------/--------->
 *    |        \    /         t
 *    |         \  /
 *    |          \/
 *
 * reverse
 *
 ***************************************************************************
 *  Revision 1.0 as of 2015-11-06
 **************************************************************************/


#include <DAVE.h>                 //Declarations from DAVE Code Generation (includes SFR declaration)

#define TICKS_PER_SECOND 100UL

bool dir = 0;
bool inc = 1;
bool act = 0;
bool rightrot = 0;
//10000 equals 100%
//Set to 50%
uint32_t duty = 5000;

int main(void)
{
  DAVE_STATUS_t status;

  status = DAVE_Init();           /* Initialization of DAVE APPs  */

  //Resetting?
  DIGITAL_IO_SetOutputHigh(&DIS);
  DIGITAL_IO_SetOutputLow(&DIS);
  PWM_SetDutyCycle(&PWM,duty);

  while(1U)
  {
	  if(act)
	  {
		  PWM_Start(&PWM);
		  DIGITAL_IO_SetOutputHigh(&LED1);
	  }else {
		  PWM_Stop(&PWM);
		  DIGITAL_IO_SetOutputLow(&LED1);
	  }

	  if(rightrot)
	  {
		  DIGITAL_IO_SetOutputHigh(&DIR);
		  DIGITAL_IO_SetOutputHigh(&LED2);
	  }else {
		  DIGITAL_IO_SetOutputLow(&DIR);
		  DIGITAL_IO_SetOutputLow(&LED2);
	  }
  }
}

void On_Off_Handler(void)
  {
	 act = PIN_INTERRUPT_GetPinValue(&ON_OFF_INTERRUPT);
  }

void Left_Right_Handler(void)
  {
	rightrot = PIN_INTERRUPT_GetPinValue(&LEFT_RIGHT_INTERRUPT);
  }

TLE493D-W2B6-Sensor

Arduino
This is the code for the XMC2Go->TLE493D-W2B6-Sensor
Error opening file.

Credits

Infineon Team

Infineon Team

90 projects • 135 followers

Comments