diff --git a/.gitignore b/.gitignore index b83e22e..e533de2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,67 +1,67 @@ -# These are some examples of commonly ignored file patterns. -# You should customize this list as applicable to your project. -# Learn more about .gitignore: -# https://www.atlassian.com/git/tutorials/saving-changes/gitignore - -# config files -/src/wifiConf.h - -# ccs artifact files -/.settings -/targetConfigs -/.ccs* -/.cproject -/.project -*.cmd -/*.c -/*.h -/.launches -/Debug - -# Node artifact files -node_modules/ -dist/ - -# VS Code artifact files -*.code-workspace - -# Compiled Java class files -*.class - -# Compiled Python bytecode -*.py[cod] - -# Log files -*.log - -# Package files -*.jar - -# Maven -target/ -dist/ - -# JetBrains IDE -.idea/ - -# Unit test reports -TEST*.xml - -# Generated by MacOS -.DS_Store - -# Generated by Windows -Thumbs.db - -# Applications -*.app -*.exe -*.war - -# Large media files -*.mp4 -*.tiff -*.avi -*.flv -*.mov -*.wmv +# These are some examples of commonly ignored file patterns. +# You should customize this list as applicable to your project. +# Learn more about .gitignore: +# https://www.atlassian.com/git/tutorials/saving-changes/gitignore + +# config files +/src/wifiConf.h + +# ccs artifact files +/.settings +/targetConfigs +/.ccs* +/.cproject +/.project +*.cmd +/*.c +/*.h +/.launches +/Debug + +# Node artifact files +node_modules/ +dist/ + +# VS Code artifact files +*.code-workspace + +# Compiled Java class files +*.class + +# Compiled Python bytecode +*.py[cod] + +# Log files +*.log + +# Package files +*.jar + +# Maven +target/ +dist/ + +# JetBrains IDE +.idea/ + +# Unit test reports +TEST*.xml + +# Generated by MacOS +.DS_Store + +# Generated by Windows +Thumbs.db + +# Applications +*.app +*.exe +*.war + +# Large media files +*.mp4 +*.tiff +*.avi +*.flv +*.mov +*.wmv diff --git a/common.syscfg b/common.syscfg index 705a042..6e1eeae 100644 --- a/common.syscfg +++ b/common.syscfg @@ -9,23 +9,17 @@ * Import the modules used in this configuration. */ const DriverLib = scripting.addModule("/ti/devices/DriverLib"); -const Display = scripting.addModule("/ti/display/Display"); -const Display1 = Display.addInstance(); const Board = scripting.addModule("/ti/drivers/Board"); -const Crypto = scripting.addModule("/ti/drivers/Crypto"); -const Crypto1 = Crypto.addInstance(); const DMA = scripting.addModule("/ti/drivers/DMA"); const GPIO = scripting.addModule("/ti/drivers/GPIO", {}, false); const GPIO1 = GPIO.addInstance(); const I2C = scripting.addModule("/ti/drivers/I2C", {}, false); const I2C1 = I2C.addInstance(); +const PWM = scripting.addModule("/ti/drivers/PWM", {}, false); +const PWM1 = PWM.addInstance(); const Power = scripting.addModule("/ti/drivers/Power"); const SPI = scripting.addModule("/ti/drivers/SPI"); const SPI1 = SPI.addInstance(); -const Timer = scripting.addModule("/ti/drivers/Timer"); -const Timer1 = Timer.addInstance(); -const Timer2 = Timer.addInstance(); -const Timer3 = Timer.addInstance(); const Watchdog = scripting.addModule("/ti/drivers/Watchdog"); const Watchdog1 = Watchdog.addInstance(); const SimpleLinkWifi = scripting.addModule("/ti/drivers/net/wifi/SimpleLinkWifi"); @@ -35,24 +29,15 @@ const SlNet1 = SlNet.addInstance(); /** * Write custom configuration values to the imported modules. */ -Display1.$name = "CONFIG_Display_0"; -Display1.$hardware = system.deviceData.board.components.XDS110UART; -Display1.uart.$name = "CONFIG_UART_0"; -Display1.uart.useDMA = true; -Display1.uart.uart.$assign = "UART0"; -Display1.uart.uart.txPin.$assign = "GP01"; -Display1.uart.uart.rxPin.$assign = "GP02"; -Display1.uart.uart.txDmaChannel.$assign = "UDMA_CH9"; -Display1.uart.uart.rxDmaChannel.$assign = "UDMA_CH8"; - -Crypto1.$name = "CONFIG_Crypto_0"; - GPIO1.$name = "CONFIG_LED_R"; GPIO1.$hardware = system.deviceData.board.components.LED_RED; I2C1.$hardware = system.deviceData.board.components.LP_I2C; I2C1.$name = "CONFIG_I2C"; +PWM1.$name = "CONFIG_PWM_0"; +PWM1.timer.pwmPin.$assign = "boosterpack.13"; + Power.ioRetentionShutdown = ["GRP_1"]; Power.parkPins.$name = "ti_drivers_power_PowerCC32XXPins0"; @@ -67,16 +52,6 @@ SPI1.spi.ssPin.$assign = "boosterpack.18"; SPI1.spi.dmaRxChannel.$assign = "UDMA_CH6"; SPI1.spi.dmaTxChannel.$assign = "UDMA_CH7"; -Timer1.$name = "CONFIG_TIMER_0"; -Timer1.timerType = "32 Bits"; -Timer1.timer.$assign = "Timer0"; - -Timer2.$name = "CONFIG_TIMER_1"; -Timer2.timer.$assign = "Timer1"; - -Timer3.$name = "CONFIG_TIMER_2"; -Timer3.timer.$assign = "Timer1"; - Watchdog1.$name = "CONFIG_WATCHDOG_0"; Watchdog1.watchdog.$assign = "WATCHDOG0"; @@ -92,3 +67,4 @@ GPIO1.gpioPin.$suggestSolution = "boosterpack.29"; I2C1.i2c.$suggestSolution = "I2C0"; I2C1.i2c.sdaPin.$suggestSolution = "boosterpack.10"; I2C1.i2c.sclPin.$suggestSolution = "boosterpack.9"; +PWM1.timer.$suggestSolution = "Timer1"; diff --git a/python server/EMS20_Groep-5_UDP-Server.pyproj b/python server/EMS20_Groep-5_UDP-Server.pyproj index c0d89fe..2cf78c6 100644 --- a/python server/EMS20_Groep-5_UDP-Server.pyproj +++ b/python server/EMS20_Groep-5_UDP-Server.pyproj @@ -1,35 +1,35 @@ - - - Debug - 2.0 - c00d3363-b79d-4e9e-be8e-6206aff6b78d - . - EMS20_Groep_5_UDP_Server.py - - - . - . - EMS20_Groep-5_UDP-Server - EMS20_Groep-5_UDP-Server - - - true - false - - - true - false - - - - - - - - - - - + + + Debug + 2.0 + c00d3363-b79d-4e9e-be8e-6206aff6b78d + . + EMS20_Groep_5_UDP_Server.py + + + . + . + EMS20_Groep-5_UDP-Server + EMS20_Groep-5_UDP-Server + + + true + false + + + true + false + + + + + + + + + + + \ No newline at end of file diff --git a/python server/EMS20_Groep_5_UDP_Server simpyfied.py b/python server/EMS20_Groep_5_UDP_Server simpyfied.py index bc90a28..ba18e38 100644 --- a/python server/EMS20_Groep_5_UDP_Server simpyfied.py +++ b/python server/EMS20_Groep_5_UDP_Server simpyfied.py @@ -1,16 +1,16 @@ -import socket -from time import sleep - -UDP_IP = '0.0.0.0' # IP van de gebruiker -UDP_PORT = 0 # Port van de UDP server - -cooleSokken = socket.socket(socket.AF_INET, # Internet - socket.SOCK_DGRAM) # UDP -cooleSokken.bind((UDP_IP, UDP_PORT)) - -def recvUDP(): - data = cooleSokken.recv(1024) - return str(data) - -while True: - print(recvUDP()) +import socket +from time import sleep + +UDP_IP = '0.0.0.0' # IP van de gebruiker +UDP_PORT = 12345 # Port van de UDP server + +cooleSokken = socket.socket(socket.AF_INET, # Internet + socket.SOCK_DGRAM) # UDP +cooleSokken.bind((UDP_IP, UDP_PORT)) + +def recvUDP(): + data = cooleSokken.recv(1024) + return str(data) + +while True: + print(recvUDP()) diff --git a/python server/EMS20_Groep_5_UDP_Server.py b/python server/EMS20_Groep_5_UDP_Server.py index b51d675..c6041e7 100644 --- a/python server/EMS20_Groep_5_UDP_Server.py +++ b/python server/EMS20_Groep_5_UDP_Server.py @@ -1,37 +1,37 @@ -import socket -from time import sleep - -UDP_IP = '0.0.0.0' # IP van de gebruiker -UDP_PORT = 0 # Port van de UDP server - -cooleSokken = socket.socket(socket.AF_INET, # Internet - socket.SOCK_DGRAM) # UDP -cooleSokken.bind((UDP_IP, UDP_PORT)) - -def recvUDP(): - data = cooleSokken.recv(1024) - return str(data) - -while True: - data = recvUDP() - if data == 'Handdruk aangeboden': - wachtEventjes = 0 - while wachtEventjes != 10: - wachtEventjes += 0.1 - data = recvUDP() - if (data != 0) & (data != 'Handdruk aangeboden'): - print(data, " heeft je hand geschud :D") - break - sleep(0.1) - - elif data != 0: - wachtEventjes = 0 - aanbieder = data - print(data + " bied je een handdruk aan") - while wachtEventjes != 10: - wachtEventjes += 0.1 - data = recvUDP() - if data == 'Handdruk aangeboden': - print("Je hebt de hand geaccepteerd van ", aanbieder, " :D") - break - sleep(0.1) +import socket +from time import sleep + +UDP_IP = '0.0.0.0' # IP van de gebruiker +UDP_PORT = 0 # Port van de UDP server + +cooleSokken = socket.socket(socket.AF_INET, # Internet + socket.SOCK_DGRAM) # UDP +cooleSokken.bind((UDP_IP, UDP_PORT)) + +def recvUDP(): + data = cooleSokken.recv(1024) + return str(data) + +while True: + data = recvUDP() + if data == 'Handdruk aangeboden': + wachtEventjes = 0 + while wachtEventjes != 10: + wachtEventjes += 0.1 + data = recvUDP() + if (data != 0) & (data != 'Handdruk aangeboden'): + print(data, " heeft je hand geschud :D") + break + sleep(0.1) + + elif data != 0: + wachtEventjes = 0 + aanbieder = data + print(data + " bied je een handdruk aan") + while wachtEventjes != 10: + wachtEventjes += 0.1 + data = recvUDP() + if data == 'Handdruk aangeboden': + print("Je hebt de hand geaccepteerd van ", aanbieder, " :D") + break + sleep(0.1) diff --git a/src/gsensor.c b/src/gsensor.c index c16938d..60e1a9e 100644 --- a/src/gsensor.c +++ b/src/gsensor.c @@ -1,81 +1,81 @@ -/* - * Accelerometer op de launchpad gekoppeld aan de I2C - * Beweging 2: achter-voor op de x-as - * - * 0971472 - Bram Bleij - * 0964590 - Mats van Reenen - * - * Begonnen op 13/10/2020 - */ - -// I2C drivers -#include -#include -#include - -extern void MQTTPublish(char * topic, char * payload); - -#define SPEEDYBOI_ADDR 0x18 -#define ACCD_X_MSB 0x03 - -char mqtt_topic[] = "top_pik"; - -extern mqd_t gsensorQueue; -typedef struct { - enum {Vooruit, Achteruit} richting; - double timestamp; - int8_t g; -} gsensorMsgQueue; -//typedef struct { -// enum {Vooruit, Achteruit} richting; -// double timestamp; -// int8_t g; -//} pakketje; - -void * GSensorTask(void *args) { - - I2C_Handle speedyBoy; - - speedyBoy = I2C_open(0, NULL); - - // buffer create - int8_t buffer_rcv; - uint8_t buffer_send = ACCD_X_MSB; - - double timer = 0; - uint32_t sleeper; - - I2C_Transaction RW_Trans; - RW_Trans.slaveAddress = SPEEDYBOI_ADDR; - RW_Trans.writeBuf = &buffer_send; - RW_Trans.writeCount = 1; - RW_Trans.readBuf = &buffer_rcv; - RW_Trans.readCount = 1; - - while(1) { - bool success = I2C_transfer(speedyBoy, &RW_Trans); - if (success == false) { - while(1); // als een connectie niet kan worden gemaakt, blijf hier - } - // publish read into mailbox (defined in mqtt.c) - timer += 0.1; - - gsensorMsgQueue pakket; - pakket.richting = (buffer_rcv < 0) ? Achteruit : Vooruit; - pakket.timestamp = timer; - pakket.g = abs(buffer_rcv); - - mq_send(gsensorQueue, (const char*)&pakket, sizeof(gsensorMsgQueue), 0); - -// char payload[150]; -// -// sprintf(&payload, "handshake (richting: %s; timestamp: %.1f; g: %d)", (buffer_rcv < 0) ? "Achteruit" : "Vooruit", timer, abs(buffer_rcv)); -// -// MQTTPublish(&mqtt_topic, &payload); - // MQTTPublish(pakket); - - usleep(100000U); - } - - return 0; -} +/* + * Accelerometer op de launchpad gekoppeld aan de I2C + * Beweging 2: achter-voor op de x-as + * + * 0971472 - Bram Bleij + * 0964590 - Mats van Reenen + * + * Begonnen op 13/10/2020 + */ + +// I2C drivers +#include +#include +#include + +extern void MQTTPublish(char * topic, char * payload); + +#define SPEEDYBOI_ADDR 0x18 +#define ACCD_X_MSB 0x03 + +char mqtt_topic[] = "top_pik"; + +extern mqd_t gsensorQueue; +typedef struct { + enum {Vooruit, Achteruit} richting; + double timestamp; + int8_t g; +} gsensorMsgQueue; +//typedef struct { +// enum {Vooruit, Achteruit} richting; +// double timestamp; +// int8_t g; +//} pakketje; + +void * GSensorTask(void *args) { + + I2C_Handle speedyBoy; + + speedyBoy = I2C_open(0, NULL); + + // buffer create + int8_t buffer_rcv; + uint8_t buffer_send = ACCD_X_MSB; + + double timer = 0; + uint32_t sleeper; + + I2C_Transaction RW_Trans; + RW_Trans.slaveAddress = SPEEDYBOI_ADDR; + RW_Trans.writeBuf = &buffer_send; + RW_Trans.writeCount = 1; + RW_Trans.readBuf = &buffer_rcv; + RW_Trans.readCount = 1; + + while(1) { + bool success = I2C_transfer(speedyBoy, &RW_Trans); + if (success == false) { + while(1); // als een connectie niet kan worden gemaakt, blijf hier + } + // publish read into mailbox (defined in mqtt.c) + timer += 0.1; + + gsensorMsgQueue pakket; + pakket.richting = (buffer_rcv < 0) ? Achteruit : Vooruit; + pakket.timestamp = timer; + pakket.g = abs(buffer_rcv); + + mq_send(gsensorQueue, (const char*)&pakket, sizeof(gsensorMsgQueue), 0); + +// char payload[150]; +// +// sprintf(&payload, "handshake (richting: %s; timestamp: %.1f; g: %d)", (buffer_rcv < 0) ? "Achteruit" : "Vooruit", timer, abs(buffer_rcv)); +// +// MQTTPublish(&mqtt_topic, &payload); + // MQTTPublish(pakket); + + usleep(100000U); + } + + return 0; +} diff --git a/src/handshake.c b/src/handshake.c index c489c29..5ddddd2 100644 --- a/src/handshake.c +++ b/src/handshake.c @@ -1,143 +1,149 @@ -/* - * handshake.c - * - * Created on: 29 Oct 2020 - * Author: MReenen - */ -#include -#include -#include "ti_drivers_config.h" - -#define TIME_BETWEEN_DIRECTION_CHANGE 1.0 -#define TIME_TO_RESPAN_ON_REQUEST 10.0 -#define G_THUSHOLD 10 -#define TIMEOUT_DURATION 11 - -const char yourName[] = "Mats"; -#define YOUR_STUDENTNUMBER "0964590" - -#define REPLY_TOPIC(n) "ems20/handshake/" n "/reply" -#define REQUEST_TOPIC(n) "ems20/handshake/" n "/request" - -mqd_t gsensorQueue; -bool replyListen = false; -bool requestListen = true; - -double timestamp = 0; -double requestTimeout = -TIME_TO_RESPAN_ON_REQUEST - 1; -double lastBack = -TIME_BETWEEN_DIRECTION_CHANGE - 1; - -char requestFrom[6]; - -char requestTopic[] = "ems20/handshake/0964590/request"; - -typedef struct { - enum {Vooruit, Achteruit} richting; - double timestamp; - int8_t g; -} gsensorMsgQueue; - - -extern void MQTTPublish(char * topic, char * payload); -extern void MQTTSubscribe(char* topic, void *cb(char* topic, char* payload)); - -extern void UDPSend (char msg[128], int len); - -void MQTTCB_reply(char* topic, char* payload){ - char msg[50]; - - if(!replyListen) - return; - - sprintf(&msg, "%s heeft je hand geschud.", payload); - UDPSend(msg, strlen(msg)); -} - -void MQTTCB_request(char* topic, char* payload){ - char msg[50]; - uint8_t i; - - if(!requestListen) - return; - - // get student number from topic - if(strlen(topic) < 16+6){ - return; //ERROR invalid topic - } - for(i=0; i<6; i++){ - requestFrom[i] = topic[i+16]; - } - - requestTimeout = timestamp + TIME_TO_RESPAN_ON_REQUEST; - sprintf(&msg, "%s bied je een handdruk aan.", payload); - UDPSend(msg, strlen(msg)); -} - -void handshake(){ - if(requestTimeout > timestamp){ - // replyed to request - requestTimeout = 0; - - replyListen = false; - requestListen = true; //?? direct luisteren naar requests na - - char topic[128]; - sprintf(&topic, "ems20/handshake/$s/reply", requestFrom); - MQTTPublish(&topic[0], &yourName[0]); - }else{ // send request - replyListen = true; - requestListen = false; - GPIO_write(CONFIG_LED_R, 1); - MQTTPublish(&requestTopic[0], &yourName[0]); - } - UDPSend("Handshake aangeboden", strlen("Handshake aangeboden")); -} - -void * handshakeTask(void *arg0){ - // create massage queue - mq_attr attr; - attr.mq_maxmsg = 10; - attr.mq_msgsize = sizeof(gsensorMsgQueue); - gsensorQueue = mq_open("gsensorQueue", O_CREAT, 0, &attr); - if(((int)gsensorQueue) <= 0){ - while(1); - } - - GPIO_write(CONFIG_LED_R, 0); - - gsensorMsgQueue queueElement; - double replyTimeout = -1; - - while(1){ - mq_receive(gsensorQueue, (char*)&queueElement, sizeof(gsensorMsgQueue), NULL); - - timestamp = queueElement.timestamp; - - if(replyTimeout >= timestamp){ - if(replyTimeout <= timestamp + 1){ - replyListen = false; - GPIO_write(CONFIG_LED_R, 0); - } - requestListen = true; - continue; - } - - if(requestTimeout > timestamp){ - uint32_t a = timestamp*2; - GPIO_write(CONFIG_LED_R, a & 0x01); - }else{ - GPIO_write(CONFIG_LED_R, 0); - } - - if(queueElement.g > G_THUSHOLD){ - if(queueElement.richting == Vooruit && timestamp - lastBack < TIME_BETWEEN_DIRECTION_CHANGE){ - replyTimeout = timestamp + TIMEOUT_DURATION; - handshake(); - } else if(queueElement.richting == Achteruit){ - lastBack = timestamp; - } - } - } -} - - +/* + * handshake.c + * + * Created on: 29 Oct 2020 + * Author: MReenen + */ +#include +#include +#include "ti_drivers_config.h" + +#define TIME_BETWEEN_DIRECTION_CHANGE 1.0 +#define TIME_TO_RESPAN_ON_REQUEST 10.0 +#define G_THUSHOLD 10 +#define TIMEOUT_DURATION 11 + +const char yourName[] = "Mats"; +#define YOUR_STUDENTNUMBER "0964590" + +#define REPLY_TOPIC(n) "ems20/handshake/" n "/reply" +#define REQUEST_TOPIC(n) "ems20/handshake/" n "/request" + +mqd_t gsensorQueue; +bool replyListen = false; +bool requestListen = true; + +double timestamp = 0; +double requestTimeout = -TIME_TO_RESPAN_ON_REQUEST - 1; +double lastBack = -TIME_BETWEEN_DIRECTION_CHANGE - 1; + +char requestFrom[7]; +char requestFromName[50]; + +char requestTopic[] = "ems20/handshake/0964590/request"; + +typedef struct { + enum {Vooruit, Achteruit} richting; + double timestamp; + int8_t g; +} gsensorMsgQueue; + + +extern void MQTTPublish(char * topic, char * payload); +extern void MQTTSubscribe(char* topic, void *cb(char* topic, char* payload)); + +extern void UDPSend (char msg[128], int len); + +void MQTTCB_reply(char* topic, char* payload){ + char msg[50]; + + if(!replyListen) + return; + + sprintf(&msg, "%s heeft je hand geschud.", payload); + UDPSend(msg, strlen(msg)); +} + +void MQTTCB_request(char* topic, char* payload){ + char msg[128]; + uint8_t i; + + if(!requestListen) + return; + + // get student number from topic + if(strlen(topic) < 16+7){ + return; //ERROR invalid topic + } + for(i=0; i<7; i++){ + requestFrom[i] = topic[i+16]; + } + for(i=0; i timestamp){ + // reply to request + requestTimeout = 0; + + replyListen = false; + requestListen = true; + + char topic[128]; + sprintf(&topic, "ems20/handshake/%s/reply", requestFrom); + MQTTPublish(&topic[0], &yourName[0]); + char msg[128]; + sprintf(&msg, "Je hebt de hand geschud van %s.", requestFromName); + UDPSend(msg, strlen(msg)); + }else{ // send request + // replyListen = true; + // requestListen = false; + GPIO_write(CONFIG_LED_R, 1); + MQTTPublish(&requestTopic[0], &yourName[0]); + UDPSend("Handshake aangeboden", strlen("Handshake aangeboden")); + } +} + +void * handshakeTask(void *arg0){ + // create massage queue + mq_attr attr; + attr.mq_maxmsg = 10; + attr.mq_msgsize = sizeof(gsensorMsgQueue); + gsensorQueue = mq_open("gsensorQueue", O_CREAT, 0, &attr); + if(((int)gsensorQueue) <= 0){ + while(1); + } + + GPIO_write(CONFIG_LED_R, 0); + + gsensorMsgQueue queueElement; + double replyTimeout = -1; + + while(1){ + mq_receive(gsensorQueue, (char*)&queueElement, sizeof(gsensorMsgQueue), NULL); + + timestamp = queueElement.timestamp; + + if(replyTimeout >= timestamp){ + if(replyTimeout <= timestamp + 1){ + replyListen = false; + GPIO_write(CONFIG_LED_R, 0); + } + requestListen = true; + continue; + } + + if(requestTimeout > timestamp){ + GPIO_write(CONFIG_LED_R, 0x01 & (uint32_t)(timestamp*2)); + }else{ + GPIO_write(CONFIG_LED_R, 0); + } + + if(queueElement.g > G_THUSHOLD){ + if(queueElement.richting == Vooruit && timestamp - lastBack < TIME_BETWEEN_DIRECTION_CHANGE){ + replyTimeout = timestamp + TIMEOUT_DURATION; + handshake(); + } else if(queueElement.richting == Achteruit){ + lastBack = timestamp; + } + } + } +} + + diff --git a/src/main_tirtos.c b/src/main_tirtos.c index 7a03049..66d866b 100644 --- a/src/main_tirtos.c +++ b/src/main_tirtos.c @@ -1,142 +1,142 @@ -/* - * Copyright (c) 2016, Texas Instruments Incorporated - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * ======== main_tirtos.c ======== - */ -#include - -/* POSIX Header files */ -#include - -/* RTOS header files */ -#include - -/* TI-RTOS Header files */ -#include - -/* TI-DRIVERS Header files */ - -#include "ti_drivers_config.h" - -extern void * GSensorTask(void *arg0); -extern void * MQTTTask(void *arg0); -extern void * handshakeTask(void *arg0); -extern void * UDPClientTask(void *arg0); - -/* Stack size in bytes */ -#define BIGOLTHREADSTACK 4096 - -/* - * ======== main ======== - */ -int main(void) -{ - pthread_attr_t attrs; - struct sched_param priParam; - int retc; - - /* Call board init functions */ - Board_init(); - I2C_init(); - GPIO_init(); - - /* Initialize the attributes structure with default values */ - pthread_attr_init(&attrs); - - /* Set priority, detach state, and stack size attributes */ - priParam.sched_priority = 1; - retc = pthread_attr_setschedparam(&attrs, &priParam); - retc |= pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED); - retc |= pthread_attr_setstacksize(&attrs, BIGOLTHREADSTACK); - if (retc != 0) { -// LOG_CRITICAL("main(): failed to set tread attributes"); - while(1); - } - - - /* =============================================== - === thread for G sensor ======================= - =============================================== - */ - pthread_t GSensorThread; - retc = pthread_create(&GSensorThread, &attrs, GSensorTask, NULL); - if (retc != 0) { - while(1); - } - - - /* =============================================== - === thread for MQTT =========================== - =============================================== - */ - pthread_t MQTTThread; - retc = pthread_create(&MQTTThread, &attrs, MQTTTask, NULL); - if (retc != 0) { - while(1); - } - - - /* =============================================== - === thread for Handshake ====================== - =============================================== - */ - pthread_t HandshakeThread; - retc = pthread_create(&HandshakeThread, &attrs, handshakeTask, NULL); - if (retc != 0) { - while(1); - } - - /* =============================================== - * == thread for UDP ============================= - * =============================================== - */ - pthread_t UDPClientThread; - retc = pthread_create(&UDPClientThread, &attrs, UDPClientTask, NULL); - if (retc != 0) { - while(1); - } - - BIOS_start(); - - return (0); -} - -/* - * ======== dummyOutput ======== - * Dummy SysMin output function needed for benchmarks and size comparison - * of FreeRTOS and TI-RTOS solutions. - */ -void dummyOutput(void) -{ -} +/* + * Copyright (c) 2016, Texas Instruments Incorporated + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of Texas Instruments Incorporated nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * ======== main_tirtos.c ======== + */ +#include + +/* POSIX Header files */ +#include + +/* RTOS header files */ +#include + +/* TI-RTOS Header files */ +#include + +/* TI-DRIVERS Header files */ + +#include "ti_drivers_config.h" + +extern void * GSensorTask(void *arg0); +extern void * MQTTTask(void *arg0); +extern void * handshakeTask(void *arg0); +extern void * UDPClientTask(void *arg0); + +/* Stack size in bytes */ +#define BIGOLTHREADSTACK 4096 + +/* + * ======== main ======== + */ +int main(void) +{ + pthread_attr_t attrs; + struct sched_param priParam; + int retc; + + /* Call board init functions */ + Board_init(); + I2C_init(); + GPIO_init(); + + /* Initialize the attributes structure with default values */ + pthread_attr_init(&attrs); + + /* Set priority, detach state, and stack size attributes */ + priParam.sched_priority = 1; + retc = pthread_attr_setschedparam(&attrs, &priParam); + retc |= pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED); + retc |= pthread_attr_setstacksize(&attrs, BIGOLTHREADSTACK); + if (retc != 0) { +// LOG_CRITICAL("main(): failed to set tread attributes"); + while(1); + } + + + /* =============================================== + === thread for G sensor ======================= + =============================================== + */ + pthread_t GSensorThread; + retc = pthread_create(&GSensorThread, &attrs, GSensorTask, NULL); + if (retc != 0) { + while(1); + } + + + /* =============================================== + === thread for MQTT =========================== + =============================================== + */ + pthread_t MQTTThread; + retc = pthread_create(&MQTTThread, &attrs, MQTTTask, NULL); + if (retc != 0) { + while(1); + } + + + /* =============================================== + === thread for Handshake ====================== + =============================================== + */ + pthread_t HandshakeThread; + retc = pthread_create(&HandshakeThread, &attrs, handshakeTask, NULL); + if (retc != 0) { + while(1); + } + + /* =============================================== + * == thread for UDP ============================= + * =============================================== + */ + pthread_t UDPClientThread; + retc = pthread_create(&UDPClientThread, &attrs, UDPClientTask, NULL); + if (retc != 0) { + while(1); + } + + BIOS_start(); + + return (0); +} + +/* + * ======== dummyOutput ======== + * Dummy SysMin output function needed for benchmarks and size comparison + * of FreeRTOS and TI-RTOS solutions. + */ +void dummyOutput(void) +{ +} diff --git a/src/mqtt_client_app.c b/src/mqtt_client_app.c index 65f1e9c..937c3ec 100644 --- a/src/mqtt_client_app.c +++ b/src/mqtt_client_app.c @@ -1,605 +1,538 @@ -/* - * Copyright (c) 2016, Texas Instruments Incorporated - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of Texas Instruments Incorporated nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/***************************************************************************** - - Application Name - MQTT Client - Application Overview - The device is running a MQTT client which is - connected to the online broker. Three LEDs on the - device can be controlled from a web client by - publishing msg on appropriate topics. Similarly, - message can be published on pre-configured topics - by pressing the switch buttons on the device. - - Application Details - Refer to 'MQTT Client' README.html - -*****************************************************************************/ -#include "mqtt_if.h" -#include -#include -#include -#include - -#include -#include - -#include -// #include -// #include - -#include - -#include "network_if.h" -#include "uart_term.h" -#include "mqtt_if.h" -#include "debug_if.h" - -#include "ti_drivers_config.h" - -extern int32_t ti_net_SlNet_initConfig(); - -#define APPLICATION_NAME "Eindopdracht" -#define APPLICATION_VERSION "0.1.0" - -#define SL_TASKSTACKSIZE 2048 -#define SPAWN_TASK_PRIORITY 9 - -// un-comment this if you want to connect to an MQTT broker securely -//#define MQTT_SECURE_CLIENT - -#define MQTT_MODULE_TASK_PRIORITY 2 -#define MQTT_MODULE_TASK_STACK_SIZE 2048 - -#define MQTT_WILL_TOPIC "jesus_cc32xx_will_topic" -#define MQTT_WILL_MSG "will_msg_works" -#define MQTT_WILL_QOS MQTT_QOS_2 -#define MQTT_WILL_RETAIN false - -#define MQTT_CLIENT_PASSWORD NULL -#define MQTT_CLIENT_USERNAME NULL -#define MQTT_CLIENT_KEEPALIVE 0 -#define MQTT_CLIENT_CLEAN_CONNECT true -#define MQTT_CLIENT_MQTT_V3_1 true -#define MQTT_CLIENT_BLOCKING_SEND true - -#ifndef MQTT_SECURE_CLIENT -#define MQTT_CONNECTION_FLAGS MQTTCLIENT_NETCONN_URL -#define MQTT_CONNECTION_ADDRESS "mqtt.eclipse.org" -#define MQTT_CONNECTION_PORT_NUMBER 1883 -#else -#define MQTT_CONNECTION_FLAGS MQTTCLIENT_NETCONN_IP4 | MQTTCLIENT_NETCONN_SEC -#define MQTT_CONNECTION_ADDRESS "192.168.178.67" -#define MQTT_CONNECTION_PORT_NUMBER 8883 -#endif - -mqd_t appQueue; -int connected; -int deinit; -int longPress = 0; - -/* Client ID */ -/* If ClientId isn't set, the MAC address of the device will be copied into */ -/* the ClientID parameter. */ -char ClientId[13] = {'\0'}; - -extern void MQTTCB_reply(char* topic, char* payload); -extern void MQTTCB_request(char* topic, char* payload); - -enum{ - APP_MQTT_PUBLISH, - APP_MQTT_CON_TOGGLE, - APP_MQTT_DEINIT, - APP_BTN_HANDLER -}; - -struct msgQueue -{ - int event; - char* topic; - char* payload; -}; - -MQTT_IF_InitParams_t mqttInitParams = -{ - MQTT_MODULE_TASK_STACK_SIZE, // stack size for mqtt module - default is 2048 - MQTT_MODULE_TASK_PRIORITY // thread priority for MQTT - default is 2 -}; - -MQTTClient_Will mqttWillParams = -{ - MQTT_WILL_TOPIC, // will topic - MQTT_WILL_MSG, // will message - MQTT_WILL_QOS, // will QoS - MQTT_WILL_RETAIN // retain flag -}; - -MQTT_IF_ClientParams_t mqttClientParams = -{ - ClientId, // client ID - MQTT_CLIENT_USERNAME, // user name - MQTT_CLIENT_PASSWORD, // password - MQTT_CLIENT_KEEPALIVE, // keep-alive time - MQTT_CLIENT_CLEAN_CONNECT, // clean connect flag - MQTT_CLIENT_MQTT_V3_1, // true = 3.1, false = 3.1.1 - MQTT_CLIENT_BLOCKING_SEND, // blocking send flag - &mqttWillParams // will parameters -}; - -#ifndef MQTT_SECURE_CLIENT -MQTTClient_ConnParams mqttConnParams = -{ - MQTT_CONNECTION_FLAGS, // connection flags - MQTT_CONNECTION_ADDRESS, // server address - MQTT_CONNECTION_PORT_NUMBER, // port number of MQTT server - 0, // method for secure socket - 0, // cipher for secure socket - 0, // number of files for secure connection - NULL // secure files -}; -#else -/* - * In order to connect to an MQTT broker securely, the MQTTCLIENT_NETCONN_SEC flag, - * method for secure socket, cipher, secure files, number of secure files must be set - * and the certificates must be programmed to the file system. - * - * The first parameter is a bit mask which configures the server address type and security mode. - * Server address type: IPv4, IPv6 and URL must be declared with the corresponding flag. - * All flags can be found in mqttclient.h. - * - * The flag MQTTCLIENT_NETCONN_SEC enables the security (TLS) which includes domain name - * verification and certificate catalog verification. Those verifications can be skipped by - * adding to the bit mask: MQTTCLIENT_NETCONN_SKIP_DOMAIN_NAME_VERIFICATION and - * MQTTCLIENT_NETCONN_SKIP_CERTIFICATE_CATALOG_VERIFICATION. - * - * Note: The domain name verification requires URL Server address type otherwise, this - * verification will be disabled. - * - * Secure clients require time configuration in order to verify the server certificate validity (date) - */ - -/* Day of month (DD format) range 1-31 */ -#define DAY 1 -/* Month (MM format) in the range of 1-12 */ -#define MONTH 5 -/* Year (YYYY format) */ -#define YEAR 2020 -/* Hours in the range of 0-23 */ -#define HOUR 4 -/* Minutes in the range of 0-59 */ -#define MINUTES 00 -/* Seconds in the range of 0-59 */ -#define SEC 00 - -char *MQTTClient_secureFiles[1] = {"ca-cert.pem"}; - -MQTTClient_ConnParams mqttConnParams = -{ - MQTT_CONNECTION_FLAGS, // connection flags - MQTT_CONNECTION_ADDRESS, // server address - MQTT_CONNECTION_PORT_NUMBER, // port number of MQTT server - SLNETSOCK_SEC_METHOD_SSLv3_TLSV1_2, // method for secure socket - SLNETSOCK_SEC_CIPHER_FULL_LIST, // cipher for secure socket - 1, // number of files for secure connection - MQTTClient_secureFiles // secure files -}; - -void setTime(){ - - SlDateTime_t dateTime = {0}; - dateTime.tm_day = (uint32_t)DAY; - dateTime.tm_mon = (uint32_t)MONTH; - dateTime.tm_year = (uint32_t)YEAR; - dateTime.tm_hour = (uint32_t)HOUR; - dateTime.tm_min = (uint32_t)MINUTES; - dateTime.tm_sec = (uint32_t)SEC; - sl_DeviceSet(SL_DEVICE_GENERAL, SL_DEVICE_GENERAL_DATE_TIME, - sizeof(SlDateTime_t), (uint8_t *)(&dateTime)); -} -#endif - -//***************************************************************************** -//! -//! Set the ClientId with its own mac address -//! This routine converts the mac address which is given -//! by an integer type variable in hexadecimal base to ASCII -//! representation, and copies it into the ClientId parameter. -//! -//! \param macAddress - Points to string Hex. -//! -//! \return void. -//! -//***************************************************************************** -int32_t SetClientIdNamefromMacAddress() -{ - int32_t ret = 0; - uint8_t Client_Mac_Name[2]; - uint8_t Index; - uint16_t macAddressLen = SL_MAC_ADDR_LEN; - uint8_t macAddress[SL_MAC_ADDR_LEN]; - - /*Get the device Mac address */ - ret = sl_NetCfgGet(SL_NETCFG_MAC_ADDRESS_GET, 0, &macAddressLen, - &macAddress[0]); - - /*When ClientID isn't set, use the mac address as ClientID */ - if(ClientId[0] == '\0') - { - /*6 bytes is the length of the mac address */ - for(Index = 0; Index < SL_MAC_ADDR_LEN; Index++) - { - /*Each mac address byte contains two hexadecimal characters */ - /*Copy the 4 MSB - the most significant character */ - Client_Mac_Name[0] = (macAddress[Index] >> 4) & 0xf; - /*Copy the 4 LSB - the least significant character */ - Client_Mac_Name[1] = macAddress[Index] & 0xf; - - if(Client_Mac_Name[0] > 9) - { - /*Converts and copies from number that is greater than 9 in */ - /*hexadecimal representation (a to f) into ascii character */ - ClientId[2 * Index] = Client_Mac_Name[0] + 'a' - 10; - } - else - { - /*Converts and copies from number 0 - 9 in hexadecimal */ - /*representation into ascii character */ - ClientId[2 * Index] = Client_Mac_Name[0] + '0'; - } - if(Client_Mac_Name[1] > 9) - { - /*Converts and copies from number that is greater than 9 in */ - /*hexadecimal representation (a to f) into ascii character */ - ClientId[2 * Index + 1] = Client_Mac_Name[1] + 'a' - 10; - } - else - { - /*Converts and copies from number 0 - 9 in hexadecimal */ - /*representation into ascii character */ - ClientId[2 * Index + 1] = Client_Mac_Name[1] + '0'; - } - } - } - return(ret); -} - - -void MQTT_EventCallback(int32_t event){ - - struct msgQueue queueElement; - - switch(event){ - - case MQTT_EVENT_CONNACK: - { - deinit = 0; - connected = 1; - LOG_INFO("MQTT_EVENT_CONNACK\r\n"); - // GPIO_clearInt(CONFIG_GPIO_BUTTON_1); - // GPIO_enableInt(CONFIG_GPIO_BUTTON_1); - break; - } - - case MQTT_EVENT_SUBACK: - { - LOG_INFO("MQTT_EVENT_SUBACK\r\n"); - break; - } - - case MQTT_EVENT_PUBACK: - { - LOG_INFO("MQTT_EVENT_PUBACK\r\n"); - break; - } - - case MQTT_EVENT_UNSUBACK: - { - LOG_INFO("MQTT_EVENT_UNSUBACK\r\n"); - break; - } - - case MQTT_EVENT_CLIENT_DISCONNECT: - { - connected = 0; - LOG_INFO("MQTT_EVENT_CLIENT_DISCONNECT\r\n"); - if(deinit == 0){ - // GPIO_clearInt(CONFIG_GPIO_BUTTON_1); - // GPIO_enableInt(CONFIG_GPIO_BUTTON_1); - } - break; - } - - case MQTT_EVENT_SERVER_DISCONNECT: - { - connected = 0; - - LOG_INFO("MQTT_EVENT_SERVER_DISCONNECT\r\n"); - - queueElement.event = APP_MQTT_CON_TOGGLE; - int res = mq_send(appQueue, (const char*)&queueElement, sizeof(struct msgQueue), 0); - if(res < 0){ - LOG_ERROR("msg queue send error %d", res); - } - break; - } - - case MQTT_EVENT_DESTROY: - { - LOG_INFO("MQTT_EVENT_DESTROY\r\n"); - break; - } - } -} - -int32_t DisplayAppBanner(char* appName, char* appVersion){ - - int32_t ret = 0; - uint8_t macAddress[SL_MAC_ADDR_LEN]; - uint16_t macAddressLen = SL_MAC_ADDR_LEN; - uint16_t ConfigSize = 0; - uint8_t ConfigOpt = SL_DEVICE_GENERAL_VERSION; - SlDeviceVersion_t ver = {0}; - - ConfigSize = sizeof(SlDeviceVersion_t); - - // get the device version info and MAC address - ret = sl_DeviceGet(SL_DEVICE_GENERAL, &ConfigOpt, &ConfigSize, (uint8_t*)(&ver)); - ret |= (int32_t)sl_NetCfgGet(SL_NETCFG_MAC_ADDRESS_GET, 0, &macAddressLen, &macAddress[0]); - - UART_PRINT("\n\r\t============================================\n\r"); - UART_PRINT("\t %s V%s",appName, appVersion); - UART_PRINT("\n\r\t============================================\n\r\n\r"); - - UART_PRINT("\t CHIP: 0x%x\n\r",ver.ChipId); - UART_PRINT("\t MAC: %d.%d.%d.%d\n\r",ver.FwVersion[0],ver.FwVersion[1], - ver.FwVersion[2], - ver.FwVersion[3]); - UART_PRINT("\t PHY: %d.%d.%d.%d\n\r",ver.PhyVersion[0],ver.PhyVersion[1], - ver.PhyVersion[2], - ver.PhyVersion[3]); - UART_PRINT("\t NWP: %d.%d.%d.%d\n\r",ver.NwpVersion[0],ver.NwpVersion[1], - ver.NwpVersion[2], - ver.NwpVersion[3]); - UART_PRINT("\t ROM: %d\n\r",ver.RomVersion); - UART_PRINT("\t HOST: %s\n\r", SL_DRIVER_VERSION); - UART_PRINT("\t MAC address: %02x:%02x:%02x:%02x:%02x:%02x\r\n", macAddress[0], - macAddress[1], macAddress[2], macAddress[3], macAddress[4], - macAddress[5]); - UART_PRINT("\n\r\t============================================\n\r"); - - return(ret); -} - -int WifiInit(){ - - int32_t ret; - SlWlanSecParams_t security_params; - pthread_t spawn_thread = (pthread_t) NULL; - pthread_attr_t pattrs_spawn; - struct sched_param pri_param; - - pthread_attr_init(&pattrs_spawn); - pri_param.sched_priority = SPAWN_TASK_PRIORITY; - ret = pthread_attr_setschedparam(&pattrs_spawn, &pri_param); - ret |= pthread_attr_setstacksize(&pattrs_spawn, SL_TASKSTACKSIZE); - ret |= pthread_attr_setdetachstate(&pattrs_spawn, PTHREAD_CREATE_DETACHED); - ret = pthread_create(&spawn_thread, &pattrs_spawn, sl_Task, NULL); - if(ret != 0){ - LOG_ERROR("could not create simplelink task"); - while(1); - } - - Network_IF_ResetMCUStateMachine(); - - Network_IF_DeInitDriver(); - - ret = Network_IF_InitDriver(ROLE_STA); - if(ret < 0){ - LOG_ERROR("Failed to start SimpleLink Device"); - while(1); - } - - DisplayAppBanner(APPLICATION_NAME, APPLICATION_VERSION); - - SetClientIdNamefromMacAddress(); - - security_params.Key = (signed char*)SECURITY_KEY; - security_params.KeyLen = strlen(SECURITY_KEY); - security_params.Type = SECURITY_TYPE; - - ret = Network_IF_ConnectAP(SSID_NAME, security_params); - if(ret < 0){ - LOG_ERROR("Connection to an AP failed"); - } - else{ - - SlWlanSecParams_t securityParams; - - securityParams.Type = SECURITY_TYPE; - securityParams.Key = (signed char*)SECURITY_KEY; - securityParams.KeyLen = strlen((const char *)securityParams.Key); - - ret = sl_WlanProfileAdd((signed char*)SSID_NAME, strlen(SSID_NAME), 0, &securityParams, NULL, 7, 0); - if(ret < 0){ - LOG_ERROR("failed to add profile %s", SSID_NAME); - } - else{ - LOG_INFO("profile added %s", SSID_NAME); - } - } - - return ret; -} - -void MQTTPublish(char * topic, char * payload){ - struct msgQueue queueElement; - queueElement.event = APP_MQTT_PUBLISH; - queueElement.topic = topic; - queueElement.payload = payload; - int res = mq_send(appQueue, (const char*)&queueElement, sizeof(struct msgQueue), 0); -} - -// void MQTTSubscribe(char* topic, void *cb(char* topic, char* payload)){ -// uint8_t ret = MQTT_IF_Subscribe(0, topic, MQTT_QOS_2, cb); -// } - -void MQTTTask(void * args){ - - int32_t ret; - UART_Handle uartHandle; - struct msgQueue queueElement; - - uartHandle = InitTerm(); - UART_control(uartHandle, UART_CMD_RXDISABLE, NULL); - - SPI_init(); - - ret = ti_net_SlNet_initConfig(); - if(0 != ret) - { - LOG_ERROR("Failed to initialize SlNetSock"); - } - - mq_attr attr; - attr.mq_maxmsg = 10; - attr.mq_msgsize = sizeof(struct msgQueue); - appQueue = mq_open("appQueue", O_CREAT, 0, &attr); - if(((int)appQueue) <= 0){ - while(1); - } - - ret = WifiInit(); - if(ret < 0){ - while(1); - } - - ret = MQTT_IF_Init(mqttInitParams); - if(ret < 0){ - while(1); - } - -#ifdef MQTT_SECURE_CLIENT - setTime(); -#endif - - MQTTClient_Handle mqttClientHandle; - - /* - * In case a persistent session is being used, subscribe is called before connect so that the module - * is aware of the topic callbacks the user is using. This is important because if the broker is holding - * messages for the client, after CONNACK the client may receive the messages before the module is aware - * of the topic callbacks. The user may still call subscribe after connect but have to be aware of this. - */ - ret = 0; - ret |= MQTT_IF_Subscribe(mqttClientHandle, "ems20/handshake/0964590/reply", MQTT_QOS_2, &MQTTCB_reply); - ret |= MQTT_IF_Subscribe(mqttClientHandle, "ems20/handshake/0971472/request", MQTT_QOS_2, &MQTTCB_request); - if(ret < 0){ - LOG_ERROR("Faild to Subscribed to topics\r\n"); - while(1); - } - else{ - LOG_INFO("Subscribed to all topics successfully\r\n"); - } - - mqttClientHandle = MQTT_IF_Connect(mqttClientParams, mqttConnParams, MQTT_EventCallback); - if(mqttClientHandle < 0){ - while(1); - } - - // wait for CONNACK - while(connected == 0); - - // GPIO_enableInt(CONFIG_GPIO_BUTTON_0); - - while(1){ - - mq_receive(appQueue, (char*)&queueElement, sizeof(struct msgQueue), NULL); - - if(queueElement.event == APP_MQTT_PUBLISH){ - - LOG_TRACE("APP_MQTT_PUBLISH"); - - MQTT_IF_Publish(mqttClientHandle, - queueElement.topic, - queueElement.payload, - strlen(queueElement.payload), - MQTT_QOS_2); - - } - else if(queueElement.event == APP_MQTT_CON_TOGGLE){ - - LOG_TRACE("APP_MQTT_CON_TOGGLE %d", connected); - - - if(connected){ - ret = MQTT_IF_Disconnect(mqttClientHandle); - if(ret >= 0){ - connected = 0; - } - } - else{ - mqttClientHandle = MQTT_IF_Connect(mqttClientParams, mqttConnParams, MQTT_EventCallback); - if((int)mqttClientHandle >= 0){ - connected = 1; - } - } - } - else if(queueElement.event == APP_BTN_HANDLER){ - LOG_TRACE("APP_BTN_HANDLER: does nothing"); - - // struct msgQueue queueElement; - - // ret = detectLongPress(); - // if(ret == 0){ - - // LOG_TRACE("APP_BTN_HANDLER SHORT PRESS\r\n"); - // queueElement.event = APP_MQTT_CON_TOGGLE; - // } - // else{ - - // LOG_TRACE("APP_BTN_HANDLER LONG PRESS\r\n"); - // queueElement.event = APP_MQTT_DEINIT; - // } - - // ret = mq_send(appQueue, (const char*)&queueElement, sizeof(struct msgQueue), 0); - // if(ret < 0){ - // LOG_ERROR("msg queue send error %d", ret); - // } - } - } -} - -//***************************************************************************** -// -// Close the Doxygen group. -//! @} -// -//***************************************************************************** +/* + * Copyright (c) 2016, Texas Instruments Incorporated + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of Texas Instruments Incorporated nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/***************************************************************************** + + Application Name - MQTT Client + Application Overview - The device is running a MQTT client which is + connected to the online broker. Three LEDs on the + device can be controlled from a web client by + publishing msg on appropriate topics. Similarly, + message can be published on pre-configured topics + by pressing the switch buttons on the device. + + Application Details - Refer to 'MQTT Client' README.html + +*****************************************************************************/ +#include "mqtt_if.h" +#include +#include +#include +#include + +#include +#include + +#include + +#include + +#include "network_if.h" +#include "uart_term.h" +#include "mqtt_if.h" +#include "debug_if.h" + +#include "ti_drivers_config.h" + +extern int32_t ti_net_SlNet_initConfig(); + +#define APPLICATION_NAME "Eindopdracht" +#define APPLICATION_VERSION "0.1.0" + +#define SL_TASKSTACKSIZE 2048 +#define SPAWN_TASK_PRIORITY 9 + +// un-comment this if you want to connect to an MQTT broker securely +//#define MQTT_SECURE_CLIENT + +#define MQTT_MODULE_TASK_PRIORITY 2 +#define MQTT_MODULE_TASK_STACK_SIZE 2048 + +#define MQTT_WILL_TOPIC "jesus_cc32xx_will_topic" +#define MQTT_WILL_MSG "will_msg_works" +#define MQTT_WILL_QOS MQTT_QOS_2 +#define MQTT_WILL_RETAIN false + +#define MQTT_CLIENT_PASSWORD NULL +#define MQTT_CLIENT_USERNAME NULL +#define MQTT_CLIENT_KEEPALIVE 0 +#define MQTT_CLIENT_CLEAN_CONNECT true +#define MQTT_CLIENT_MQTT_V3_1 true +#define MQTT_CLIENT_BLOCKING_SEND true + +#ifndef MQTT_SECURE_CLIENT +#define MQTT_CONNECTION_FLAGS MQTTCLIENT_NETCONN_URL +#define MQTT_CONNECTION_ADDRESS "mqtt.eclipse.org" +#define MQTT_CONNECTION_PORT_NUMBER 1883 +#else +#define MQTT_CONNECTION_FLAGS MQTTCLIENT_NETCONN_IP4 | MQTTCLIENT_NETCONN_SEC +#define MQTT_CONNECTION_ADDRESS "192.168.178.67" +#define MQTT_CONNECTION_PORT_NUMBER 8883 +#endif + +mqd_t appQueue; +int connected; +int deinit; +int longPress = 0; + +/* Client ID */ +/* If ClientId isn't set, the MAC address of the device will be copied into */ +/* the ClientID parameter. */ +char ClientId[13] = {'\0'}; + +extern void MQTTCB_reply(char* topic, char* payload); +extern void MQTTCB_request(char* topic, char* payload); + +enum{ + APP_MQTT_PUBLISH, + APP_MQTT_CON_TOGGLE, + APP_MQTT_DEINIT, + APP_BTN_HANDLER +}; + +struct msgQueue +{ + int event; + char* topic; + char* payload; +}; + +MQTT_IF_InitParams_t mqttInitParams = +{ + MQTT_MODULE_TASK_STACK_SIZE, // stack size for mqtt module - default is 2048 + MQTT_MODULE_TASK_PRIORITY // thread priority for MQTT - default is 2 +}; + +MQTTClient_Will mqttWillParams = +{ + MQTT_WILL_TOPIC, // will topic + MQTT_WILL_MSG, // will message + MQTT_WILL_QOS, // will QoS + MQTT_WILL_RETAIN // retain flag +}; + +MQTT_IF_ClientParams_t mqttClientParams = +{ + ClientId, // client ID + MQTT_CLIENT_USERNAME, // user name + MQTT_CLIENT_PASSWORD, // password + MQTT_CLIENT_KEEPALIVE, // keep-alive time + MQTT_CLIENT_CLEAN_CONNECT, // clean connect flag + MQTT_CLIENT_MQTT_V3_1, // true = 3.1, false = 3.1.1 + MQTT_CLIENT_BLOCKING_SEND, // blocking send flag + &mqttWillParams // will parameters +}; + +MQTTClient_ConnParams mqttConnParams = +{ + MQTT_CONNECTION_FLAGS, // connection flags + MQTT_CONNECTION_ADDRESS, // server address + MQTT_CONNECTION_PORT_NUMBER, // port number of MQTT server + 0, // method for secure socket + 0, // cipher for secure socket + 0, // number of files for secure connection + NULL // secure files +}; + +//***************************************************************************** +//! +//! Set the ClientId with its own mac address +//! This routine converts the mac address which is given +//! by an integer type variable in hexadecimal base to ASCII +//! representation, and copies it into the ClientId parameter. +//! +//! \param macAddress - Points to string Hex. +//! +//! \return void. +//! +//***************************************************************************** +int32_t SetClientIdNamefromMacAddress() +{ + int32_t ret = 0; + uint8_t Client_Mac_Name[2]; + uint8_t Index; + uint16_t macAddressLen = SL_MAC_ADDR_LEN; + uint8_t macAddress[SL_MAC_ADDR_LEN]; + + /*Get the device Mac address */ + ret = sl_NetCfgGet(SL_NETCFG_MAC_ADDRESS_GET, 0, &macAddressLen, + &macAddress[0]); + + /*When ClientID isn't set, use the mac address as ClientID */ + if(ClientId[0] == '\0') + { + /*6 bytes is the length of the mac address */ + for(Index = 0; Index < SL_MAC_ADDR_LEN; Index++) + { + /*Each mac address byte contains two hexadecimal characters */ + /*Copy the 4 MSB - the most significant character */ + Client_Mac_Name[0] = (macAddress[Index] >> 4) & 0xf; + /*Copy the 4 LSB - the least significant character */ + Client_Mac_Name[1] = macAddress[Index] & 0xf; + + if(Client_Mac_Name[0] > 9) + { + /*Converts and copies from number that is greater than 9 in */ + /*hexadecimal representation (a to f) into ascii character */ + ClientId[2 * Index] = Client_Mac_Name[0] + 'a' - 10; + } + else + { + /*Converts and copies from number 0 - 9 in hexadecimal */ + /*representation into ascii character */ + ClientId[2 * Index] = Client_Mac_Name[0] + '0'; + } + if(Client_Mac_Name[1] > 9) + { + /*Converts and copies from number that is greater than 9 in */ + /*hexadecimal representation (a to f) into ascii character */ + ClientId[2 * Index + 1] = Client_Mac_Name[1] + 'a' - 10; + } + else + { + /*Converts and copies from number 0 - 9 in hexadecimal */ + /*representation into ascii character */ + ClientId[2 * Index + 1] = Client_Mac_Name[1] + '0'; + } + } + } + return(ret); +} + + +void MQTT_EventCallback(int32_t event){ + + struct msgQueue queueElement; + + switch(event){ + + case MQTT_EVENT_CONNACK: + { + deinit = 0; + connected = 1; + LOG_INFO("MQTT_EVENT_CONNACK\r\n"); + // GPIO_clearInt(CONFIG_GPIO_BUTTON_1); + // GPIO_enableInt(CONFIG_GPIO_BUTTON_1); + break; + } + + case MQTT_EVENT_SUBACK: + { + LOG_INFO("MQTT_EVENT_SUBACK\r\n"); + break; + } + + case MQTT_EVENT_PUBACK: + { + LOG_INFO("MQTT_EVENT_PUBACK\r\n"); + break; + } + + case MQTT_EVENT_UNSUBACK: + { + LOG_INFO("MQTT_EVENT_UNSUBACK\r\n"); + break; + } + + case MQTT_EVENT_CLIENT_DISCONNECT: + { + connected = 0; + LOG_INFO("MQTT_EVENT_CLIENT_DISCONNECT\r\n"); + if(deinit == 0){ + // GPIO_clearInt(CONFIG_GPIO_BUTTON_1); + // GPIO_enableInt(CONFIG_GPIO_BUTTON_1); + } + break; + } + + case MQTT_EVENT_SERVER_DISCONNECT: + { + connected = 0; + + LOG_INFO("MQTT_EVENT_SERVER_DISCONNECT\r\n"); + + queueElement.event = APP_MQTT_CON_TOGGLE; + int res = mq_send(appQueue, (const char*)&queueElement, sizeof(struct msgQueue), 0); + if(res < 0){ + LOG_ERROR("msg queue send error %d", res); + } + break; + } + + case MQTT_EVENT_DESTROY: + { + LOG_INFO("MQTT_EVENT_DESTROY\r\n"); + break; + } + } +} + +int32_t DisplayAppBanner(char* appName, char* appVersion){ + + int32_t ret = 0; + uint8_t macAddress[SL_MAC_ADDR_LEN]; + uint16_t macAddressLen = SL_MAC_ADDR_LEN; + uint16_t ConfigSize = 0; + uint8_t ConfigOpt = SL_DEVICE_GENERAL_VERSION; + SlDeviceVersion_t ver = {0}; + + ConfigSize = sizeof(SlDeviceVersion_t); + + // get the device version info and MAC address + ret = sl_DeviceGet(SL_DEVICE_GENERAL, &ConfigOpt, &ConfigSize, (uint8_t*)(&ver)); + ret |= (int32_t)sl_NetCfgGet(SL_NETCFG_MAC_ADDRESS_GET, 0, &macAddressLen, &macAddress[0]); + + UART_PRINT("\n\r\t============================================\n\r"); + UART_PRINT("\t %s V%s",appName, appVersion); + UART_PRINT("\n\r\t============================================\n\r\n\r"); + + UART_PRINT("\t CHIP: 0x%x\n\r",ver.ChipId); + UART_PRINT("\t MAC: %d.%d.%d.%d\n\r",ver.FwVersion[0],ver.FwVersion[1], + ver.FwVersion[2], + ver.FwVersion[3]); + UART_PRINT("\t PHY: %d.%d.%d.%d\n\r",ver.PhyVersion[0],ver.PhyVersion[1], + ver.PhyVersion[2], + ver.PhyVersion[3]); + UART_PRINT("\t NWP: %d.%d.%d.%d\n\r",ver.NwpVersion[0],ver.NwpVersion[1], + ver.NwpVersion[2], + ver.NwpVersion[3]); + UART_PRINT("\t ROM: %d\n\r",ver.RomVersion); + UART_PRINT("\t HOST: %s\n\r", SL_DRIVER_VERSION); + UART_PRINT("\t MAC address: %02x:%02x:%02x:%02x:%02x:%02x\r\n", macAddress[0], + macAddress[1], macAddress[2], macAddress[3], macAddress[4], + macAddress[5]); + UART_PRINT("\n\r\t============================================\n\r"); + + return(ret); +} + +int WifiInit(){ + + int32_t ret; + SlWlanSecParams_t security_params; + pthread_t spawn_thread = (pthread_t) NULL; + pthread_attr_t pattrs_spawn; + struct sched_param pri_param; + + pthread_attr_init(&pattrs_spawn); + pri_param.sched_priority = SPAWN_TASK_PRIORITY; + ret = pthread_attr_setschedparam(&pattrs_spawn, &pri_param); + ret |= pthread_attr_setstacksize(&pattrs_spawn, SL_TASKSTACKSIZE); + ret |= pthread_attr_setdetachstate(&pattrs_spawn, PTHREAD_CREATE_DETACHED); + ret = pthread_create(&spawn_thread, &pattrs_spawn, sl_Task, NULL); + if(ret != 0){ + LOG_ERROR("could not create simplelink task"); + while(1); + } + + Network_IF_ResetMCUStateMachine(); + + Network_IF_DeInitDriver(); + + ret = Network_IF_InitDriver(ROLE_STA); + if(ret < 0){ + LOG_ERROR("Failed to start SimpleLink Device"); + while(1); + } + + DisplayAppBanner(APPLICATION_NAME, APPLICATION_VERSION); + + SetClientIdNamefromMacAddress(); + + security_params.Key = (signed char*)SECURITY_KEY; + security_params.KeyLen = strlen(SECURITY_KEY); + security_params.Type = SECURITY_TYPE; + + ret = Network_IF_ConnectAP(SSID_NAME, security_params); + if(ret < 0){ + LOG_ERROR("Connection to an AP failed"); + } + else{ + + SlWlanSecParams_t securityParams; + + securityParams.Type = SECURITY_TYPE; + securityParams.Key = (signed char*)SECURITY_KEY; + securityParams.KeyLen = strlen((const char *)securityParams.Key); + + ret = sl_WlanProfileAdd((signed char*)SSID_NAME, strlen(SSID_NAME), 0, &securityParams, NULL, 7, 0); + if(ret < 0){ + LOG_ERROR("failed to add profile %s", SSID_NAME); + } + else{ + LOG_INFO("profile added %s", SSID_NAME); + } + } + + return ret; +} + +void MQTTPublish(char * topic, char * payload){ + struct msgQueue queueElement; + queueElement.event = APP_MQTT_PUBLISH; + queueElement.topic = topic; + queueElement.payload = payload; + int res = mq_send(appQueue, (const char*)&queueElement, sizeof(struct msgQueue), 0); +} + +void MQTTTask(void * args){ + + int32_t ret; + UART_Handle uartHandle; + struct msgQueue queueElement; + + uartHandle = InitTerm(); + UART_control(uartHandle, UART_CMD_RXDISABLE, NULL); + + SPI_init(); + + ret = ti_net_SlNet_initConfig(); + if(0 != ret) + { + LOG_ERROR("Failed to initialize SlNetSock"); + } + + mq_attr attr; + attr.mq_maxmsg = 10; + attr.mq_msgsize = sizeof(struct msgQueue); + appQueue = mq_open("appQueue", O_CREAT, 0, &attr); + if(((int)appQueue) <= 0){ + while(1); + } + + ret = WifiInit(); + if(ret < 0){ + while(1); + } + + ret = MQTT_IF_Init(mqttInitParams); + if(ret < 0){ + while(1); + } + +#ifdef MQTT_SECURE_CLIENT + setTime(); +#endif + + MQTTClient_Handle mqttClientHandle; + + /* + * In case a persistent session is being used, subscribe is called before connect so that the module + * is aware of the topic callbacks the user is using. This is important because if the broker is holding + * messages for the client, after CONNACK the client may receive the messages before the module is aware + * of the topic callbacks. The user may still call subscribe after connect but have to be aware of this. + */ + ret = 0; + ret |= MQTT_IF_Subscribe(mqttClientHandle, "ems20/handshake/0964590/reply", MQTT_QOS_2, &MQTTCB_reply); + ret |= MQTT_IF_Subscribe(mqttClientHandle, "ems20/handshake/0971472/request", MQTT_QOS_2, &MQTTCB_request); + if(ret < 0){ + LOG_ERROR("Faild to Subscribed to topics\r\n"); + while(1); + } + else{ + LOG_INFO("Subscribed to all topics successfully\r\n"); + } + + mqttClientHandle = MQTT_IF_Connect(mqttClientParams, mqttConnParams, MQTT_EventCallback); + if(mqttClientHandle < 0){ + while(1); + } + + // wait for CONNACK + while(connected == 0); + + // GPIO_enableInt(CONFIG_GPIO_BUTTON_0); + + while(1){ + + mq_receive(appQueue, (char*)&queueElement, sizeof(struct msgQueue), NULL); + + if(queueElement.event == APP_MQTT_PUBLISH){ + + LOG_TRACE("APP_MQTT_PUBLISH"); + + MQTT_IF_Publish(mqttClientHandle, + queueElement.topic, + queueElement.payload, + strlen(queueElement.payload), + MQTT_QOS_2); + + } + else if(queueElement.event == APP_MQTT_CON_TOGGLE){ + + LOG_TRACE("APP_MQTT_CON_TOGGLE %d", connected); + + + if(connected){ + ret = MQTT_IF_Disconnect(mqttClientHandle); + if(ret >= 0){ + connected = 0; + } + } + else{ + mqttClientHandle = MQTT_IF_Connect(mqttClientParams, mqttConnParams, MQTT_EventCallback); + if((int)mqttClientHandle >= 0){ + connected = 1; + } + } + } + else if(queueElement.event == APP_BTN_HANDLER){ + LOG_TRACE("APP_BTN_HANDLER: does nothing"); + + // struct msgQueue queueElement; + + // ret = detectLongPress(); + // if(ret == 0){ + + // LOG_TRACE("APP_BTN_HANDLER SHORT PRESS\r\n"); + // queueElement.event = APP_MQTT_CON_TOGGLE; + // } + // else{ + + // LOG_TRACE("APP_BTN_HANDLER LONG PRESS\r\n"); + // queueElement.event = APP_MQTT_DEINIT; + // } + + // ret = mq_send(appQueue, (const char*)&queueElement, sizeof(struct msgQueue), 0); + // if(ret < 0){ + // LOG_ERROR("msg queue send error %d", ret); + // } + } + } +} + +//***************************************************************************** +// +// Close the Doxygen group. +//! @} +// +//***************************************************************************** diff --git a/src/udp_client.c b/src/udp_client.c index cb07ece..575c483 100644 --- a/src/udp_client.c +++ b/src/udp_client.c @@ -1,75 +1,75 @@ -/* - * udp_client.c - * - * Created on: 6 Nov 2020 - * Author: BramB - */ - -#include -#include -#include - -Display_Handle lookielookie; -mqd_t UDPQueue; - -#define UDP_PORT sl_Htons(12345) // Port gedefineerd in de UDP server -#define UDP_IP sl_Htonl(SL_IPV4_VAL(10, 2, 0, 2)) // IP gedefineerd in de UDP server - -typedef struct { - _u8 buffboi[128]; - _u8 len; -} UDPMsgQueue; - -void UDPSend (char msg[128], int len) { - UDPMsgQueue Msg; - uint8_t i; - for(i=0; i<128; i++){ - Msg.buffboi[i] = msg[i]; - } - Msg.len = len; - mq_send(UDPQueue, (const char*)&Msg.buffboi, sizeof(UDPMsgQueue), 0); -} - -void* UDPClientTask(void *args) { - sleep(2); - - _i16 sokken = sl_Socket(SL_AF_INET, SL_SOCK_DGRAM, SL_IPPROTO_UDP); - if (sokken < 0) { - while(1); - } - - SlSockAddrIn_t clientAddress = {SL_AF_INET, UDP_PORT, sl_Htonl(SL_INADDR_ANY)}; - SlSockAddrIn_t serverAddress = {SL_AF_INET, UDP_PORT, UDP_IP}; - - _i16 error = sl_Connect(sokken, (SlSockAddr_t *)&serverAddress, sizeof(serverAddress)); - if (error < 0) { - while(1); - } - - _u8 buffering[100]; - -// _i16 sokkenAan = sl_Recv(sokken, &buffering, 100, 0); -// if (error < 0) { -// while(1); -// } - Display_printf(lookielookie, 0, 0, "Ontvangen van server: %s", buffering); - - mq_attr attr; - attr.mq_maxmsg = 10; - attr.mq_msgsize = sizeof(UDPMsgQueue); - UDPQueue = mq_open("UDPQueue", O_CREAT, 0, &attr); - if(((int)UDPQueue) <= 0){ - while(1); - } - - UDPMsgQueue queueElement; - - while(1) { - mq_receive(UDPQueue, (char*)&queueElement, sizeof(UDPMsgQueue), NULL); - - error = sl_Send(sokken, &queueElement.buffboi, queueElement.len, NULL); - if (error < 0) { - while(1); - } - } -} +/* + * udp_client.c + * + * Created on: 6 Nov 2020 + * Author: BramB + */ + +#include +#include +#include + +Display_Handle lookielookie; +mqd_t UDPQueue; + +#define UDP_PORT sl_Htons(12345) // Port gedefineerd in de UDP server +#define UDP_IP sl_Htonl(SL_IPV4_VAL(10, 2, 0, 2)) // IP gedefineerd in de UDP server + +typedef struct { + _u8 buffboi[128]; + _u8 len; +} UDPMsgQueue; + +void UDPSend (char msg[128], int len) { + UDPMsgQueue Msg; + uint8_t i; + for(i=0; i<128; i++){ + Msg.buffboi[i] = msg[i]; + } + Msg.len = len; + mq_send(UDPQueue, (const char*)&Msg.buffboi, sizeof(UDPMsgQueue), 0); +} + +void* UDPClientTask(void *args) { + sleep(2); + + _i16 sokken = sl_Socket(SL_AF_INET, SL_SOCK_DGRAM, SL_IPPROTO_UDP); + if (sokken < 0) { + while(1); + } + + SlSockAddrIn_t clientAddress = {SL_AF_INET, UDP_PORT, sl_Htonl(SL_INADDR_ANY)}; + SlSockAddrIn_t serverAddress = {SL_AF_INET, UDP_PORT, UDP_IP}; + + _i16 error = sl_Connect(sokken, (SlSockAddr_t *)&serverAddress, sizeof(serverAddress)); + if (error < 0) { + while(1); + } + + _u8 buffering[100]; + +// _i16 sokkenAan = sl_Recv(sokken, &buffering, 100, 0); +// if (error < 0) { +// while(1); +// } + Display_printf(lookielookie, 0, 0, "Ontvangen van server: %s", buffering); + + mq_attr attr; + attr.mq_maxmsg = 10; + attr.mq_msgsize = sizeof(UDPMsgQueue); + UDPQueue = mq_open("UDPQueue", O_CREAT, 0, &attr); + if(((int)UDPQueue) <= 0){ + while(1); + } + + UDPMsgQueue queueElement; + + while(1) { + mq_receive(UDPQueue, (char*)&queueElement, sizeof(UDPMsgQueue), NULL); + + error = sl_Send(sokken, &queueElement.buffboi, queueElement.len, NULL); + if (error < 0) { + while(1); + } + } +} diff --git a/src/wifiConf.h.example b/src/wifiConf.h.example index 94ab119..18064ac 100644 --- a/src/wifiConf.h.example +++ b/src/wifiConf.h.example @@ -1,19 +1,19 @@ -/* - * wifiConf.h - * - * Created on: 28 Oct 2020 - * Author: MReenen - */ - -#ifndef SRC_WIFICONF_H_ -#define SRC_WIFICONF_H_ - -/* AP SSID */ -#define SSID_NAME "" -/* Security type (OPEN or WEP or WPA) */ -#define SECURITY_TYPE SL_WLAN_SEC_TYPE_WPA_WPA2 -//#define SECURITY_TYPE SL_WLAN_SEC_TYPE_OPEN -/* Password of the secured AP */ -#define SECURITY_KEY "" +/* Security type (OPEN or WEP or WPA) */ +#define SECURITY_TYPE SL_WLAN_SEC_TYPE_WPA_WPA2 +//#define SECURITY_TYPE SL_WLAN_SEC_TYPE_OPEN +/* Password of the secured AP */ +#define SECURITY_KEY "