Kromek Radangel gamma spectrometer USB HID daemon and WebUI. https://git.unino.de/pvivell/radangel
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

radangel.c 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*
  2. * RadAngel gamma spectrometer USB HID device control and readout program
  3. *
  4. * gcc -std=gnu99 -Wall radangel.c -o radangel -pthread -lm -lhidapi-libusb
  5. *
  6. * strip -s radangel
  7. *
  8. * echo 'SUBSYSTEM=="usb", ATTR{idVendor}=="04d8", ATTR{idProduct}=="0100", MODE="0666"' | sudo tee /etc/udev/rules.d/99-kromek-radangel.rules
  9. *
  10. */
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <stdarg.h>
  14. #include <pthread.h>
  15. #include <string.h>
  16. #include <getopt.h>
  17. #include <sys/time.h>
  18. #include <hidapi/hidapi.h>
  19. #include <unistd.h> // usleep()
  20. #define MAX_STR 255
  21. #define MAX_CHANNEL 4096
  22. #define QUEUESIZE 1024
  23. #define DEV_VID 0x4d8
  24. #define DEV_PID 0x100
  25. #define LINE_MAX 4096
  26. // non blocking
  27. #define HID_TIMEOUT -1
  28. // 500 ms timeout
  29. //#define HID_TIMEOUT 500
  30. typedef struct {
  31. struct timespec start_time;
  32. } config;
  33. typedef struct {
  34. FILE* file;
  35. char* name;
  36. } output;
  37. typedef struct {
  38. hid_device* handle;
  39. config config;
  40. output event;
  41. output stats;
  42. } context;
  43. typedef struct {
  44. struct timespec event_time;
  45. unsigned short channel;
  46. } data;
  47. typedef struct {
  48. data data[QUEUESIZE];
  49. long head, tail;
  50. int full, empty;
  51. pthread_mutex_t *mutex;
  52. pthread_cond_t *not_full, *not_empty;
  53. context context;
  54. } queue;
  55. void usage(char* name);
  56. void info(const char* fmt, ...);
  57. void timespec_diff(struct timespec *start, struct timespec *stop, struct timespec *result);
  58. queue *queue_init(void);
  59. void queue_free(queue *q);
  60. void queue_add(queue *q, data src);
  61. void queue_del(queue *q, data *dst);
  62. void *event_source(void *args);
  63. void *event_sink(void *args);
  64. //void *update_context(void *args);
  65. static int verbose_flag; // Flag set by -v | --verbose
  66. void usage(char* name) {
  67. info("%s [<arguments>]\n\n", name);
  68. info("\t-h | --help Usage message.\n");
  69. info("\t-v | --verbose Verbose output.\n");
  70. info("\t-e <string> | --event <string> Event data file path.\n");
  71. info("\t-s <string> | --stats <string> Stats data file path.\n");
  72. info("\n");
  73. }
  74. int main(int argc, char **argv) {
  75. queue *fifo = NULL;
  76. pthread_t pro, con;
  77. struct timespec start_time = { 0, 0 };
  78. int c;
  79. int option_index = 0;
  80. fifo = queue_init();
  81. if (fifo == NULL) {
  82. info("Error: main queue_init() failed.\n");
  83. exit(1);
  84. }
  85. fifo->context.event.name = "-";
  86. fifo->context.event.file = stdout;
  87. fifo->context.stats.name = NULL;
  88. fifo->context.stats.file = NULL;
  89. while (1) {
  90. static struct option long_options[] = {
  91. {"verbose", no_argument, &verbose_flag, 1 },
  92. {"help", no_argument, NULL, 'h'},
  93. {"event", required_argument, NULL, 'e'},
  94. {"stats", required_argument, NULL, 's'},
  95. {0, 0, 0, 0 } // end of options
  96. };
  97. option_index = 0;
  98. c = getopt_long(argc, argv, "he:s:", long_options, &option_index);
  99. if (c == -1) { // end of options
  100. break;
  101. }
  102. switch (c) {
  103. case 0:
  104. if (long_options[option_index].flag != 0) { // option sets a flag
  105. break;
  106. }
  107. info("option %s", long_options[option_index].name);
  108. if (optarg) {
  109. info(" with arg %s", optarg);
  110. }
  111. info("\n");
  112. break;
  113. case 'e':
  114. fifo->context.event.name = optarg;
  115. break;
  116. case 's':
  117. fifo->context.stats.name = optarg;
  118. break;
  119. case 'h':
  120. usage(argv[0]);
  121. queue_free(fifo);
  122. exit(1);
  123. break;
  124. case '?': // getopt_long already printed an error message.
  125. break;
  126. default:
  127. abort();
  128. }
  129. }
  130. if (optind < argc) { // remaining command line arguments (not options).
  131. info("unknown argument: ");
  132. while (optind < argc) {
  133. info("%s ", argv[optind++]);
  134. }
  135. info("\n");
  136. queue_free(fifo);
  137. exit(1);
  138. }
  139. // ensure input
  140. if (hid_init()) {
  141. info("Error: unable to initialize hidapi.\n");
  142. queue_free(fifo);
  143. exit(1);
  144. }
  145. // open device later in read thread, might not be connected yet
  146. // measurement start
  147. clock_gettime(CLOCK_MONOTONIC, &start_time);
  148. fifo->context.config.start_time = start_time;
  149. // start the producer and consumer threads
  150. pthread_create(&pro, NULL, event_source, fifo);
  151. pthread_create(&con, NULL, event_sink, fifo);
  152. pthread_join(pro, NULL);
  153. pthread_join(con, NULL);
  154. if (fifo->context.event.file != NULL) {
  155. fclose(fifo->context.event.file);
  156. }
  157. if (fifo->context.stats.file != NULL) {
  158. fclose(fifo->context.stats.file);
  159. }
  160. if (fifo->context.handle != NULL) {
  161. hid_close(fifo->context.handle);
  162. }
  163. hid_exit(); // Free static HIDAPI objects
  164. queue_free(fifo);
  165. return 0;
  166. }
  167. void info(const char* fmt, ...) {
  168. va_list args;
  169. va_start(args, fmt);
  170. if (verbose_flag) {
  171. fprintf(stderr, fmt, args);
  172. }
  173. va_end(args);
  174. }
  175. queue *queue_init(void) {
  176. queue *q;
  177. q = (queue *) malloc (sizeof (queue));
  178. if (q == NULL) return (NULL);
  179. q->empty = 1;
  180. q->full = 0;
  181. q->head = 0;
  182. q->tail = 0;
  183. q->mutex = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
  184. pthread_mutex_init(q->mutex, NULL);
  185. q->not_full = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
  186. pthread_cond_init(q->not_full, NULL);
  187. q->not_empty = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
  188. pthread_cond_init(q->not_empty, NULL);
  189. return (q);
  190. }
  191. void queue_free(queue *q) {
  192. pthread_mutex_destroy(q->mutex);
  193. free(q->mutex);
  194. pthread_cond_destroy(q->not_full);
  195. free(q->not_full);
  196. pthread_cond_destroy(q->not_empty);
  197. free(q->not_empty);
  198. free(q);
  199. }
  200. void queue_add(queue *q, data src) {
  201. q->data[q->tail] = src;
  202. q->tail++;
  203. if (q->tail == QUEUESIZE) {
  204. q->tail = 0;
  205. }
  206. if (q->tail == q->head) {
  207. q->full = 1;
  208. }
  209. q->empty = 0;
  210. return;
  211. }
  212. void queue_del(queue *q, data *dst) {
  213. *dst = q->data[q->head];
  214. q->head++;
  215. if (q->head == QUEUESIZE) {
  216. q->head = 0;
  217. }
  218. if (q->head == q->tail) {
  219. q->empty = 1;
  220. }
  221. q->full = 0;
  222. return;
  223. }
  224. void *event_source(void *q) {
  225. queue *fifo;
  226. fifo = (queue *)q;
  227. data data;
  228. hid_device* handle = fifo->context.handle;
  229. unsigned char buffer[64];
  230. int result;
  231. struct timespec event_time = { 0, 0L };
  232. struct timespec sleep_time = { 0, 500000000L}; // retry time
  233. do { // read events loop
  234. while (handle == NULL) { // try to aquire handle
  235. handle = hid_open(DEV_VID, DEV_PID, NULL);
  236. if (handle != NULL) {
  237. fifo->context.handle = handle;
  238. } else {
  239. nanosleep(&sleep_time, NULL); // wait to retry
  240. }
  241. }
  242. while (handle != NULL) { // try to read data
  243. memset(buffer, 0, sizeof(buffer));
  244. result = hid_read_timeout(handle, buffer, sizeof(buffer), HID_TIMEOUT);
  245. if (result > 0) { // got some bytes
  246. break;
  247. } else if (result < 0) { // something went wrong: disconnect?
  248. hid_close(handle);
  249. handle = NULL; // invalidate handle for reaquire
  250. fifo->context.handle = handle;
  251. }
  252. }
  253. clock_gettime(CLOCK_MONOTONIC, &event_time);
  254. if (buffer[0] == 4) { // got an event
  255. data.channel = (((buffer[1] << 8) | buffer[2]) >> 4);
  256. data.event_time = event_time;
  257. // lock the queue, wait for space, push
  258. pthread_mutex_lock(fifo->mutex);
  259. while (fifo->full) { // queue is full, wait for consumer
  260. pthread_cond_wait(fifo->not_full, fifo->mutex); // unlocks, block, relock
  261. }
  262. queue_add(fifo, data);
  263. pthread_mutex_unlock(fifo->mutex);
  264. pthread_cond_signal(fifo->not_empty);
  265. }
  266. } while (1); // read events loop
  267. return (NULL);
  268. }
  269. void timespec_diff(struct timespec *start, struct timespec *stop, struct timespec *result) {
  270. if ((stop->tv_nsec - start->tv_nsec) < 0) {
  271. result->tv_sec = stop->tv_sec - start->tv_sec - 1;
  272. result->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000;
  273. } else {
  274. result->tv_sec = stop->tv_sec - start->tv_sec;
  275. result->tv_nsec = stop->tv_nsec - start->tv_nsec;
  276. }
  277. return;
  278. }
  279. void *event_sink(void *q) {
  280. queue *fifo;
  281. fifo = (queue *)q;
  282. data data;
  283. char *events_filename = fifo->context.event.name;
  284. char *stats_filename = fifo->context.stats.name;
  285. char *events_filemode = "a+";
  286. char *stats_filemode = "w";
  287. FILE *events_file = events_filename ? ((strncmp(events_filename, "-", 1) == 0) ? stdout : fopen(events_filename, events_filemode)) : NULL;
  288. FILE *stats_file = stats_filename ? ((strncmp(stats_filename, "-", 1) == 0) ? stdout : fopen(stats_filename, stats_filemode )) : NULL;
  289. fifo->context.event.file = events_file;
  290. fifo->context.stats.file = stats_file;
  291. struct timespec start_time = fifo->context.config.start_time;
  292. struct timespec event_time = { 0, 0L };
  293. struct timespec sleep_time = { 0, 500000000L}; // retry time
  294. long int tv_sec;
  295. unsigned long int tv_nsec;
  296. unsigned int channel = 0;
  297. unsigned long histogram[MAX_CHANNEL];
  298. memset(histogram, 0, MAX_CHANNEL * sizeof(unsigned long));
  299. const char event_header[] = "time\tchannel\n";
  300. const char event_format[] = "%ld.%03ld\t%d\n";
  301. const char stats_header[] = "channel\n";
  302. const char stats_format[] = "%ld\n";
  303. char line[LINE_MAX];
  304. int i, result = 1;
  305. // reconstruct event_time and histogram
  306. if (events_filename && events_file && (events_file != stdout)) {
  307. rewind(events_file);
  308. while (fgets(line, LINE_MAX, events_file) != NULL) {
  309. if(sscanf(line, event_format, &tv_sec, &tv_nsec, &channel) == 3) {
  310. event_time.tv_sec = tv_sec;
  311. event_time.tv_nsec = tv_nsec;
  312. histogram[channel % MAX_CHANNEL] += 1; // update histogram
  313. }
  314. }
  315. }
  316. if (events_filename && events_file && ((events_file == stdout) || (ftell(events_file) == 0))) {
  317. fprintf(events_file, event_header);
  318. }
  319. // readjust start_time
  320. timespec_diff(&event_time, &start_time, &start_time);
  321. fifo->context.config.start_time = start_time;
  322. if (stats_file && stats_filename) {
  323. stats_file = (strncmp(stats_filename, "-", 1) == 0) ? stdout : freopen(stats_filename, stats_filemode, stats_file);
  324. fifo->context.stats.file = stats_file;
  325. result = !!stats_file;
  326. if (stats_file) {
  327. result = fprintf(stats_file, stats_header);
  328. for (i = 0; i < MAX_CHANNEL; i++) {
  329. result = result && (fprintf(stats_file, stats_format,
  330. histogram[i]
  331. ) > 0);
  332. }
  333. fflush(stats_file);
  334. }
  335. }
  336. do { // output loop
  337. // lock the queue, wait for data, pull
  338. pthread_mutex_lock(fifo->mutex);
  339. while (fifo->empty) { // queue is empty, wait for producer
  340. pthread_cond_wait(fifo->not_empty, fifo->mutex); // unlock, block, relock
  341. }
  342. queue_del(fifo, &data);
  343. pthread_mutex_unlock (fifo->mutex);
  344. pthread_cond_signal(fifo->not_full);
  345. // event time since measurement start
  346. event_time = data.event_time;
  347. channel = data.channel;
  348. timespec_diff(&start_time, &event_time, &event_time);
  349. // update histogram
  350. histogram[channel % MAX_CHANNEL] += 1;
  351. if (events_file) {
  352. result = (fprintf(events_file, event_format,
  353. event_time.tv_sec,
  354. event_time.tv_nsec / 1000000,
  355. channel
  356. ) > 0);
  357. fflush(events_file);
  358. } else if (events_filename) {// try reopen
  359. nanosleep(&sleep_time, NULL); // wait to retry
  360. events_file = (strncmp(events_filename, "-", 1) == 0) ? stdout : freopen(events_filename, events_filemode, events_file);
  361. fifo->context.event.file = events_file;
  362. result = !!events_file;
  363. }
  364. if (stats_file && stats_filename) {
  365. stats_file = (strncmp(stats_filename, "-", 1) == 0) ? stdout : freopen(stats_filename, stats_filemode, stats_file);
  366. fifo->context.stats.file = stats_file;
  367. result = !!stats_file;
  368. if (stats_file) {
  369. for (i = 0; i < MAX_CHANNEL; i++) {
  370. result = result && (fprintf(stats_file, stats_format,
  371. histogram[i]
  372. ) > 0);
  373. }
  374. fflush(stats_file);
  375. }
  376. }
  377. } while (result); // output loop
  378. return (NULL);
  379. }
  380. /*
  381. void *update_context (void *q) {
  382. queue *fifo;
  383. fifo = (queue *)q;
  384. return (NULL);
  385. }
  386. */