update C snipplets

This commit is contained in:
2024-04-27 23:54:46 +03:00
parent 42d18ccae1
commit f2b20118e0
59 changed files with 589 additions and 831 deletions

View File

@@ -0,0 +1,2 @@
[{*.c,*.h}]
indent_size = unset

6
code/C/Web/ulfius-server/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
orcania/
ulfius/
*.a
rest

View File

@@ -0,0 +1,7 @@
CC = clang
all:
$(CC) -std=c99 -Wall -O3 -o rest main.c -lulfius -lorcania
tcc:
tcc -O3 -I./ulfius/include -I./orcania/include -o rest main.c libulfius.2.7.13.a liborcania.2.3.2.a -lyder -lgnutls -lz -ljansson -lmicrohttpd -lcurl

View File

@@ -0,0 +1,16 @@
REST API
--------
* `http://localhost:8000/api/param/:name` - возвращает `:name`
* `http://localhost:8000/api/param/quit` - завершит выполнение программы
Зависимости
-----------
* [ulfius](https://github.com/babelouest/ulfius)
* [orcania](https://github.com/babelouest/orcania)
```sh
ar rcs libulfius.2.7.13.a ulfius.o u_map.o u_request.o u_response.o u_send_request.o u_websocket.o yuarel.o
ar rcs liborcania.2.3.2.a orcania.o memory.o base64.o
```

View File

@@ -0,0 +1,26 @@
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <pthread.h>
#include <ulfius.h>
#include <stdatomic.h>
#include "utils.h"
#include "server.h"
int main(int argc, char **argv) {
// создаём отдельный поток, в котором запускаем сервер
pthread_t tid;
pthread_create(&tid, NULL, thread_server, (void *)&tid);
// while (true) {
// }
pthread_exit(NULL);
return 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

View File

@@ -0,0 +1,61 @@
Помогите с проблемой. Не завершается `while` цикл при изменении переменной `running`.
```
while (running) {
// loop
}
```
Использую библиотеку `ulfius` для реализации REST API сервера.
Есть функция `thread_server()`, которую из `main()` запускаю в отдельном потоке,
в которой запускается `ulfius` сервер.
```
pthread_t tid;
pthread_create(&tid, NULL, thread_server, (void *)&tid);
```
Сервер запускаю следующим образом:
```
int ret;
ret = ulfius_start_framework(&instance);
if (ret == U_OK) {
printf("Server started at %d.\n", PORT);
} else {
printf("Error starting server as %d port.\n", PORT);
}
while (running) {
printf("\r%b", running);
}
printf("Server halt.\n");
ulfius_stop_framework(&instance);
ulfius_clean_instance(&instance);
```
`running` - глобальная переменная типа `bool`.
В документации к библиотеке, чтобы сервер не схлопывался используется следующий код.
```
if (ret == U_OK) {
getchar();
}
```
Есть callback функция, которая вызывается при обращении к API,
в которой я проверяю отправленное пользователем значение, и если оно равняется `quit`
присваиваю переменной `running` значение `false`, чтобы сервер закрылся.
Если из цикла `while (running) { printf("\r%b", running); }` убрать `printf()`,
либо выполнять другие операции, например присвоение `a = 1;` то сервер не закрывается,
хотя значение `running` равняется `0`.
Я пишу утилиту для внутенного использования, которая общается с Arduino платой
посредством библиотеки `libserialport` и в цикле читает данные.
Хочу, чтобы утилита по REST получала данные и отправляла их на плату,
но не получается реализовать нормальное завершение программы, потому что сервер не умирает.
**OS:** Linux

View File

@@ -0,0 +1,75 @@
atomic_bool running = true;
#define PORT 8000
#define PREFIX "/api"
int callback_default(const struct _u_request *request,
struct _u_response *response, void *user_data);
int callback_all_test_foo(const struct _u_request *request,
struct _u_response *response, void *user_data);
void *thread_server(void *vargp) {
int ret;
struct _u_instance instance;
if (ulfius_init_instance(&instance, PORT, NULL, NULL) != U_OK) {
exit(1);
}
instance.max_post_body_size = 1024;
ulfius_add_endpoint_by_val(&instance, "GET", PREFIX, "/param/:name", 0,
&callback_all_test_foo, "user data 1");
ulfius_add_endpoint_by_val(&instance, "POST", PREFIX, "/param/:name", 0,
&callback_all_test_foo, "user data 2");
ulfius_set_default_endpoint(&instance, &callback_default, NULL);
ret = ulfius_start_framework(&instance);
if (ret == U_OK) {
printf("Server started at %d.\n", PORT);
} else {
printf("Error starting server as %d port.\n", PORT);
}
while (running) {
}
printf("Server halt.\n");
ulfius_stop_framework(&instance);
ulfius_clean_instance(&instance);
}
int callback_default(const struct _u_request *request,
struct _u_response *response, void *user_data) {
(void)(request);
(void)(user_data);
ulfius_set_string_body_response(response, 404,
"Page not found, do what you want");
return U_CALLBACK_CONTINUE;
}
int callback_all_test_foo(const struct _u_request *request,
struct _u_response *response, void *user_data) {
// url_params = request->map_url
// post_params = request->map_post_body
const char **keys, *value;
keys = u_map_enum_keys(request->map_url);
value = u_map_get(request->map_url, keys[0]);
if (strcmp("quit", value) == 0) {
running = false;
}
char *response_body = msprintf("Your %s is %s\n", keys[0], value);
print_to_terminal(response_body);
ulfius_set_string_body_response(response, 200, response_body);
o_free(response_body);
return U_CALLBACK_CONTINUE;
}

View File

@@ -0,0 +1 @@
void print_to_terminal(char *text) { printf("%s", text); }

View File

@@ -0,0 +1,2 @@
[{*.c,*.h}]
indent_size = unset

View File

@@ -0,0 +1,129 @@
// Call C from JavaScript Example
#include "webui.h"
void my_function_string(webui_event_t* e) {
// JavaScript:
// webui_fn('MyID_One', 'Hello');
const char* str = webui_get_string(e);
printf("my_function_string: %s\n", str); // Hello
// Need Multiple Arguments?
//
// WebUI support only one argument. To get multiple arguments
// you can send a JSON string from JavaScript then decode it.
// Example:
//
// my_json = my_json_decoder(str);
// foo = my_json[0];
// bar = my_json[1];
}
void my_function_integer(webui_event_t* e) {
// JavaScript:
// webui_fn('MyID_Two', 123456789);
long long number = webui_get_int(e);
printf("my_function_integer: %lld\n", number); // 123456789
}
void my_function_boolean(webui_event_t* e) {
// JavaScript:
// webui_fn('MyID_Three', true);
bool status = webui_get_bool(e); // True
if(status)
printf("my_function_boolean: True\n");
else
printf("my_function_boolean: False\n");
}
void my_function_with_response(webui_event_t* e) {
// JavaScript:
// const result = webui_fn('MyID_Four', number);
long long number = webui_get_int(e);
number = number * 2;
printf("my_function_with_response: %lld\n", number);
// Send back the response to JavaScript
webui_return_int(e, number);
}
int main() {
// HTML
const char* my_html =
"<html>"
" <head>"
" <title>Call C from JavaScript Example</title>"
" <style>"
" body {"
" color: white;"
" background: #0F2027;"
" text-align: center;"
" font-size: 16px;"
" font-family: sans-serif;"
" }"
" </style>"
" </head>"
" <body>"
" <h2>WebUI - Call C from JavaScript Example</h2>"
" <p>Call C function with argument (<em>See the logs in your terminal</em>)</p>"
" <br>"
" <button onclick=\"webui_fn('MyID_One', 'Hello');\">Call my_function_string()</button>"
" <br>"
" <br>"
" <button onclick=\"webui_fn('MyID_Two', 123456789);\">Call my_function_integer()</button>"
" <br>"
" <br>"
" <button onclick=\"webui_fn('MyID_Three', true);\">Call my_function_boolean()</button>"
" <br>"
" <br>"
" <p>Call C function and wait for the response</p>"
" <br>"
" <button onclick=\"MyJS();\">Call my_function_with_response()</button>"
" <br>"
" <br>"
" <input type=\"text\" id=\"MyInputID\" value=\"2\">"
" <script>"
" function MyJS() {"
" const MyInput = document.getElementById('MyInputID');"
" const number = MyInput.value;"
" webui_fn('MyID_Four', number).then((response) => {"
" MyInput.value = response;"
" });"
" }"
" </script>"
" <script src=\"/webui.js\"></script>"
" </body>"
"</html>";
// Create a window
size_t my_window = webui_new_window();
// Bind HTML elements with C functions
webui_bind(my_window, "MyID_One", my_function_string);
webui_bind(my_window, "MyID_Two", my_function_integer);
webui_bind(my_window, "MyID_Three", my_function_boolean);
webui_bind(my_window, "MyID_Four", my_function_with_response);
// Show the window
webui_show(my_window, my_html); // webui_show_browser(my_window, my_html, Chrome);
// Wait until all windows get closed
webui_wait();
return 0;
}
#if defined(_MSC_VER)
int APIENTRY WinMain(HINSTANCE hInst, HINSTANCE hInstPrev, PSTR cmdline, int cmdshow) {
return main();
}
#endif

View File

@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ololo</title>
<script src="/webui.js"></script>
</head>
<body>
<button onclick="abc('string');">ssf</button>
<br>
<button id="clck">Click</button>
<script type="text/javascript">
window.onload = function () {
window.resizeTo(500, 500);
}
function abc(text) {
webui_fn('MyID', text).then((response) => { console.log(response); });
}
</script>
</body>
</html>

View File

@@ -0,0 +1,24 @@
#include <stdio.h>
#include "webui.h"
void fn_one(webui_event_t *e) {
const char *str = webui_get_string(e);
printf("Data from JavaScript: %s\n", str);
webui_return_string(e, "Message from C");
}
void fn_two(webui_event_t *e) { puts("Click!"); }
int main() {
size_t my_window = webui_new_window();
webui_bind(my_window, "MyID", fn_one);
webui_bind(my_window, "clck", fn_two);
webui_show(my_window, "index.html");
webui_run(my_window, "alert('Fast!');");
webui_wait();
return 0;
}