Air Quality Monitor
Portable C application for collecting, storing, and analyzing air quality sensor readings
Loading...
Searching...
No Matches
sensor_loader.c
1#include "sensor/sensor_loader.h"
2#include <stdio.h>
3#include <string.h>
4
5#ifdef _WIN32
6#include <windows.h>
7#else
8#include <dlfcn.h>
9#endif
10
11int sensor_module_load(const char *path, SensorModule *out) {
12 if (!path || !out || !path[0])
13 return -1;
14
15 memset(out, 0, sizeof(*out));
16
17#ifdef _WIN32
18 HMODULE h = LoadLibraryA(path);
19 if (!h) {
20 fprintf(stderr, "Failed to load sensor module: %s\n", path);
21 return -1;
22 }
23 SensorPlugin *plugin = (SensorPlugin *)GetProcAddress(h, "sensor_plugin");
24 if (!plugin) {
25 fprintf(stderr, "Symbol sensor_plugin not found in %s\n", path);
26 FreeLibrary(h);
27 return -1;
28 }
29 out->handle = (void *)h;
30 out->plugin = plugin;
31#else
32 void *h = dlopen(path, RTLD_NOW);
33 if (!h) {
34 fprintf(stderr, "Failed to load sensor module %s: %s\n", path, dlerror());
35 return -1;
36 }
37 SensorPlugin *plugin = (SensorPlugin *)dlsym(h, "sensor_plugin");
38 if (!plugin) {
39 fprintf(stderr, "Symbol sensor_plugin not found in %s: %s\n", path, dlerror());
40 dlclose(h);
41 return -1;
42 }
43 out->handle = h;
44 out->plugin = plugin;
45#endif
46
47 if (out->plugin->api_version != SENSOR_PLUGIN_API_VERSION) {
48 fprintf(stderr, "Plugin ABI mismatch in %s (got %d, expected %d)\n", path, out->plugin->api_version,
49 SENSOR_PLUGIN_API_VERSION);
50 sensor_module_unload(out);
51 return -1;
52 }
53
54 if (!out->plugin->name || !out->plugin->plugin_version || !out->plugin->description || !out->plugin->read_sample ||
55 !out->plugin->init || !out->plugin->shutdown) {
56 fprintf(stderr, "Invalid plugin ABI in %s\n", path);
57 sensor_module_unload(out);
58 return -1;
59 }
60
61 return 0;
62}
63
64void sensor_module_unload(SensorModule *module) {
65 if (!module || !module->handle)
66 return;
67
68#ifdef _WIN32
69 FreeLibrary((HMODULE)module->handle);
70#else
71 dlclose(module->handle);
72#endif
73 module->handle = NULL;
74 module->plugin = NULL;
75}
76
A dynamically loaded sensor plugin and its OS-level handle.
Runtime contract every sensor plugin (.so/.dylib/.dll) must implement.
Definition sensor.h:35
const char * description
Short description shown in sensor info/listing screens.
Definition sensor.h:43
int(* read_sample)(AirQualityData *out)
Reads one sample into *out.
Definition sensor.h:53
int api_version
Must equal SENSOR_PLUGIN_API_VERSION at build time.
Definition sensor.h:37
int(* shutdown)(void)
Called once before unloading, for cleanup.
Definition sensor.h:55
const char * plugin_version
Plugin version string, e.g.
Definition sensor.h:41
const char * name
Human-readable sensor name, e.g.
Definition sensor.h:39
int(* init)(void)
Called once after loading.
Definition sensor.h:47