diff --git a/HelloNativeLibs/README.md b/HelloNativeLibs/README.md new file mode 100644 index 0000000..0701a4d --- /dev/null +++ b/HelloNativeLibs/README.md @@ -0,0 +1,151 @@ +# Native Libraries development using GCC + + + +## Contents of this tutorial: +1) Static V.S. Dynamic Native libraries. +2) Simple project compilation using gcc for intel/arm processors V.S. avr-gcc. + + +## 1) Static V.S. Dynamic Native libraries: + +| `Objective` | `Static Native libraries` | `Dynamic Native libraries` | +|-------------|---------------------------|----------------------------| +| Definition | Are object files that includes all the sources for the target compiled project including the external included sources | Are object files that includes the project sources only and symbolic runtime links for the other dynamic libraries | +| Other names | Compile-time libraries | Shared or Runtime libraries | +| Time of linking | At the compile time, the static object files are linked to the project and compiled with the project sources to an executable file | At the runtime, the loader loads the runtime library | + +-------------------------------------------------------- +## 2) Simple project compilation using intel gcc V.S. avr-gcc: + +### Quick Overview: + +| `Compiling for intel/arm processors` | `Compiling for avr MCUs` | +|--------------------------------------|--------------------------| +| For intel/arm processors, it's far direct to compile object files and the obejct files are compiled into shared or dynamic libs by default unless specified `-static` compiler option explicitly. | Object files are compiled into static object files by default and the compiler don't support dynamic compilation | + +1) Compiling the project into a dynamic/shared (or runtime) library for intel processors: + +- The linker gnu (GNU ld) program makes sure to load the dynamic library on application runtime and link the library to the application code automatically, however you can do this also manually and here comes the difference in operation between shared and dynamic libs. + +- Here is how to compile the project to a dynamic library: +```bash +function linux_x86_x64() { + local native_sources=$1 + if [[ ! -d $linux_natives_dir'/linux-x86-x64' ]]; then + mkdir -p $linux_natives_dir'/linux-x86-x64' + fi + $gcc -fPIC -v $native_sources -shared -o $linux_natives_dir'/linux-x86-x64/'${clibName} \ + -I${JAVA__HOME%/*}'/include' \ + -I${JAVA__HOME%/*}'/include/linux' \ + -I${nativessrc_directory}'/include/linux/' \ + -I${nativessrc_directory}'/include/' \ + + return $? +} +``` + +- Here is how to link the library to another project and add the library path to the gnu ld: +```bash +function linux_x86_x64() { + local native_sources=$1 + if [[ ! -d $output_dir'/linux-x86-x64' ]]; then + mkdir -p $output_dir'/linux-x86-x64' + fi + $gcc -fpie $native_sources -o $output_dir'/linux-x86-x64/'${clibName} \ + -I${JAVA__HOME%/*}'/include' \ + -I${JAVA__HOME%/*}'/include/linux' \ + -I${nativessrc_directory}'/include/linux/' \ + -I${nativessrc_directory}'/include' \ + -L$linux_libs_root_dir \ + -Wl,-rpath,$linux_libs_root_dir \ + -l'rs232' + + return $? +} +``` + +- For shared libraries, the linker library can be included in the code using `dlfcn.h` and dynamic libraries can be loaded in code using the absolute file path and you won't need to link the library at the project compile-time. + +2) Compiling the project into a static (or compile-time) library for intel processors: + +--- WIP --- + +3) Compiling the project into a dynamic/shared (or runtime) library for avr MCUs: + +``` +There is no way to use the dynamic linked libraries on a microcontroller, +since there is no a runtime environment to act upon (the linker program needs a linux machine), +so shared libraries on avr-gcc isn't supported. +``` + +4) Compiling the project into a static library for avr MCUs: + +- Compiling of source files into object files and then packaging the object files into a library archive using the `ar` archive gnu binutil tool: +```bash +function compile() { + + cd ${project}'/src/lib/' + nativeSources=(`ls *.c *.cpp *.c++ *.cxx`) + + for ((i=0; i<${#nativeSources[@]}; i++)); do + ${AVR_HOME}'/bin/avr-g++' \ + -c -O -x c++ \ + -mmcu=${CHIP} "${project}/src/lib/${nativeSources[i]}" \ + -I${AVR_HOME}'/avr/include' \ + -I${project}'/src/include' \ + -o "${project}/output/${nativeSources[i]}.o" + done + + objectcode=`find ${project}'/output/' -name '*.o'` + + ${AVR_HOME}'/bin/avr-ar' rcs ${output}'.a' $objectcode + + ${AVR_HOME}'/bin/avr-nm' ${output}'.a' > ${output}'.map' + +} +``` +- Linking the static library to another project: +```bash +function compile() { + # addLibsTold + # attrs : dir to compile & sharedLib name + nativeSources=`find ${project}'/src/lib' -name '*.c' -o -name '*.cxx' -o -name '*.cpp' -o -name '*.c++'` + + # compile to ``.elf`` full program (Executable and Linkable format) + ${AVR_HOME}'/bin/avr-g++' -O2 -x c++ \ + -mmcu=${CHIP} ${nativeSources} \ + -I${AVR_HOME}'/avr/include' \ + -I${project}'/src/include' \ + -L"${project}/libs/" -l'uart' \ + -o ${output}'.elf' + + return $? +} +``` +- Object files are selectively added to the final code if a call has been made to their source functions in the main source code (to resolve undefined references), otherwise they aren't added to the final elf, even if you have included their function prototypes. + +5) Analysis of the compiler command and command options: + +- `gcc`: GNU C Collections Toolchains (or GNU C Compiler), is a GNU binutil designed to compile and link C code into static object files and shared object files, object-code is a machine specific generated code, this machine-code is interpreted into hex code when runnning on the CPU, you need to do the interpretation manually on some tiny devices like (MCUs) before uploading using the `object-copy` gnu binutils as follows: +```bash +function convertToHex() { + ${AVR_HOME}'/bin/avr-objcopy' -I 'elf32-avr' -O 'ihex' ${output}'.elf' ${output}'.hex' + return $? +} +``` +- `g++`: GNU C++ Compiler Toolchains, is the same as gcc with added functionalities to compile and link C++ code into object files. + +- `-mmcu=[CHIP]`: Defines the chip (micro-controller unit) used to compile the code, this ensures that the io package is the right package for the target hardware at the compile-time. + +- `-I[DIR]`: Adds a directory to the include path. + +- `-L[LIB-DIR]`: Adds a library directory to the gnu linker at compile-time. + +- `-Wl,-rpath=[DYNAMIC-LIB-DIR]`: Adds a library path (dynamic library) to the runtime path of the linker. + +- `-o[OUTPUT]`: Specifies the output object-code. + +- `-c`: Commands the gnu compiler to compile the source only to static object files and skip the linking step. + +- `-x[LANGUAGE]`: Explicitly specifies the language to use. diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/build/build.sh b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/build/build.sh new file mode 100755 index 0000000..b370e2b --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/build/build.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +echo "Compiling the project" +echo -e $RESET_Cs +echo "--------Script start--------" + +source $build_dir'/compile.sh' + +echo -e $RESET_Cs + +compile + +echo -e $RESET_Cs +echo "--------Script end--------" diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/build/compile.sh b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/build/compile.sh new file mode 100644 index 0000000..97fc784 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/build/compile.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +source $build_dir'/variables.sh' + +## +# Compile and build native sources. +# +# @echo Script Succeeded if all the commands have passed successfully, exit with error code otherwise. +## +function compile() { + native_sources=`find $nativessrc_directory'/main' $nativessrc_directory'/lib' -name '*.c' -o -name '*.cxx' -o -name '*.cpp' -o -name '*.c++'-o -name '*.ino'` + # tests if the sources exist, then give the current user full permissions on them and compile them + chmod +x $native_sources + # append -lwiringPi for raspberry wiringPi includes + # ${JAVA__HOME%/*} : % returns back to the root base directory of the java home, / is the separator delimiter of the directory string + # compile and build a shared lib for linux systems + if [[ `linux_x86_x64 "${native_sources}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Linux-x86-x64 : Succeeded" + else + echo -e "$RED_C Task@Build Linux-x86-x64 : Failed" + echo -e "$RED_C Exiting Script with error 150" + exit 150 + fi + echo -e "$GREEN_C---MajorTask@Build Native Sources : Succeeded---" +} + +## +# Build for desktop linux systems +# +# @param nativeSources sources to be compiled for linux desktop. +# @return 0 if command passes, non zero number otherwise with exit code 150 (search the code on repo's wiki). +## +function linux_x86_x64() { + local native_sources=$1 + if [[ ! -d $output_dir'/linux-x86-x64' ]]; then + mkdir -p $output_dir'/linux-x86-x64' + fi + $gcc -fpie $native_sources -o $output_dir'/linux-x86-x64/'${clibName} \ + -I${JAVA__HOME%/*}'/include' \ + -I${JAVA__HOME%/*}'/include/linux' \ + -I${nativessrc_directory}'/include/linux/' \ + -I${nativessrc_directory}'/include' \ + -L$linux_libs_root_dir \ + -Wl,-rpath,$linux_libs_root_dir \ + -l'rs232' + + return $? +} \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/build/variables.sh b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/build/variables.sh new file mode 100644 index 0000000..1832bcb --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/build/variables.sh @@ -0,0 +1,39 @@ +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +# print the canonical file name from its symbolic link +canonical_link=`readlink -f ${0}` +#!/bin/bash + +# get the directory name of this canonical name +build_dir=`dirname $canonical_link` + +# work directories +project_root="${build_dir%/*}" + +dynamic_libs_dir="${project_root%/*}" + +amd_examples_dir="${dynamic_libs_dir%/*}" + +hello_native_libs="${amd_examples_dir%/*}" + +# cut the working directory from its end by a one '/' delimiter again +avr_sandbox_root="${hello_native_libs%/*}" + +# constant independent +clibName=('HelloRs232.elf') + +# native toolchains +gcc='g++-10' + +# code sources +nativessrc_directory=$project_root'/src' + +# native shared/dynamic libs +linux_libs_root_dir=$project_root'/libs/shared/native/Linux/linux-x86-x64/' +output_dir=$project_root'/output' + +source $avr_sandbox_root'/CommonVariables.sh' diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/libs/shared/native/Linux/linux-x86-x64/librs232.so b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/libs/shared/native/Linux/linux-x86-x64/librs232.so new file mode 100755 index 0000000..bdecefb Binary files /dev/null and b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/libs/shared/native/Linux/linux-x86-x64/librs232.so differ diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/output/linux-x86-x64/HelloRs232.elf b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/output/linux-x86-x64/HelloRs232.elf new file mode 100755 index 0000000..66d0ad4 Binary files /dev/null and b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/output/linux-x86-x64/HelloRs232.elf differ diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/BufferUtils.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/BufferUtils.h new file mode 100644 index 0000000..7e08167 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/BufferUtils.h @@ -0,0 +1,124 @@ +/** + * @file BufferUtils.util + * @author pavl_g. + * @brief Represents utility functions for buffers. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _BUFFER_UTILS +#define _BUFFER_UTILS + +#include +#include +#include + +namespace BufferUtils { + + /** + * Nullifies a single buffer cell at the index. + * + * @param buffer the buffer to nullify its cell. + * @param index the index of the buffer cell to nullify. + */ + static inline void nullifyBuffer(void** buffer, int index) { + buffer[index] = NULL; + } + + /** + * Frees the memory utilized by the individual buffer cells on a [buffer] with [count] number of cells. + * + * @param buffer the buffer to free its cells. + * @param count the number of cells to free, starting from index zero. + */ + static inline void freeBufferCells(void** buffer, int* count) { + for (int i = 0; i < *count; i++) { + BufferUtils::nullifyBuffer(buffer, i); + free(buffer[i]); + } + } + + /** + * @brief Deletes a typified buffer and frees its memory. + * + * @param buffer the buffer to delete. + */ + static inline void deleteBuffer(void* buffer) { + free(buffer); + BufferUtils::nullifyBuffer(&buffer, 0); + } + + /** + * @brief Deeply copies the data of the [src] buffer into a new + * buffer and returns it. + * + * @param src the source buffer to get the data from. + * @param count the count length of the buffer. + * @return void** a new buffer with the same data as the source. + */ + static inline void** copy(void** src, int* count) { + void** copy = (void**) calloc(1, sizeof(void**)); + for (int i = 0; i < *count; i++) { + /* add new memory on the next array block */ + copy[i] = (void*) calloc(1, sizeof(void*)); + copy[i] = src[i]; + } + return copy; + } + + /** + * @brief Re-validates the buffer from [NULL] pointers. + * + * @param buffer the buffer to re-validate. + * @param count the pointers count. + */ + static inline void reValidateBuffer(void** buffer, int* count, int* isProcessed) { + /* get a temp copy from flagged buffer */ + void** temp = BufferUtils::copy(buffer, count); + /* free the buffer cells to prepare the buffer to be reinitialized */ + BufferUtils::freeBufferCells(buffer, count); + /* re-init the buffer, removing the null pointers */ + for (int i = 0, j = 0; i < *count; i++) { + if (temp[i] == NULL) { + printf("%s\n", "zero"); + continue; + } + buffer[j] = (void*) calloc(1, sizeof(void*)); + buffer[j] = temp[i]; + j++; + } + *isProcessed = 1; + /* free the temp buffer */ + BufferUtils::freeBufferCells(temp, count); + } +} +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/DynamicBuffer.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/DynamicBuffer.h new file mode 100644 index 0000000..21d3285 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/DynamicBuffer.h @@ -0,0 +1,155 @@ +/** + * @file DynamicBuffer.h + * @author pavl_g. + * @brief Represents a cross platform dynamic buffer wrapper. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _DYNAMIC_BUFFER +#define _DYNAMIC_BUFFER + +#include +#include +#include + +struct DynamicBuffer { + + int count = 0; + int isProcessed = 0; + + /** + * Declares and initializes a pointer that points to + * other void* buffers starting from index zero. + * + * @note The pointer is of single size of a type. + * @note The pointer points to only and only one buffer at a time. + * @note New buffers can be added to this pointer by dereferencing it and adding one to the memory address to move + * it to a new cell block. + * e.g: + * 1) First way of adding a new buffer to this pointer using the deep copy: + * buffer[index] = (void*) calloc(1, sizeof(void*)); + * buffer[index] = item; + * + * 2) Second way of adding a new buffer to this pointer (the one used here): + * *(buffer += count) = (void*) calloc(1, sizeof(void*)); + * *buffer = item; + * buffer -= count; + * + * 3) The superficial copy example: + * buffer[index] = item; + */ + void** buffer = (void**) calloc(1, sizeof(void**));; + + static inline struct DynamicBuffer* createNewInstance() { + return (struct DynamicBuffer*) calloc(1, sizeof(struct DynamicBuffer)); + } + + /** + * Retrieves the pointer to this dynamic buffer. + * + * @return a pointer to this array of buffers. + */ + void** getBuffer() { + return buffer; + } + + /** + * Retrieves this structure size. + * + * @return an integer representing this struct in bytes. + */ + size_t getBufferSize() { + return sizeof(struct DynamicBuffer); + } + + /** + * Resets the pointer value back to zero. + */ + void resetDataPointer() { + this->count = 0; + } + + /** + * Gets the memory address to the integer of the items count. + * + * @return a pointer referring to the memory address of the integer that represents the item counts. + */ + int* getItemsCount(); + + /** + * Adds a new buffer to this pointer in a new index. + * + * @param item a void* buffer to add. + */ + void add(void* item); + + /** + * Adds a new buffer on a particular location in this pointer replacing an old one if exists. + * + * @param index the index where the new buffer will be located in this pointer. + * @param item the buffer to add. + */ + void add(int index, void* item); + + /** + * Frees a buffer from the memory at a particular index. + * @warning this method call is expensive as it removes and revalidates the whole buffer from NULL pointers. + * + * @param index the index of the buffer to remove. + */ + void removeAt(int index); + + /** + * Frees all the buffers of this pointer from the memory. + */ + void removeAll(); + + /** + * Retrieves a buffer index. + * + * @param item the buffer to get its index. + * @return the buffer index in an integer format. + */ + int getItemIndex(void* item); + + /** + * Retrieves a buffer from this pointer using its index. + * + * @param index the index where the buffer is located in this pointer. + * @return the buffer corresponding to this index. + */ + void* getItem(int index); +}; + + +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/ErrnoUtils.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/ErrnoUtils.h new file mode 100644 index 0000000..58ec430 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/ErrnoUtils.h @@ -0,0 +1,53 @@ +/** + * @file ErrnoUtils.util + * @author pavl_g. + * @brief Represents native user and machine errnos. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _ERRNO_UTILS +#define _ERRNO_UTILS + +#include + +#define ERR_INVALID_PORT (-2) +#define ERR_INVALID_DIR (-3) +#define ERR_NO_RESULT (0) +#define LOGGER_DISABLED (-5) +#define ERR_OPERATION_FAILED (-1) +#define ERR_NO_AVAILABLE_TTY_DEVICES (-4) + +#define OPERATION_SUCCEEDED (1) + + +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/Rs232Service.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/Rs232Service.h new file mode 100644 index 0000000..a5e00b4 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/Rs232Service.h @@ -0,0 +1,34 @@ +#ifndef _RS232_SERVICE +#define _RS232_SERVICE + +#include +#include +#include +#include +#include + +#define PORT ((const char*) "/dev/ttyUSB0") +#define HANDSHAKING_SIGNAL ((const char*) "_HANDSHAKER0 2022") +#define HANDSHAKES_LEN ((size_t) sizeof(HANDSHAKING_SIGNAL) / sizeof(HANDSHAKING_SIGNAL[0])) + +static pthread_mutex_t handshake_mutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t handshake_cond = PTHREAD_COND_INITIALIZER; + +static pthread_t handshakeTx_service; +static pthread_t handshakeRx_service; + +static int fd = 0; + +int* startRs232Service(); + +void initRs232Service(int* fd); + +void* stopRs232Service(int*); + +void* handshakeDeviceDriver(void*); + +void* logHandshakingSignals(void*); + +void releaseRs232Service(); + +#endif \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/info.md b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/info.md new file mode 100644 index 0000000..166e55d --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/info.md @@ -0,0 +1,6 @@ +# Serial4j API C Utils + +## Includes the following: +- BufferUtils.h: for managing native buffers. +- DynamicBuffer.h: for creating dynamic buffers. +- ErrnoUtils.h: for checking and referencing different errno code numbers. \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/SerialUtils.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/SerialUtils.h new file mode 100644 index 0000000..007d1a5 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/SerialUtils.h @@ -0,0 +1,77 @@ +/** + * @file SerialUtils.util + * @author pavl_g. + * @brief Represents utilities for the [Serial.h] library. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _SERIAL_UTILS +#define _SERIAL_UTILS + +#include +#include +#include +#include +#include + +namespace SerialUtils { + + /** + * @brief Converts a [file] into a [device] and outputs the + * result into a [buffer]. + * + * @param buffer a buffer to fill in the operation. + * @param file the file to convert into a device. + * @return char* a buffer of {"/dev/"} formula. + */ + static inline char* concatIntoDevice(char* buffer, const char* file, const char* DEVICES_DIR) { + strcat(buffer, DEVICES_DIR); + strcat(buffer, file); + return buffer; + } + + /** + * @brief Tests whether the PATH specified is a real serial port. + * + * @param path the path to specify if its a serial port. + * @return int 1 if FD is a valid descriptor, 0 otherwise. + */ + static inline int isSerialPort(char* path, const int FLAG) { + int fdp = open(path, FLAG); + int state = isatty(fdp); + close(fdp); + return state; + } +} + +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/TerminalDevice.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/TerminalDevice.h new file mode 100644 index 0000000..571d1c5 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/TerminalDevice.h @@ -0,0 +1,258 @@ +/** + * @file Serial.h + * @author pavl_g. + * @brief Represents the serial port devices control and operation for POSIX systems. + * @note This is the base [HAL] (Hardware abstraction layer) for the Serial4j api. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API, RS232. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _RS232 +#define _RS232 "RS232-Interface" + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#define READ_CONFIG_SIZE (2) +#define DEVICES_DIR ((const char*) "/dev/") + +/** The default flags for the base file api */ +#define DEFAULT_FLAGS (O_RDWR | O_NONBLOCK | O_NOCTTY) + +typedef unsigned short int TerminalFlag; + +namespace TerminalDevice { + + /** Param@0 = VTIME, Param@1 = VMIN */ + const cc_t POLLING_READ[READ_CONFIG_SIZE] = {0, 0}; + const cc_t BLOCKING_READ_ONE_CHAR[READ_CONFIG_SIZE] = {0, 1}; + const cc_t READ_WITH_TIMEOUT[READ_CONFIG_SIZE] = {1, 0}; + const cc_t READ_WITH_INTERBYTE_TIMEOUT[READ_CONFIG_SIZE] = {1, 1}; + + /** + * Retrieves the termios of this tty device described by the file descriptor (fd). + * + * @param fd the virtual file descriptor for this tty device. + * @return a memory reference to the termios defining this tty device terminal attributes. + */ + struct termios* getTermiosFromFd(int* fd); + + /** + * @brief Fetches serial port devices on "/dev/" into [serialPorts] buffer. + * @note Uses , , , and . + * + * @return int (-3) if the directory ["/dev"] is invalid, (-4) if there are no tty + * devices available at the ["/dev"] directory, (1) if operation succeeded. + */ + int fetchSerialPorts(struct DynamicBuffer* serialPorts); + + /** + * @brief Opens a serial port device with a name. + * @note Uses Unix file base api and . + * + * @param port the path for the serial port device. + * @return int* a memory reference for the port file descriptor. + */ + int openPort(const char* port, int flag); + + /** + * @brief Initializes the default terminal for this device with the following default charachteristics: + * ----------- + * # c_cflag: for control mode flags. + * *** Enable these bits: + * - [CREAD]: Allow input to be received. + * - [CS8]: For charachter size 8-bit, you can use the bit mask CSIZE to read this value. + * - [CLOCAL]: Ignore modem status lines (don’t check carrier signal). + * ----------- + * # c_lflag: for local mode flags. + * ***Disable these bits: + * - [ICANON]: Canonical mode (line-by-line) input. + * - [ECHO]: Echo input characters. + * - [ECHOE]: Perform ERASE visually. + * - [ECHOK]: Echo KILL visually. + * - [ECHOKE]: Don’t output a newline after echoed KILL. + * - [ECHONL]: Echo NL (in canonical mode) even if echoing is disabled. + * - [ECHOPRT]: Echo deleted characters backward (between \ and / ). + * - [ECHOCTL]: Echo control characters visually (e.g., ^L ). + * - [ISIG]: Enable signal-generating characters (INTR, QUIT, SUSP). + * - [IEXTEN]: Enable extended processing of input characters. + * ----------- + * # c_oflag: for output mode flags. + * ***Disable these bits: + * - [OPOST]: Perform output postprocessing. + * - [ONLCR]: Map NL to CR-NL on output. + * ----------- + * # c_iflag: for input mode flags. + * ***Disable all input bit masks. + * ----------- + * # c_cc: For control characters. + * ***Sets to BLOCKING READ ONE CHAR AT A TIME MODE. + * ----------- + * + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int initTermios(int* fd); + + /** + * @brief Sets the Terminal Control Flag [c_cflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalControlFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Local Flag [c_lflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalLocalFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Output Flag [c_oflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalOutputFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Input Flag [c_iflag] for the [termios] variable. + * + * @param flags bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalInputFlag(TerminalFlag flag, int* fd); + + /** + * @brief Gets the Terminal Control Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal control flag in [unsigned short int]. + */ + TerminalFlag getTerminalControlFlag(int* fd); + + /** + * @brief Gets the Terminal Local Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal local flag in [unsigned short int]. + */ + TerminalFlag getTerminalLocalFlag(int* fd); + + /** + * @brief Gets the Terminal Input Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal input flag in [unsigned short int]. + */ + TerminalFlag getTerminalInputFlag(int* fd); + + /** + * @brief Gets the Terminal Output Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal output flag in [unsigned short int]. + */ + TerminalFlag getTerminalOutputFlag(int* fd); + + /** + * @brief Sets the Read Configuration Mode using a ReadConfiguration with a + * VMIN_VALUE for lesser bytes to read and VTIME_VALUE for the elapsed time to + * set if the ReadConfiguration mode provides a timeout. + * + * @param VTIME_VALUE the value of the read timeout elapsed time, the timer starts + * with this value after read() is called. + * @param VMIN_VALUE the value of the minimum number of bytes to read. + * @return int (ERR_INVALID_PORT = -2) if port isn't available, (0) otherwise. + */ + int setReadConfigurationMode(const int VTIME_VALUE, const int VMIN_VALUE, int* fd); + + /** + * @brief Get the Read Configuration Mode in a new pointer. + * + * @return int* a memory reference to the new read configuration instance holding the VTIME and VMIN. + */ + cc_t* getReadConfigurationMode(int* fd); + + /** + * @brief Sets the Baud Rate object for the terminal io. + * + * @param baudRate the baud rate (bits/seconds). + * @return int (1) for success, (-1) for failure, (-2) for invalid port. + */ + int setBaudRate(int baudRate, int* fd); + + /** + * @brief Gets the Baud Rate object. + * + * @return speed_t baud rate in integers. + */ + speed_t getBaudRate(int* fd); + + /** + * @brief Writes a data to the serial port device from a buffer. + * + * @param buffer a buffer to write to the file. + * @param length the number of charachters to write from the buffer. + * @return ssize_t the number of bytes written to the serial device, (-1) for failure, (-2) for invalid port. + */ + ssize_t writeData(const void* buffer, int length, int* fd); + + /** + * @brief Reads data from the serial port device and saves it to a buffer. + * + * @param buffer a buffer to read from the file to it. + * @param length the number of the charachters to read by this buffer. + * @return ssize_t the number of bytes read from the terminal, (-1) for failure, (-2) for invalid port. + */ + ssize_t readData(void* buffer, int length, int* fd); + + /** + * @brief Closes the serial port device. + * + * @return int (1) for success, (-1) for failure, (-2) for invalid port. + */ + int closePort(int* fd); + +} + + +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/Thread.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/Thread.h new file mode 100644 index 0000000..7b57ec4 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/Thread.h @@ -0,0 +1,51 @@ +/** + * @file Thread.h + * @author pavl_g. + * @brief Optional header for operating within PThreads. + * @version 0.1 + * @date 2022-08-24 + * + * @note TODO. + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _THREADS +#define _THREADS + +#include + +namespace POSIX { + struct Thread { + + }; +} + +#endif \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/info.md b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/info.md new file mode 100644 index 0000000..000fa07 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/include/linux/info.md @@ -0,0 +1 @@ +# Rs232-Interface API designed for Linux/Unix diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/lib/Rs232Service.c b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/lib/Rs232Service.c new file mode 100755 index 0000000..f5448d1 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/lib/Rs232Service.c @@ -0,0 +1,145 @@ +#include +#include + +static inline void terminatePrinterFormat(int* numberOfPrintedChars, size_t targetLength) { + if (*numberOfPrintedChars == targetLength) { + printf("\r\n"); + *numberOfPrintedChars = 0; + } +} + +int* startRs232Service() { + /** create a service block to enable the retry again criteria */ + service: { + fd = TerminalDevice::openPort(PORT, DEFAULT_FLAGS); + + if (fd <= 0) { + TerminalDevice::closePort(&fd); + } else { + printf("%s\n", " --- Rs232 driver service opened --- "); + } + + // try again and block until a request is accepted -- services retry criteria. + if (fd <= 0) { + goto service; + } + } + + return &fd; +} + +void initRs232Service(int* fd) { + int state = TerminalDevice::initTermios(fd); + int baud_state = TerminalDevice::setBaudRate(B57600, fd); + if ((state | baud_state) == -2) { + perror(" --- Invalid Port --- \n"); + } else if (state < 0) { + perror(" --- Failed to initialize the service --- \n"); + } else { + printf("%s\n", " --- Initialized the Rs232 driver service --- "); + } +} + +void* handshakeDeviceDriver(void* data) { + int* service_descriptor = (int*) data; + + printf("%s\n", " --- Started Rs232 handshake service --- "); + + handshake_service:{ + assert(pthread_mutex_lock(&handshake_mutex) == 0); + assert(pthread_cond_wait(&handshake_cond, &handshake_mutex) == 0); + /* critical section starts */ + + int numberOfWrittenBytes = TerminalDevice::writeData(HANDSHAKING_SIGNAL, strlen(HANDSHAKING_SIGNAL), service_descriptor); + if (numberOfWrittenBytes == -2) { + perror(" --- Invalid Port --- \n"); + } else if (numberOfWrittenBytes < 0) { + perror(" --- Failed to handshake the service --- \n"); + } + + /* critical section ends */ + assert(pthread_mutex_unlock(&handshake_mutex) == 0); + + usleep(100000); /* send data each 100,000 micros = 0.1 seconds */ + + goto handshake_service; + } + + + pthread_exit(NULL); +} + +void* logHandshakingSignals(void* data) { + + int* service_descriptor = (int*) data; + + char* vacant = (char*) calloc(1, sizeof(char)); + + int numberOfPrintedChars = 0; + + printf("%s\n", " --- Started Rs232 log service --- "); + + /* wait for the start of the reading thread */ + printf("%s\n\r", " --- Read Rs232 driver service handshakes --- "); + + read_service:{ + assert(pthread_mutex_lock(&handshake_mutex) == 0); + /* critical section starts */ + + int numberOfReadBytes = TerminalDevice::readData((void*) vacant, 1, service_descriptor); + + if (*vacant == 0x20) { + /* critical section ends */ + assert(pthread_cond_signal(&handshake_cond) == 0); + assert(pthread_mutex_unlock(&handshake_mutex) == 0); + + goto read_service; + } + + if (numberOfReadBytes > 0) { + printf("%c", *vacant); + *vacant = 0; + numberOfPrintedChars += 1; + } else if (numberOfReadBytes == -2) { + perror(" --- Invalid Port --- \n"); + return NULL; + } + + terminatePrinterFormat(&numberOfPrintedChars, strlen(HANDSHAKING_SIGNAL)); + + /* critical section ends */ + assert(pthread_cond_signal(&handshake_cond) == 0); + assert(pthread_mutex_unlock(&handshake_mutex) == 0); + + goto read_service; + } + + pthread_exit(NULL); +} + +void* stopRs232Service(int* service_descriptor) { + + assert(pthread_mutex_lock(&handshake_mutex) == 0); + + /* run the main command and retrieve the state */ + int state = TerminalDevice::closePort(service_descriptor); + /* log the error/print according to the state or behave differently or use a retry criteria as defined above */ + if (state == -2) { + perror(" --- Invalid Port --- \n"); + } else if (state < 0) { + perror(" --- Failed to stop the service --- \n"); + } else { + printf("%s\n", " --- Stopped Rs232 driver service successfully --- "); + } + + assert(pthread_mutex_unlock(&handshake_mutex) == 0); + + releaseRs232Service(); + + pthread_exit(NULL); +} + +void releaseRs232Service() { + assert(pthread_mutex_destroy(&handshake_mutex) == 0); + assert(pthread_cond_destroy(&handshake_cond) == 0); +} \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/main/main.c b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/main/main.c new file mode 100755 index 0000000..28db4de --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Hello-Rs232/src/main/main.c @@ -0,0 +1,28 @@ +#include + +static inline int* prepareRs232Service() { + + int* service_descriptor = startRs232Service(); + initRs232Service(service_descriptor); + + return service_descriptor; +} + +static inline void dispatchRs232Services() { + + const int* handshake_descriptor = prepareRs232Service(); + + pthread_create(&handshakeRx_service, NULL, &logHandshakingSignals, (void*) handshake_descriptor); + usleep(2000000); /* sleep 2 seconds until the read service starts */ + pthread_create(&handshakeTx_service, NULL, &handshakeDeviceDriver, (void*) handshake_descriptor); + + pthread_join(handshakeRx_service, NULL); /* wait for the Rx thread to terminate */ +} + +int main(int argc, char **argv) { + printf("%s\n", " --- Started Rs232 driver example --- "); + + dispatchRs232Services(); + + return 0; +} diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/build/build.sh b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/build/build.sh new file mode 100755 index 0000000..d1a27d0 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/build/build.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +echo "Compiling the project" +echo -e $RESET_Cs +echo "--------Script start--------" + +source $build_dir'/compile.sh' + +echo -e $RESET_Cs + +if [[ $enable_natives_build == true ]]; then + echo -e "$MAGNETA_C---MajorTask@Build Native Sources : Native build started" + compile + copyToExample + echo -e "$MAGNETA_C---MajorTask@Build Native Sources : Native build finished" +fi + +echo -e $RESET_Cs +echo "--------Script end--------" diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/build/compile.sh b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/build/compile.sh new file mode 100644 index 0000000..d5f4b98 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/build/compile.sh @@ -0,0 +1,131 @@ +#!/bin/bash + +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +source $build_dir'/variables.sh' + +## +# Compile and build native sources. +# +# @echo Script Succeeded if all the commands have passed successfully, exit with error code otherwise. +## +function compile() { + native_sources=`find $nativessrc_directory'/lib' -name '*.c' -o -name '*.cxx' -o -name '*.cpp' -o -name '*.c++'-o -name '*.ino'` + # tests if the sources exist, then give the current user full permissions on them and compile them + if [[ $native_sources ]]; then + chmod +x $native_sources + # append -lwiringPi for raspberry wiringPi includes + # ${JAVA__HOME%/*} : % returns back to the root base directory of the java home, / is the separator delimiter of the directory string + # compile and build a shared lib for linux systems + if [[ `linux_x86_x64 "${native_sources}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Linux-x86-x64 : Succeeded" + else + echo -e "$RED_C Task@Build Linux-x86-x64 : Failed" + echo -e "$RED_C Exiting Script with error 150" + exit 150 + fi + # compile and build a shared lib for android systems + if [[ $enable_android_build == true ]]; then + if [[ `linux_android "${arm64}" "${arm64_lib}" "${native_sources}" "${min_android_sdk}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Android-Arm-64 : Succeeded" + else + echo -e "$RED_C Task@Build Android-Arm-64 : Failed" + echo -e "$RED_C Exiting Script with error 250" + exit 250 + fi + + if [[ `linux_android "${arm32}" "${arm32_lib}" "${native_sources}" "${min_android_sdk}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Android-Arm-32 : Succeeded" + else + echo -e "$RED_C Task@Build Android-Arm-32 : Failed" + echo -e "$RED_C Exiting Script with error 350" + exit 350 + fi + + if [[ `linux_android "${intel64}" "${intel64_lib}" "${native_sources}" "${min_android_sdk}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Android-Intel-64 : Succeeded" + else + echo -e "$RED_C Task@Build Android-Intel-64 : Failed" + echo -e "$RED_C Exiting Script with error 450" + exit 450 + fi + + if [[ `linux_android "${intel32}" "${intel32_lib}" "${native_sources}" "${min_android_sdk}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Android-Intel-32 : Succeeded" + else + echo -e "$RED_C Task@Build Android-Intel-32 : Failed" + echo -e "$RED_C Exiting Script with error 550" + exit 550 + fi + fi + fi + echo -e "$GREEN_C---MajorTask@Build Native Sources : Succeeded---" +} + +## +# Build for desktop linux systems +# +# @param nativeSources sources to be compiled for linux desktop. +# @return 0 if command passes, non zero number otherwise with exit code 150 (search the code on repo's wiki). +## +function linux_x86_x64() { + local native_sources=$1 + if [[ ! -d $linux_natives_dir'/linux-x86-x64' ]]; then + mkdir -p $linux_natives_dir'/linux-x86-x64' + fi + $gcc -fPIC -v $native_sources -shared -o $linux_natives_dir'/linux-x86-x64/'${clibName} \ + -I${JAVA__HOME%/*}'/include' \ + -I${JAVA__HOME%/*}'/include/linux' \ + -I${nativessrc_directory}'/include/linux/' \ + -I${nativessrc_directory}'/include/' \ + + return $? +} + +## +# Building native code for arm and intel android. +# +# @param triple the ABI triple name, also used for -target flag of the clang++. +# @param folder the created folder name. +# @param sources the sources to compile and build an object file for them. +# @param min_android_sdk the minimum android sdk to compile against. +# @return 0 if command passes, non zero number otherwise. +## +function linux_android() { + # parameters attributes + local triple=$1 + local folder=$2 + local sources=$3 + local min_android_sdk=$4 + + if [[ ! -d $android_natives_dir ]]; then + mkdir $android_natives_dir + fi + + if [[ ! -d $android_natives_dir"/$folder" ]]; then + mkdir $android_natives_dir"/$folder" + fi + $NDK__BASEHOME'/toolchains/llvm/prebuilt/linux-x86_64/bin/clang++' -v -target ${triple}${min_android_sdk} \ + -fPIC $sources -shared \ + -stdlib=libstdc++ \ + -o $android_natives_dir"/$folder/"${clibName} \ + -I$nativessrc_directory'/includes' \ + -I$NDK__BASEHOME'/sources/cxx-stl/llvm-libc++/include' \ + -lc++_shared + result=$? + cp $NDK__BASEHOME"/sources/cxx-stl/llvm-libc++/libs/${folder}/libc++_shared.so" $android_natives_dir"/$folder" + return $result +} + +function copyToExample() { + local hello_rs232="`dirname $project_root`/Hello-Rs232" + cp -r $shared_root_dir $hello_rs232'/libs/' + cp -r ${nativessrc_directory}'/include/.' $hello_rs232'/src/include/' +} diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/build/variables.sh b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/build/variables.sh new file mode 100644 index 0000000..2f5c1b2 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/build/variables.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +# print the canonical file name from its symbolic link +canonical_link=`readlink -f ${0}` +# get the directory name of this canonical name +build_dir=`dirname $canonical_link` + +# work directories +project_root="${build_dir%/*}" + +dynamic_libs_dir="${project_root%/*}" + +amd_examples_dir="${dynamic_libs_dir%/*}" + +hello_native_libs="${amd_examples_dir%/*}" + +# cut the working directory from its end by a one '/' delimiter again +avr_sandbox_root="${hello_native_libs%/*}" + +# constant independent +clibName=('librs232.so') + +# native toolchains +gcc='g++-10' + +# android tool-chain constants +min_android_sdk=21 +arm64="aarch64-linux-android" +arm64_lib="arm64-v8a" +arm32="armv7a-linux-androideabi" +arm32_lib="armeabi-v7a" +intel32="i686-linux-android" +intel32_lib="x86" +intel64="x86_64-linux-android" +intel64_lib="x86_64" +android_natives_jar="android-natives-${min_android_sdk}.jar" + +# set some build guards +enable_natives_build=true +enable_android_build=false + +# code sources +nativessrc_directory=$project_root'/src' + +# native shared/dynamic libs +shared_root_dir=$project_root'/shared' +android_natives_dir=$project_root'/shared/lib' +linux_natives_dir=$project_root'/shared/native/Linux' + +source $avr_sandbox_root'/NDKPATH.sh' +source $avr_sandbox_root'/CommonVariables.sh' diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/shared/native/Linux/linux-x86-x64/librs232.so b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/shared/native/Linux/linux-x86-x64/librs232.so new file mode 100755 index 0000000..bdecefb Binary files /dev/null and b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/shared/native/Linux/linux-x86-x64/librs232.so differ diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/BufferUtils.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/BufferUtils.h new file mode 100644 index 0000000..7e08167 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/BufferUtils.h @@ -0,0 +1,124 @@ +/** + * @file BufferUtils.util + * @author pavl_g. + * @brief Represents utility functions for buffers. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _BUFFER_UTILS +#define _BUFFER_UTILS + +#include +#include +#include + +namespace BufferUtils { + + /** + * Nullifies a single buffer cell at the index. + * + * @param buffer the buffer to nullify its cell. + * @param index the index of the buffer cell to nullify. + */ + static inline void nullifyBuffer(void** buffer, int index) { + buffer[index] = NULL; + } + + /** + * Frees the memory utilized by the individual buffer cells on a [buffer] with [count] number of cells. + * + * @param buffer the buffer to free its cells. + * @param count the number of cells to free, starting from index zero. + */ + static inline void freeBufferCells(void** buffer, int* count) { + for (int i = 0; i < *count; i++) { + BufferUtils::nullifyBuffer(buffer, i); + free(buffer[i]); + } + } + + /** + * @brief Deletes a typified buffer and frees its memory. + * + * @param buffer the buffer to delete. + */ + static inline void deleteBuffer(void* buffer) { + free(buffer); + BufferUtils::nullifyBuffer(&buffer, 0); + } + + /** + * @brief Deeply copies the data of the [src] buffer into a new + * buffer and returns it. + * + * @param src the source buffer to get the data from. + * @param count the count length of the buffer. + * @return void** a new buffer with the same data as the source. + */ + static inline void** copy(void** src, int* count) { + void** copy = (void**) calloc(1, sizeof(void**)); + for (int i = 0; i < *count; i++) { + /* add new memory on the next array block */ + copy[i] = (void*) calloc(1, sizeof(void*)); + copy[i] = src[i]; + } + return copy; + } + + /** + * @brief Re-validates the buffer from [NULL] pointers. + * + * @param buffer the buffer to re-validate. + * @param count the pointers count. + */ + static inline void reValidateBuffer(void** buffer, int* count, int* isProcessed) { + /* get a temp copy from flagged buffer */ + void** temp = BufferUtils::copy(buffer, count); + /* free the buffer cells to prepare the buffer to be reinitialized */ + BufferUtils::freeBufferCells(buffer, count); + /* re-init the buffer, removing the null pointers */ + for (int i = 0, j = 0; i < *count; i++) { + if (temp[i] == NULL) { + printf("%s\n", "zero"); + continue; + } + buffer[j] = (void*) calloc(1, sizeof(void*)); + buffer[j] = temp[i]; + j++; + } + *isProcessed = 1; + /* free the temp buffer */ + BufferUtils::freeBufferCells(temp, count); + } +} +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/DynamicBuffer.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/DynamicBuffer.h new file mode 100644 index 0000000..21d3285 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/DynamicBuffer.h @@ -0,0 +1,155 @@ +/** + * @file DynamicBuffer.h + * @author pavl_g. + * @brief Represents a cross platform dynamic buffer wrapper. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _DYNAMIC_BUFFER +#define _DYNAMIC_BUFFER + +#include +#include +#include + +struct DynamicBuffer { + + int count = 0; + int isProcessed = 0; + + /** + * Declares and initializes a pointer that points to + * other void* buffers starting from index zero. + * + * @note The pointer is of single size of a type. + * @note The pointer points to only and only one buffer at a time. + * @note New buffers can be added to this pointer by dereferencing it and adding one to the memory address to move + * it to a new cell block. + * e.g: + * 1) First way of adding a new buffer to this pointer using the deep copy: + * buffer[index] = (void*) calloc(1, sizeof(void*)); + * buffer[index] = item; + * + * 2) Second way of adding a new buffer to this pointer (the one used here): + * *(buffer += count) = (void*) calloc(1, sizeof(void*)); + * *buffer = item; + * buffer -= count; + * + * 3) The superficial copy example: + * buffer[index] = item; + */ + void** buffer = (void**) calloc(1, sizeof(void**));; + + static inline struct DynamicBuffer* createNewInstance() { + return (struct DynamicBuffer*) calloc(1, sizeof(struct DynamicBuffer)); + } + + /** + * Retrieves the pointer to this dynamic buffer. + * + * @return a pointer to this array of buffers. + */ + void** getBuffer() { + return buffer; + } + + /** + * Retrieves this structure size. + * + * @return an integer representing this struct in bytes. + */ + size_t getBufferSize() { + return sizeof(struct DynamicBuffer); + } + + /** + * Resets the pointer value back to zero. + */ + void resetDataPointer() { + this->count = 0; + } + + /** + * Gets the memory address to the integer of the items count. + * + * @return a pointer referring to the memory address of the integer that represents the item counts. + */ + int* getItemsCount(); + + /** + * Adds a new buffer to this pointer in a new index. + * + * @param item a void* buffer to add. + */ + void add(void* item); + + /** + * Adds a new buffer on a particular location in this pointer replacing an old one if exists. + * + * @param index the index where the new buffer will be located in this pointer. + * @param item the buffer to add. + */ + void add(int index, void* item); + + /** + * Frees a buffer from the memory at a particular index. + * @warning this method call is expensive as it removes and revalidates the whole buffer from NULL pointers. + * + * @param index the index of the buffer to remove. + */ + void removeAt(int index); + + /** + * Frees all the buffers of this pointer from the memory. + */ + void removeAll(); + + /** + * Retrieves a buffer index. + * + * @param item the buffer to get its index. + * @return the buffer index in an integer format. + */ + int getItemIndex(void* item); + + /** + * Retrieves a buffer from this pointer using its index. + * + * @param index the index where the buffer is located in this pointer. + * @return the buffer corresponding to this index. + */ + void* getItem(int index); +}; + + +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/ErrnoUtils.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/ErrnoUtils.h new file mode 100644 index 0000000..58ec430 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/ErrnoUtils.h @@ -0,0 +1,53 @@ +/** + * @file ErrnoUtils.util + * @author pavl_g. + * @brief Represents native user and machine errnos. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _ERRNO_UTILS +#define _ERRNO_UTILS + +#include + +#define ERR_INVALID_PORT (-2) +#define ERR_INVALID_DIR (-3) +#define ERR_NO_RESULT (0) +#define LOGGER_DISABLED (-5) +#define ERR_OPERATION_FAILED (-1) +#define ERR_NO_AVAILABLE_TTY_DEVICES (-4) + +#define OPERATION_SUCCEEDED (1) + + +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/info.md b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/info.md new file mode 100644 index 0000000..166e55d --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/info.md @@ -0,0 +1,6 @@ +# Serial4j API C Utils + +## Includes the following: +- BufferUtils.h: for managing native buffers. +- DynamicBuffer.h: for creating dynamic buffers. +- ErrnoUtils.h: for checking and referencing different errno code numbers. \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/SerialUtils.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/SerialUtils.h new file mode 100644 index 0000000..007d1a5 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/SerialUtils.h @@ -0,0 +1,77 @@ +/** + * @file SerialUtils.util + * @author pavl_g. + * @brief Represents utilities for the [Serial.h] library. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _SERIAL_UTILS +#define _SERIAL_UTILS + +#include +#include +#include +#include +#include + +namespace SerialUtils { + + /** + * @brief Converts a [file] into a [device] and outputs the + * result into a [buffer]. + * + * @param buffer a buffer to fill in the operation. + * @param file the file to convert into a device. + * @return char* a buffer of {"/dev/"} formula. + */ + static inline char* concatIntoDevice(char* buffer, const char* file, const char* DEVICES_DIR) { + strcat(buffer, DEVICES_DIR); + strcat(buffer, file); + return buffer; + } + + /** + * @brief Tests whether the PATH specified is a real serial port. + * + * @param path the path to specify if its a serial port. + * @return int 1 if FD is a valid descriptor, 0 otherwise. + */ + static inline int isSerialPort(char* path, const int FLAG) { + int fdp = open(path, FLAG); + int state = isatty(fdp); + close(fdp); + return state; + } +} + +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/TerminalDevice.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/TerminalDevice.h new file mode 100644 index 0000000..571d1c5 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/TerminalDevice.h @@ -0,0 +1,258 @@ +/** + * @file Serial.h + * @author pavl_g. + * @brief Represents the serial port devices control and operation for POSIX systems. + * @note This is the base [HAL] (Hardware abstraction layer) for the Serial4j api. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API, RS232. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _RS232 +#define _RS232 "RS232-Interface" + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#define READ_CONFIG_SIZE (2) +#define DEVICES_DIR ((const char*) "/dev/") + +/** The default flags for the base file api */ +#define DEFAULT_FLAGS (O_RDWR | O_NONBLOCK | O_NOCTTY) + +typedef unsigned short int TerminalFlag; + +namespace TerminalDevice { + + /** Param@0 = VTIME, Param@1 = VMIN */ + const cc_t POLLING_READ[READ_CONFIG_SIZE] = {0, 0}; + const cc_t BLOCKING_READ_ONE_CHAR[READ_CONFIG_SIZE] = {0, 1}; + const cc_t READ_WITH_TIMEOUT[READ_CONFIG_SIZE] = {1, 0}; + const cc_t READ_WITH_INTERBYTE_TIMEOUT[READ_CONFIG_SIZE] = {1, 1}; + + /** + * Retrieves the termios of this tty device described by the file descriptor (fd). + * + * @param fd the virtual file descriptor for this tty device. + * @return a memory reference to the termios defining this tty device terminal attributes. + */ + struct termios* getTermiosFromFd(int* fd); + + /** + * @brief Fetches serial port devices on "/dev/" into [serialPorts] buffer. + * @note Uses , , , and . + * + * @return int (-3) if the directory ["/dev"] is invalid, (-4) if there are no tty + * devices available at the ["/dev"] directory, (1) if operation succeeded. + */ + int fetchSerialPorts(struct DynamicBuffer* serialPorts); + + /** + * @brief Opens a serial port device with a name. + * @note Uses Unix file base api and . + * + * @param port the path for the serial port device. + * @return int* a memory reference for the port file descriptor. + */ + int openPort(const char* port, int flag); + + /** + * @brief Initializes the default terminal for this device with the following default charachteristics: + * ----------- + * # c_cflag: for control mode flags. + * *** Enable these bits: + * - [CREAD]: Allow input to be received. + * - [CS8]: For charachter size 8-bit, you can use the bit mask CSIZE to read this value. + * - [CLOCAL]: Ignore modem status lines (don’t check carrier signal). + * ----------- + * # c_lflag: for local mode flags. + * ***Disable these bits: + * - [ICANON]: Canonical mode (line-by-line) input. + * - [ECHO]: Echo input characters. + * - [ECHOE]: Perform ERASE visually. + * - [ECHOK]: Echo KILL visually. + * - [ECHOKE]: Don’t output a newline after echoed KILL. + * - [ECHONL]: Echo NL (in canonical mode) even if echoing is disabled. + * - [ECHOPRT]: Echo deleted characters backward (between \ and / ). + * - [ECHOCTL]: Echo control characters visually (e.g., ^L ). + * - [ISIG]: Enable signal-generating characters (INTR, QUIT, SUSP). + * - [IEXTEN]: Enable extended processing of input characters. + * ----------- + * # c_oflag: for output mode flags. + * ***Disable these bits: + * - [OPOST]: Perform output postprocessing. + * - [ONLCR]: Map NL to CR-NL on output. + * ----------- + * # c_iflag: for input mode flags. + * ***Disable all input bit masks. + * ----------- + * # c_cc: For control characters. + * ***Sets to BLOCKING READ ONE CHAR AT A TIME MODE. + * ----------- + * + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int initTermios(int* fd); + + /** + * @brief Sets the Terminal Control Flag [c_cflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalControlFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Local Flag [c_lflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalLocalFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Output Flag [c_oflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalOutputFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Input Flag [c_iflag] for the [termios] variable. + * + * @param flags bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalInputFlag(TerminalFlag flag, int* fd); + + /** + * @brief Gets the Terminal Control Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal control flag in [unsigned short int]. + */ + TerminalFlag getTerminalControlFlag(int* fd); + + /** + * @brief Gets the Terminal Local Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal local flag in [unsigned short int]. + */ + TerminalFlag getTerminalLocalFlag(int* fd); + + /** + * @brief Gets the Terminal Input Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal input flag in [unsigned short int]. + */ + TerminalFlag getTerminalInputFlag(int* fd); + + /** + * @brief Gets the Terminal Output Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal output flag in [unsigned short int]. + */ + TerminalFlag getTerminalOutputFlag(int* fd); + + /** + * @brief Sets the Read Configuration Mode using a ReadConfiguration with a + * VMIN_VALUE for lesser bytes to read and VTIME_VALUE for the elapsed time to + * set if the ReadConfiguration mode provides a timeout. + * + * @param VTIME_VALUE the value of the read timeout elapsed time, the timer starts + * with this value after read() is called. + * @param VMIN_VALUE the value of the minimum number of bytes to read. + * @return int (ERR_INVALID_PORT = -2) if port isn't available, (0) otherwise. + */ + int setReadConfigurationMode(const int VTIME_VALUE, const int VMIN_VALUE, int* fd); + + /** + * @brief Get the Read Configuration Mode in a new pointer. + * + * @return int* a memory reference to the new read configuration instance holding the VTIME and VMIN. + */ + cc_t* getReadConfigurationMode(int* fd); + + /** + * @brief Sets the Baud Rate object for the terminal io. + * + * @param baudRate the baud rate (bits/seconds). + * @return int (1) for success, (-1) for failure, (-2) for invalid port. + */ + int setBaudRate(int baudRate, int* fd); + + /** + * @brief Gets the Baud Rate object. + * + * @return speed_t baud rate in integers. + */ + speed_t getBaudRate(int* fd); + + /** + * @brief Writes a data to the serial port device from a buffer. + * + * @param buffer a buffer to write to the file. + * @param length the number of charachters to write from the buffer. + * @return ssize_t the number of bytes written to the serial device, (-1) for failure, (-2) for invalid port. + */ + ssize_t writeData(const void* buffer, int length, int* fd); + + /** + * @brief Reads data from the serial port device and saves it to a buffer. + * + * @param buffer a buffer to read from the file to it. + * @param length the number of the charachters to read by this buffer. + * @return ssize_t the number of bytes read from the terminal, (-1) for failure, (-2) for invalid port. + */ + ssize_t readData(void* buffer, int length, int* fd); + + /** + * @brief Closes the serial port device. + * + * @return int (1) for success, (-1) for failure, (-2) for invalid port. + */ + int closePort(int* fd); + +} + + +#endif diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/Thread.h b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/Thread.h new file mode 100644 index 0000000..7b57ec4 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/Thread.h @@ -0,0 +1,51 @@ +/** + * @file Thread.h + * @author pavl_g. + * @brief Optional header for operating within PThreads. + * @version 0.1 + * @date 2022-08-24 + * + * @note TODO. + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _THREADS +#define _THREADS + +#include + +namespace POSIX { + struct Thread { + + }; +} + +#endif \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/info.md b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/info.md new file mode 100644 index 0000000..000fa07 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/include/linux/info.md @@ -0,0 +1 @@ +# Rs232-Interface API designed for Linux/Unix diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/DynamicBuffer.c b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/DynamicBuffer.c new file mode 100755 index 0000000..0bd1320 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/DynamicBuffer.c @@ -0,0 +1,62 @@ +#include + +void DynamicBuffer::add(void* item) { + + /* move the pointer to point to the last item */ + /* then, obtain a superficial copy */ + void** copy = (buffer += count); + /* dereference and evalute using the superficial copy */ + *copy = (void*) calloc(1, sizeof(void*)); + *copy = item; + /* move the pointer back to the start of the buffer (first item) */ + buffer -= count; + count++; +} + +void DynamicBuffer::add(int index, void* item) { + /* adds on the count if the location was empty previously */ + if (buffer[index] == NULL) { + ++count; + } + buffer[index] = item; +} + +void DynamicBuffer::removeAt(int index) { + BufferUtils::nullifyBuffer(buffer, index); + BufferUtils::reValidateBuffer(buffer, getItemsCount(), &(this->isProcessed)); + + while (!this->isProcessed); + this->isProcessed = 0; + + count--; +} + +void DynamicBuffer::removeAll() { + for (int i = 0; i < *(this->getItemsCount()); i++) { + BufferUtils::nullifyBuffer(buffer, i); + } + + BufferUtils::reValidateBuffer(buffer, getItemsCount(), &(this->isProcessed)); + + while (!this->isProcessed); + this->isProcessed = 0; + + this->resetDataPointer(); +} + +void* DynamicBuffer::getItem(int index) { + return buffer[index]; +} + +int DynamicBuffer::getItemIndex(void* item) { + for (int i = 0; i < *getItemsCount(); i++) { + if (buffer[i] == item) { + return i; + } + } + return ERR_OPERATION_FAILED; +} + +int* DynamicBuffer::getItemsCount() { + return &count; +} diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/info.md b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/info.md new file mode 100644 index 0000000..d9a935a --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/info.md @@ -0,0 +1,4 @@ +# Serial4j API C Utils + +## Includes the following: +- DynamicBuffer.c: for creating dynamic buffers. \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/linux/TerminalDevice.c b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/linux/TerminalDevice.c new file mode 100755 index 0000000..fc587fa --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/linux/TerminalDevice.c @@ -0,0 +1,249 @@ +#include + +struct termios* TerminalDevice::getTermiosFromFd(int* fd) { + if (fd == NULL) { + return NULL; + } + struct termios* tty = (struct termios*) calloc(1, sizeof(struct termios)); + /* update the termios struct pointer with the data from the port descriptor */ + tcgetattr(*fd, tty); + return tty; +} + +int TerminalDevice::openPort(const char* port, int flag) { + return open(port, flag); +} + +int TerminalDevice::fetchSerialPorts(struct DynamicBuffer* serialPorts) { + + DIR* dirp = opendir(DEVICES_DIR); + + /* sanity check the input */ + if (dirp == NULL) { + return ERR_INVALID_DIR; + } + + struct dirent* dp = (struct dirent*) calloc(1, sizeof(struct dirent)); + + /* start at the beginning of the buffer to override last data */ + serialPorts->resetDataPointer(); + + /* start reading available ports */ + while ((dp = readdir(dirp)) != NULL) { + + char* device = (char*) calloc(1, sizeof(char)); + device = SerialUtils::concatIntoDevice(device, dp->d_name, DEVICES_DIR); + + /* delete the device buffer if it's not a serial port */ + if (!SerialUtils::isSerialPort(device, DEFAULT_FLAGS)) { + BufferUtils::deleteBuffer(device); + continue; + } + + /* add the device to the serial ports major buffer and count up */ + serialPorts->add(device); + } + + /* release resources */ + closedir(dirp); + BufferUtils::deleteBuffer(dp); + + /* throws error indicating the availability issues */ + if (serialPorts->getItem(0) == NULL) { + return ERR_NO_AVAILABLE_TTY_DEVICES; + } + return OPERATION_SUCCEEDED; +} + +int TerminalDevice::initTermios(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + /* setup tty attributes */ + tty->c_cflag &= ~(CBAUDEX | CBAUD); /* clear BAUDs */ + tty->c_cflag |= (CREAD | CS8 | CLOCAL); /* set flags */ + tty->c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHOKE | ECHONL | ECHOPRT | ECHOCTL | ISIG | IEXTEN); + tty->c_oflag &= ~(OPOST | ONLCR); + tty->c_iflag = 0x00; + + /* define default read mode as blocking read on char at a time */ + tty->c_cc[VTIME] = BLOCKING_READ_ONE_CHAR[0]; + tty->c_cc[VMIN] = BLOCKING_READ_ONE_CHAR[1]; + + /* apply attriutes flag bits */ + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +int TerminalDevice::setTerminalControlFlag(TerminalFlag flag, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_cflag = flag; + /* sets the new terminal settings to the file descriptor with flushing any output */ + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +int TerminalDevice::setTerminalLocalFlag(TerminalFlag flag, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_lflag = flag; + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +int TerminalDevice::setTerminalInputFlag(TerminalFlag flag, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_iflag = flag; + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +int TerminalDevice::setTerminalOutputFlag(TerminalFlag flag, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_oflag = flag; + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +TerminalFlag TerminalDevice::getTerminalControlFlag(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + return tty->c_cflag; +} + +TerminalFlag TerminalDevice::getTerminalLocalFlag(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + return tty->c_lflag; +} + +TerminalFlag TerminalDevice::getTerminalInputFlag(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + return tty->c_iflag; +} + +TerminalFlag TerminalDevice::getTerminalOutputFlag(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + return tty->c_oflag; +} + +int TerminalDevice::setReadConfigurationMode(const int VTIME_VALUE, const int VMIN_VALUE, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_cc[VTIME] = VTIME_VALUE; + tty->c_cc[VMIN] = VMIN_VALUE; + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +cc_t* TerminalDevice::getReadConfigurationMode(int* fd) { + cc_t* readConfig = (cc_t*) calloc(2, sizeof(unsigned char)); + if (*fd <= 0) { + readConfig[0] = ERR_INVALID_PORT; + readConfig[1] = ERR_INVALID_PORT; + return readConfig; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + readConfig[0] = tty->c_cc[VTIME]; + readConfig[1] = tty->c_cc[VMIN]; + BufferUtils::deleteBuffer(tty); + + return readConfig; +} + +int TerminalDevice::setBaudRate(int baudRate, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + /* update the baud rate of the termios */ + cfsetspeed(tty, baudRate); + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +speed_t TerminalDevice::getBaudRate(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + int speed = cfgetospeed(tty); + BufferUtils::deleteBuffer(tty); + + return speed; +} + +ssize_t TerminalDevice::writeData(const void* buffer, int length, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + return write(*fd, buffer, length); +} + +ssize_t TerminalDevice::readData(void* buffer, int length, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + return read(*fd, buffer, length); +} + +int TerminalDevice::closePort(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + return close(*fd); +} diff --git a/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/linux/Thread.c b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/linux/Thread.c new file mode 100755 index 0000000..a0dd490 --- /dev/null +++ b/HelloNativeLibs/amd-64/Dynamic-Libraries/Rs232-Interface/src/lib/linux/Thread.c @@ -0,0 +1,40 @@ +/** + * @file Thread.c + * @author pavl_g. + * @brief Optional source for operating within PThreads. + * @version 0.1 + * @date 2022-08-24 + * + * @note TODO. + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#include \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/build/build.sh b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/build/build.sh new file mode 100755 index 0000000..fd8b054 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/build/build.sh @@ -0,0 +1,21 @@ +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +echo "Compiling the project" +echo -e $RESET_Cs +echo "--------Script start--------" + +source $build_dir'/compile.sh' + +echo -e $RESET_Cs + +compile + +echo -e $RESET_Cs +echo "--------Script end--------" diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/build/compile.sh b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/build/compile.sh new file mode 100644 index 0000000..cdd849f --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/build/compile.sh @@ -0,0 +1,54 @@ +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +source $build_dir'/variables.sh' + +## +# Compile and build native sources. +# +# @echo Script Succeeded if all the commands have passed successfully, exit with error code otherwise. +## +function compile() { + native_sources=`find $nativessrc_directory'/main' -name '*.c' -o -name '*.cxx' -o -name '*.cpp' -o -name '*.c++'-o -name '*.ino'` + # tests if the sources exist, then give the current user full permissions on them and compile them + chmod +x $native_sources + # append -lwiringPi for raspberry wiringPi includes + # ${JAVA__HOME%/*} : % returns back to the root base directory of the java home, / is the separator delimiter of the directory string + # compile and build a shared lib for linux systems + if [[ `linux_x86_x64 "${native_sources}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Linux-x86-x64 : Succeeded" + else + echo -e "$RED_C Task@Build Linux-x86-x64 : Failed" + echo -e "$RED_C Exiting Script with error 150" + exit 150 + fi + echo -e "$GREEN_C---MajorTask@Build Native Sources : Succeeded---" +} + +## +# Build for desktop linux systems +# +# @param nativeSources sources to be compiled for linux desktop. +# @return 0 if command passes, non zero number otherwise with exit code 150 (search the code on repo's wiki). +## +function linux_x86_x64() { + local native_sources=$1 + if [[ ! -d $output_dir'/linux-x86-x64' ]]; then + mkdir -p $output_dir'/linux-x86-x64' + fi + $gcc -fpie $native_sources -v -o $output_dir'/linux-x86-x64/'${clibName} \ + -I${JAVA__HOME%/*}'/include' \ + -I${JAVA__HOME%/*}'/include/linux' \ + -I${nativessrc_directory}'/include/linux/' \ + -I${nativessrc_directory}'/include' \ + -L$linux_libs_root_dir \ + -l'rs232' + + return $? +} \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/build/variables.sh b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/build/variables.sh new file mode 100644 index 0000000..2dfc13b --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/build/variables.sh @@ -0,0 +1,37 @@ +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +# print the canonical file name from its symbolic link +canonical_link=`readlink -f ${0}` +# get the directory name of this canonical name +build_dir=`dirname $canonical_link` + +# work directories +project_root="${build_dir%/*}" + +dynamic_libs_dir="${project_root%/*}" + +amd_examples_dir="${dynamic_libs_dir%/*}" + +hello_native_libs="${amd_examples_dir%/*}" + +# cut the working directory from its end by a one '/' delimiter again +avr_sandbox_root="${hello_native_libs%/*}" + +# constant independent +clibName=('HelloRs232.elf') + +# native toolchains +gcc='g++-10' + +# code sources +nativessrc_directory=$project_root'/src' + +# native shared/dynamic libs +linux_libs_root_dir=$project_root'/libs/shared/native/Linux/linux-x86-x64/' +output_dir=$project_root'/output' + +source $avr_sandbox_root'/CommonVariables.sh' diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/output/linux-x86-x64/HelloRs232.elf b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/output/linux-x86-x64/HelloRs232.elf new file mode 100755 index 0000000..eae86db Binary files /dev/null and b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/output/linux-x86-x64/HelloRs232.elf differ diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/BufferUtils.h b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/BufferUtils.h new file mode 100644 index 0000000..7e08167 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/BufferUtils.h @@ -0,0 +1,124 @@ +/** + * @file BufferUtils.util + * @author pavl_g. + * @brief Represents utility functions for buffers. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _BUFFER_UTILS +#define _BUFFER_UTILS + +#include +#include +#include + +namespace BufferUtils { + + /** + * Nullifies a single buffer cell at the index. + * + * @param buffer the buffer to nullify its cell. + * @param index the index of the buffer cell to nullify. + */ + static inline void nullifyBuffer(void** buffer, int index) { + buffer[index] = NULL; + } + + /** + * Frees the memory utilized by the individual buffer cells on a [buffer] with [count] number of cells. + * + * @param buffer the buffer to free its cells. + * @param count the number of cells to free, starting from index zero. + */ + static inline void freeBufferCells(void** buffer, int* count) { + for (int i = 0; i < *count; i++) { + BufferUtils::nullifyBuffer(buffer, i); + free(buffer[i]); + } + } + + /** + * @brief Deletes a typified buffer and frees its memory. + * + * @param buffer the buffer to delete. + */ + static inline void deleteBuffer(void* buffer) { + free(buffer); + BufferUtils::nullifyBuffer(&buffer, 0); + } + + /** + * @brief Deeply copies the data of the [src] buffer into a new + * buffer and returns it. + * + * @param src the source buffer to get the data from. + * @param count the count length of the buffer. + * @return void** a new buffer with the same data as the source. + */ + static inline void** copy(void** src, int* count) { + void** copy = (void**) calloc(1, sizeof(void**)); + for (int i = 0; i < *count; i++) { + /* add new memory on the next array block */ + copy[i] = (void*) calloc(1, sizeof(void*)); + copy[i] = src[i]; + } + return copy; + } + + /** + * @brief Re-validates the buffer from [NULL] pointers. + * + * @param buffer the buffer to re-validate. + * @param count the pointers count. + */ + static inline void reValidateBuffer(void** buffer, int* count, int* isProcessed) { + /* get a temp copy from flagged buffer */ + void** temp = BufferUtils::copy(buffer, count); + /* free the buffer cells to prepare the buffer to be reinitialized */ + BufferUtils::freeBufferCells(buffer, count); + /* re-init the buffer, removing the null pointers */ + for (int i = 0, j = 0; i < *count; i++) { + if (temp[i] == NULL) { + printf("%s\n", "zero"); + continue; + } + buffer[j] = (void*) calloc(1, sizeof(void*)); + buffer[j] = temp[i]; + j++; + } + *isProcessed = 1; + /* free the temp buffer */ + BufferUtils::freeBufferCells(temp, count); + } +} +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/DynamicBuffer.h b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/DynamicBuffer.h new file mode 100644 index 0000000..21d3285 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/DynamicBuffer.h @@ -0,0 +1,155 @@ +/** + * @file DynamicBuffer.h + * @author pavl_g. + * @brief Represents a cross platform dynamic buffer wrapper. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _DYNAMIC_BUFFER +#define _DYNAMIC_BUFFER + +#include +#include +#include + +struct DynamicBuffer { + + int count = 0; + int isProcessed = 0; + + /** + * Declares and initializes a pointer that points to + * other void* buffers starting from index zero. + * + * @note The pointer is of single size of a type. + * @note The pointer points to only and only one buffer at a time. + * @note New buffers can be added to this pointer by dereferencing it and adding one to the memory address to move + * it to a new cell block. + * e.g: + * 1) First way of adding a new buffer to this pointer using the deep copy: + * buffer[index] = (void*) calloc(1, sizeof(void*)); + * buffer[index] = item; + * + * 2) Second way of adding a new buffer to this pointer (the one used here): + * *(buffer += count) = (void*) calloc(1, sizeof(void*)); + * *buffer = item; + * buffer -= count; + * + * 3) The superficial copy example: + * buffer[index] = item; + */ + void** buffer = (void**) calloc(1, sizeof(void**));; + + static inline struct DynamicBuffer* createNewInstance() { + return (struct DynamicBuffer*) calloc(1, sizeof(struct DynamicBuffer)); + } + + /** + * Retrieves the pointer to this dynamic buffer. + * + * @return a pointer to this array of buffers. + */ + void** getBuffer() { + return buffer; + } + + /** + * Retrieves this structure size. + * + * @return an integer representing this struct in bytes. + */ + size_t getBufferSize() { + return sizeof(struct DynamicBuffer); + } + + /** + * Resets the pointer value back to zero. + */ + void resetDataPointer() { + this->count = 0; + } + + /** + * Gets the memory address to the integer of the items count. + * + * @return a pointer referring to the memory address of the integer that represents the item counts. + */ + int* getItemsCount(); + + /** + * Adds a new buffer to this pointer in a new index. + * + * @param item a void* buffer to add. + */ + void add(void* item); + + /** + * Adds a new buffer on a particular location in this pointer replacing an old one if exists. + * + * @param index the index where the new buffer will be located in this pointer. + * @param item the buffer to add. + */ + void add(int index, void* item); + + /** + * Frees a buffer from the memory at a particular index. + * @warning this method call is expensive as it removes and revalidates the whole buffer from NULL pointers. + * + * @param index the index of the buffer to remove. + */ + void removeAt(int index); + + /** + * Frees all the buffers of this pointer from the memory. + */ + void removeAll(); + + /** + * Retrieves a buffer index. + * + * @param item the buffer to get its index. + * @return the buffer index in an integer format. + */ + int getItemIndex(void* item); + + /** + * Retrieves a buffer from this pointer using its index. + * + * @param index the index where the buffer is located in this pointer. + * @return the buffer corresponding to this index. + */ + void* getItem(int index); +}; + + +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/ErrnoUtils.h b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/ErrnoUtils.h new file mode 100644 index 0000000..58ec430 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/ErrnoUtils.h @@ -0,0 +1,53 @@ +/** + * @file ErrnoUtils.util + * @author pavl_g. + * @brief Represents native user and machine errnos. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _ERRNO_UTILS +#define _ERRNO_UTILS + +#include + +#define ERR_INVALID_PORT (-2) +#define ERR_INVALID_DIR (-3) +#define ERR_NO_RESULT (0) +#define LOGGER_DISABLED (-5) +#define ERR_OPERATION_FAILED (-1) +#define ERR_NO_AVAILABLE_TTY_DEVICES (-4) + +#define OPERATION_SUCCEEDED (1) + + +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/info.md b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/info.md new file mode 100644 index 0000000..166e55d --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/info.md @@ -0,0 +1,6 @@ +# Serial4j API C Utils + +## Includes the following: +- BufferUtils.h: for managing native buffers. +- DynamicBuffer.h: for creating dynamic buffers. +- ErrnoUtils.h: for checking and referencing different errno code numbers. \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/SerialUtils.h b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/SerialUtils.h new file mode 100644 index 0000000..007d1a5 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/SerialUtils.h @@ -0,0 +1,77 @@ +/** + * @file SerialUtils.util + * @author pavl_g. + * @brief Represents utilities for the [Serial.h] library. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _SERIAL_UTILS +#define _SERIAL_UTILS + +#include +#include +#include +#include +#include + +namespace SerialUtils { + + /** + * @brief Converts a [file] into a [device] and outputs the + * result into a [buffer]. + * + * @param buffer a buffer to fill in the operation. + * @param file the file to convert into a device. + * @return char* a buffer of {"/dev/"} formula. + */ + static inline char* concatIntoDevice(char* buffer, const char* file, const char* DEVICES_DIR) { + strcat(buffer, DEVICES_DIR); + strcat(buffer, file); + return buffer; + } + + /** + * @brief Tests whether the PATH specified is a real serial port. + * + * @param path the path to specify if its a serial port. + * @return int 1 if FD is a valid descriptor, 0 otherwise. + */ + static inline int isSerialPort(char* path, const int FLAG) { + int fdp = open(path, FLAG); + int state = isatty(fdp); + close(fdp); + return state; + } +} + +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/TerminalDevice.h b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/TerminalDevice.h new file mode 100644 index 0000000..571d1c5 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/TerminalDevice.h @@ -0,0 +1,258 @@ +/** + * @file Serial.h + * @author pavl_g. + * @brief Represents the serial port devices control and operation for POSIX systems. + * @note This is the base [HAL] (Hardware abstraction layer) for the Serial4j api. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API, RS232. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _RS232 +#define _RS232 "RS232-Interface" + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#define READ_CONFIG_SIZE (2) +#define DEVICES_DIR ((const char*) "/dev/") + +/** The default flags for the base file api */ +#define DEFAULT_FLAGS (O_RDWR | O_NONBLOCK | O_NOCTTY) + +typedef unsigned short int TerminalFlag; + +namespace TerminalDevice { + + /** Param@0 = VTIME, Param@1 = VMIN */ + const cc_t POLLING_READ[READ_CONFIG_SIZE] = {0, 0}; + const cc_t BLOCKING_READ_ONE_CHAR[READ_CONFIG_SIZE] = {0, 1}; + const cc_t READ_WITH_TIMEOUT[READ_CONFIG_SIZE] = {1, 0}; + const cc_t READ_WITH_INTERBYTE_TIMEOUT[READ_CONFIG_SIZE] = {1, 1}; + + /** + * Retrieves the termios of this tty device described by the file descriptor (fd). + * + * @param fd the virtual file descriptor for this tty device. + * @return a memory reference to the termios defining this tty device terminal attributes. + */ + struct termios* getTermiosFromFd(int* fd); + + /** + * @brief Fetches serial port devices on "/dev/" into [serialPorts] buffer. + * @note Uses , , , and . + * + * @return int (-3) if the directory ["/dev"] is invalid, (-4) if there are no tty + * devices available at the ["/dev"] directory, (1) if operation succeeded. + */ + int fetchSerialPorts(struct DynamicBuffer* serialPorts); + + /** + * @brief Opens a serial port device with a name. + * @note Uses Unix file base api and . + * + * @param port the path for the serial port device. + * @return int* a memory reference for the port file descriptor. + */ + int openPort(const char* port, int flag); + + /** + * @brief Initializes the default terminal for this device with the following default charachteristics: + * ----------- + * # c_cflag: for control mode flags. + * *** Enable these bits: + * - [CREAD]: Allow input to be received. + * - [CS8]: For charachter size 8-bit, you can use the bit mask CSIZE to read this value. + * - [CLOCAL]: Ignore modem status lines (don’t check carrier signal). + * ----------- + * # c_lflag: for local mode flags. + * ***Disable these bits: + * - [ICANON]: Canonical mode (line-by-line) input. + * - [ECHO]: Echo input characters. + * - [ECHOE]: Perform ERASE visually. + * - [ECHOK]: Echo KILL visually. + * - [ECHOKE]: Don’t output a newline after echoed KILL. + * - [ECHONL]: Echo NL (in canonical mode) even if echoing is disabled. + * - [ECHOPRT]: Echo deleted characters backward (between \ and / ). + * - [ECHOCTL]: Echo control characters visually (e.g., ^L ). + * - [ISIG]: Enable signal-generating characters (INTR, QUIT, SUSP). + * - [IEXTEN]: Enable extended processing of input characters. + * ----------- + * # c_oflag: for output mode flags. + * ***Disable these bits: + * - [OPOST]: Perform output postprocessing. + * - [ONLCR]: Map NL to CR-NL on output. + * ----------- + * # c_iflag: for input mode flags. + * ***Disable all input bit masks. + * ----------- + * # c_cc: For control characters. + * ***Sets to BLOCKING READ ONE CHAR AT A TIME MODE. + * ----------- + * + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int initTermios(int* fd); + + /** + * @brief Sets the Terminal Control Flag [c_cflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalControlFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Local Flag [c_lflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalLocalFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Output Flag [c_oflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalOutputFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Input Flag [c_iflag] for the [termios] variable. + * + * @param flags bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalInputFlag(TerminalFlag flag, int* fd); + + /** + * @brief Gets the Terminal Control Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal control flag in [unsigned short int]. + */ + TerminalFlag getTerminalControlFlag(int* fd); + + /** + * @brief Gets the Terminal Local Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal local flag in [unsigned short int]. + */ + TerminalFlag getTerminalLocalFlag(int* fd); + + /** + * @brief Gets the Terminal Input Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal input flag in [unsigned short int]. + */ + TerminalFlag getTerminalInputFlag(int* fd); + + /** + * @brief Gets the Terminal Output Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal output flag in [unsigned short int]. + */ + TerminalFlag getTerminalOutputFlag(int* fd); + + /** + * @brief Sets the Read Configuration Mode using a ReadConfiguration with a + * VMIN_VALUE for lesser bytes to read and VTIME_VALUE for the elapsed time to + * set if the ReadConfiguration mode provides a timeout. + * + * @param VTIME_VALUE the value of the read timeout elapsed time, the timer starts + * with this value after read() is called. + * @param VMIN_VALUE the value of the minimum number of bytes to read. + * @return int (ERR_INVALID_PORT = -2) if port isn't available, (0) otherwise. + */ + int setReadConfigurationMode(const int VTIME_VALUE, const int VMIN_VALUE, int* fd); + + /** + * @brief Get the Read Configuration Mode in a new pointer. + * + * @return int* a memory reference to the new read configuration instance holding the VTIME and VMIN. + */ + cc_t* getReadConfigurationMode(int* fd); + + /** + * @brief Sets the Baud Rate object for the terminal io. + * + * @param baudRate the baud rate (bits/seconds). + * @return int (1) for success, (-1) for failure, (-2) for invalid port. + */ + int setBaudRate(int baudRate, int* fd); + + /** + * @brief Gets the Baud Rate object. + * + * @return speed_t baud rate in integers. + */ + speed_t getBaudRate(int* fd); + + /** + * @brief Writes a data to the serial port device from a buffer. + * + * @param buffer a buffer to write to the file. + * @param length the number of charachters to write from the buffer. + * @return ssize_t the number of bytes written to the serial device, (-1) for failure, (-2) for invalid port. + */ + ssize_t writeData(const void* buffer, int length, int* fd); + + /** + * @brief Reads data from the serial port device and saves it to a buffer. + * + * @param buffer a buffer to read from the file to it. + * @param length the number of the charachters to read by this buffer. + * @return ssize_t the number of bytes read from the terminal, (-1) for failure, (-2) for invalid port. + */ + ssize_t readData(void* buffer, int length, int* fd); + + /** + * @brief Closes the serial port device. + * + * @return int (1) for success, (-1) for failure, (-2) for invalid port. + */ + int closePort(int* fd); + +} + + +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/Thread.h b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/Thread.h new file mode 100644 index 0000000..7b57ec4 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/Thread.h @@ -0,0 +1,51 @@ +/** + * @file Thread.h + * @author pavl_g. + * @brief Optional header for operating within PThreads. + * @version 0.1 + * @date 2022-08-24 + * + * @note TODO. + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _THREADS +#define _THREADS + +#include + +namespace POSIX { + struct Thread { + + }; +} + +#endif \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/info.md b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/info.md new file mode 100644 index 0000000..000fa07 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/include/linux/info.md @@ -0,0 +1 @@ +# Rs232-Interface API designed for Linux/Unix diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/main/main.c b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/main/main.c new file mode 100755 index 0000000..6f9c990 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Hello-Rs232/src/main/main.c @@ -0,0 +1,34 @@ +#include + +static inline int* startRs232Service() { + printf("%s\n", " --- Started Rs232 driver service --- "); + + static int fd = TerminalDevice::openPort("/dev/ttyUSB0", DEFAULT_FLAGS); + if (fd <= 0) { + perror("Error driver not available, trying again......"); + } + + // try again and block until a request is accepted + while (fd <= 0 ) { + startRs232Service(); + } + + return &fd; +} + +static inline void initRs232Service(int* fd) { + int state = TerminalDevice::initTermios(fd); + if (state > 0) { + perror("Cannot initialize port"); + } +} + +int main(int argc, char **argv) { + printf("%s\n", " --- Started Rs232 driver example --- "); + + int* service_descriptor = startRs232Service(); + + initRs232Service(service_descriptor); + + return 0; +} diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/build/build.sh b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/build/build.sh new file mode 100755 index 0000000..ca2f35c --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/build/build.sh @@ -0,0 +1,26 @@ +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +echo "Compiling the project" +echo -e $RESET_Cs +echo "--------Script start--------" + +source $build_dir'/compile.sh' + +echo -e $RESET_Cs + +if [[ $enable_natives_build == true ]]; then + echo -e "$MAGNETA_C---MajorTask@Build Native Sources : Native build started" + compile + copyToExample + echo -e "$MAGNETA_C---MajorTask@Build Native Sources : Native build finished" +fi + +echo -e $RESET_Cs +echo "--------Script end--------" diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/build/compile.sh b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/build/compile.sh new file mode 100644 index 0000000..cac0b3e --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/build/compile.sh @@ -0,0 +1,129 @@ +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +source $build_dir'/variables.sh' + +## +# Compile and build native sources. +# +# @echo Script Succeeded if all the commands have passed successfully, exit with error code otherwise. +## +function compile() { + native_sources=`find $nativessrc_directory'/lib' -name '*.c' -o -name '*.cxx' -o -name '*.cpp' -o -name '*.c++'-o -name '*.ino'` + # tests if the sources exist, then give the current user full permissions on them and compile them + if [[ $native_sources ]]; then + chmod +x $native_sources + # append -lwiringPi for raspberry wiringPi includes + # ${JAVA__HOME%/*} : % returns back to the root base directory of the java home, / is the separator delimiter of the directory string + # compile and build a shared lib for linux systems + if [[ `linux_x86_x64 "${native_sources}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Linux-x86-x64 : Succeeded" + else + echo -e "$RED_C Task@Build Linux-x86-x64 : Failed" + echo -e "$RED_C Exiting Script with error 150" + exit 150 + fi + # compile and build a shared lib for android systems + if [[ $enable_android_build == true ]]; then + if [[ `linux_android "${arm64}" "${arm64_lib}" "${native_sources}" "${min_android_sdk}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Android-Arm-64 : Succeeded" + else + echo -e "$RED_C Task@Build Android-Arm-64 : Failed" + echo -e "$RED_C Exiting Script with error 250" + exit 250 + fi + + if [[ `linux_android "${arm32}" "${arm32_lib}" "${native_sources}" "${min_android_sdk}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Android-Arm-32 : Succeeded" + else + echo -e "$RED_C Task@Build Android-Arm-32 : Failed" + echo -e "$RED_C Exiting Script with error 350" + exit 350 + fi + + if [[ `linux_android "${intel64}" "${intel64_lib}" "${native_sources}" "${min_android_sdk}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Android-Intel-64 : Succeeded" + else + echo -e "$RED_C Task@Build Android-Intel-64 : Failed" + echo -e "$RED_C Exiting Script with error 450" + exit 450 + fi + + if [[ `linux_android "${intel32}" "${intel32_lib}" "${native_sources}" "${min_android_sdk}"` -eq 0 ]]; then + echo -e "$GREEN_C Task@Build Android-Intel-32 : Succeeded" + else + echo -e "$RED_C Task@Build Android-Intel-32 : Failed" + echo -e "$RED_C Exiting Script with error 550" + exit 550 + fi + fi + fi + echo -e "$GREEN_C---MajorTask@Build Native Sources : Succeeded---" +} + +## +# Build for desktop linux systems +# +# @param nativeSources sources to be compiled for linux desktop. +# @return 0 if command passes, non zero number otherwise with exit code 150 (search the code on repo's wiki). +## +function linux_x86_x64() { + local native_sources=$1 + if [[ ! -d $linux_natives_dir'/linux-x86-x64' ]]; then + mkdir -p $linux_natives_dir'/linux-x86-x64' + fi + $gcc -fPIC -v $native_sources -shared -o $linux_natives_dir'/linux-x86-x64/'${clibName} \ + -I${JAVA__HOME%/*}'/include' \ + -I${JAVA__HOME%/*}'/include/linux' \ + -I${nativessrc_directory}'/include/linux/' \ + -I${nativessrc_directory}'/include/' \ + + return $? +} + +## +# Building native code for arm and intel android. +# +# @param triple the ABI triple name, also used for -target flag of the clang++. +# @param folder the created folder name. +# @param sources the sources to compile and build an object file for them. +# @param min_android_sdk the minimum android sdk to compile against. +# @return 0 if command passes, non zero number otherwise. +## +function linux_android() { + # parameters attributes + local triple=$1 + local folder=$2 + local sources=$3 + local min_android_sdk=$4 + + if [[ ! -d $android_natives_dir ]]; then + mkdir $android_natives_dir + fi + + if [[ ! -d $android_natives_dir"/$folder" ]]; then + mkdir $android_natives_dir"/$folder" + fi + $NDK__BASEHOME'/toolchains/llvm/prebuilt/linux-x86_64/bin/clang++' -v -target ${triple}${min_android_sdk} \ + -fPIC $sources -shared \ + -stdlib=libstdc++ \ + -o $android_natives_dir"/$folder/"${clibName} \ + -I$nativessrc_directory'/includes' \ + -I$NDK__BASEHOME'/sources/cxx-stl/llvm-libc++/include' \ + -lc++_shared + result=$? + cp $NDK__BASEHOME"/sources/cxx-stl/llvm-libc++/libs/${folder}/libc++_shared.so" $android_natives_dir"/$folder" + return $result +} + +function copyToExample() { + local hello_rs232="`dirname $project_root`/Hello-Rs232" + cp -r $shared_root_dir $hello_rs232'/libs/' + cp -r ${nativessrc_directory}'/include/.' $hello_rs232'/src/include/' +} diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/build/variables.sh b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/build/variables.sh new file mode 100644 index 0000000..8c18f23 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/build/variables.sh @@ -0,0 +1,37 @@ +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +# print the canonical file name from its symbolic link +canonical_link=`readlink -f ${0}` +# get the directory name of this canonical name +build_dir=`dirname $canonical_link` + +# work directories +project_root="${build_dir%/*}" + +static_libs_dir="${project_root%/*}" + +amd_examples_dir="${static_libs_dir%/*}" + +hello_native_libs="${amd_examples_dir%/*}" + +# cut the working directory from its end by a one '/' delimiter again +avr_sandbox_root="${hello_native_libs%/*}" + +# constant independent +clibName=('librs232.a') + +# native toolchains +gcc='g++-10' + +# code sources +nativessrc_directory=$project_root'/src' + +# native static libs +shared_root_dir=$project_root'/static' +linux_natives_dir=$project_root'/static/native/Linux' + +source $avr_sandbox_root'/CommonVariables.sh' diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/BufferUtils.h b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/BufferUtils.h new file mode 100644 index 0000000..7e08167 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/BufferUtils.h @@ -0,0 +1,124 @@ +/** + * @file BufferUtils.util + * @author pavl_g. + * @brief Represents utility functions for buffers. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _BUFFER_UTILS +#define _BUFFER_UTILS + +#include +#include +#include + +namespace BufferUtils { + + /** + * Nullifies a single buffer cell at the index. + * + * @param buffer the buffer to nullify its cell. + * @param index the index of the buffer cell to nullify. + */ + static inline void nullifyBuffer(void** buffer, int index) { + buffer[index] = NULL; + } + + /** + * Frees the memory utilized by the individual buffer cells on a [buffer] with [count] number of cells. + * + * @param buffer the buffer to free its cells. + * @param count the number of cells to free, starting from index zero. + */ + static inline void freeBufferCells(void** buffer, int* count) { + for (int i = 0; i < *count; i++) { + BufferUtils::nullifyBuffer(buffer, i); + free(buffer[i]); + } + } + + /** + * @brief Deletes a typified buffer and frees its memory. + * + * @param buffer the buffer to delete. + */ + static inline void deleteBuffer(void* buffer) { + free(buffer); + BufferUtils::nullifyBuffer(&buffer, 0); + } + + /** + * @brief Deeply copies the data of the [src] buffer into a new + * buffer and returns it. + * + * @param src the source buffer to get the data from. + * @param count the count length of the buffer. + * @return void** a new buffer with the same data as the source. + */ + static inline void** copy(void** src, int* count) { + void** copy = (void**) calloc(1, sizeof(void**)); + for (int i = 0; i < *count; i++) { + /* add new memory on the next array block */ + copy[i] = (void*) calloc(1, sizeof(void*)); + copy[i] = src[i]; + } + return copy; + } + + /** + * @brief Re-validates the buffer from [NULL] pointers. + * + * @param buffer the buffer to re-validate. + * @param count the pointers count. + */ + static inline void reValidateBuffer(void** buffer, int* count, int* isProcessed) { + /* get a temp copy from flagged buffer */ + void** temp = BufferUtils::copy(buffer, count); + /* free the buffer cells to prepare the buffer to be reinitialized */ + BufferUtils::freeBufferCells(buffer, count); + /* re-init the buffer, removing the null pointers */ + for (int i = 0, j = 0; i < *count; i++) { + if (temp[i] == NULL) { + printf("%s\n", "zero"); + continue; + } + buffer[j] = (void*) calloc(1, sizeof(void*)); + buffer[j] = temp[i]; + j++; + } + *isProcessed = 1; + /* free the temp buffer */ + BufferUtils::freeBufferCells(temp, count); + } +} +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/DynamicBuffer.h b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/DynamicBuffer.h new file mode 100644 index 0000000..21d3285 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/DynamicBuffer.h @@ -0,0 +1,155 @@ +/** + * @file DynamicBuffer.h + * @author pavl_g. + * @brief Represents a cross platform dynamic buffer wrapper. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _DYNAMIC_BUFFER +#define _DYNAMIC_BUFFER + +#include +#include +#include + +struct DynamicBuffer { + + int count = 0; + int isProcessed = 0; + + /** + * Declares and initializes a pointer that points to + * other void* buffers starting from index zero. + * + * @note The pointer is of single size of a type. + * @note The pointer points to only and only one buffer at a time. + * @note New buffers can be added to this pointer by dereferencing it and adding one to the memory address to move + * it to a new cell block. + * e.g: + * 1) First way of adding a new buffer to this pointer using the deep copy: + * buffer[index] = (void*) calloc(1, sizeof(void*)); + * buffer[index] = item; + * + * 2) Second way of adding a new buffer to this pointer (the one used here): + * *(buffer += count) = (void*) calloc(1, sizeof(void*)); + * *buffer = item; + * buffer -= count; + * + * 3) The superficial copy example: + * buffer[index] = item; + */ + void** buffer = (void**) calloc(1, sizeof(void**));; + + static inline struct DynamicBuffer* createNewInstance() { + return (struct DynamicBuffer*) calloc(1, sizeof(struct DynamicBuffer)); + } + + /** + * Retrieves the pointer to this dynamic buffer. + * + * @return a pointer to this array of buffers. + */ + void** getBuffer() { + return buffer; + } + + /** + * Retrieves this structure size. + * + * @return an integer representing this struct in bytes. + */ + size_t getBufferSize() { + return sizeof(struct DynamicBuffer); + } + + /** + * Resets the pointer value back to zero. + */ + void resetDataPointer() { + this->count = 0; + } + + /** + * Gets the memory address to the integer of the items count. + * + * @return a pointer referring to the memory address of the integer that represents the item counts. + */ + int* getItemsCount(); + + /** + * Adds a new buffer to this pointer in a new index. + * + * @param item a void* buffer to add. + */ + void add(void* item); + + /** + * Adds a new buffer on a particular location in this pointer replacing an old one if exists. + * + * @param index the index where the new buffer will be located in this pointer. + * @param item the buffer to add. + */ + void add(int index, void* item); + + /** + * Frees a buffer from the memory at a particular index. + * @warning this method call is expensive as it removes and revalidates the whole buffer from NULL pointers. + * + * @param index the index of the buffer to remove. + */ + void removeAt(int index); + + /** + * Frees all the buffers of this pointer from the memory. + */ + void removeAll(); + + /** + * Retrieves a buffer index. + * + * @param item the buffer to get its index. + * @return the buffer index in an integer format. + */ + int getItemIndex(void* item); + + /** + * Retrieves a buffer from this pointer using its index. + * + * @param index the index where the buffer is located in this pointer. + * @return the buffer corresponding to this index. + */ + void* getItem(int index); +}; + + +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/ErrnoUtils.h b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/ErrnoUtils.h new file mode 100644 index 0000000..58ec430 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/ErrnoUtils.h @@ -0,0 +1,53 @@ +/** + * @file ErrnoUtils.util + * @author pavl_g. + * @brief Represents native user and machine errnos. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _ERRNO_UTILS +#define _ERRNO_UTILS + +#include + +#define ERR_INVALID_PORT (-2) +#define ERR_INVALID_DIR (-3) +#define ERR_NO_RESULT (0) +#define LOGGER_DISABLED (-5) +#define ERR_OPERATION_FAILED (-1) +#define ERR_NO_AVAILABLE_TTY_DEVICES (-4) + +#define OPERATION_SUCCEEDED (1) + + +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/info.md b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/info.md new file mode 100644 index 0000000..166e55d --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/info.md @@ -0,0 +1,6 @@ +# Serial4j API C Utils + +## Includes the following: +- BufferUtils.h: for managing native buffers. +- DynamicBuffer.h: for creating dynamic buffers. +- ErrnoUtils.h: for checking and referencing different errno code numbers. \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/SerialUtils.h b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/SerialUtils.h new file mode 100644 index 0000000..007d1a5 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/SerialUtils.h @@ -0,0 +1,77 @@ +/** + * @file SerialUtils.util + * @author pavl_g. + * @brief Represents utilities for the [Serial.h] library. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _SERIAL_UTILS +#define _SERIAL_UTILS + +#include +#include +#include +#include +#include + +namespace SerialUtils { + + /** + * @brief Converts a [file] into a [device] and outputs the + * result into a [buffer]. + * + * @param buffer a buffer to fill in the operation. + * @param file the file to convert into a device. + * @return char* a buffer of {"/dev/"} formula. + */ + static inline char* concatIntoDevice(char* buffer, const char* file, const char* DEVICES_DIR) { + strcat(buffer, DEVICES_DIR); + strcat(buffer, file); + return buffer; + } + + /** + * @brief Tests whether the PATH specified is a real serial port. + * + * @param path the path to specify if its a serial port. + * @return int 1 if FD is a valid descriptor, 0 otherwise. + */ + static inline int isSerialPort(char* path, const int FLAG) { + int fdp = open(path, FLAG); + int state = isatty(fdp); + close(fdp); + return state; + } +} + +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/TerminalDevice.h b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/TerminalDevice.h new file mode 100644 index 0000000..571d1c5 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/TerminalDevice.h @@ -0,0 +1,258 @@ +/** + * @file Serial.h + * @author pavl_g. + * @brief Represents the serial port devices control and operation for POSIX systems. + * @note This is the base [HAL] (Hardware abstraction layer) for the Serial4j api. + * @version 0.1 + * @date 2022-08-24 + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API, RS232. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _RS232 +#define _RS232 "RS232-Interface" + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#define READ_CONFIG_SIZE (2) +#define DEVICES_DIR ((const char*) "/dev/") + +/** The default flags for the base file api */ +#define DEFAULT_FLAGS (O_RDWR | O_NONBLOCK | O_NOCTTY) + +typedef unsigned short int TerminalFlag; + +namespace TerminalDevice { + + /** Param@0 = VTIME, Param@1 = VMIN */ + const cc_t POLLING_READ[READ_CONFIG_SIZE] = {0, 0}; + const cc_t BLOCKING_READ_ONE_CHAR[READ_CONFIG_SIZE] = {0, 1}; + const cc_t READ_WITH_TIMEOUT[READ_CONFIG_SIZE] = {1, 0}; + const cc_t READ_WITH_INTERBYTE_TIMEOUT[READ_CONFIG_SIZE] = {1, 1}; + + /** + * Retrieves the termios of this tty device described by the file descriptor (fd). + * + * @param fd the virtual file descriptor for this tty device. + * @return a memory reference to the termios defining this tty device terminal attributes. + */ + struct termios* getTermiosFromFd(int* fd); + + /** + * @brief Fetches serial port devices on "/dev/" into [serialPorts] buffer. + * @note Uses , , , and . + * + * @return int (-3) if the directory ["/dev"] is invalid, (-4) if there are no tty + * devices available at the ["/dev"] directory, (1) if operation succeeded. + */ + int fetchSerialPorts(struct DynamicBuffer* serialPorts); + + /** + * @brief Opens a serial port device with a name. + * @note Uses Unix file base api and . + * + * @param port the path for the serial port device. + * @return int* a memory reference for the port file descriptor. + */ + int openPort(const char* port, int flag); + + /** + * @brief Initializes the default terminal for this device with the following default charachteristics: + * ----------- + * # c_cflag: for control mode flags. + * *** Enable these bits: + * - [CREAD]: Allow input to be received. + * - [CS8]: For charachter size 8-bit, you can use the bit mask CSIZE to read this value. + * - [CLOCAL]: Ignore modem status lines (don’t check carrier signal). + * ----------- + * # c_lflag: for local mode flags. + * ***Disable these bits: + * - [ICANON]: Canonical mode (line-by-line) input. + * - [ECHO]: Echo input characters. + * - [ECHOE]: Perform ERASE visually. + * - [ECHOK]: Echo KILL visually. + * - [ECHOKE]: Don’t output a newline after echoed KILL. + * - [ECHONL]: Echo NL (in canonical mode) even if echoing is disabled. + * - [ECHOPRT]: Echo deleted characters backward (between \ and / ). + * - [ECHOCTL]: Echo control characters visually (e.g., ^L ). + * - [ISIG]: Enable signal-generating characters (INTR, QUIT, SUSP). + * - [IEXTEN]: Enable extended processing of input characters. + * ----------- + * # c_oflag: for output mode flags. + * ***Disable these bits: + * - [OPOST]: Perform output postprocessing. + * - [ONLCR]: Map NL to CR-NL on output. + * ----------- + * # c_iflag: for input mode flags. + * ***Disable all input bit masks. + * ----------- + * # c_cc: For control characters. + * ***Sets to BLOCKING READ ONE CHAR AT A TIME MODE. + * ----------- + * + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int initTermios(int* fd); + + /** + * @brief Sets the Terminal Control Flag [c_cflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalControlFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Local Flag [c_lflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalLocalFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Output Flag [c_oflag] for the [termios] variable. + * + * @param flag bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalOutputFlag(TerminalFlag flag, int* fd); + + /** + * @brief Sets the Terminal Input Flag [c_iflag] for the [termios] variable. + * + * @param flags bits to set, concatenate the flags using bitwise OR [|]. + * @return int (-1) for failure, (-2) for invalid port or (1) for success. + */ + int setTerminalInputFlag(TerminalFlag flag, int* fd); + + /** + * @brief Gets the Terminal Control Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal control flag in [unsigned short int]. + */ + TerminalFlag getTerminalControlFlag(int* fd); + + /** + * @brief Gets the Terminal Local Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal local flag in [unsigned short int]. + */ + TerminalFlag getTerminalLocalFlag(int* fd); + + /** + * @brief Gets the Terminal Input Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal input flag in [unsigned short int]. + */ + TerminalFlag getTerminalInputFlag(int* fd); + + /** + * @brief Gets the Terminal Output Flag defined by the termios attributes for this serial device. + * + * @return TerminalFlag the terminal output flag in [unsigned short int]. + */ + TerminalFlag getTerminalOutputFlag(int* fd); + + /** + * @brief Sets the Read Configuration Mode using a ReadConfiguration with a + * VMIN_VALUE for lesser bytes to read and VTIME_VALUE for the elapsed time to + * set if the ReadConfiguration mode provides a timeout. + * + * @param VTIME_VALUE the value of the read timeout elapsed time, the timer starts + * with this value after read() is called. + * @param VMIN_VALUE the value of the minimum number of bytes to read. + * @return int (ERR_INVALID_PORT = -2) if port isn't available, (0) otherwise. + */ + int setReadConfigurationMode(const int VTIME_VALUE, const int VMIN_VALUE, int* fd); + + /** + * @brief Get the Read Configuration Mode in a new pointer. + * + * @return int* a memory reference to the new read configuration instance holding the VTIME and VMIN. + */ + cc_t* getReadConfigurationMode(int* fd); + + /** + * @brief Sets the Baud Rate object for the terminal io. + * + * @param baudRate the baud rate (bits/seconds). + * @return int (1) for success, (-1) for failure, (-2) for invalid port. + */ + int setBaudRate(int baudRate, int* fd); + + /** + * @brief Gets the Baud Rate object. + * + * @return speed_t baud rate in integers. + */ + speed_t getBaudRate(int* fd); + + /** + * @brief Writes a data to the serial port device from a buffer. + * + * @param buffer a buffer to write to the file. + * @param length the number of charachters to write from the buffer. + * @return ssize_t the number of bytes written to the serial device, (-1) for failure, (-2) for invalid port. + */ + ssize_t writeData(const void* buffer, int length, int* fd); + + /** + * @brief Reads data from the serial port device and saves it to a buffer. + * + * @param buffer a buffer to read from the file to it. + * @param length the number of the charachters to read by this buffer. + * @return ssize_t the number of bytes read from the terminal, (-1) for failure, (-2) for invalid port. + */ + ssize_t readData(void* buffer, int length, int* fd); + + /** + * @brief Closes the serial port device. + * + * @return int (1) for success, (-1) for failure, (-2) for invalid port. + */ + int closePort(int* fd); + +} + + +#endif diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/Thread.h b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/Thread.h new file mode 100644 index 0000000..7b57ec4 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/Thread.h @@ -0,0 +1,51 @@ +/** + * @file Thread.h + * @author pavl_g. + * @brief Optional header for operating within PThreads. + * @version 0.1 + * @date 2022-08-24 + * + * @note TODO. + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project, Serial4j API. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#ifndef _THREADS +#define _THREADS + +#include + +namespace POSIX { + struct Thread { + + }; +} + +#endif \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/info.md b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/info.md new file mode 100644 index 0000000..000fa07 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/include/linux/info.md @@ -0,0 +1 @@ +# Rs232-Interface API designed for Linux/Unix diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/DynamicBuffer.c b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/DynamicBuffer.c new file mode 100755 index 0000000..0bd1320 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/DynamicBuffer.c @@ -0,0 +1,62 @@ +#include + +void DynamicBuffer::add(void* item) { + + /* move the pointer to point to the last item */ + /* then, obtain a superficial copy */ + void** copy = (buffer += count); + /* dereference and evalute using the superficial copy */ + *copy = (void*) calloc(1, sizeof(void*)); + *copy = item; + /* move the pointer back to the start of the buffer (first item) */ + buffer -= count; + count++; +} + +void DynamicBuffer::add(int index, void* item) { + /* adds on the count if the location was empty previously */ + if (buffer[index] == NULL) { + ++count; + } + buffer[index] = item; +} + +void DynamicBuffer::removeAt(int index) { + BufferUtils::nullifyBuffer(buffer, index); + BufferUtils::reValidateBuffer(buffer, getItemsCount(), &(this->isProcessed)); + + while (!this->isProcessed); + this->isProcessed = 0; + + count--; +} + +void DynamicBuffer::removeAll() { + for (int i = 0; i < *(this->getItemsCount()); i++) { + BufferUtils::nullifyBuffer(buffer, i); + } + + BufferUtils::reValidateBuffer(buffer, getItemsCount(), &(this->isProcessed)); + + while (!this->isProcessed); + this->isProcessed = 0; + + this->resetDataPointer(); +} + +void* DynamicBuffer::getItem(int index) { + return buffer[index]; +} + +int DynamicBuffer::getItemIndex(void* item) { + for (int i = 0; i < *getItemsCount(); i++) { + if (buffer[i] == item) { + return i; + } + } + return ERR_OPERATION_FAILED; +} + +int* DynamicBuffer::getItemsCount() { + return &count; +} diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/info.md b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/info.md new file mode 100644 index 0000000..d9a935a --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/info.md @@ -0,0 +1,4 @@ +# Serial4j API C Utils + +## Includes the following: +- DynamicBuffer.c: for creating dynamic buffers. \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/linux/TerminalDevice.c b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/linux/TerminalDevice.c new file mode 100755 index 0000000..fc587fa --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/linux/TerminalDevice.c @@ -0,0 +1,249 @@ +#include + +struct termios* TerminalDevice::getTermiosFromFd(int* fd) { + if (fd == NULL) { + return NULL; + } + struct termios* tty = (struct termios*) calloc(1, sizeof(struct termios)); + /* update the termios struct pointer with the data from the port descriptor */ + tcgetattr(*fd, tty); + return tty; +} + +int TerminalDevice::openPort(const char* port, int flag) { + return open(port, flag); +} + +int TerminalDevice::fetchSerialPorts(struct DynamicBuffer* serialPorts) { + + DIR* dirp = opendir(DEVICES_DIR); + + /* sanity check the input */ + if (dirp == NULL) { + return ERR_INVALID_DIR; + } + + struct dirent* dp = (struct dirent*) calloc(1, sizeof(struct dirent)); + + /* start at the beginning of the buffer to override last data */ + serialPorts->resetDataPointer(); + + /* start reading available ports */ + while ((dp = readdir(dirp)) != NULL) { + + char* device = (char*) calloc(1, sizeof(char)); + device = SerialUtils::concatIntoDevice(device, dp->d_name, DEVICES_DIR); + + /* delete the device buffer if it's not a serial port */ + if (!SerialUtils::isSerialPort(device, DEFAULT_FLAGS)) { + BufferUtils::deleteBuffer(device); + continue; + } + + /* add the device to the serial ports major buffer and count up */ + serialPorts->add(device); + } + + /* release resources */ + closedir(dirp); + BufferUtils::deleteBuffer(dp); + + /* throws error indicating the availability issues */ + if (serialPorts->getItem(0) == NULL) { + return ERR_NO_AVAILABLE_TTY_DEVICES; + } + return OPERATION_SUCCEEDED; +} + +int TerminalDevice::initTermios(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + /* setup tty attributes */ + tty->c_cflag &= ~(CBAUDEX | CBAUD); /* clear BAUDs */ + tty->c_cflag |= (CREAD | CS8 | CLOCAL); /* set flags */ + tty->c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHOKE | ECHONL | ECHOPRT | ECHOCTL | ISIG | IEXTEN); + tty->c_oflag &= ~(OPOST | ONLCR); + tty->c_iflag = 0x00; + + /* define default read mode as blocking read on char at a time */ + tty->c_cc[VTIME] = BLOCKING_READ_ONE_CHAR[0]; + tty->c_cc[VMIN] = BLOCKING_READ_ONE_CHAR[1]; + + /* apply attriutes flag bits */ + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +int TerminalDevice::setTerminalControlFlag(TerminalFlag flag, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_cflag = flag; + /* sets the new terminal settings to the file descriptor with flushing any output */ + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +int TerminalDevice::setTerminalLocalFlag(TerminalFlag flag, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_lflag = flag; + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +int TerminalDevice::setTerminalInputFlag(TerminalFlag flag, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_iflag = flag; + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +int TerminalDevice::setTerminalOutputFlag(TerminalFlag flag, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_oflag = flag; + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +TerminalFlag TerminalDevice::getTerminalControlFlag(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + return tty->c_cflag; +} + +TerminalFlag TerminalDevice::getTerminalLocalFlag(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + return tty->c_lflag; +} + +TerminalFlag TerminalDevice::getTerminalInputFlag(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + return tty->c_iflag; +} + +TerminalFlag TerminalDevice::getTerminalOutputFlag(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + return tty->c_oflag; +} + +int TerminalDevice::setReadConfigurationMode(const int VTIME_VALUE, const int VMIN_VALUE, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + tty->c_cc[VTIME] = VTIME_VALUE; + tty->c_cc[VMIN] = VMIN_VALUE; + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +cc_t* TerminalDevice::getReadConfigurationMode(int* fd) { + cc_t* readConfig = (cc_t*) calloc(2, sizeof(unsigned char)); + if (*fd <= 0) { + readConfig[0] = ERR_INVALID_PORT; + readConfig[1] = ERR_INVALID_PORT; + return readConfig; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + readConfig[0] = tty->c_cc[VTIME]; + readConfig[1] = tty->c_cc[VMIN]; + BufferUtils::deleteBuffer(tty); + + return readConfig; +} + +int TerminalDevice::setBaudRate(int baudRate, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + /* update the baud rate of the termios */ + cfsetspeed(tty, baudRate); + int state = tcsetattr(*fd, TCSAFLUSH, tty); + BufferUtils::deleteBuffer(tty); + + return state; +} + +speed_t TerminalDevice::getBaudRate(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + struct termios* tty = TerminalDevice::getTermiosFromFd(fd); + + int speed = cfgetospeed(tty); + BufferUtils::deleteBuffer(tty); + + return speed; +} + +ssize_t TerminalDevice::writeData(const void* buffer, int length, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + return write(*fd, buffer, length); +} + +ssize_t TerminalDevice::readData(void* buffer, int length, int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + return read(*fd, buffer, length); +} + +int TerminalDevice::closePort(int* fd) { + if (*fd <= 0) { + return ERR_INVALID_PORT; + } + return close(*fd); +} diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/linux/Thread.c b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/linux/Thread.c new file mode 100755 index 0000000..a0dd490 --- /dev/null +++ b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/src/lib/linux/Thread.c @@ -0,0 +1,40 @@ +/** + * @file Thread.c + * @author pavl_g. + * @brief Optional source for operating within PThreads. + * @version 0.1 + * @date 2022-08-24 + * + * @note TODO. + * + * @copyright + * BSD 3-Clause License + * + * Copyright (c) 2022, Scrappers Team, The AVR-Sandbox Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. 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. + * + * 3. Neither the name of the copyright holder 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 HOLDER 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. + */ +#include \ No newline at end of file diff --git a/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/static/native/Linux/linux-x86-x64/librs232.so b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/static/native/Linux/linux-x86-x64/librs232.so new file mode 100755 index 0000000..bdecefb Binary files /dev/null and b/HelloNativeLibs/amd-64/Static-Libraries/Rs232-Interface/static/native/Linux/linux-x86-x64/librs232.so differ diff --git a/HelloNativeLibs/avr/Hellouart/README.md b/HelloNativeLibs/avr/Hellouart/README.md new file mode 100644 index 0000000..e69de29 diff --git a/HelloNativeLibs/avr/Hellouart/build/build.sh b/HelloNativeLibs/avr/Hellouart/build/build.sh new file mode 100755 index 0000000..bd0c09f --- /dev/null +++ b/HelloNativeLibs/avr/Hellouart/build/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +echo "Ccoffee Script starts" +echo "---------------------------------------------" +source $build_dir"/"compile.sh +source $build_dir"/"upload.sh +echo "---------------------------------------------" +echo "Ccoffee Script finishes" diff --git a/HelloNativeLibs/avr/Hellouart/build/compile.sh b/HelloNativeLibs/avr/Hellouart/build/compile.sh new file mode 100755 index 0000000..fbc53f0 --- /dev/null +++ b/HelloNativeLibs/avr/Hellouart/build/compile.sh @@ -0,0 +1,55 @@ +#!/bin/bash + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +source $build_dir"/"variables.sh + +function addLibsTold() { + sudo ${AVR_HOME}'/bin/avr-ld' --library-path "${project}/libs" "${project}/libs/libuart" +} + +function compile() { + # addLibsTold + # attrs : dir to compile & sharedLib name + nativeSources=`find ${project}'/src/lib' -name '*.c' -o -name '*.cxx' -o -name '*.cpp' -o -name '*.c++'` + + # compile to ``.elf`` full program (Executable and Linkable format) + ${AVR_HOME}'/bin/avr-g++' -O2 -x c++ \ + -mmcu=${CHIP} ${nativeSources} \ + -I${AVR_HOME}'/avr/include' \ + -I${project}'/src/include' \ + -L"${project}/libs/" -l'uart' \ + -o ${output}'.elf' + + # get the elf32bit file from the object linked data -- the elf is the whole application + # ${AVR_HOME}'/bin/avr-g++' -mmcu=${CHIP} -O2 ${output}'.o' -L"${project}/libs/" -l'uart' -o ${output}'.elf' + + return $? +} + +function convertToHex() { + ${AVR_HOME}'/bin/avr-objcopy' -I 'elf32-avr' -O 'ihex' ${output}'.elf' ${output}'.hex' + return $? +} + +echo -e "${WHITE_C} --MajorTask@Compile : Compiling the project" + +echo -e ${RESET_Cs} + +if [[ ! `compile` -eq 0 ]]; then + echo -e "${RED_C} --MajorTask@Compile : Failed compiling sources, exits with errno500." + exit 500 +else + echo -e "${GREEN_C} --MajorTask@Compile : Compilation succeeded." +fi +echo -e ${RESET_Cs} + +echo -e "${WHITE_C} --MajorTask@Hexing : Creating Hex file" +if [[ ! `convertToHex` -eq 0 ]]; then + echo -e "${RED_C} --MajorTask@Hexing : Failed to create hex file, exits with errno600." + exit 600 +else + echo -e "${GREEN_C} --MajorTask@Hexing : Hex file created successfully." +fi +echo -e ${RESET_Cs} diff --git a/HelloNativeLibs/avr/Hellouart/build/upload.sh b/HelloNativeLibs/avr/Hellouart/build/upload.sh new file mode 100755 index 0000000..3c9fabd --- /dev/null +++ b/HelloNativeLibs/avr/Hellouart/build/upload.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +source $build_dir"/"variables.sh + +function prepare() { + sudo stty -F ${PORT} ${BAUD_RATE} +} + +function upload() { + sudo avrdude -c ${PROGRAMMER} -b${BAUD_RATE} -P${PORT} -p${CHIP_ALIAS} -F -U flash:w:${output}'.hex' + return $? +} +prepare +echo -e "${WHITE_C} --MajorTask@UploadingCode : Uploading Hex file" +if [[ ! `upload` -eq 0 ]]; then + echo -e "${RED_C} --MajorTask@UploadingCode : Failed to upload hex file, exits with errno700." + exit 700 +else + echo -e "${GREEN_C} --MajorTask@UploadingCode : Task finished." +fi +echo -e ${RESET_Cs} diff --git a/HelloNativeLibs/avr/Hellouart/build/variables.sh b/HelloNativeLibs/avr/Hellouart/build/variables.sh new file mode 100644 index 0000000..3f01617 --- /dev/null +++ b/HelloNativeLibs/avr/Hellouart/build/variables.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# +export LC_ALL=C +# define work directory + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +project="${build_dir%/*}" + +avr_examples_dir="${project%/*}" + +hello_native_libs="${avr_examples_dir%/*}" +# cut the working directory from its end by a one '/' delimiter again +rootProject="${hello_native_libs%/*}" +# pass the value of the dire + +clibName=('libHelloUART') +# AVR-DUDE properties +BAUD_RATE='57600' +PORT='/dev/ttyUSB0' +CHIP='atmega328p' +CHIP_ALIAS='m328' +PROGRAMMER='arduino' +# Common Variables contain colors +source ${rootProject}'/CommonVariables.sh' +AVR_HOME=${rootProject}'/avr8-gnu-toolchain-linux_x86_64' +output=${project}'/output/'${clibName} diff --git a/HelloNativeLibs/avr/Hellouart/libs/libuart.a b/HelloNativeLibs/avr/Hellouart/libs/libuart.a new file mode 100755 index 0000000..70857d2 Binary files /dev/null and b/HelloNativeLibs/avr/Hellouart/libs/libuart.a differ diff --git a/HelloNativeLibs/avr/Hellouart/libs/libuart.map b/HelloNativeLibs/avr/Hellouart/libs/libuart.map new file mode 100644 index 0000000..41c9cad --- /dev/null +++ b/HelloNativeLibs/avr/Hellouart/libs/libuart.map @@ -0,0 +1,149 @@ + +udr_sprintln.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart6sprintEPc +00000000 T _ZN4uart8sprintlnEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss + U __do_copy_data +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +transmitter_isr.c.o: +00000000 b _ZL13uart_instance +0000000e T _ZN4uart18stopTransmitterISREv +00000000 T _ZN4uart19startTransmitterISREv + U _ZN4uart5state23onDataTransmitCompletedEh +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +0000001a T __vector_20 +00000001 a __zero_reg__ + +udr_println.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart5printExh + U _ZN4uart6sprintEPc +00000000 T _ZN4uart7printlnExh +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss + U __do_copy_data +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +start.c.o: +00000000 b _ZL13uart_instance +00000000 T _ZN4uart13startProtocolEj + U _ZN4uart16startReceiverISREv + U _ZN4uart5state17onProtocolStartedEv +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +stop.c.o: +00000000 b _ZL13uart_instance +00000000 T _ZN4uart12stopProtocolEv + U _ZN4uart5state17onProtocolStoppedEv +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +udr_print.c.o: +00000000 b _ZL13uart_instance +00000000 T _ZN4uart5printExh + U _ZN4uart6cprintEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss + U __itoa +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + U calloc + U free + +udr_plain_io.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart19startTransmitterISREv +00000000 T _ZN4uart23setTransmitDataRegisterEPKh + U _ZN4uart31startDataRegisterEmptyBufferISREv +00000020 T _ZN4uart9readASCIIEv +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +udr_sprint.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart6cprintEPc +00000000 T _ZN4uart6sprintEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +udr_reset_isr.c.o: +00000000 b _ZL13uart_instance +0000000e T _ZN4uart30stopDataRegisterEmptyBufferISREv +00000000 T _ZN4uart31startDataRegisterEmptyBufferISREv + U _ZN4uart5state19onDataBufferClearedEPKh +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +0000001a T __vector_19 +00000001 a __zero_reg__ + +udr_cprint.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart19startTransmitterISREv +00000000 T _ZN4uart6cprintEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +udr_cprintln.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart6cprintEPc + U _ZN4uart6sprintEPc +00000000 T _ZN4uart8cprintlnEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss + U __do_copy_data +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +receiver_isr.c.o: +00000000 b _ZL13uart_instance +0000005e T _ZN4uart15stopReceiverISREv +00000050 T _ZN4uart16startReceiverISREv + U _ZN4uart5state22onDataReceiveCompletedEh +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000000 T __vector_18 +00000001 a __zero_reg__ diff --git a/HelloNativeLibs/avr/Hellouart/output/libHelloUART.elf b/HelloNativeLibs/avr/Hellouart/output/libHelloUART.elf new file mode 100755 index 0000000..65efcb9 Binary files /dev/null and b/HelloNativeLibs/avr/Hellouart/output/libHelloUART.elf differ diff --git a/HelloNativeLibs/avr/Hellouart/output/libHelloUART.hex b/HelloNativeLibs/avr/Hellouart/output/libHelloUART.hex new file mode 100644 index 0000000..d3441b0 --- /dev/null +++ b/HelloNativeLibs/avr/Hellouart/output/libHelloUART.hex @@ -0,0 +1,47 @@ +:100000000C9434000C9451000C9451000C94510049 +:100010000C9451000C9451000C9451000C9451001C +:100020000C9451000C9451000C9451000C9451000C +:100030000C9451000C9451000C9451000C945100FC +:100040000C9451000C9451000C94C5000C94510078 +:100050000C9407010C9451000C9451000C94510025 +:100060000C9451000C94510011241FBECFEFD8E026 +:10007000DEBFCDBF11E0A0E0B1E0E8E7F2E002C0F2 +:1000800005900D92A635B107D9F721E0A6E5B1E0BC +:1000900001C01D92AB36B207E1F70E9433010C9408 +:1000A0003A010C94000062E071E086E591E00C9466 +:1000B0007200089565E171E086E591E00C947200AC +:1000C000CF93DF931F92CDB7DEB76983BE016F5F19 +:1000D0007F4F86E591E00E94B7000F90DF91CF91AE +:1000E0000895089589E591E00E94900063E571E02C +:1000F00089E591E00E949000089588E18093C10015 +:100100008EE08093C2007093C5006093C4008CE5BC +:1001100091E00E9459008CE591E00E94ED00089565 +:10012000EF92FF920F931F93CF93DF938B01D0E059 +:10013000C0E07B0181E0E81AF108F801019000209D +:10014000E9F73197E01BF10BCE17DF0748F4219652 +:10015000B7016C0F7D1F8FE591E00E94B700EDCFD6 +:10016000DF91CF911F910F91FF90EF900895E0ECF8 +:10017000F0E0808185FFFDCFFB0180818093C60088 +:1001800082E691E00E94FA0008951F920F920FB646 +:100190000F9211242F933F934F935F936F937F930D +:1001A0008F939F93AF93BF93EF93FF936091C6009C +:1001B00085E691E00E946000FF91EF91BF91AF91C1 +:1001C0009F918F917F916F915F914F913F912F916F +:1001D0000F900FBE0F901F901895E1ECF0E080811A +:1001E0008068808378940895E1ECF0E080818F77D7 +:1001F00080830895E1ECF0E08081806480837894CE +:100200000895E1ECF0E080818F7B808308951F9258 +:100210000F920FB60F9211242F933F934F935F933A +:100220006F937F938F939F93AF93BF93EF93FF93BE +:100230006091C60088E691E00E94710088E691E036 +:100240000E940101FF91EF91BF91AF919F918F911A +:100250007F916F915F914F913F912F910F900FBEC2 +:100260000F901F90189560E170E086E591E00E9484 +:080270007D00FFCFF894FFCFE1 +:10027800280144617461205472616E736D697474ED +:10028800656420210050726F746F636F6C20537423 +:100298006F7070656420210044617461205472613C +:1002A8006E736D697373696F6E20636F6D706C65C3 +:1002B800746564207375636365737366756C6C79B4 +:0602C8002021000A0D00D8 +:00000001FF diff --git a/HelloNativeLibs/avr/Hellouart/src/include/serial.h b/HelloNativeLibs/avr/Hellouart/src/include/serial.h new file mode 100644 index 0000000..49746fc --- /dev/null +++ b/HelloNativeLibs/avr/Hellouart/src/include/serial.h @@ -0,0 +1,304 @@ +/** + * @file Serial.h + * @author pavl_g. + * @brief Controls the UART IO Protocol which involves sending and receiving bits and firing listeners upon that (Concrete Command pattern). + * @version 0.1 + * @date 2022-07-02 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef _SERIAL_UART +#define _SERIAL_UART 1 + +#include +#include +#include +#include + +#if defined (__AVR_ATmega32__) + +/** UCSRA register */ +# define REG_UCSRA UCSRA +# define BIT_RXC RXC +# define BIT_TXC TXC +# define BIT_UDRE UDRE +# define BIT_FE FE +# define BIT_PE PE +# define BIT_U2X U2X +# define BIT_MPCM MPCM + +/** UCSRB register */ +# define REG_UCSRB UCSRB +# define BIT_RXCIE RXCIE +# define BIT_TXCIE TXCIE +# define BIT_UDRIE UDRIE +# define BIT_RXEN RXEN +# define BIT_TXEN TXEN +# define BIT_UCSZ2 UCSZ2 +# define BIT_RXB8 RXB8 +# define BIT_TXB8 TXB8 + +/** UCSRC register */ +# define REG_UCSRC UCSRC +# define BIT_URSEL URSEL +# define BIT_UMSEL UMSEL +# define BIT_UPM0 UPM0 +# define BIT_UPM1 UPM1 +# define BIT_USBS USBS +# define BIT_UCSZ0 UCSZ0 +# define BIT_UCSZ1 UCSZ1 +# define BIT_UCPOL UCPOL + +# define REG_UBRR UBRR + +/** UBRRL register */ +# define REG_UBRRL UBRRL + +/** UBRRH register */ +# define REG_UBRRH UBRRH + +/** UDR register */ +# define REG_UDR UDR + +# define __vector_USART_RX USART_RXC_vect +# define __vector_USART_TX USART_TXC_vect + +#elif defined (__AVR_ATmega328P__) + +/** UCSRA register */ +# define REG_UCSRA UCSR0A +# define BIT_RXC RXC0 +# define BIT_TXC TXC0 +# define BIT_UDRE UDRE0 +# define BIT_FE FE0 +# define BIT_PE PE0 +# define BIT_U2X U2X0 +# define BIT_MPCM MPCM0 + +/** UCSRB register */ +# define REG_UCSRB UCSR0B +# define BIT_RXCIE RXCIE0 +# define BIT_TXCIE TXCIE0 +# define BIT_UDRIE UDRIE0 +# define BIT_RXEN RXEN0 +# define BIT_TXEN TXEN0 +# define BIT_UCSZ2 UCSZ02 +# define BIT_RXB8 RXB80 +# define BIT_TXB8 TXB80 + +/** UCSRC register */ +# define REG_UCSRC UCSR0C +# define BIT_URSEL URSEL0 +# define BIT_UMSEL UMSEL0 +# define BIT_UPM0 UPM00 +# define BIT_UPM1 UPM01 +# define BIT_USBS USBS0 +# define BIT_UCSZ0 UCSZ00 +# define BIT_UCSZ1 UCSZ01 +# define BIT_UCPOL UCPOL0 + +# define REG_UBRR UBRR0 + +/** UBRRL register */ +# define REG_UBRRL UBRR0L + +/** UBRRH register */ +# define REG_UBRRH UBRR0H + +/** UDR register */ +# define REG_UDR UDR0 + +# define __vector_USART_RX USART_RX_vect +# define __vector_USART_TX USART_TX_vect + +#endif + +#define BAUD_RATE_9600 ((const uint8_t) 0x67) +#define BAUD_RATE_57600 ((const uint8_t) 0x10) + +/** + * @brief Defines a constant for the carriage return combined with the new line in a single value. + */ +#define NEW_LINE_CARRIAGE_R (char*)"\n\r" + +/** + * @brief Defines a constant for the decimal radix base to print the number in decimal case. + */ +#define DEC_RADIX (const uint8_t) 10 + +/** + * @brief Defines a constant for the binary radix base to print the numbner in binary case. + */ +#define BIN_RADIX (const uint8_t) 2 + +/** + * @brief Allocates an expandable string buffer for small/medium/large integers and clears the buffer to zero. + * + * @example For decimal base 10: 155 is the same as saying [const char str[] = {'155', NULL};] or [char str[] = {'155', '\0'};]. + * @example For binary base 2: 0b11110000 is the same as saying [const char str[] = {'1', '1' ,'1', '1', '0', '0', '0', '0', '\0'};], + * i.e. one character for each bit plus one for the string terminator '\0' which is (NULL). + */ +#define allocateStringBuffer() ((char*) calloc(1, sizeof(char*))) + +/** + * @brief Operates, controls, read/write to UART serial port. + */ +struct uart { + + struct state { + + void onProtocolStarted(); + + void onProtocolStopped(); + + /** + * @brief Triggered when the data receive is completed at the Rx pin. + * + * @param data the received byte at the Rx pin. + */ + void onDataReceiveCompleted(const uint8_t); + + /** + * @brief Triggered when the data transmit is completed at the Tx pin. + * + * @param data the transmitted byte at the Tx pin which is equal to UDRn at that moment. + */ + void onDataTransmitCompleted(const uint8_t); + + void onDataBufferCleared(const uint8_t*); + + } state_instance; + + /** + * @warning Internal use only. + * + * @brief A volatile buffer to assign the transmitter data to the data register (UDRn). + * @see Serial::UART::setTransmitDataRegister(const uint8_t* transmitData) for implementation. + */ + volatile uint8_t* transmitData; + + /** + * @brief Sets the Transmit Data Register to be used by the UDR when the UDRE bit is set. + * + * @param transmitData the data buffer to transmit. + */ + void setTransmitDataRegister(const uint8_t* transmitData); + + /** + * @brief Starts the UART Protocol by setting up the control status registers and the baud rate register. + * it operates the UART as Tx and Rx. + * + * @param BAUD_RATE_VAL the code for the baud rate. + */ + void startProtocol(const uint16_t BAUD_RATE_VAL); + + /** + * @brief Stops the UART protocol by setting [UCSRB] to zero. + */ + void stopProtocol(); + + /** + * @warning Internal use only. + * + * @brief Activates the ISR handler for the UDRE (Data register empty) bit. + */ + void startDataRegisterEmptyBufferISR(); + + /** + * @warning Internal use only. + * + * @brief Activates the ISR handler for the RXC bit (Receiver Complete). + */ + void startReceiverISR(); + + /** + * @warning Internal use only. + * @brief Activates the ISR handler for the TXC bit (Transmitter Complete). + */ + void startTransmitterISR(); + + /** + * @warning Internal use only. + * + * @brief Deactivates the ISR handler for the UDRE (Data register empty) bit. + */ + void stopDataRegisterEmptyBufferISR(); + + /** + * @warning Internal use only. + * + * @brief Deactivates the ISR handler for the RXC bit (Receiver Complete). + */ + void stopReceiverISR(); + + /** + * @warning Internal use only. + * + * @brief Deactivates the ISR handler for the TXC bit (Transmitter Complete). + */ + void stopTransmitterISR(); + + /** + * @brief Reads the [UDR0] Data register in ASCII as default. + * + * @return uint8_t an 8-bit integer read from the UDR0, the output is in ascii. + */ + uint8_t readASCII(); + + /** + * @brief Reads the [UDR0] Data register in Integers after converting from ASCII by subtracting the result from '0' aka [48]. + * + * @return uint8_t + */ + uint8_t readInteger(); + + /** + * @brief Prints a charachter data to the serial stream. + * + * @param data a char data of 8-bit size. + */ + void cprint(char* data); + + /** + * @brief Prints a charachter data to the serial stream in a new line. + * + * @param data a char data of 8-bit size. + */ + void cprintln(char* data); + + /** + * @brief Prints a string (char array) buffer to the serial stream. + * + * @param data the string buffer to print. + */ + void sprint(char* data); + + /** + * @brief Prints a string (char array) buffer to the serial stream in a new line with a carriage return [(\n\r)]. + * + * @param data the string buffer to print. + */ + void sprintln(char* data); + + /** + * @brief Prints an integer data of max 64-bits with a base radix (2 for binary print or 10 for decimal print). + * + * @param data the integer to print. + * @param base the base, either 2 for binary print () + */ + void print(const int64_t data, const uint8_t base); + + /** + * @brief Prints an integer data of max 64-bits with a base radix (2 for binary print or 10 for decimal print) + * in a new line with carriage return [(\n\r)]. + * + * @param data the integer to print. + * @param base the base, either 2 for binary print (with max size = 64 * sizeof(uint8_t) + 1) or 10 for decimal print + * (with max size = 1 * sizeof(int64_t) + 1). + */ + void println(const int64_t data, const uint8_t base); +} static uart_instance; + + +#endif \ No newline at end of file diff --git a/HelloNativeLibs/avr/Hellouart/src/lib/hello_uart.cpp b/HelloNativeLibs/avr/Hellouart/src/lib/hello_uart.cpp new file mode 100644 index 0000000..50f14a3 --- /dev/null +++ b/HelloNativeLibs/avr/Hellouart/src/lib/hello_uart.cpp @@ -0,0 +1,81 @@ +/** + * @file hello_uart.c. + * @author pavl_g. + * @brief Shows a basic implementation of the [libuart] library based on the command-state pattern. + * @version 0.1 + * @date 2022-10-08 + * + * @copyright Copyright (c) 2022 + * + */ +#include +#include + +#include + +const char* message = "Data Transmission completed successfully !"; + +/** + * Called when the data buffer is cleared and is available to carry a new data on the UDR. + * + * Use the uart::setTransmitterData(uint_8*) from the udr_plain_io.c.o objectcode + */ +void uart::state::onDataBufferCleared(const uint8_t* transmitData) { + uart_instance.sprintln((char*) "Data Transmitted !"); +} + +/** + * An implementation (function definition) for the function prototype. + * + * Listens for the protocol start command and fires accordingly. + */ +void uart::state::onProtocolStarted() { + // uart_instance.sprintln((char*) "Protocol Started Successfully !"); +} + +/** + * An implementation (function definition) for the function prototype. + * + * Listens for the protocol stop command and fires accordingly. + */ +void uart::state::onProtocolStopped() { + uart_instance.sprintln((char*) "Protocol Stopped !"); +} + +/** + * An implementation (function definition) for the function prototype. + * + * Listens for the receive vector interrupt service subroutine ISR(RX) as it + * fires the listener when a data is received on the UDR register. + * + * @param data a data to be received through the interrupt service from the data register. + */ +void uart::state::onDataReceiveCompleted(const uint8_t data) { + uart_instance.cprint((char*) &data); +} + +/** + * An implementation (function definition) for the function prototype. + * + * Listens for the transmitter vector interrupt service subroutine ISR(TX) as it + * fires the listener when a data is transmitted on the UDR register. + * + * @param data a data to be transmitted through the interrupt service from the data register. + */ +void uart::state::onDataTransmitCompleted(const uint8_t data) { + // uart_instance.sprintln((char*) message); +} + +/** + * The main application entry point. + * + * @param void parameters to pass from the compiler. + */ +int main(void) { + + uart_instance.startProtocol(BAUD_RATE_57600); + + while (true); // wait forever + + return 0; +} diff --git a/HelloNativeLibs/avr/libuart/.gitignore b/HelloNativeLibs/avr/libuart/.gitignore new file mode 100644 index 0000000..8b66d9b --- /dev/null +++ b/HelloNativeLibs/avr/libuart/.gitignore @@ -0,0 +1,3 @@ +./*.executable +./*.hex +./*.buildconfig diff --git a/HelloNativeLibs/avr/libuart/README.md b/HelloNativeLibs/avr/libuart/README.md new file mode 100644 index 0000000..71a8275 --- /dev/null +++ b/HelloNativeLibs/avr/libuart/README.md @@ -0,0 +1,17 @@ +# libuart + +libuart: is a C avr library designed to interface and control the UART protocol with an implementation biased design towards file streams and file io (startProtocol, sendData and readData). + +The library has one header `serial.h` and 12 source `.C` files, each file has one function or 2 highly connected functions at most so far. + +This library is completely based on the HelloUART example written previously on the AVR-Sandbox project with removal of some ridiculous object-oriented patterns (the singleton pointer and the struct) since the developer already knows that the protocol is a singleton in its hardware implementation (you cannot have 2 different pointers pointing at the same hardware and behaving differently). + +The design of this library is based on a tweaked version of the Concrete Command-State pattern. + +The concrete command-state pattern of the `serial.h`: + +1) It's a concrete pattern, i.e: no abstraction layer. + +2) Encapsulate the boolean operations for the `initialization` and `termination` of the universal async/sync receiver/transmitter protocol by triggering status control registers. + +3) Firing listeners as a response to a command to the interrupt uint of the avr. \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/build/build.sh b/HelloNativeLibs/avr/libuart/build/build.sh new file mode 100755 index 0000000..68c2c0b --- /dev/null +++ b/HelloNativeLibs/avr/libuart/build/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +echo -e "--Building the libuart into a static object file---" +echo "Ccoffee Script starts" +echo "---------------------------------------------" +source $build_dir"/"compile.sh +echo "---------------------------------------------" +echo "Ccoffee Script finishes" diff --git a/HelloNativeLibs/avr/libuart/build/compile.sh b/HelloNativeLibs/avr/libuart/build/compile.sh new file mode 100755 index 0000000..f8d6dca --- /dev/null +++ b/HelloNativeLibs/avr/libuart/build/compile.sh @@ -0,0 +1,77 @@ +#!/bin/bash + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +source $build_dir"/"variables.sh + +function compile() { + # attrs : dir to compile & sharedLib name + cd ${project}'/src/lib/' + nativeSources=(`ls *.c *.cpp *.c++ *.cxx`) + + for ((i=0; i<${#nativeSources[@]}; i++)); do + ${AVR_HOME}'/bin/avr-g++' \ + -c -O -x c++ \ + -mmcu=${CHIP} "${project}/src/lib/${nativeSources[i]}" \ + -I${AVR_HOME}'/avr/include' \ + -I${project}'/src/include' \ + -o "${project}/output/${nativeSources[i]}.o" + done + + objectcode=`find ${project}'/output/' -name '*.o'` + + ${AVR_HOME}'/bin/avr-ar' rcs ${output}'.a' $objectcode + + ${AVR_HOME}'/bin/avr-nm' ${output}'.a' > ${output}'.map' + +} + +function provokePermissions() { + sudo chmod +xrwrwrw ${output}'.a' +} + +function copyToExample() { + cp ${output}'.a' ${avr_examples_dir}'/Hellouart/libs' + cp ${output}'.map' ${avr_examples_dir}'/Hellouart/libs' + cp -r ${project}'/src/include/.' ${avr_examples_dir}'/Hellouart/src/include/' +} + +echo -e "${WHITE_C} --MajorTask@Compile : Compiling the project" + +echo -e ${RESET_Cs} + +compile + +if [[ ! $? -eq 0 ]]; then + echo -e "${RED_C} --MajorTask@Compile : Failed compiling sources, exits with errno500." + exit 500 +else + echo -e "${GREEN_C} --MajorTask@Compile : Compilation succeeded." +fi +echo -e ${RESET_Cs} + +echo -e "${WHITE_C} --MajorTask@PermissionControl : Provoking permissions to the object file." + +echo -e ${RESET_Cs} + +provokePermissions + +if [[ ! $? -eq 0 ]]; then + echo -e "${RED_C} --MajorTask@PermissionsControl : Failed to provoke permissions." + exit 500 +else + echo -e "${GREEN_C} --MajorTask@PermissionsControl : Permissions provoked successfully." +fi +echo -e ${RESET_Cs} + +copyToExample + +if [[ ! $? -eq 0 ]]; then + echo -e "${RED_C} --MajorTask@Copying : " + exit 500 +else + echo -e "${GREEN_C} --MajorTask@Copying : " +fi +echo -e ${RESET_Cs} + diff --git a/HelloNativeLibs/avr/libuart/build/variables.sh b/HelloNativeLibs/avr/libuart/build/variables.sh new file mode 100644 index 0000000..2916374 --- /dev/null +++ b/HelloNativeLibs/avr/libuart/build/variables.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +#** +#* Ccoffee Build tool, manual build, alpha-v1. +#* +#* @author pavl_g. +#*# + +# export all locales as C +export LC_ALL=C + +canonical_link=`readlink -f ${0}` +build_dir=`dirname $canonical_link` + +# cut the working directory from its end by a one '/' delimiter +project=`dirname $build_dir` + +avr_examples_dir="${project%/*}" + +hello_native_libs="${avr_examples_dir%/*}" +# cut the working directory from its end by a one '/' delimiter again +rootProject="${hello_native_libs%/*}" +# pass the value of the dire + +clibName=('libuart') +# AVR-DUDE properties +CHIP='atmega328p' + +# Common Variables contain colors +source ${rootProject}'/CommonVariables.sh' +# provide avr home +AVR_HOME=${rootProject}'/avr8-gnu-toolchain-linux_x86_64' +output=${project}'/output/'${clibName} diff --git a/HelloNativeLibs/avr/libuart/output/libuart.a b/HelloNativeLibs/avr/libuart/output/libuart.a new file mode 100755 index 0000000..70857d2 Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/libuart.a differ diff --git a/HelloNativeLibs/avr/libuart/output/libuart.map b/HelloNativeLibs/avr/libuart/output/libuart.map new file mode 100644 index 0000000..41c9cad --- /dev/null +++ b/HelloNativeLibs/avr/libuart/output/libuart.map @@ -0,0 +1,149 @@ + +udr_sprintln.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart6sprintEPc +00000000 T _ZN4uart8sprintlnEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss + U __do_copy_data +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +transmitter_isr.c.o: +00000000 b _ZL13uart_instance +0000000e T _ZN4uart18stopTransmitterISREv +00000000 T _ZN4uart19startTransmitterISREv + U _ZN4uart5state23onDataTransmitCompletedEh +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +0000001a T __vector_20 +00000001 a __zero_reg__ + +udr_println.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart5printExh + U _ZN4uart6sprintEPc +00000000 T _ZN4uart7printlnExh +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss + U __do_copy_data +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +start.c.o: +00000000 b _ZL13uart_instance +00000000 T _ZN4uart13startProtocolEj + U _ZN4uart16startReceiverISREv + U _ZN4uart5state17onProtocolStartedEv +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +stop.c.o: +00000000 b _ZL13uart_instance +00000000 T _ZN4uart12stopProtocolEv + U _ZN4uart5state17onProtocolStoppedEv +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +udr_print.c.o: +00000000 b _ZL13uart_instance +00000000 T _ZN4uart5printExh + U _ZN4uart6cprintEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss + U __itoa +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + U calloc + U free + +udr_plain_io.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart19startTransmitterISREv +00000000 T _ZN4uart23setTransmitDataRegisterEPKh + U _ZN4uart31startDataRegisterEmptyBufferISREv +00000020 T _ZN4uart9readASCIIEv +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +udr_sprint.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart6cprintEPc +00000000 T _ZN4uart6sprintEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +udr_reset_isr.c.o: +00000000 b _ZL13uart_instance +0000000e T _ZN4uart30stopDataRegisterEmptyBufferISREv +00000000 T _ZN4uart31startDataRegisterEmptyBufferISREv + U _ZN4uart5state19onDataBufferClearedEPKh +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +0000001a T __vector_19 +00000001 a __zero_reg__ + +udr_cprint.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart19startTransmitterISREv +00000000 T _ZN4uart6cprintEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +udr_cprintln.c.o: +00000000 b _ZL13uart_instance + U _ZN4uart6cprintEPc + U _ZN4uart6sprintEPc +00000000 T _ZN4uart8cprintlnEPc +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss + U __do_copy_data +00000000 a __tmp_reg__ +00000001 a __zero_reg__ + +receiver_isr.c.o: +00000000 b _ZL13uart_instance +0000005e T _ZN4uart15stopReceiverISREv +00000050 T _ZN4uart16startReceiverISREv + U _ZN4uart5state22onDataReceiveCompletedEh +0000003e a __SP_H__ +0000003d a __SP_L__ +0000003f a __SREG__ + U __do_clear_bss +00000000 a __tmp_reg__ +00000000 T __vector_18 +00000001 a __zero_reg__ diff --git a/HelloNativeLibs/avr/libuart/output/receiver_isr.c.o b/HelloNativeLibs/avr/libuart/output/receiver_isr.c.o new file mode 100644 index 0000000..ac3a942 Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/receiver_isr.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/start.c.o b/HelloNativeLibs/avr/libuart/output/start.c.o new file mode 100644 index 0000000..e5a6186 Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/start.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/stop.c.o b/HelloNativeLibs/avr/libuart/output/stop.c.o new file mode 100644 index 0000000..79e7489 Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/stop.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/transmitter_isr.c.o b/HelloNativeLibs/avr/libuart/output/transmitter_isr.c.o new file mode 100644 index 0000000..4b8ac5f Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/transmitter_isr.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/udr_cprint.c.o b/HelloNativeLibs/avr/libuart/output/udr_cprint.c.o new file mode 100644 index 0000000..d98c538 Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/udr_cprint.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/udr_cprintln.c.o b/HelloNativeLibs/avr/libuart/output/udr_cprintln.c.o new file mode 100644 index 0000000..475b86c Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/udr_cprintln.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/udr_plain_io.c.o b/HelloNativeLibs/avr/libuart/output/udr_plain_io.c.o new file mode 100644 index 0000000..16e108a Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/udr_plain_io.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/udr_print.c.o b/HelloNativeLibs/avr/libuart/output/udr_print.c.o new file mode 100644 index 0000000..795b566 Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/udr_print.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/udr_println.c.o b/HelloNativeLibs/avr/libuart/output/udr_println.c.o new file mode 100644 index 0000000..765762b Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/udr_println.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/udr_reset_isr.c.o b/HelloNativeLibs/avr/libuart/output/udr_reset_isr.c.o new file mode 100644 index 0000000..a06bc97 Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/udr_reset_isr.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/udr_sprint.c.o b/HelloNativeLibs/avr/libuart/output/udr_sprint.c.o new file mode 100644 index 0000000..6b9187b Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/udr_sprint.c.o differ diff --git a/HelloNativeLibs/avr/libuart/output/udr_sprintln.c.o b/HelloNativeLibs/avr/libuart/output/udr_sprintln.c.o new file mode 100644 index 0000000..703739d Binary files /dev/null and b/HelloNativeLibs/avr/libuart/output/udr_sprintln.c.o differ diff --git a/HelloNativeLibs/avr/libuart/src/include/serial.h b/HelloNativeLibs/avr/libuart/src/include/serial.h new file mode 100644 index 0000000..49746fc --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/include/serial.h @@ -0,0 +1,304 @@ +/** + * @file Serial.h + * @author pavl_g. + * @brief Controls the UART IO Protocol which involves sending and receiving bits and firing listeners upon that (Concrete Command pattern). + * @version 0.1 + * @date 2022-07-02 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef _SERIAL_UART +#define _SERIAL_UART 1 + +#include +#include +#include +#include + +#if defined (__AVR_ATmega32__) + +/** UCSRA register */ +# define REG_UCSRA UCSRA +# define BIT_RXC RXC +# define BIT_TXC TXC +# define BIT_UDRE UDRE +# define BIT_FE FE +# define BIT_PE PE +# define BIT_U2X U2X +# define BIT_MPCM MPCM + +/** UCSRB register */ +# define REG_UCSRB UCSRB +# define BIT_RXCIE RXCIE +# define BIT_TXCIE TXCIE +# define BIT_UDRIE UDRIE +# define BIT_RXEN RXEN +# define BIT_TXEN TXEN +# define BIT_UCSZ2 UCSZ2 +# define BIT_RXB8 RXB8 +# define BIT_TXB8 TXB8 + +/** UCSRC register */ +# define REG_UCSRC UCSRC +# define BIT_URSEL URSEL +# define BIT_UMSEL UMSEL +# define BIT_UPM0 UPM0 +# define BIT_UPM1 UPM1 +# define BIT_USBS USBS +# define BIT_UCSZ0 UCSZ0 +# define BIT_UCSZ1 UCSZ1 +# define BIT_UCPOL UCPOL + +# define REG_UBRR UBRR + +/** UBRRL register */ +# define REG_UBRRL UBRRL + +/** UBRRH register */ +# define REG_UBRRH UBRRH + +/** UDR register */ +# define REG_UDR UDR + +# define __vector_USART_RX USART_RXC_vect +# define __vector_USART_TX USART_TXC_vect + +#elif defined (__AVR_ATmega328P__) + +/** UCSRA register */ +# define REG_UCSRA UCSR0A +# define BIT_RXC RXC0 +# define BIT_TXC TXC0 +# define BIT_UDRE UDRE0 +# define BIT_FE FE0 +# define BIT_PE PE0 +# define BIT_U2X U2X0 +# define BIT_MPCM MPCM0 + +/** UCSRB register */ +# define REG_UCSRB UCSR0B +# define BIT_RXCIE RXCIE0 +# define BIT_TXCIE TXCIE0 +# define BIT_UDRIE UDRIE0 +# define BIT_RXEN RXEN0 +# define BIT_TXEN TXEN0 +# define BIT_UCSZ2 UCSZ02 +# define BIT_RXB8 RXB80 +# define BIT_TXB8 TXB80 + +/** UCSRC register */ +# define REG_UCSRC UCSR0C +# define BIT_URSEL URSEL0 +# define BIT_UMSEL UMSEL0 +# define BIT_UPM0 UPM00 +# define BIT_UPM1 UPM01 +# define BIT_USBS USBS0 +# define BIT_UCSZ0 UCSZ00 +# define BIT_UCSZ1 UCSZ01 +# define BIT_UCPOL UCPOL0 + +# define REG_UBRR UBRR0 + +/** UBRRL register */ +# define REG_UBRRL UBRR0L + +/** UBRRH register */ +# define REG_UBRRH UBRR0H + +/** UDR register */ +# define REG_UDR UDR0 + +# define __vector_USART_RX USART_RX_vect +# define __vector_USART_TX USART_TX_vect + +#endif + +#define BAUD_RATE_9600 ((const uint8_t) 0x67) +#define BAUD_RATE_57600 ((const uint8_t) 0x10) + +/** + * @brief Defines a constant for the carriage return combined with the new line in a single value. + */ +#define NEW_LINE_CARRIAGE_R (char*)"\n\r" + +/** + * @brief Defines a constant for the decimal radix base to print the number in decimal case. + */ +#define DEC_RADIX (const uint8_t) 10 + +/** + * @brief Defines a constant for the binary radix base to print the numbner in binary case. + */ +#define BIN_RADIX (const uint8_t) 2 + +/** + * @brief Allocates an expandable string buffer for small/medium/large integers and clears the buffer to zero. + * + * @example For decimal base 10: 155 is the same as saying [const char str[] = {'155', NULL};] or [char str[] = {'155', '\0'};]. + * @example For binary base 2: 0b11110000 is the same as saying [const char str[] = {'1', '1' ,'1', '1', '0', '0', '0', '0', '\0'};], + * i.e. one character for each bit plus one for the string terminator '\0' which is (NULL). + */ +#define allocateStringBuffer() ((char*) calloc(1, sizeof(char*))) + +/** + * @brief Operates, controls, read/write to UART serial port. + */ +struct uart { + + struct state { + + void onProtocolStarted(); + + void onProtocolStopped(); + + /** + * @brief Triggered when the data receive is completed at the Rx pin. + * + * @param data the received byte at the Rx pin. + */ + void onDataReceiveCompleted(const uint8_t); + + /** + * @brief Triggered when the data transmit is completed at the Tx pin. + * + * @param data the transmitted byte at the Tx pin which is equal to UDRn at that moment. + */ + void onDataTransmitCompleted(const uint8_t); + + void onDataBufferCleared(const uint8_t*); + + } state_instance; + + /** + * @warning Internal use only. + * + * @brief A volatile buffer to assign the transmitter data to the data register (UDRn). + * @see Serial::UART::setTransmitDataRegister(const uint8_t* transmitData) for implementation. + */ + volatile uint8_t* transmitData; + + /** + * @brief Sets the Transmit Data Register to be used by the UDR when the UDRE bit is set. + * + * @param transmitData the data buffer to transmit. + */ + void setTransmitDataRegister(const uint8_t* transmitData); + + /** + * @brief Starts the UART Protocol by setting up the control status registers and the baud rate register. + * it operates the UART as Tx and Rx. + * + * @param BAUD_RATE_VAL the code for the baud rate. + */ + void startProtocol(const uint16_t BAUD_RATE_VAL); + + /** + * @brief Stops the UART protocol by setting [UCSRB] to zero. + */ + void stopProtocol(); + + /** + * @warning Internal use only. + * + * @brief Activates the ISR handler for the UDRE (Data register empty) bit. + */ + void startDataRegisterEmptyBufferISR(); + + /** + * @warning Internal use only. + * + * @brief Activates the ISR handler for the RXC bit (Receiver Complete). + */ + void startReceiverISR(); + + /** + * @warning Internal use only. + * @brief Activates the ISR handler for the TXC bit (Transmitter Complete). + */ + void startTransmitterISR(); + + /** + * @warning Internal use only. + * + * @brief Deactivates the ISR handler for the UDRE (Data register empty) bit. + */ + void stopDataRegisterEmptyBufferISR(); + + /** + * @warning Internal use only. + * + * @brief Deactivates the ISR handler for the RXC bit (Receiver Complete). + */ + void stopReceiverISR(); + + /** + * @warning Internal use only. + * + * @brief Deactivates the ISR handler for the TXC bit (Transmitter Complete). + */ + void stopTransmitterISR(); + + /** + * @brief Reads the [UDR0] Data register in ASCII as default. + * + * @return uint8_t an 8-bit integer read from the UDR0, the output is in ascii. + */ + uint8_t readASCII(); + + /** + * @brief Reads the [UDR0] Data register in Integers after converting from ASCII by subtracting the result from '0' aka [48]. + * + * @return uint8_t + */ + uint8_t readInteger(); + + /** + * @brief Prints a charachter data to the serial stream. + * + * @param data a char data of 8-bit size. + */ + void cprint(char* data); + + /** + * @brief Prints a charachter data to the serial stream in a new line. + * + * @param data a char data of 8-bit size. + */ + void cprintln(char* data); + + /** + * @brief Prints a string (char array) buffer to the serial stream. + * + * @param data the string buffer to print. + */ + void sprint(char* data); + + /** + * @brief Prints a string (char array) buffer to the serial stream in a new line with a carriage return [(\n\r)]. + * + * @param data the string buffer to print. + */ + void sprintln(char* data); + + /** + * @brief Prints an integer data of max 64-bits with a base radix (2 for binary print or 10 for decimal print). + * + * @param data the integer to print. + * @param base the base, either 2 for binary print () + */ + void print(const int64_t data, const uint8_t base); + + /** + * @brief Prints an integer data of max 64-bits with a base radix (2 for binary print or 10 for decimal print) + * in a new line with carriage return [(\n\r)]. + * + * @param data the integer to print. + * @param base the base, either 2 for binary print (with max size = 64 * sizeof(uint8_t) + 1) or 10 for decimal print + * (with max size = 1 * sizeof(int64_t) + 1). + */ + void println(const int64_t data, const uint8_t base); +} static uart_instance; + + +#endif \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/receiver_isr.c b/HelloNativeLibs/avr/libuart/src/lib/receiver_isr.c new file mode 100644 index 0000000..9b88dd6 --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/receiver_isr.c @@ -0,0 +1,19 @@ +#include + +/** + * @brief Triggered when the RXC0 is settled and the receiving has been completed. + */ +ISR (__vector_USART_RX) { + uart_instance.state_instance.onDataReceiveCompleted((const uint8_t) REG_UDR); +} + +void uart::startReceiverISR() { + REG_UCSRB |= (1 << BIT_RXCIE); + /* start the interrupt service handlers */ + sei(); +} + +void uart::stopReceiverISR() { + // Finds the 1s complement of all bits in RXCIE0 ---> eg: 0b11111101 + REG_UCSRB &= ~(1 << BIT_RXCIE); +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/start.c b/HelloNativeLibs/avr/libuart/src/lib/start.c new file mode 100644 index 0000000..0318bca --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/start.c @@ -0,0 +1,9 @@ +#include + +void uart::startProtocol(const uint16_t BAUD_RATE_VAL) { + REG_UCSRB = (1 << BIT_TXEN) | (1 << BIT_RXEN); /* enable the transmit and receiver buffers and their interrupt services */ + REG_UCSRC = (1 << BIT_USBS) | (3 << BIT_UCSZ0); // enables the UCSZ0, UCSZ1 and URSEL + REG_UBRR = BAUD_RATE_VAL; // 0x10 (16) for BR = 57600 // 0x33 (51) for 9600 + uart_instance.state_instance.onProtocolStarted(); + uart_instance.startReceiverISR(); +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/stop.c b/HelloNativeLibs/avr/libuart/src/lib/stop.c new file mode 100644 index 0000000..f974657 --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/stop.c @@ -0,0 +1,6 @@ +#include + +void uart::stopProtocol() { + uart_instance.state_instance.onProtocolStopped(); + REG_UCSRB = 0x00; +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/transmitter_isr.c b/HelloNativeLibs/avr/libuart/src/lib/transmitter_isr.c new file mode 100644 index 0000000..0c86bcc --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/transmitter_isr.c @@ -0,0 +1,20 @@ +#include + +/** + * @brief Triggered when the bit TXC is settled and the data transmission has been completed. + */ +ISR (__vector_USART_TX) { + uart_instance.state_instance.onDataTransmitCompleted((const uint8_t) REG_UDR); + uart_instance.stopTransmitterISR(); +} + +void uart::startTransmitterISR() { + REG_UCSRB |= (1 << BIT_TXCIE); + /* start the interrupt service handlers */ + sei(); +} + +void uart::stopTransmitterISR() { + // Finds the 1s complement of all bits in RXCIE0 ---> eg: 0b11111101 + REG_UCSRB &= ~(1 << BIT_TXCIE); +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/udr_cprint.c b/HelloNativeLibs/avr/libuart/src/lib/udr_cprint.c new file mode 100644 index 0000000..32d9fe7 --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/udr_cprint.c @@ -0,0 +1,7 @@ +#include + +void uart::cprint(char* data) { + while (!(REG_UCSRA & (1 << BIT_UDRE))); + REG_UDR = *data; + uart_instance.startTransmitterISR(); +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/udr_cprintln.c b/HelloNativeLibs/avr/libuart/src/lib/udr_cprintln.c new file mode 100644 index 0000000..6c2ab8e --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/udr_cprintln.c @@ -0,0 +1,6 @@ +#include + +void uart::cprintln(char* data) { + uart_instance.cprint(data); + uart_instance.sprint(NEW_LINE_CARRIAGE_R); +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/udr_plain_io.c b/HelloNativeLibs/avr/libuart/src/lib/udr_plain_io.c new file mode 100644 index 0000000..0f3c763 --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/udr_plain_io.c @@ -0,0 +1,12 @@ +#include + +void uart::setTransmitDataRegister(const uint8_t* transmitData) { + *(uart_instance.transmitData) = *transmitData; + uart_instance.startDataRegisterEmptyBufferISR(); + uart_instance.startTransmitterISR(); +} + +uint8_t uart::readASCII() { + while (!(REG_UCSRA & (1 << BIT_RXC))); + return REG_UDR; +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/udr_print.c b/HelloNativeLibs/avr/libuart/src/lib/udr_print.c new file mode 100644 index 0000000..bedf39e --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/udr_print.c @@ -0,0 +1,12 @@ +#include + +void uart::print(const int64_t data, const uint8_t base) { + char* strBuffer = allocateStringBuffer(); + // convert input to string + itoa(data, strBuffer, base); + int i = 0; + while (i < strlen(strBuffer)) { + uart_instance.cprint(&strBuffer[i++]); + } + free(strBuffer); +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/udr_println.c b/HelloNativeLibs/avr/libuart/src/lib/udr_println.c new file mode 100644 index 0000000..74299eb --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/udr_println.c @@ -0,0 +1,6 @@ +#include + +void uart::println(const int64_t data, const uint8_t base) { + uart_instance.print(data, base); + uart_instance.sprint(NEW_LINE_CARRIAGE_R); +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/udr_reset_isr.c b/HelloNativeLibs/avr/libuart/src/lib/udr_reset_isr.c new file mode 100644 index 0000000..920d7fc --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/udr_reset_isr.c @@ -0,0 +1,21 @@ +#include + +/** + * @brief Triggered when the bit UDRE0 is one (the data register buffer is empty and ready to send data). + */ +ISR (USART_UDRE_vect) { + REG_UDR = *(uart_instance.transmitData); + uart_instance.state_instance.onDataBufferCleared((const uint8_t*) uart_instance.transmitData); + uart_instance.stopDataRegisterEmptyBufferISR(); +} + +void uart::startDataRegisterEmptyBufferISR() { + REG_UCSRB |= (1 << BIT_UDRIE); + /* start the interrupt service handlers */ + sei(); +} + +void uart::stopDataRegisterEmptyBufferISR() { + // Finds the 1s complement of all bits in UDRIE0 ---> eg: 0b11111101 + REG_UCSRB &= ~(1 << BIT_UDRIE); +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/udr_sprint.c b/HelloNativeLibs/avr/libuart/src/lib/udr_sprint.c new file mode 100644 index 0000000..6894830 --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/udr_sprint.c @@ -0,0 +1,8 @@ +#include + +void uart::sprint(char* data) { + int i = 0; + while (i < strlen(data)) { + uart_instance.cprint(&data[i++]); + } +} \ No newline at end of file diff --git a/HelloNativeLibs/avr/libuart/src/lib/udr_sprintln.c b/HelloNativeLibs/avr/libuart/src/lib/udr_sprintln.c new file mode 100644 index 0000000..ac75dbb --- /dev/null +++ b/HelloNativeLibs/avr/libuart/src/lib/udr_sprintln.c @@ -0,0 +1,6 @@ +#include + +void uart::sprintln(char* data) { + uart_instance.sprint(data); + uart_instance.sprint(NEW_LINE_CARRIAGE_R); +} \ No newline at end of file