// Installed libcolorhug APIs only. Cancellation is cooperative: SIGKILL cannot // guarantee rollback, nor can these budgets bound non-cancellable GUsb setup. #include #include #include #include typedef struct { ChColorSelect channel; ChFreqScale scale; guint16 integral; } Settings; typedef struct { GCancellable *active; gboolean work; gboolean interrupted; gboolean expired; } Control; typedef enum { READ_SETTINGS, SET_SCALE, SET_INTEGRAL, SAMPLE } Operation; static const char *channel_name(ChColorSelect channel) { switch (channel) { case CH_COLOR_SELECT_RED: return "red"; case CH_COLOR_SELECT_WHITE: return "white"; case CH_COLOR_SELECT_BLUE: return "blue"; case CH_COLOR_SELECT_GREEN: return "green"; default: return ""; } } static int frequency_percent(ChFreqScale scale) { switch (scale) { case CH_FREQ_SCALE_0: return 0; case CH_FREQ_SCALE_2: return 2; case CH_FREQ_SCALE_20: return 20; case CH_FREQ_SCALE_100: return 100; default: return -1; } } static gboolean valid(const Settings *s) { return *channel_name(s->channel) && frequency_percent(s->scale) >= 0; } static gboolean equal(const Settings *a, const Settings *b) { return a->channel == b->channel && a->scale == b->scale && a->integral == b->integral; } static gboolean interrupted(gpointer data) { Control *c = data; c->interrupted = TRUE; if (c->work && c->active != NULL) g_cancellable_cancel(c->active); return G_SOURCE_CONTINUE; } static gboolean expired(gpointer data) { Control *c = data; c->expired = TRUE; g_cancellable_cancel(c->active); return G_SOURCE_REMOVE; } // Every operation owns a new queue and token. A failed queue must never replay. // Absolute deadlines keep three-field snapshots inside one phase budget. static gboolean call(Control *c, GUsbDevice *device, Operation op, Settings *settings, guint32 *raw, gint64 deadline) { gint64 remaining = deadline - g_get_monotonic_time(); GError *error = NULL; ChDeviceQueue *queue = NULL; gboolean ok; guint timer; if (remaining <= 0 || (c->work && c->interrupted)) return FALSE; c->active = g_cancellable_new(); c->expired = FALSE; timer = g_timeout_add((guint)((remaining + 999) / 1000), expired, c); if (op == SET_INTEGRAL) { // The queue setter rejects zero; the direct installed API accepts it. ok = ch_device_set_integral_time(device, settings->integral, c->active, &error); } else { queue = ch_device_queue_new(); switch (op) { case READ_SETTINGS: ch_device_queue_get_color_select(queue, device, &settings->channel); ch_device_queue_get_multiplier(queue, device, &settings->scale); ch_device_queue_get_integral_time(queue, device, &settings->integral); break; case SET_SCALE: ch_device_queue_set_multiplier(queue, device, settings->scale); break; case SAMPLE: ch_device_queue_take_reading_raw(queue, device, raw); break; case SET_INTEGRAL: g_assert_not_reached(); } ok = ch_device_queue_process(queue, CH_DEVICE_QUEUE_PROCESS_FLAGS_NONE, c->active, &error); } // Dispatch queued Unix signals even when a synchronous call returned fast. while (g_main_context_pending(NULL)) g_main_context_iteration(NULL, FALSE); if (!c->expired) g_source_remove(timer); ok = ok && !c->expired && g_get_monotonic_time() < deadline && !(c->work && c->interrupted); g_clear_object(&queue); g_clear_object(&c->active); g_clear_error(&error); return ok; } static const char *work_error(Control *c, gint64 deadline, const char *fallback) { if (c->interrupted) return "interrupted"; if (g_get_monotonic_time() >= deadline) return "work-timeout"; return fallback; } static void print_settings(const Settings *s, gboolean present) { if (!present) { printf("null"); return; } printf("{\"channel\":\"%s\",\"frequencyPercent\":%d,\"integrationTime\":%u}", channel_name(s->channel), frequency_percent(s->scale), (unsigned)s->integral); } int main(int argc, char **argv) { const gint64 deadline = g_get_monotonic_time() + 4000000; Control control = { .work = TRUE }; Settings original = {0}, desired = {0}, effective = {0}, readback = {0}; gboolean have_original = FALSE, have_effective = FALSE, have_readback = FALSE; gboolean changed_scale = FALSE, changed_integral = FALSE, raw_valid = FALSE; gboolean opened = FALSE, claimed = FALSE, found = FALSE; GUsbContext *context = NULL; GUsbDevice *device = NULL; GPtrArray *devices = NULL; GError *error = NULL; const char *operation_error = "", *restore_error = ""; const char *verification_error = "", *cleanup_error = ""; const char *restoration = "not-needed", *code; guint32 raw = 0; guint term = 0, intr = 0; int configuration; const gboolean probe = argc == 2 && g_strcmp0(argv[1], "--probe") == 0; if (argc == 2 && g_strcmp0(argv[1], "--help") == 0) { puts("usage: read [--probe]"); return 0; } if (argc != 1 && !probe) { operation_error = "invalid-arguments"; goto out; } term = g_unix_signal_add(SIGTERM, interrupted, &control); intr = g_unix_signal_add(SIGINT, interrupted, &control); context = g_usb_context_new(&error); if (context == NULL) { operation_error = "usb-context-failed"; goto out; } g_usb_context_enumerate(context); devices = g_usb_context_get_devices(context); for (guint i = 0; i < devices->len; i++) { GUsbDevice *candidate = g_ptr_array_index(devices, i); if (g_usb_device_get_vid(candidate) == CH_USB_VID && g_usb_device_get_pid(candidate) == CH_USB_PID_FIRMWARE_ALS) { device = candidate; found = TRUE; break; } } if (device == NULL) { operation_error = "no-device"; goto out; } // Enumeration-only discovery follows VID/PID across USB port changes. // Never opens, claims, activates or samples the device. if (probe) goto out; if (!g_usb_device_open(device, &error)) { operation_error = "usb-open-failed"; goto out; } opened = TRUE; configuration = g_usb_device_get_configuration(device, &error); if (configuration != CH_USB_CONFIG) { operation_error = configuration < 0 ? "configuration-read-failed" : "unexpected-configuration"; goto out; } if (!g_usb_device_claim_interface(device, CH_USB_INTERFACE, G_USB_DEVICE_CLAIM_INTERFACE_BIND_KERNEL_DRIVER, &error)) { operation_error = "interface-claim-failed"; goto out; } claimed = TRUE; if (!call(&control, device, READ_SETTINGS, &original, NULL, deadline)) { operation_error = work_error(&control, deadline, "sensor-state-read-failed"); goto out; } if (!valid(&original)) { operation_error = "sensor-state-invalid"; goto out; } have_original = TRUE; desired = original; if (original.scale == CH_FREQ_SCALE_0) desired.scale = CH_FREQ_SCALE_20; if (original.integral == 0) desired.integral = CH_INTEGRAL_TIME_VALUE_100MS; if (desired.scale != original.scale) { changed_scale = TRUE; // Include applied writes whose acknowledgement is lost. if (!call(&control, device, SET_SCALE, &desired, NULL, deadline)) { operation_error = work_error(&control, deadline, "activation-scale-failed"); goto rollback; } } if (desired.integral != original.integral) { changed_integral = TRUE; if (!call(&control, device, SET_INTEGRAL, &desired, NULL, deadline)) { operation_error = work_error(&control, deadline, "activation-integral-failed"); goto rollback; } } if (!call(&control, device, READ_SETTINGS, &effective, NULL, deadline)) { operation_error = work_error(&control, deadline, "effective-read-failed"); goto rollback; } have_effective = valid(&effective); if (!have_effective || !equal(&desired, &effective)) { operation_error = "effective-mismatch"; goto rollback; } if (!call(&control, device, SAMPLE, NULL, &raw, deadline)) { operation_error = work_error(&control, deadline, "sensor-reading-failed"); goto rollback; } raw_valid = TRUE; rollback: // Signals still record interruption, but never cancel or skip rollback. control.work = FALSE; if (changed_scale && !call(&control, device, SET_SCALE, &original, NULL, g_get_monotonic_time() + 1000000)) restore_error = "restore-scale-failed"; if (changed_integral && !call(&control, device, SET_INTEGRAL, &original, NULL, g_get_monotonic_time() + 1000000) && !*restore_error) restore_error = "restore-integral-failed"; // Independent storage, fresh queue, all three fields even after restore error. if (!call(&control, device, READ_SETTINGS, &readback, NULL, g_get_monotonic_time() + 1500000)) { restoration = "unverified"; verification_error = "verification-read-failed"; } else if (!valid(&readback)) { restoration = "unverified"; verification_error = "verification-state-invalid"; } else { have_readback = TRUE; restoration = equal(&original, &readback) ? "verified" : "mismatch"; if (!equal(&original, &readback)) verification_error = "verification-mismatch"; } out: control.work = FALSE; g_clear_error(&error); if (claimed && !g_usb_device_release_interface(device, CH_USB_INTERFACE, G_USB_DEVICE_CLAIM_INTERFACE_BIND_KERNEL_DRIVER, &error)) cleanup_error = "interface-release-failed"; g_clear_error(&error); if (opened && !g_usb_device_close(device, &error) && !*cleanup_error) cleanup_error = "usb-close-failed"; g_clear_error(&error); g_clear_pointer(&devices, g_ptr_array_unref); g_clear_object(&context); while (g_main_context_pending(NULL)) g_main_context_iteration(NULL, FALSE); if (term) g_source_remove(term); if (intr) g_source_remove(intr); if (control.interrupted && !*operation_error) operation_error = "interrupted"; code = *operation_error ? operation_error : *restore_error ? restore_error : *verification_error ? verification_error : cleanup_error; if (probe) { const char *probe_error = g_strcmp0(code, "no-device") == 0 ? "" : code; printf("{\"found\":%s,\"error\":\"%s\"}\n", found ? "true" : "false", probe_error); return *probe_error ? 1 : 0; } printf("{\"status\":\"%s\",\"error\":\"%s\",\"raw\":", *code ? "unavailable" : "ready", code); if (raw_valid) printf("%" G_GUINT32_FORMAT, raw); else printf("null"); printf(",\"unit\":\"counts\",\"channel\":\"%s\",\"frequencyPercent\":%d," "\"integrationTime\":%u,\"original\":", have_effective ? channel_name(effective.channel) : "", have_effective ? frequency_percent(effective.scale) : 0, have_effective ? (unsigned)effective.integral : 0); print_settings(&original, have_original); printf(",\"effective\":"); print_settings(&effective, have_effective); printf(",\"restored\":"); print_settings(&readback, have_readback); printf(",\"restoration\":\"%s\",\"operationError\":\"%s\",\"restoreError\":\"%s\"," "\"verificationError\":\"%s\",\"cleanupError\":\"%s\"}\n", restoration, operation_error, restore_error, verification_error, cleanup_error); return *code ? 1 : 0; }